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 { 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([]); const [slots, setSlots] = useState([]); const [policy, setPolicy] = useState(emptyPolicy); const [form, setForm] = useState(emptyForm); const [editingId, setEditingId] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [notice, setNotice] = useState(null); const loadProfiles = useCallback(async () => { try { const [profileResult, slotResult, policyResult] = await Promise.all([ invoke("list_connection_profiles"), invoke("list_connection_slots"), invoke("connection_policy_status"), ]); setProfiles(connectionProfileListSchema.parse(profileResult)); setSlots(connectionSlotListSchema.parse(slotResult)); setPolicy(connectionPolicyStatusSchema.parse(policyResult)); setError(null); } catch (reason) { setError(`Profile storage unavailable: ${errorMessage(reason)}`); } }, []); useEffect(() => { void loadProfiles(); }, [loadProfiles]); async function submitProfile(event: FormEvent) { event.preventDefault(); setBusy(true); setError(null); setNotice(null); try { const profileInput = toProfileInput(form); const result = editingId ? await invoke("update_connection_profile", { request: { id: editingId, profile: profileInput, } satisfies UpdateConnectionProfileRequest, }) : await invoke("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("assign_connection_slot", { request: { slot, profileId, } satisfies AssignConnectionSlotRequest, }) : await invoke("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("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 (

P02 · dual connections

连接 Profile

这里只管理非敏感连接元数据。Token、密码和 API Key 不会进入 React 或 SQLite 普通字段。

{slots.map((slot) => (
{slotLabel(slot.slot)}槽位 {connectionStateLabel(slot.state)}

{slot.serverInstanceId ? `服务器:${slot.serverInstanceId}` : "当前仅保存本地槽位归属,尚未启动网络连接。"}

{slot.slot === "operations" && policy.operationsSwitchLocked ? (

运维任务进行中,已锁定运维槽位切换( {policy.activeOperationsTaskCount} 个活动任务)。

) : null}
))}

槽位分配不会授予本机工具权限,也不会读取凭据;正式连接激活将在协议与凭据生命周期确认后启用。

{policy.duplicateServerInstanceWarnings.length > 0 ? (
{policy.duplicateServerInstanceWarnings.map((warning) => (

服务器实例 {warning.serverInstanceId} 被多个 Profile 引用: {warning.displayNames.join("、")}。它们保持独立,不会静默合并。

))}
) : null}

{editingId ? "编辑 Profile" : "新建 Profile"}

{form.transportKind === "astrbot-openapi" ? ( <> ) : null}

自动连接配置最多两个 Profile,且槽位不可重复;真正的 REST/SSE 激活仍需等待协议与凭据边界确认。

{editingId ? ( ) : null}

已保存({profiles.length})

{profiles.length === 0 ? (

尚未保存 Profile。

) : ( profiles.map((profile) => (
{profile.displayName} {roleLabel(profile.role)}
{profile.baseUrl}

{profile.authenticationType === "api-key" ? "API Key 引用" : "设备 Token 引用"} {" · "} {profile.credentialReference ? "已登记" : "待登记"}

{profile.autoConnect ? `自动连接:${slotLabel(profile.autoConnectSlot ?? "companion")}` : "自动连接:关闭"} {profile.serverInstanceId ? ` · 服务器 ${profile.serverInstanceId}` : ""}

)) )}
{notice ? (

{notice}

) : null} {error ? (

{error}

) : null}
); } 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 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); }