From 907a8a38da5f171d4d82f85ac8b900392842739f Mon Sep 17 00:00:00 2001 From: YokiiroBW Date: Sat, 18 Jul 2026 23:36:59 +0800 Subject: [PATCH] feat(profile-ui): add basic profile management --- src/App.test.tsx | 141 +++++++- src/App.tsx | 6 +- src/features/profiles/ProfileManager.tsx | 396 +++++++++++++++++++++++ src/styles.css | 190 ++++++++++- src/test/setup.ts | 7 + src/types/profile.ts | 54 ++++ tests/e2e/bootstrap.spec.ts | 10 +- 7 files changed, 787 insertions(+), 17 deletions(-) create mode 100644 src/features/profiles/ProfileManager.tsx create mode 100644 src/types/profile.ts diff --git a/src/App.test.tsx b/src/App.test.tsx index 265439b..0b29552 100644 --- a/src/App.test.tsx +++ b/src/App.test.tsx @@ -1,21 +1,36 @@ import { invoke } from "@tauri-apps/api/core"; -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { App } from "./App"; +import type { + ConnectionProfile, + ConnectionProfileInput, + UpdateConnectionProfileRequest, +} from "./types/profile"; vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(), })); +const bootstrapStatus = { + appVersion: "0.1.0-alpha.0", + platform: "windows", + rustCore: "ready", + protocolVersion: "desktop-v1alpha1", + databaseSchemaVersion: 2, +}; + describe("App", () => { beforeEach(() => { - vi.mocked(invoke).mockResolvedValue({ - appVersion: "0.1.0-alpha.0", - platform: "windows", - rustCore: "ready", - protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 1, + vi.mocked(invoke).mockImplementation(async (command) => { + if (command === "bootstrap_status") { + return bootstrapStatus; + } + if (command === "list_connection_profiles") { + return []; + } + throw new Error(`Unexpected command: ${command}`); }); }); @@ -24,15 +39,21 @@ describe("App", () => { expect(await screen.findByText("ready")).toBeInTheDocument(); expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument(); + expect(screen.getByText("连接 Profile")).toBeInTheDocument(); }); it("rejects an invalid Rust IPC payload", async () => { - vi.mocked(invoke).mockResolvedValueOnce({ - appVersion: "0.1.0-alpha.0", - platform: "windows", - rustCore: "unexpected", - protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 1, + vi.mocked(invoke).mockImplementation(async (command) => { + if (command === "bootstrap_status") { + return { + ...bootstrapStatus, + rustCore: "unexpected", + }; + } + if (command === "list_connection_profiles") { + return []; + } + throw new Error(`Unexpected command: ${command}`); }); render(); @@ -40,4 +61,98 @@ describe("App", () => { expect(await screen.findByText(/IPC unavailable:/)).toBeInTheDocument(); expect(screen.queryByText("unexpected")).not.toBeInTheDocument(); }); + + it("creates, edits, and deletes non-sensitive profile metadata", async () => { + let profiles: ConnectionProfile[] = []; + vi.mocked(invoke).mockImplementation(async (command, args) => { + if (command === "bootstrap_status") { + return bootstrapStatus; + } + if (command === "list_connection_profiles") { + return profiles; + } + if (command === "create_connection_profile") { + const { request } = args as { request: ConnectionProfileInput }; + const created: ConnectionProfile = { + id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a", + ...request, + autoConnect: false, + createdAt: "2026-07-18T02:00:00Z", + updatedAt: "2026-07-18T02:00:00Z", + }; + profiles = [created]; + return created; + } + if (command === "update_connection_profile") { + const { request } = args as { + request: UpdateConnectionProfileRequest; + }; + const existing = profiles.find((profile) => profile.id === request.id); + if (!existing) { + throw new Error("Profile not found"); + } + const updated: ConnectionProfile = { + ...existing, + ...request.profile, + updatedAt: "2026-07-18T02:10:00Z", + }; + profiles = [updated]; + return updated; + } + if (command === "delete_connection_profile") { + const { id } = args as { id: string }; + profiles = profiles.filter((profile) => profile.id !== id); + return undefined; + } + throw new Error(`Unexpected command: ${command}`); + }); + vi.spyOn(window, "confirm").mockReturnValue(true); + + render(); + expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument(); + + 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( + await screen.findByText("已创建 Profile:家庭运维"), + ).toBeInTheDocument(); + expect(screen.getByLabelText("编辑 家庭运维")).toBeEnabled(); + + fireEvent.click(screen.getByLabelText("编辑 家庭运维")); + fireEvent.change(screen.getByLabelText("显示名称"), { + target: { value: "家庭运维(主)" }, + }); + fireEvent.click(screen.getByRole("button", { name: "更新 Profile" })); + + expect( + await screen.findByText("已更新 Profile:家庭运维(主)"), + ).toBeInTheDocument(); + fireEvent.click(screen.getByLabelText("删除 家庭运维(主)")); + + await waitFor(() => { + expect( + screen.getByText("已删除 Profile:家庭运维(主)"), + ).toBeInTheDocument(); + }); + expect(screen.getByText("尚未保存 Profile。")).toBeInTheDocument(); + expect(invoke).toHaveBeenCalledWith( + "create_connection_profile", + expect.objectContaining({ + request: expect.not.objectContaining({ + token: expect.anything(), + password: expect.anything(), + apiKey: expect.anything(), + }), + }), + ); + }); }); diff --git a/src/App.tsx b/src/App.tsx index e967145..f5199ab 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,6 +1,7 @@ import { invoke } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState } from "react"; +import { ProfileManager } from "./features/profiles/ProfileManager"; import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap"; const initialStatus: BootstrapStatus = { @@ -8,7 +9,7 @@ const initialStatus: BootstrapStatus = { platform: "unknown", rustCore: "pending", protocolVersion: "desktop-v1alpha1", - databaseSchemaVersion: 1, + databaseSchemaVersion: 2, }; export function App() { @@ -32,7 +33,7 @@ export function App() { return (
-

P00 · bootstrap

+

P01 · foundation

AstrBot Desktop

双实例陪伴与本机助手的安全 Windows 客户端工程底座。 @@ -61,6 +62,7 @@ export function App() {

  • 文件事务默认保留源文件,且不会静默覆盖。
  • + + {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 ? "已登记" : "待登记"} +

    +
    + + +
    +
    + )) + )} +
    + + + {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, + allowInsecureHttp: form.allowInsecureHttp, + pinnedCertificateFingerprint: fingerprint || 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 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); +} diff --git a/src/styles.css b/src/styles.css index 0e302e7..0ddf472 100644 --- a/src/styles.css +++ b/src/styles.css @@ -43,8 +43,13 @@ button:hover { background: #204b88; } +button:disabled { + cursor: not-allowed; + opacity: 0.58; +} + .app-shell { - width: min(920px, calc(100% - 2rem)); + width: min(1120px, calc(100% - 2rem)); margin: 0 auto; padding: 4rem 0; } @@ -123,6 +128,158 @@ h1 { border-color: rgb(255 115 115 / 45%); } +.profile-manager { + margin: 2rem 0; + padding: 1.5rem; + border: 1px solid rgb(137 175 232 / 28%); + border-radius: 1rem; + background: rgb(13 29 52 / 78%); + box-shadow: 0 1rem 3rem rgb(0 0 0 / 18%); +} + +.section-heading { + display: grid; + grid-template-columns: minmax(0, 0.8fr) minmax(280px, 1.2fr); + gap: 2rem; + align-items: end; + margin-bottom: 1.25rem; +} + +.section-heading h2, +.profile-form h3, +.profile-list h3 { + margin: 0.3rem 0 0; +} + +.section-heading > p, +.form-note, +.empty-state, +.profile-card p { + color: #aebfda; +} + +.profile-layout { + display: grid; + grid-template-columns: minmax(300px, 0.95fr) minmax(320px, 1.05fr); + gap: 1rem; +} + +.profile-form, +.profile-list { + padding: 1.2rem; + border: 1px solid rgb(137 175 232 / 24%); + border-radius: 0.9rem; + background: rgb(7 18 34 / 52%); +} + +.profile-form { + display: grid; + gap: 1rem; +} + +.profile-form label:not(.checkbox-field) { + display: grid; + gap: 0.45rem; +} + +.profile-form label > span { + color: #c7d4e9; + font-size: 0.9rem; + font-weight: 650; +} + +input, +select { + width: 100%; + padding: 0.72rem 0.8rem; + border: 1px solid rgb(137 175 232 / 38%); + border-radius: 0.65rem; + color: inherit; + background: #0b1b31; + font: inherit; +} + +input:focus, +select:focus { + outline: 2px solid #6aa3ff; + outline-offset: 2px; +} + +.checkbox-field { + display: flex; + gap: 0.7rem; + align-items: flex-start; +} + +.checkbox-field input { + width: auto; + margin-top: 0.2rem; +} + +.form-note { + margin: 0; + font-size: 0.9rem; +} + +.button-row { + display: flex; + flex-wrap: wrap; + gap: 0.65rem; +} + +.button-secondary { + border-color: rgb(157 181 218 / 48%); + background: #20314b; +} + +.button-danger { + border-color: rgb(255 122 122 / 65%); + background: #5a2430; +} + +.profile-list { + display: grid; + align-content: start; + gap: 0.8rem; +} + +.profile-card { + display: grid; + gap: 0.7rem; + padding: 1rem; + border: 1px solid rgb(137 175 232 / 22%); + border-radius: 0.75rem; + background: rgb(20 42 72 / 72%); +} + +.profile-card > div:first-child { + display: flex; + justify-content: space-between; + gap: 1rem; +} + +.profile-card span { + color: #8db9ff; +} + +.profile-card code { + color: #dbe8ff; + overflow-wrap: anywhere; +} + +.profile-card p { + margin: 0; + font-size: 0.9rem; +} + +.notice-banner { + padding: 1rem; + border: 1px solid rgb(96 211 153 / 42%); + border-radius: 0.8rem; + color: #c8f7dc; + background: rgb(20 83 57 / 45%); +} + @media (prefers-color-scheme: light) { :root { color: #102039; @@ -141,10 +298,17 @@ h1 { .status-card, .boundaries, + .profile-manager, .error-banner { background: rgb(255 255 255 / 86%); } + .profile-form, + .profile-list, + .profile-card { + background: rgb(245 249 255 / 90%); + } + .status-card strong { color: #102039; } @@ -153,4 +317,28 @@ h1 { .subtitle { color: #405775; } + + input, + select { + color: #102039; + background: #ffffff; + } + + .section-heading > p, + .form-note, + .empty-state, + .profile-card p { + color: #405775; + } +} + +@media (max-width: 760px) { + .section-heading, + .profile-layout { + grid-template-columns: 1fr; + } + + .app-shell { + padding: 2rem 0; + } } diff --git a/src/test/setup.ts b/src/test/setup.ts index f149f27..004761e 100644 --- a/src/test/setup.ts +++ b/src/test/setup.ts @@ -1 +1,8 @@ import "@testing-library/jest-dom/vitest"; + +import { cleanup } from "@testing-library/react"; +import { afterEach } from "vitest"; + +afterEach(() => { + cleanup(); +}); diff --git a/src/types/profile.ts b/src/types/profile.ts new file mode 100644 index 0000000..6da7222 --- /dev/null +++ b/src/types/profile.ts @@ -0,0 +1,54 @@ +import { z } from "zod"; + +export const profileRoleSchema = z.enum(["companion", "operations", "general"]); + +export const authenticationTypeSchema = z.enum(["device-token", "api-key"]); + +const optionalIdentifier = z.string().min(1).optional(); + +export const connectionProfileSchema = z + .object({ + id: z.uuid(), + displayName: z.string().min(1).max(80), + role: profileRoleSchema, + baseUrl: z.url(), + eventStreamUrl: z.url().optional(), + authenticationType: authenticationTypeSchema, + credentialReference: optionalIdentifier, + allowInsecureHttp: z.boolean(), + pinnedCertificateFingerprint: z + .string() + .regex(/^[A-F0-9]{64}$/) + .optional(), + autoConnectSlot: z.enum(["companion", "operations"]).optional(), + autoConnect: z.boolean(), + serverInstanceId: optionalIdentifier, + serverVersion: optionalIdentifier, + protocolVersion: optionalIdentifier, + localToolPolicyId: optionalIdentifier, + lastConnectedAt: optionalIdentifier, + createdAt: z.string().min(1), + updatedAt: z.string().min(1), + }) + .strict(); + +export const connectionProfileListSchema = z.array(connectionProfileSchema); + +export type ProfileRole = z.infer; +export type AuthenticationType = z.infer; +export type ConnectionProfile = z.infer; + +export interface ConnectionProfileInput { + displayName: string; + role: ProfileRole; + baseUrl: string; + eventStreamUrl?: string; + authenticationType: AuthenticationType; + allowInsecureHttp: boolean; + pinnedCertificateFingerprint?: string; +} + +export interface UpdateConnectionProfileRequest { + id: string; + profile: ConnectionProfileInput; +} diff --git a/tests/e2e/bootstrap.spec.ts b/tests/e2e/bootstrap.spec.ts index 9204191..856ebfa 100644 --- a/tests/e2e/bootstrap.spec.ts +++ b/tests/e2e/bootstrap.spec.ts @@ -12,5 +12,13 @@ test("renders the bootstrap shell and safe browser fallback", async ({ await expect( page.getByText("IPC unavailable:", { exact: false }), ).toBeVisible(); - await expect(page.getByRole("button")).toBeEnabled(); + await expect( + page.getByRole("heading", { name: "连接 Profile" }), + ).toBeVisible(); + await expect( + page.getByText("Profile storage unavailable:", { exact: false }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "重新检查 IPC" }), + ).toBeEnabled(); });