feat(profile-ui): add basic profile management

这个提交存在于:
YokiiroBW 2026-07-18 23:36:59 +08:00
父节点 02fd25afaf
当前提交 907a8a38da
共有 7 个文件被更改,包括 787 次插入 和 17 次删除

查看文件

@ -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(<App />);
@ -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(<App />);
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(),
}),
}),
);
});
});

查看文件

@ -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 (
<main className="app-shell">
<header className="hero">
<p className="eyebrow">P00 · bootstrap</p>
<p className="eyebrow">P01 · foundation</p>
<h1>AstrBot Desktop</h1>
<p className="subtitle">
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
@ -61,6 +62,7 @@ export function App() {
<li>文件事务默认保留源文件,且不会静默覆盖。</li>
</ul>
</section>
<ProfileManager />
<button type="button" onClick={() => void refreshStatus()}>
重新检查 IPC

查看文件

@ -0,0 +1,396 @@
import { invoke } from "@tauri-apps/api/core";
import { useCallback, useEffect, useState, type FormEvent } from "react";
import {
connectionProfileListSchema,
connectionProfileSchema,
type AuthenticationType,
type ConnectionProfile,
type ConnectionProfileInput,
type ProfileRole,
type UpdateConnectionProfileRequest,
} from "../../types/profile";
interface ProfileFormState {
displayName: string;
role: ProfileRole;
baseUrl: string;
eventStreamUrl: string;
authenticationType: AuthenticationType;
allowInsecureHttp: boolean;
pinnedCertificateFingerprint: string;
}
const emptyForm: ProfileFormState = {
displayName: "",
role: "general",
baseUrl: "https://",
eventStreamUrl: "",
authenticationType: "device-token",
allowInsecureHttp: false,
pinnedCertificateFingerprint: "",
};
export function ProfileManager() {
const [profiles, setProfiles] = useState<ConnectionProfile[]>([]);
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 result = await invoke<unknown>("list_connection_profiles");
setProfiles(connectionProfileListSchema.parse(result));
setError(null);
} catch (reason) {
setError(`Profile storage unavailable: ${errorMessage(reason)}`);
}
}, []);
useEffect(() => {
void loadProfiles();
}, [loadProfiles]);
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,
]),
);
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,
allowInsecureHttp: profile.allowInsecureHttp,
pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "",
});
setError(null);
setNotice(null);
}
async function deleteProfile(profile: ConnectionProfile) {
if (
!window.confirm(
`删除 Profile“${profile.displayName}”?此操作不会删除凭据值,因为 P01 不接触凭据。`,
)
) {
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),
);
if (editingId === profile.id) {
resetForm();
}
setNotice(`已删除 Profile:${profile.displayName}`);
} catch (reason) {
setError(`Profile deletion failed: ${errorMessage(reason)}`);
} finally {
setBusy(false);
}
}
function resetForm() {
setEditingId(null);
setForm(emptyForm);
}
return (
<section className="profile-manager" aria-labelledby="profile-heading">
<div className="section-heading">
<div>
<p className="eyebrow">P01 · foundation</p>
<h2 id="profile-heading">连接 Profile</h2>
</div>
<p>
这里只管理非敏感连接元数据。Token、密码和 API Key 不会进入 React 或
SQLite 普通字段。
</p>
</div>
<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>
</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>
<p className="form-note">
槽位分配、自动连接和连接切换保护将在 P02 实现。
</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>
<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>
</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,
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);
}

查看文件

@ -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;
}
}

查看文件

@ -1 +1,8 @@
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(() => {
cleanup();
});

54
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<typeof profileRoleSchema>;
export type AuthenticationType = z.infer<typeof authenticationTypeSchema>;
export type ConnectionProfile = z.infer<typeof connectionProfileSchema>;
export interface ConnectionProfileInput {
displayName: string;
role: ProfileRole;
baseUrl: string;
eventStreamUrl?: string;
authenticationType: AuthenticationType;
allowInsecureHttp: boolean;
pinnedCertificateFingerprint?: string;
}
export interface UpdateConnectionProfileRequest {
id: string;
profile: ConnectionProfileInput;
}

查看文件

@ -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();
});