AstrBot-Desktop/src/features/profiles/ProfileManager.tsx

703 行
23 KiB
TypeScript

import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useState, type FormEvent } from "react";
import {
connectionPolicyStatusSchema,
connectionSlotListSchema,
connectionSlotSchema,
type ActiveSlotKind,
type AssignConnectionSlotRequest,
type ConnectionPolicyStatus,
type ConnectionSlot,
} from "../../types/connection";
import {
connectionProfileListSchema,
connectionProfileSchema,
type AuthenticationType,
type ConnectionProfile,
type ConnectionProfileInput,
type ProfileRole,
type TransportKind,
type UpdateConnectionProfileRequest,
} from "../../types/profile";
import { connectionRuntimeStatusSchema } from "../chat/types";
import { CredentialEnrollmentCard } from "./CredentialEnrollmentCard";
interface ProfileFormState {
displayName: string;
role: ProfileRole;
baseUrl: string;
eventStreamUrl: string;
authenticationType: AuthenticationType;
transportKind: TransportKind;
remoteUsername: string;
remoteDisplayName: string;
allowInsecureHttp: boolean;
pinnedCertificateFingerprint: string;
autoConnect: boolean;
autoConnectSlot: "" | ActiveSlotKind;
}
const emptyForm: ProfileFormState = {
displayName: "",
role: "general",
baseUrl: "https://",
eventStreamUrl: "",
authenticationType: "device-token",
transportKind: "desktop-v1",
remoteUsername: "",
remoteDisplayName: "",
allowInsecureHttp: false,
pinnedCertificateFingerprint: "",
autoConnect: false,
autoConnectSlot: "",
};
const emptyPolicy: ConnectionPolicyStatus = {
operationsSwitchLocked: false,
activeOperationsTaskCount: 0,
duplicateServerInstanceWarnings: [],
};
export function ProfileManager() {
const [profiles, setProfiles] = useState<ConnectionProfile[]>([]);
const [slots, setSlots] = useState<ConnectionSlot[]>([]);
const [policy, setPolicy] = useState<ConnectionPolicyStatus>(emptyPolicy);
const [form, setForm] = useState<ProfileFormState>(emptyForm);
const [editingId, setEditingId] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const loadProfiles = useCallback(async () => {
try {
const [profileResult, slotResult, policyResult, runtimeResult] =
await Promise.all([
invoke<unknown>("list_connection_profiles"),
invoke<unknown>("list_connection_slots"),
invoke<unknown>("connection_policy_status"),
invoke<unknown>("connection_runtime_status"),
]);
setProfiles(connectionProfileListSchema.parse(profileResult));
const storedSlots = connectionSlotListSchema.parse(slotResult);
const runtime = connectionRuntimeStatusSchema.parse(runtimeResult);
setSlots(mergeRuntimeSlots(storedSlots, runtime));
setPolicy(connectionPolicyStatusSchema.parse(policyResult));
setError(null);
} catch (reason) {
setError(`Profile storage unavailable: ${errorMessage(reason)}`);
}
}, []);
const refreshRuntimeStatus = useCallback(async () => {
try {
const runtime = connectionRuntimeStatusSchema.parse(
await invoke<unknown>("connection_runtime_status"),
);
setSlots((current) => mergeRuntimeSlots(current, runtime));
} catch {
// Keep the last slot snapshot when the runtime is temporarily unavailable.
}
}, []);
useEffect(() => {
void loadProfiles();
const refreshTimer = window.setInterval(() => void refreshRuntimeStatus(), 2000);
return () => window.clearInterval(refreshTimer);
}, [loadProfiles, refreshRuntimeStatus]);
async function submitProfile(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setBusy(true);
setError(null);
setNotice(null);
try {
const profileInput = toProfileInput(form);
const result = editingId
? await invoke<unknown>("update_connection_profile", {
request: {
id: editingId,
profile: profileInput,
} satisfies UpdateConnectionProfileRequest,
})
: await invoke<unknown>("create_connection_profile", {
request: profileInput,
});
const saved = connectionProfileSchema.parse(result);
setProfiles((current) =>
sortProfiles([
...current.filter((profile) => profile.id !== saved.id),
saved,
]),
);
await refreshPolicy();
setNotice(
editingId
? `已更新 Profile:${saved.displayName}`
: `已创建 Profile:${saved.displayName}`,
);
resetForm();
} catch (reason) {
setError(`Profile save failed: ${errorMessage(reason)}`);
} finally {
setBusy(false);
}
}
function editProfile(profile: ConnectionProfile) {
setEditingId(profile.id);
setForm({
displayName: profile.displayName,
role: profile.role,
baseUrl: profile.baseUrl,
eventStreamUrl: profile.eventStreamUrl ?? "",
authenticationType: profile.authenticationType,
transportKind: profile.transportKind ?? "desktop-v1",
remoteUsername: profile.remoteUsername ?? "",
remoteDisplayName: profile.remoteDisplayName ?? "",
allowInsecureHttp: profile.allowInsecureHttp,
pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "",
autoConnect: profile.autoConnect,
autoConnectSlot: profile.autoConnectSlot ?? "",
});
setError(null);
setNotice(null);
}
async function deleteProfile(profile: ConnectionProfile) {
if (
!window.confirm(
`删除 Profile“${profile.displayName}”?此操作不会删除凭据值,因为当前阶段不接触凭据。`,
)
) {
return;
}
setBusy(true);
setError(null);
setNotice(null);
try {
await invoke("delete_connection_profile", { id: profile.id });
setProfiles((current) =>
current.filter((item) => item.id !== profile.id),
);
setSlots((current) =>
current.map((slot) =>
slot.profileId === profile.id
? { ...slot, profileId: undefined, serverInstanceId: undefined }
: slot,
),
);
await refreshPolicy();
if (editingId === profile.id) {
resetForm();
}
setNotice(`已删除 Profile:${profile.displayName}`);
} catch (reason) {
setError(`Profile deletion failed: ${errorMessage(reason)}`);
} finally {
setBusy(false);
}
}
async function updateSlot(slot: ActiveSlotKind, profileId: string) {
setBusy(true);
setError(null);
setNotice(null);
try {
const result = profileId
? await invoke<unknown>("assign_connection_slot", {
request: {
slot,
profileId,
} satisfies AssignConnectionSlotRequest,
})
: await invoke<unknown>("clear_connection_slot", { slot });
const saved = connectionSlotSchema.parse(result);
setSlots((current) =>
current.map((item) => (item.slot === saved.slot ? saved : item)),
);
await refreshPolicy();
const profile = profiles.find((item) => item.id === saved.profileId);
setNotice(
profile
? `已将${profile.displayName}分配到${slotLabel(slot)}槽位。`
: `已清空${slotLabel(slot)}槽位。`,
);
} catch (reason) {
setError(`Slot update failed: ${errorMessage(reason)}`);
} finally {
setBusy(false);
}
}
async function refreshPolicy() {
try {
const policyResult = await invoke<unknown>("connection_policy_status");
setPolicy(connectionPolicyStatusSchema.parse(policyResult));
} catch {
// Keep the previous policy snapshot when only the refresh fails.
}
}
function resetForm() {
setEditingId(null);
setForm(emptyForm);
}
return (
<section className="profile-manager" aria-labelledby="profile-heading">
<div className="section-heading">
<div>
<p className="eyebrow">P02 · dual connections</p>
<h2 id="profile-heading">连接 Profile</h2>
</div>
<p>
这里只管理非敏感连接元数据。Token、密码和 API Key 不会进入 React 或
SQLite 普通字段。
</p>
</div>
<div className="slot-grid" aria-label="活动连接槽位">
{slots.map((slot) => (
<article className="slot-card" key={slot.slot}>
<div>
<span>{slotLabel(slot.slot)}槽位</span>
<strong>{connectionStateLabel(slot.state)}</strong>
</div>
<label>
<span>{slotLabel(slot.slot)} Profile</span>
<select
aria-label={`${slotLabel(slot.slot)} Profile`}
disabled={
busy ||
(slot.slot === "operations" && policy.operationsSwitchLocked)
}
value={slot.profileId ?? ""}
onChange={(event) =>
void updateSlot(slot.slot, event.target.value)
}
>
<option value="">未分配</option>
{profiles.map((profile) => (
<option
key={profile.id}
value={profile.id}
disabled={slots.some(
(other) =>
other.slot !== slot.slot &&
other.profileId === profile.id,
)}
>
{profile.displayName} · {roleLabel(profile.role)}
</option>
))}
</select>
</label>
<p>
{slot.serverInstanceId
? `服务器:${slot.serverInstanceId}`
: "当前仅保存本地槽位归属,尚未启动网络连接。"}
</p>
{slot.slot === "operations" && policy.operationsSwitchLocked ? (
<p className="warning-inline">
运维任务进行中,已锁定运维槽位切换(
{policy.activeOperationsTaskCount} 个活动任务)。
</p>
) : null}
</article>
))}
</div>
<p className="slot-boundary-note">
槽位分配不会授予本机工具权限,也不会读取凭据;正式连接激活将在协议与凭据生命周期确认后启用。
</p>
{policy.duplicateServerInstanceWarnings.length > 0 ? (
<div
className="warning-banner"
role="status"
aria-label="重复服务器实例提示"
>
{policy.duplicateServerInstanceWarnings.map((warning) => (
<p key={warning.serverInstanceId}>
服务器实例 {warning.serverInstanceId} 被多个 Profile 引用:
{warning.displayNames.join("、")}。它们保持独立,不会静默合并。
</p>
))}
</div>
) : null}
<div className="profile-layout">
<form className="profile-form" onSubmit={submitProfile}>
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
<label>
<span>显示名称</span>
<input
name="displayName"
required
maxLength={80}
value={form.displayName}
onChange={(event) =>
setForm((current) => ({
...current,
displayName: event.target.value,
}))
}
/>
</label>
<label>
<span>角色</span>
<select
name="role"
value={form.role}
onChange={(event) =>
setForm((current) => ({
...current,
role: event.target.value as ProfileRole,
}))
}
>
<option value="general">通用</option>
<option value="companion">陪伴</option>
<option value="operations">运维</option>
</select>
</label>
<label>
<span>REST 基础 URL</span>
<input
name="baseUrl"
type="url"
required
value={form.baseUrl}
onChange={(event) =>
setForm((current) => ({
...current,
baseUrl: event.target.value,
}))
}
/>
</label>
<label>
<span>SSE URL(可选)</span>
<input
name="eventStreamUrl"
type="url"
value={form.eventStreamUrl}
onChange={(event) =>
setForm((current) => ({
...current,
eventStreamUrl: event.target.value,
}))
}
/>
</label>
<label>
<span>认证类型</span>
<select
name="authenticationType"
value={form.authenticationType}
onChange={(event) =>
setForm((current) => ({
...current,
authenticationType: event.target.value as AuthenticationType,
}))
}
>
<option value="device-token">设备 Token</option>
<option value="api-key">API Key</option>
<option value="jwt">AstrBot JWT</option>
</select>
</label>
<label>
<span>证书 SHA-256 指纹(可选)</span>
<input
name="pinnedCertificateFingerprint"
inputMode="text"
placeholder="64 位十六进制"
value={form.pinnedCertificateFingerprint}
onChange={(event) =>
setForm((current) => ({
...current,
pinnedCertificateFingerprint: event.target.value,
}))
}
/>
</label>
<label className="checkbox-field">
<input
name="allowInsecureHttp"
type="checkbox"
checked={form.allowInsecureHttp}
onChange={(event) =>
setForm((current) => ({
...current,
allowInsecureHttp: event.target.checked,
}))
}
/>
<span>明确允许不安全 HTTP(仅限受信任网络)</span>
</label>
<label>
传输协议
<select
value={form.transportKind}
onChange={(event) =>
setForm((current) => ({
...current,
transportKind: event.target.value as TransportKind,
}))
}
>
<option value="desktop-v1">Desktop Mock/Gateway</option>
<option value="astr-bot-open-api">AstrBot OpenAPI</option>
</select>
</label>
{form.transportKind === "astr-bot-open-api" ? (
<>
<label>
AstrBot 用户名
<input
value={form.remoteUsername}
onChange={(event) =>
setForm((current) => ({
...current,
remoteUsername: event.target.value,
}))
}
placeholder="desktop-companion"
/>
</label>
<label>
BOT 称呼昵称
<input
value={form.remoteDisplayName}
maxLength={80}
onChange={(event) =>
setForm((current) => ({
...current,
remoteDisplayName: event.target.value,
}))
}
placeholder="小明"
/>
</label>
</>
) : null}
<label className="checkbox-field">
<input
name="autoConnect"
type="checkbox"
checked={form.autoConnect}
onChange={(event) =>
setForm((current) => ({
...current,
autoConnect: event.target.checked,
autoConnectSlot: event.target.checked
? current.autoConnectSlot || "companion"
: "",
}))
}
/>
<span>启动时自动连接(不会在本阶段真正建立网络会话)</span>
</label>
<label>
<span>自动连接槽位</span>
<select
name="autoConnectSlot"
aria-label="自动连接槽位"
disabled={!form.autoConnect}
value={form.autoConnectSlot}
onChange={(event) =>
setForm((current) => ({
...current,
autoConnectSlot: event.target.value as "" | ActiveSlotKind,
}))
}
>
<option value="">不自动连接</option>
<option value="companion">陪伴槽位</option>
<option value="operations">运维槽位</option>
</select>
</label>
<p className="form-note">
自动连接配置最多两个 Profile,且槽位不可重复;真正的 REST/SSE
激活仍需等待协议与凭据边界确认。
</p>
<div className="button-row">
<button type="submit" disabled={busy}>
{editingId ? "更新 Profile" : "保存 Profile"}
</button>
{editingId ? (
<button
type="button"
className="button-secondary"
disabled={busy}
onClick={resetForm}
>
取消编辑
</button>
) : null}
</div>
</form>
<div className="profile-list" aria-label="已保存 Profile">
<h3>已保存({profiles.length})</h3>
{profiles.length === 0 ? (
<p className="empty-state">尚未保存 Profile。</p>
) : (
profiles.map((profile) => (
<article className="profile-card" key={profile.id}>
<div>
<strong>{profile.displayName}</strong>
<span>{roleLabel(profile.role)}</span>
</div>
<code>{profile.baseUrl}</code>
<p>
{profile.authenticationType === "api-key"
? "API Key 引用"
: "设备 Token 引用"}
{" · "}
{profile.credentialReference ? "已登记" : "待登记"}
</p>
<p>
{profile.autoConnect
? `自动连接:${slotLabel(profile.autoConnectSlot ?? "companion")}`
: "自动连接:关闭"}
{profile.serverInstanceId
? ` · 服务器 ${profile.serverInstanceId}`
: ""}
</p>
<div className="button-row">
<button
type="button"
className="button-secondary"
disabled={busy}
aria-label={`编辑 ${profile.displayName}`}
onClick={() => editProfile(profile)}
>
编辑
</button>
<button
type="button"
className="button-danger"
disabled={busy}
aria-label={`删除 ${profile.displayName}`}
onClick={() => void deleteProfile(profile)}
>
删除
</button>
</div>
<CredentialEnrollmentCard
profile={profile}
onChanged={loadProfiles}
/>
</article>
))
)}
</div>
</div>
{notice ? (
<p className="notice-banner" aria-live="polite">
{notice}
</p>
) : null}
{error ? (
<p className="error-banner" role="alert">
{error}
</p>
) : null}
</section>
);
}
function toProfileInput(form: ProfileFormState): ConnectionProfileInput {
const eventStreamUrl = form.eventStreamUrl.trim();
const fingerprint = form.pinnedCertificateFingerprint.trim();
return {
displayName: form.displayName.trim(),
role: form.role,
baseUrl: form.baseUrl.trim(),
eventStreamUrl: eventStreamUrl || undefined,
authenticationType: form.authenticationType,
transportKind: form.transportKind,
remoteUsername: form.remoteUsername.trim() || undefined,
remoteDisplayName: form.remoteDisplayName.trim() || undefined,
allowInsecureHttp: form.allowInsecureHttp,
pinnedCertificateFingerprint: fingerprint || undefined,
autoConnect: form.autoConnect,
autoConnectSlot: form.autoConnect
? form.autoConnectSlot || undefined
: undefined,
};
}
function mergeRuntimeSlots(
slots: ConnectionSlot[],
runtime: ReturnType<typeof connectionRuntimeStatusSchema.parse>,
) {
return slots.map((slot) => {
const snapshot = runtime[slot.slot];
return {
...slot,
state: snapshot.state,
serverInstanceId: snapshot.serverInstanceId ?? slot.serverInstanceId,
};
});
}
function sortProfiles(profiles: ConnectionProfile[]) {
return [...profiles].sort((left, right) =>
left.displayName.localeCompare(right.displayName, "zh-CN"),
);
}
function roleLabel(role: ProfileRole) {
switch (role) {
case "companion":
return "陪伴";
case "operations":
return "运维";
case "general":
return "通用";
}
}
function slotLabel(slot: ActiveSlotKind) {
return slot === "companion" ? "陪伴" : "运维";
}
function connectionStateLabel(state: ConnectionSlot["state"]) {
return state === "disconnected" ? "未连接" : state;
}
function errorMessage(reason: unknown) {
if (reason instanceof Error) {
return reason.message;
}
if (
typeof reason === "object" &&
reason !== null &&
"message" in reason &&
typeof reason.message === "string"
) {
return reason.message;
}
return String(reason);
}