fix: close browser session lifecycle gaps

This commit is contained in:
Wenxin Duan
2026-09-08 11:12:12 +08:00
parent 8fa006344d
commit ba45382747
12 changed files with 149 additions and 11 deletions
+3 -3
View File
@@ -94,7 +94,7 @@ Anthropic 使用 `AGENT_PROVIDER=anthropic`、`LLM_API=anthropic-messages` 和 `
也可以在页面右上角打开 Settings,填写 Provider、API 类型、Base URL、API Key、Model 和图片能力。保存后配置只属于当前 Session。连接测试在当前实现中安全地返回“首次运行验证”,不会编造一次真实调用成功。 也可以在页面右上角打开 Settings,填写 Provider、API 类型、Base URL、API Key、Model 和图片能力。保存后配置只属于当前 Session。连接测试在当前实现中安全地返回“首次运行验证”,不会编造一次真实调用成功。
API Key 从同源请求提交后只驻留服务器进程内存,并在 Pi `InMemoryCredentialStore` 中注入;不会写入 localStorage、sessionStorage、IndexedDB、SSE、事件、响应或用户目录。GET 只返回脱敏的 `keyHint`。刷新页面会新建 Session;删除 Session、清除凭证或重启进程都会丢失该内存配置。 API Key 从同源请求提交后只驻留服务器进程内存,并在 Pi `InMemoryCredentialStore` 中注入;不会写入 localStorage、sessionStorage、IndexedDB、SSE、事件、响应或用户目录。GET 只返回脱敏的 `keyHint`。使用页面“重置训练会话”、清除凭证或重启进程会清除对应内存配置。
## 图片链路 ## 图片链路
@@ -139,7 +139,7 @@ pnpm test
pnpm build pnpm build
``` ```
最近一次完整测试包含 117 条测试:shared 13、harness 68、server 16、web 20。默认测试使用可编程 Fake AgentSession,不需要真实 API Key、真实模型或外网。最终交付前还会重新运行以上四个命令并以实际结果为准。 最近一次完整测试包含 123 条测试:shared 13、harness 68、server 17、web 25。默认测试使用可编程 Fake AgentSession,不需要真实 API Key、真实模型或外网。最终交付前还会重新运行以上四个命令并以实际结果为准。
## 当前依赖与 API 核对 ## 当前依赖与 API 核对
@@ -153,6 +153,6 @@ pnpm build
## 已知限制与生产化 ## 已知限制与生产化
课堂版是单进程、单实例、内存 EventStore / ApprovalBroker / ModelConnectionStore;刷新会创建新 Session,进程退出不会恢复运行,报告和附件只是本机临时文件。它没有用户身份、跨设备同步、分布式事件总线或操作系统级隔离。 课堂版是单进程、单实例、内存 EventStore / ApprovalBroker / ModelConnectionStore;进程退出不会恢复运行,报告和附件只是本机临时文件。浏览器直接刷新会丢失旧 Session 的 UI 引用,旧 Session 要到 Server 重启时统一清理,因此正常操作应使用页面“重置训练会话”。它没有用户身份、跨设备同步、分布式事件总线或操作系统级隔离。
生产化需要 Redis/Postgres 持久化、对象存储、KMS/Secret Manager、身份鉴权、授权与租户隔离、CSRF 和速率限制、容器或 microVM Sandbox、出站网络策略、不可篡改审计日志、分布式锁与可重放 SSE。路线见 [docs/production-roadmap.md](docs/production-roadmap.md)。 生产化需要 Redis/Postgres 持久化、对象存储、KMS/Secret Manager、身份鉴权、授权与租户隔离、CSRF 和速率限制、容器或 microVM Sandbox、出站网络策略、不可篡改审计日志、分布式锁与可重放 SSE。路线见 [docs/production-roadmap.md](docs/production-roadmap.md)。
+3
View File
@@ -40,6 +40,9 @@ function mapError(error: FastifyError | Error): {
if ("statusCode" in error && error.statusCode === 413) { if ("statusCode" in error && error.statusCode === 413) {
return { statusCode: 413, code: "PAYLOAD_TOO_LARGE", message: "Request payload is too large", details: {} }; return { statusCode: 413, code: "PAYLOAD_TOO_LARGE", message: "Request payload is too large", details: {} };
} }
if ("statusCode" in error && error.statusCode === 400) {
return { statusCode: 400, code: "INVALID_REQUEST_BODY", message: "Request body could not be processed", details: {} };
}
return { statusCode: 500, code: "INTERNAL_ERROR", message: "Internal server error", details: {} }; return { statusCode: 500, code: "INTERNAL_ERROR", message: "Internal server error", details: {} };
} }
+17
View File
@@ -53,4 +53,21 @@ describe("HTTP API", () => {
expect(busy.statusCode).toBe(409); expect(busy.statusCode).toBe(409);
expect(busy.body).not.toContain("stack"); expect(busy.body).not.toContain("stack");
}); });
it("keeps Fastify body parse errors as safe client errors", async () => {
const { app } = createTestApp();
apps.push(app);
const response = await app.inject({
method: "POST",
url: "/api/sessions",
headers: { "content-type": "application/json" },
payload: "",
});
expect(response.statusCode).toBe(400);
expect(response.json()).toMatchObject({
error: { code: "INVALID_REQUEST_BODY", message: "Request body could not be processed" },
});
expect(response.body).not.toContain("stack");
});
}); });
+12 -1
View File
@@ -14,6 +14,7 @@ import { HarnessClientStore } from "./store/harness-client-store.js";
type AppStore = HarnessRuntimeStore & { type AppStore = HarnessRuntimeStore & {
start(): Promise<void>; start(): Promise<void>;
dispose?: () => Promise<void>;
getModelConfig(): Promise<{ modelConfig: ModelView }>; getModelConfig(): Promise<{ modelConfig: ModelView }>;
putModelConfig?: (input: ModelConnectionInput) => Promise<{ modelConfig: ModelView }>; putModelConfig?: (input: ModelConnectionInput) => Promise<{ modelConfig: ModelView }>;
testModelConfig?: () => Promise<{ status: "ok" | "deferred"; message: string }>; testModelConfig?: () => Promise<{ status: "ok" | "deferred"; message: string }>;
@@ -87,7 +88,17 @@ export function App({ store: suppliedStore, autoStart = true, modelConfigured: s
modelLabel: model.modelId ?? "No model", modelLabel: model.modelId ?? "No model",
supportsImages: model.supportsImages ?? false, supportsImages: model.supportsImages ?? false,
onOpenSettings: () => setSettingsOpen(true), onOpenSettings: () => setSettingsOpen(true),
onReset: () => window.location.reload(), onReset: () => {
if (store.dispose === undefined) {
window.location.reload();
return;
}
void store.dispose()
.then(() => store.start())
.then(() => store.getModelConfig())
.then((response) => setModel(response.modelConfig))
.catch(() => undefined);
},
}} }}
skills={<SkillsPanel skills={snapshot.skills} />} skills={<SkillsPanel skills={snapshot.skills} />}
chat={<Thread chat={<Thread
+1 -1
View File
@@ -87,7 +87,7 @@ export class HarnessApi {
const { body, ...init } = options; const { body, ...init } = options;
const isForm = body instanceof FormData; const isForm = body instanceof FormData;
const headers = new Headers(init.headers); const headers = new Headers(init.headers);
if (!isForm) headers.set("Content-Type", "application/json"); if (body !== undefined && !isForm) headers.set("Content-Type", "application/json");
const response = await fetch(`${this.baseUrl}${path}`, { const response = await fetch(`${this.baseUrl}${path}`, {
...init, ...init,
headers, headers,
@@ -83,17 +83,17 @@ export function ModelSettings({ open, busy, current, onClose, onSave, onTest, on
<button className="icon-button" type="button" aria-label="关闭模型设置" onClick={onClose}><X size={19} /></button> <button className="icon-button" type="button" aria-label="关闭模型设置" onClick={onClose}><X size={19} /></button>
</div> </div>
<p className="settings-intro">密钥仅发送到本机服务并保存在当前会话内存中,不会写入浏览器存储。</p> <p className="settings-intro">密钥仅发送到本机服务并保存在当前会话内存中,不会写入浏览器存储。</p>
<form className="settings-form" onSubmit={(event) => void submit(event)}> <form className="settings-form" autoComplete="off" onSubmit={(event) => void submit(event)}>
<label>服务商<select ref={firstInput} value={providerId} onChange={(event) => { <label>服务商<select ref={firstInput} value={providerId} onChange={(event) => {
const value = event.target.value; const value = event.target.value;
setProviderId(value); setProviderId(value);
setApi(value === "anthropic" ? "anthropic-messages" : "openai-responses"); setApi(value === "anthropic" ? "anthropic-messages" : "openai-responses");
}}><option value="openai">OpenAI</option><option value="anthropic">Anthropic</option><option value="compatible">OpenAI Compatible</option></select></label> }}><option value="openai">OpenAI</option><option value="anthropic">Anthropic</option><option value="compatible">OpenAI Compatible</option></select></label>
<label>API 类型<select value={api} onChange={(event) => setApi(event.target.value as ModelApi)}><option value="openai-responses">OpenAI Responses</option><option value="openai-completions">OpenAI Completions</option><option value="anthropic-messages">Anthropic Messages</option></select></label> <label>API 类型<select value={api} onChange={(event) => setApi(event.target.value as ModelApi)}><option value="openai-responses">OpenAI Responses</option><option value="openai-completions">OpenAI Completions</option><option value="anthropic-messages">Anthropic Messages</option></select></label>
<label className="settings-form__wide">Base URL(可选)<input type="url" value={baseUrl} placeholder="https://api.example.com/v1" onChange={(event) => setBaseUrl(event.target.value)} /></label> <label className="settings-form__wide">Base URL(可选)<input name="agent-base-url" autoComplete="off" type="url" value={baseUrl} placeholder="https://api.example.com/v1" onChange={(event) => setBaseUrl(event.target.value)} /></label>
<label>模型 ID<input aria-label="模型 ID" required value={modelId} onChange={(event) => setModelId(event.target.value)} /></label> <label>模型 ID<input name="agent-model-id" autoComplete="off" aria-label="模型 ID" required value={modelId} onChange={(event) => setModelId(event.target.value)} /></label>
<label>图片能力<select value={supportsImages ? "yes" : "no"} onChange={(event) => setSupportsImages(event.target.value === "yes")}><option value="yes">支持图片</option><option value="no">仅文本</option></select></label> <label>图片能力<select value={supportsImages ? "yes" : "no"} onChange={(event) => setSupportsImages(event.target.value === "yes")}><option value="yes">支持图片</option><option value="no">仅文本</option></select></label>
<label className="settings-form__wide">API Key<div className="password-field"><KeyRound size={17} /><input aria-label="API Key" type={reveal ? "text" : "password"} value={apiKey} autoComplete="off" onChange={(event) => setApiKey(event.target.value)} /><button type="button" aria-label={reveal ? "隐藏 API Key" : "显示 API Key"} onClick={() => setReveal((value) => !value)}>{reveal ? <EyeOff size={17} /> : <Eye size={17} />}</button></div></label> <label className="settings-form__wide">API Key<div className="password-field"><KeyRound size={17} /><input name="agent-api-key" aria-label="API Key" type={reveal ? "text" : "password"} value={apiKey} autoComplete="new-password" onChange={(event) => setApiKey(event.target.value)} /><button type="button" aria-label={reveal ? "隐藏 API Key" : "显示 API Key"} onClick={() => setReveal((value) => !value)}>{reveal ? <EyeOff size={17} /> : <Eye size={17} />}</button></div></label>
{saved?.keyHint === undefined ? null : <p className="key-hint">服务器中的密钥:<strong>{saved.keyHint}</strong></p>} {saved?.keyHint === undefined ? null : <p className="key-hint">服务器中的密钥:<strong>{saved.keyHint}</strong></p>}
{message === "" ? null : <p className="settings-message" role="status">{message}</p>} {message === "" ? null : <p className="settings-message" role="status">{message}</p>}
{busy ? <p className="settings-message settings-message--warning">运行期间不能更改模型配置</p> : null} {busy ? <p className="settings-message settings-message--warning">运行期间不能更改模型配置</p> : null}
@@ -38,6 +38,7 @@ export class HarnessClientStore {
public async dispose(): Promise<void> { public async dispose(): Promise<void> {
this.#eventSource?.close(); this.#eventSource?.close();
this.#eventSource = undefined; this.#eventSource = undefined;
this.#starting = undefined;
const sessionId = this.#state.sessionId; const sessionId = this.#state.sessionId;
if (sessionId !== undefined) await this.api.deleteSession(sessionId); if (sessionId !== undefined) await this.api.deleteSession(sessionId);
this.#setState(createInitialHarnessState()); this.#setState(createInitialHarnessState());
+1 -1
View File
@@ -6,7 +6,7 @@
.side-panel { display: flex; flex-direction: column; overflow: hidden; background: var(--surface); } .side-panel { display: flex; flex-direction: column; overflow: hidden; background: var(--surface); }
.chat-panel { background: var(--bg); } .chat-panel { background: var(--bg); }
.mobile-tabs { display: none; } .mobile-tabs { display: none; }
@media (max-width: 1080px) { @media (min-width: 721px) and (max-width: 1080px) {
.workspace-grid { grid-template-columns: minmax(210px, 240px) minmax(400px, 1fr); } .workspace-grid { grid-template-columns: minmax(210px, 240px) minmax(400px, 1fr); }
.workspace-grid > div:last-child { display: none; } .workspace-grid > div:last-child { display: none; }
} }
+34
View File
@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { HarnessApi } from "../src/api/harness-api.js";
afterEach(() => vi.unstubAllGlobals());
describe("HarnessApi request headers", () => {
it("does not claim an empty POST contains JSON", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
sessionId: "ses_1",
requestId: "req_1",
}), { status: 201, headers: { "Content-Type": "application/json" } }));
vi.stubGlobal("fetch", fetchMock);
await new HarnessApi().createSession();
const request = fetchMock.mock.calls[0]?.[1] as RequestInit;
expect(new Headers(request.headers).has("Content-Type")).toBe(false);
expect(request.body).toBeUndefined();
});
it("sets JSON content type when a structured body is present", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
runId: "run_1",
requestId: "req_1",
}), { status: 202, headers: { "Content-Type": "application/json" } }));
vi.stubGlobal("fetch", fetchMock);
await new HarnessApi().sendMessage("ses_1", { text: "hello", attachmentIds: [] });
const request = fetchMock.mock.calls[0]?.[1] as RequestInit;
expect(new Headers(request.headers).get("Content-Type")).toBe("application/json");
expect(request.body).toBe(JSON.stringify({ text: "hello", attachmentIds: [] }));
});
});
+37 -1
View File
@@ -1,7 +1,7 @@
import { render, screen } from "@testing-library/react"; import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest"; import { afterEach, describe, expect, it, vi } from "vitest";
import { App } from "../src/App.js"; import { App } from "../src/App.js";
import { createInitialHarnessState, type HarnessClientState } from "../src/store/reducer.js"; import { createInitialHarnessState, type HarnessClientState } from "../src/store/reducer.js";
@@ -24,6 +24,7 @@ function makeStore() {
subscribe: () => () => undefined, subscribe: () => () => undefined,
sendMessage, sendMessage,
cancel: vi.fn().mockResolvedValue({ cancelled: false }), cancel: vi.fn().mockResolvedValue({ cancelled: false }),
dispose: vi.fn().mockResolvedValue(undefined),
start: vi.fn().mockResolvedValue(undefined), start: vi.fn().mockResolvedValue(undefined),
getModelConfig: vi.fn().mockResolvedValue({ getModelConfig: vi.fn().mockResolvedValue({
modelConfig: { configured: true, source: "environment", providerId: "openai", api: "openai-responses", modelId: "gpt-test", supportsImages: true }, modelConfig: { configured: true, source: "environment", providerId: "openai", api: "openai-responses", modelId: "gpt-test", supportsImages: true },
@@ -31,6 +32,8 @@ function makeStore() {
}; };
} }
afterEach(() => vi.unstubAllGlobals());
describe("App", () => { describe("App", () => {
it("renders the three primary work areas", () => { it("renders the three primary work areas", () => {
render(<App store={makeStore()} autoStart={false} modelConfigured />); render(<App store={makeStore()} autoStart={false} modelConfigured />);
@@ -55,4 +58,37 @@ describe("App", () => {
expect(screen.getByRole("button", { name: "发送消息" })).toBeDisabled(); expect(screen.getByRole("button", { name: "发送消息" })).toBeDisabled();
expect(screen.getByText("请先配置模型连接")).toBeVisible(); expect(screen.getByText("请先配置模型连接")).toBeVisible();
}); });
it("switches to the event timeline in the mobile tab layout", async () => {
vi.stubGlobal("matchMedia", vi.fn(() => ({
matches: true,
media: "(max-width: 720px)",
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})));
const user = userEvent.setup();
render(<App store={makeStore()} autoStart={false} modelConfigured />);
await user.click(screen.getByRole("tab", { name: "Events" }));
expect(screen.getByRole("tab", { name: "Events" })).toHaveAttribute("aria-selected", "true");
expect(screen.getByRole("region", { name: "Event Timeline" })).toBeVisible();
expect(screen.queryByRole("main", { name: "Streaming Chat" })).not.toBeInTheDocument();
});
it("deletes the old session before starting a reset session", async () => {
const user = userEvent.setup();
const store = makeStore();
render(<App store={store} autoStart={false} modelConfigured />);
await user.click(screen.getByRole("button", { name: "重置训练会话" }));
expect(store.dispose).toHaveBeenCalledTimes(1);
expect(store.start).toHaveBeenCalledTimes(1);
expect(store.dispose.mock.invocationCallOrder[0]).toBeLessThan(store.start.mock.invocationCallOrder[0] ?? 0);
});
}); });
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it, vi } from "vitest";
import type { HarnessApi } from "../src/api/harness-api.js";
import { HarnessClientStore } from "../src/store/harness-client-store.js";
describe("HarnessClientStore lifecycle", () => {
it("deletes the current session and can start a fresh session after dispose", async () => {
const createSession = vi.fn()
.mockResolvedValueOnce({ sessionId: "ses_1", requestId: "req_1" })
.mockResolvedValueOnce({ sessionId: "ses_2", requestId: "req_2" });
const deleteSession = vi.fn().mockResolvedValue({ deleted: true, requestId: "req_delete" });
const api = {
createSession,
deleteSession,
getSkills: vi.fn().mockResolvedValue({ skills: [], requestId: "req_skills" }),
eventsUrl: (sessionId: string) => `/api/sessions/${sessionId}/events`,
} as unknown as HarnessApi;
const eventSources: Array<{ close: ReturnType<typeof vi.fn> }> = [];
const store = new HarnessClientStore(api, () => {
const source = { addEventListener: vi.fn(), close: vi.fn() };
eventSources.push(source);
return source;
});
await store.start();
expect(store.getSnapshot().sessionId).toBe("ses_1");
await store.dispose();
await store.start();
expect(deleteSession).toHaveBeenCalledWith("ses_1");
expect(createSession).toHaveBeenCalledTimes(2);
expect(eventSources[0]?.close).toHaveBeenCalledTimes(1);
expect(store.getSnapshot().sessionId).toBe("ses_2");
});
});
+2
View File
@@ -10,6 +10,8 @@ describe("ModelSettings", () => {
const save = vi.fn().mockResolvedValue({ configured: true, source: "session", keyHint: "••••cret" }); const save = vi.fn().mockResolvedValue({ configured: true, source: "session", keyHint: "••••cret" });
render(<ModelSettings open onClose={vi.fn()} busy={false} onSave={save} onTest={vi.fn()} onClear={vi.fn()} />); render(<ModelSettings open onClose={vi.fn()} busy={false} onSave={save} onTest={vi.fn()} onClear={vi.fn()} />);
expect(screen.getByLabelText("模型 ID")).toHaveAttribute("autocomplete", "off");
expect(screen.getByLabelText("API Key")).toHaveAttribute("autocomplete", "new-password");
await user.type(screen.getByLabelText("API Key"), "sk-browser-secret"); await user.type(screen.getByLabelText("API Key"), "sk-browser-secret");
await user.type(screen.getByLabelText("模型 ID"), "gpt-test"); await user.type(screen.getByLabelText("模型 ID"), "gpt-test");
await user.click(screen.getByRole("button", { name: "保存配置" })); await user.click(screen.getByRole("button", { name: "保存配置" }));