diff --git a/src/App.test.tsx b/src/App.test.tsx index 4bd6cad..25e3b61 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -227,15 +227,16 @@ describe("App", () => { await openConnectionsPage(); expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText("服务器地址"), { + target: { value: "https://ops.example.test" }, + }); + fireEvent.change(screen.getByLabelText("适配器 ID"), { + target: { value: "opsbot" }, + }); + // Lives under 高级设置; the disclosure only hides it visually. fireEvent.change(screen.getByLabelText("显示名称"), { target: { value: "家庭运维" }, }); - fireEvent.change(screen.getByLabelText("角色"), { - target: { value: "operations" }, - }); - fireEvent.change(screen.getByLabelText("REST 基础 URL"), { - target: { value: "https://ops.example.test" }, - }); fireEvent.click(screen.getByRole("button", { name: "保存 Profile" })); expect( @@ -354,13 +355,24 @@ describe("App", () => { const created: ConnectionProfile = { id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", ...request, - transportKind: "desktop-v1", + transportKind: request.transportKind ?? "astr-bot-open-api", createdAt: "2026-07-19T03:00:00Z", updatedAt: "2026-07-19T03:00:00Z", }; profiles = [created]; return created; } + if (command === "assign_connection_slot") { + const { request } = args as { + request: { slot: ActiveSlotKind; profileId: string }; + }; + return { + slot: request.slot, + profileId: request.profileId, + state: "disconnected", + unreadCount: 0, + }; + } throw new Error(`Unexpected command: ${command}`); }); @@ -368,19 +380,18 @@ describe("App", () => { await openConnectionsPage(); expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText("服务器地址"), { + target: { value: "https://companion.example.test" }, + }); + fireEvent.change(screen.getByLabelText("适配器 ID"), { + target: { value: "companionbot" }, + }); fireEvent.change(screen.getByLabelText("显示名称"), { target: { value: "自动陪伴" }, }); - fireEvent.change(screen.getByLabelText("角色"), { - target: { value: "companion" }, - }); - fireEvent.change(screen.getByLabelText("REST 基础 URL"), { - target: { value: "https://companion.example.test" }, - }); - fireEvent.click( - screen.getByLabelText("启动时自动连接(不会在本阶段真正建立网络会话)"), - ); - fireEvent.change(screen.getByLabelText("自动连接槽位"), { + // Choosing a slot is now the single control: it assigns the slot, sets the + // role, and points startup auto-connect at it. + fireEvent.change(screen.getByLabelText("槽位"), { target: { value: "companion" }, }); fireEvent.click(screen.getByRole("button", { name: "保存 Profile" })); @@ -388,19 +399,25 @@ describe("App", () => { expect( await screen.findByText("已创建 Profile:自动陪伴"), ).toBeInTheDocument(); - expect(screen.getByText("自动连接:陪伴")).toBeInTheDocument(); expect(invoke).toHaveBeenCalledWith("create_connection_profile", { request: { displayName: "自动陪伴", role: "companion", baseUrl: "https://companion.example.test", - authenticationType: "device-token", - transportKind: "desktop-v1", + authenticationType: "api-key", + transportKind: "astr-bot-open-api", + remoteUsername: "companionbot", allowInsecureHttp: false, autoConnect: true, autoConnectSlot: "companion", }, }); + expect(invoke).toHaveBeenCalledWith("assign_connection_slot", { + request: { + slot: "companion", + profileId: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", + }, + }); }); it("shows duplicate server-instance warnings and locks the operations slot", async () => { diff --git a/src/features/profiles/ProfileManager.tsx b/src/features/profiles/ProfileManager.tsx index 8244727..4947df1 100644 --- a/src/features/profiles/ProfileManager.tsx +++ b/src/features/profiles/ProfileManager.tsx @@ -25,35 +25,68 @@ import { errorMessage } from "../../lib/errorMessage"; import { CredentialEnrollmentCard } from "./CredentialEnrollmentCard"; interface ProfileFormState { - displayName: string; - role: ProfileRole; baseUrl: string; - eventStreamUrl: string; + apiKey: string; + remoteUsername: string; + slot: "" | ActiveSlotKind; + displayName: string; + remoteDisplayName: 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", + baseUrl: "http://", + apiKey: "", remoteUsername: "", + slot: "", + displayName: "", remoteDisplayName: "", + authenticationType: "api-key", + transportKind: "astr-bot-open-api", allowInsecureHttp: false, - pinnedCertificateFingerprint: "", - autoConnect: false, - autoConnectSlot: "", + autoConnect: true, }; +/// Names the connection after the server and identity when the user did not. +/// +/// The display name is `NOT NULL` in the database and is what the profile list +/// and the slot cards show, but asking for it adds a field that carries no +/// information the other three do not already provide. +function derivedDisplayName(form: ProfileFormState): string { + const explicit = form.displayName.trim(); + if (explicit) return explicit; + const username = form.remoteUsername.trim(); + const host = hostOf(form.baseUrl); + if (host && username) return `${username}@${host}`; + return username || host || "AstrBot 连接"; +} + +function hostOf(value: string): string { + try { + return new URL(value.trim()).host; + } catch { + return ""; + } +} + +/// The slot a profile serves is the only meaningful reading of its role. +function roleForSlot(slot: "" | ActiveSlotKind): ProfileRole { + return slot === "" ? "general" : slot; +} + +/// True when the address needs the explicit insecure-transport approval. +/// +/// `normalize_url` in `profiles.rs` rejects an `http://` base URL unless the +/// profile carries that approval, so the checkbox has to appear before the user +/// can save a LAN address — but showing it unconditionally invites turning it on +/// for an `https://` endpoint that never needed it. +function needsInsecureApproval(baseUrl: string): boolean { + return baseUrl.trim().toLowerCase().startsWith("http://"); +} + const emptyPolicy: ConnectionPolicyStatus = { operationsSwitchLocked: false, activeOperationsTaskCount: 0, @@ -103,7 +136,10 @@ export function ProfileManager() { useEffect(() => { void loadProfiles(); - const refreshTimer = window.setInterval(() => void refreshRuntimeStatus(), 2000); + const refreshTimer = window.setInterval( + () => void refreshRuntimeStatus(), + 2000, + ); return () => window.clearInterval(refreshTimer); }, [loadProfiles, refreshRuntimeStatus]); @@ -132,15 +168,65 @@ export function ProfileManager() { saved, ]), ); + + // The remaining steps each need the profile to exist, so they cannot be + // folded into the create call. A failure in either leaves a usable + // profile, so report it rather than treating the save as failed. + const followUp: string[] = []; + + if (form.slot) { + try { + const assigned = connectionSlotSchema.parse( + await invoke("assign_connection_slot", { + request: { + slot: form.slot, + profileId: saved.id, + } satisfies AssignConnectionSlotRequest, + }), + ); + setSlots((current) => + current.map((item) => + item.slot === assigned.slot ? assigned : item, + ), + ); + } catch (reason) { + followUp.push(`槽位指派失败:${errorMessage(reason)}`); + } + } + + const secret = form.apiKey.trim(); + if (secret) { + try { + await invoke("enroll_profile_credential", { + request: { + profileId: saved.id, + authenticationType: saved.authenticationType, + secret, + username: saved.remoteUsername ?? undefined, + }, + }); + } catch (reason) { + followUp.push( + `凭据登记失败:${errorMessage(reason)}。Profile 已保存,可在下方凭据卡片重试。`, + ); + } + } + + await loadProfiles(); await refreshPolicy(); - setNotice( - editingId - ? `已更新 Profile:${saved.displayName}` - : `已创建 Profile:${saved.displayName}`, - ); + if (followUp.length > 0) { + setError(followUp.join(" ")); + setNotice(`已保存 Profile:${saved.displayName}`); + } else { + setNotice( + editingId + ? `已更新 Profile:${saved.displayName}` + : `已创建 Profile:${saved.displayName}`, + ); + } resetForm(); } catch (reason) { - setError(`Profile save failed: ${errorMessage(reason)}`); + setError(`Profile 保存失败:${errorMessage(reason)}`); } finally { setBusy(false); } @@ -148,19 +234,25 @@ export function ProfileManager() { function editProfile(profile: ConnectionProfile) { setEditingId(profile.id); + // The persisted slot assignment is authoritative for which slot a profile + // serves; `autoConnectSlot` only says where startup connection should go. + const assignedSlot = slots.find( + (slot) => slot.profileId === profile.id, + )?.slot; setForm({ - displayName: profile.displayName, - role: profile.role, baseUrl: profile.baseUrl, - eventStreamUrl: profile.eventStreamUrl ?? "", - authenticationType: profile.authenticationType, - transportKind: profile.transportKind ?? "desktop-v1", + // Never populated from a stored profile: the secret lives in Windows + // Credential Manager and never crosses IPC. Rotation goes through the + // credential card. + apiKey: "", remoteUsername: profile.remoteUsername ?? "", + slot: assignedSlot ?? profile.autoConnectSlot ?? "", + displayName: profile.displayName, remoteDisplayName: profile.remoteDisplayName ?? "", + authenticationType: profile.authenticationType, + transportKind: profile.transportKind ?? "astr-bot-open-api", allowInsecureHttp: profile.allowInsecureHttp, - pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "", autoConnect: profile.autoConnect, - autoConnectSlot: profile.autoConnectSlot ?? "", }); setError(null); setNotice(null); @@ -335,45 +427,12 @@ export function ProfileManager() {

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

- - - - - - - - - - - - - - {form.transportKind === "astr-bot-open-api" ? ( - <> - - - - ) : null} - +

+ AstrBot 的会话身份,3–32 位英文或数字。两个槽位必须使用不同的 + ID,否则会共用同一段对话。 +

+ + {editingId ? null : ( + <> + +

+ 保存时一次性写入 Windows + 凭据管理器,不会进入本地数据库或前端状态。 +

+ + )} -

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

+ {needsInsecureApproval(form.baseUrl) ? ( + + ) : null} + +
+ 高级设置 + + + + + + + + + + +
- + - + )) )} @@ -628,23 +701,22 @@ export function ProfileManager() { } function toProfileInput(form: ProfileFormState): ConnectionProfileInput { - const eventStreamUrl = form.eventStreamUrl.trim(); - const fingerprint = form.pinnedCertificateFingerprint.trim(); + const slot = form.slot || undefined; return { - displayName: form.displayName.trim(), - role: form.role, + displayName: derivedDisplayName(form), + role: roleForSlot(form.slot), 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, + // `normalize_url` only consults this for an `http://` address, and leaving a + // stale approval on an `https://` profile would silently permit a later + // downgrade of that address. + allowInsecureHttp: + needsInsecureApproval(form.baseUrl) && form.allowInsecureHttp, + autoConnect: form.autoConnect && Boolean(slot), + autoConnectSlot: form.autoConnect ? slot : undefined, }; } diff --git a/src/styles.css b/src/styles.css index 662ead5..22a0c3c 100644 --- a/src/styles.css +++ b/src/styles.css @@ -265,6 +265,32 @@ select:focus { font-size: 0.9rem; } +/* Everything the AstrBot connection does not need in order to work. Collapsed + by default so the common path is four fields. */ +.profile-advanced { + padding: 0.75rem 0.9rem; + border: 1px solid var(--ui-line, rgb(137 175 232 / 26%)); + border-radius: 0.65rem; + background: var(--ui-surface-soft, rgb(11 27 49 / 45%)); +} + +.profile-advanced > summary { + color: var(--ui-subtle, #9fb4d4); + font-size: 0.9rem; + font-weight: 650; + cursor: pointer; + list-style-position: inside; +} + +.profile-advanced[open] > summary { + margin-bottom: 0.9rem; +} + +.profile-advanced > label:not(:last-child), +.profile-advanced > .checkbox-field:not(:last-child) { + margin-bottom: 0.9rem; +} + .button-row { display: flex; flex-wrap: wrap;