A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 导入 Trace 被拒时原因留在这一行下面,不再只活六秒
lmlihengeb3fad0188ec
diff --git a/changelog/unreleased/2026-11-01-trace-import-refusal.md b/changelog/unreleased/2026-11-01-trace-import-refusal.mdnew file mode 100644index 00000000..e312cf96--- /dev/null+++ b/changelog/unreleased/2026-11-01-trace-import-refusal.md@@ -0,0 +1,51 @@+# A refused Trace import says why in its own row, instead of in a toast that expires++- **Date:** 2026-11-01+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-01-trace-import-refusal.zh.md)++Settings → General → 「Import Trace」 is one row of three controls — the Project, the Agent and the+file pick — and every way that row can fail used to report itself in a toast that dismissed after six+seconds. A refused import writes nothing: the pickers stay exactly where they were, and picking a+file again is the retry. So the reason belonged to the row that had just done nothing, and the toast+left the reader looking at a row that seemed untouched — unable to tell a duplicate Session from a+malformed file, from a file that was simply too large.++The row now draws the sentence under its pickers, in the danger ink, as a `role="alert"` clamped to+two lines with the whole of it on hover, and the sentence stays until the next attempt starts. All+three failures land there: the server's refusal (a Session id this install already has, a file whose+first record is not `session_meta`), a file past the ceiling for its kind, and a file the browser+failed to read. No new copy was written — the server's answer goes through the shared+`refusalText()`, and the ceiling sentences already existed.++## Details++- `packages/web/src/features/settings/trace-import-row.tsx`: a `refusal` state, filled by all three+ failure paths instead of `toastError` and cleared when another file is picked (the sentence about+ the last attempt is stale from that moment on). The pickers and the sentence share one column, so+ the sentence is drawn under the pick it was about.+- `traceImportSizeRefusal(fileName, sizeBytes)` — which ceiling a picked file answers to (14MB for a+ `.jsonl` Trace file, the server's 48MB for a whole-Session `.json` bundle) — is now a function of+ its own, judged on the file's name and size rather than on its bytes, so a 40MB file is never read+ into memory to be told it is too large.++## Tests++- `packages/web/test/trace-import-row.test.ts` (new, four unit cases): a Trace file is let through up+ to its own ceiling and refused one byte past it; a bundle of 20MB is read, and one past 48MB is+ refused with the bundle's sentence; a 48MB+ Trace file still gets the Trace sentence rather than+ the bundle's; the extension decides case-insensitively, and a name the picker does not offer gets+ the smaller ceiling rather than a pass.+- `packages/web/e2e/trace-import-refusal.spec.mjs` (new, two browser cases against the real server):+ a Trace imported twice leaves the route's own 409 on the row — nothing in the notification area,+ still there seven seconds later, the destination pickers unmoved — and the next pick clears it and+ lands a second Session; a `.jsonl` one byte past 14MB is refused in place with no upload request+ sent at all, and a file that fits still lands afterwards.++## Compatibility++- No API or request change: the row sends the same `{dataBase64}` to the same route and reads the+ same answers. Only the failed paths stopped using a toast.diff --git a/changelog/unreleased/2026-11-01-trace-import-refusal.zh.md b/changelog/unreleased/2026-11-01-trace-import-refusal.zh.mdnew file mode 100644index 00000000..ff68e316--- /dev/null+++ b/changelog/unreleased/2026-11-01-trace-import-refusal.zh.md@@ -0,0 +1,41 @@+# 导入 Trace 被拒时,原因留在这一行下面,不再只活六秒++- **日期:** 2026-11-01+- **类型:** fix+- **范围:** `web`+- **破坏性:** 无++[English](2026-11-01-trace-import-refusal.md)++设置 → 通用 →「导入 Trace」是一行三个控件 —— 项目、Agent 与选文件 —— 而这一行此前每一条失败的路+都把原因交给六秒后自己消失的 toast。被拒的导入什么都没写进去:三个控件原样不动,再选一次文件就是+重试。所以那句话属于刚刚什么都没做的这一行;toast 留下的却是一行看起来没被碰过的控件,读者分不清+是重名的会话、还是文件本身坏了、还是文件只是太大。++现在这一行把句子画在自己的控件下面:danger 色、`role="alert"`、限两行、整句挂悬停,并且一直留到+下一次尝试开始。三条失败的路都落在这里:服务端的拒绝(本机已有同名 Session、首条记录不是+`session_meta`)、按文件种类超过上限、以及浏览器读不出来。没有新增文案 —— 服务端的答复走共享的+`refusalText()`,两条上限句子本来就有。++## 细节++- `packages/web/src/features/settings/trace-import-row.tsx`:多一个 `refusal` 状态,三条失败的路都填它+ (不再 `toastError`),再选一个文件时清空(从那一刻起,「上一次」的句子就是过期的)。三个控件与+ 这句话共用同一列,所以句子就画在它针对的那次选择下面。+- `traceImportSizeRefusal(fileName, sizeBytes)` —— 选中的文件按哪个上限算(`.jsonl` 轨迹文件 14MB、+ 整会话 `.json` 包走服务端的 48MB)—— 现在是独立的一个函数,只看文件名与大小、不看内容,40MB 的+ 文件不会被读进内存才被告知超限。++## 测试++- `packages/web/test/trace-import-row.test.ts`(新,4 条单测):轨迹文件到自己那个上限都放行,多一字节+ 即拒绝;20MB 的整会话包照读,过了 48MB 才用包那句话拒绝;48MB 以上的轨迹文件拿到的是轨迹那句、+ 不是包那句;扩展名不分大小写,而选择器不给的名字拿到的是小的那个上限而不是放行。+- `packages/web/e2e/trace-import-refusal.spec.mjs`(新,真服务端两条):同一份 Trace 导两次,路由自己的+ 409 留在这一行上 —— 通知区里什么都没有、七秒后仍在、目的地两个下拉没动 —— 再选一次即清掉并落进+ 第二个会话;`.jsonl` 多一字节即就地拒绝且一条上传请求都没发,随后换成放得下的文件照旧落地。++## 兼容++- 接口与请求都没变:这一行发的还是同一个 `{dataBase64}` 到同一个路由,读的也是同样的答复。只有失败+ 那条路不再用 toast。diff --git a/packages/web/e2e/trace-import-refusal.spec.mjs b/packages/web/e2e/trace-import-refusal.spec.mjsnew file mode 100644index 00000000..323d08ec--- /dev/null+++ b/packages/web/e2e/trace-import-refusal.spec.mjs@@ -0,0 +1,212 @@+/**+ * Regression: an import that was REFUSED says why in the row that asked (Settings → General →+ * 「导入 Trace」), under its three pickers, and the sentence outlives the six seconds a toast lives.+ *+ * The row keeps everything on a refusal: the import writes nothing, so both pickers and the file+ * pick stay exactly as they were, and picking a file again is the retry. The reason used to arrive+ * as a notification over them — so a reader who looked away was left with a row that looked+ * untouched and no way to tell a duplicate Session from a malformed file.+ *+ * Both cases run against the real server: a Trace is imported twice (the second one is the route's+ * own 409 `trace_session_exists`), and a file past the client's ceiling is refused before a byte of+ * it is read — the second test counts the import requests to prove nothing was uploaded. Session ids+ * carry a per-run suffix, so a run over a data root that already holds one still starts fresh.+ */+import { test, expect } from "@playwright/test";+import { ADMIN_ID, ADMIN_PASSWORD, login } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;++/** A Session id no earlier run of this spec has used (ids are unique across the whole install). */+function sessionId() {+ return `session-2026-07-06-09-00-00-${Math.random().toString(16).slice(2, 10)}`;+}++/** The lines the row draws: the shared lead-in plus the app's sentence for the code / the ceiling. */+const DUPLICATE_REFUSED = "操作被拒绝:该 Agent 已存在同名 Session,无法导入重复的 Trace。";+const TOO_LARGE_REFUSED = "操作被拒绝:文件超过 14MB 上限。";++/**+ * A Trace file the import route accepts: JSONL whose first record is `session_meta` (a shard with+ * no meta is refused — the import derives the Session's identity and date directory from it).+ */+function traceFile(sessionId, name) {+ const rec = (timestamp, type, payload) => JSON.stringify({ timestamp, type, payload });+ const lines = [+ rec("2026-07-06T02:00:00.000Z", "session_meta", {+ session_id: sessionId,+ model_id: "m",+ provider: "custom",+ model_context_window: 1000,+ system_prompt: "",+ agent_state: "/tmp/a",+ workspace: "/tmp/w",+ source: "user",+ }),+ rec("2026-07-06T02:00:01.000Z", "model_msg", {+ type: "text",+ role: "user",+ text: `imported ${sessionId}`,+ }),+ ];+ return { name, mimeType: "application/x-ndjson", buffer: Buffer.from(`${lines.join("\n")}\n`) };+}++/**+ * Sign in as the seeded administrator (the row is the Project owner's) and give the Project a+ * model — the onboarding overlay covers the page without one.+ */+async function ready(page) {+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]+ .projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();+ return projectId;+}++/** The Sessions the receiving Agent has, by id — the import's own record that something landed. */+async function importedIds(request, projectId) {+ const res = await request.get(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`);+ return (await res.json()).sessions.map((s) => s.sessionId);+}++/** The settings dialog, opened the way a person opens it: the user menu, then 通用. */+async function openGeneral(page) {+ // The user menu shares its name with the Project switcher, so take the last match (as chat.spec).+ await page.getByRole("button", { name: ADMIN_ID }).last().click();+ await page.getByRole("menuitem", { name: "设置", exact: true }).click();+ const settings = page.getByRole("dialog", { name: "设置" });+ await expect(settings).toBeVisible();+ await settings.getByRole("button", { name: "通用", exact: true }).click();+ return settings;+}++/**+ * The row's own column: the pickers and the refusal share one `data-slot="control"` box, which is+ * what makes "the sentence is in this row" checkable — the page has other rows, and none of them+ * may draw it.+ */+function controlOf(settings) {+ return settings.locator(+ 'div[data-slot="control"]:has(input[type="file"][accept=".jsonl,.json"])',+ );+}++/**+ * Wait until the row can work at all: its Agent list is fetched after the Project is known, and+ * while it is empty the row disables its own pick (a pick before then is a no-op for the reader).+ */+async function settled(row) {+ await expect(row.getByRole("button", { name: "导入到 Agent" })).toContainText("General Agent");+}++/** Pick a file in the row, and wait for the next pick to be possible again. */+async function pick(row, file) {+ await row.locator('input[type="file"]').setInputFiles(file);+ await expect(row.getByText("选择文件", { exact: true })).toBeVisible();+}++/** The upload the row sends for a file it reads. */+const isImport = (res) => res.request().method() === "POST" && res.url().includes("/traces/import");++test("a refused import keeps its reason under the pickers, past the toast it used to be", async ({+ page,+}) => {+ const projectId = await ready(page);+ const first = sessionId();+ const second = sessionId();+ await page.goto("/");+ const settings = await openGeneral(page);+ const row = controlOf(settings);+ await expect(row).toBeVisible();+ await settled(row);+ const notices = page.getByRole("region", { name: "通知" });++ // The first import lands, and the row has nothing to say about it.+ const landed = page.waitForResponse(isImport);+ await pick(row, traceFile(first, "session-a.jsonl"));+ expect((await landed).status(), "first import").toBe(200);+ await expect(row.getByRole("alert")).toHaveCount(0);+ expect(await importedIds(page.request, projectId)).toContain(first);++ // The same file again: the route refuses it (a Trace may only ever create a Session), and the+ // reason is drawn by the row itself — not by a notification.+ const refused = page.waitForResponse(isImport);+ await pick(row, traceFile(first, "session-a.jsonl"));+ expect((await refused).status(), "duplicate import").toBe(409);+ await expect(row.getByRole("alert")).toHaveText(DUPLICATE_REFUSED);+ await expect(notices.getByRole("button")).toHaveCount(0);+ // Nothing was written: both destination pickers are still there, still enabled, and the Agent+ // one still names the Agent it started on.+ await expect(row.getByRole("button", { name: "导入到项目" })).toBeEnabled();+ await expect(row.getByRole("button", { name: "导入到 Agent" })).toBeEnabled();++ // Six seconds is how long a toast lives; this sentence has to still be there after it.+ await page.waitForTimeout(7_000);+ await expect(row.getByRole("alert")).toHaveText(DUPLICATE_REFUSED);+ await expect(notices.getByRole("button")).toHaveCount(0);++ // The next pick is the retry: another Session's Trace lands, and the sentence goes with the+ // attempt it belonged to.+ const retried = page.waitForResponse(isImport);+ await pick(row, traceFile(second, "session-b.jsonl"));+ expect((await retried).status(), "retry").toBe(200);+ await expect(row.getByRole("alert")).toHaveCount(0);+ const ids = await importedIds(page.request, projectId);+ expect(ids).toContain(first);+ expect(ids).toContain(second);+});++test("a file past the 14MB ceiling is refused in place, without being uploaded", async ({+ page,+}) => {+ const projectId = await ready(page);+ const fresh = sessionId();+ /** Every upload the row attempted: a refused-before-reading file must not add one. */+ const uploads = [];+ page.on("request", (req) => {+ if (req.method() === "POST" && req.url().includes("/traces/import")) uploads.push(req.url());+ });++ await page.goto("/");+ const settings = await openGeneral(page);+ const row = controlOf(settings);+ await expect(row).toBeVisible();+ await settled(row);++ // One byte past the Trace file's ceiling — a file this large is never read into the browser.+ // (A whole-Session bundle answers to the server's larger 48MB ceiling instead; which of the two+ // applies to a name is a rule of the row's own, held by `test/trace-import-row.test.ts`.)+ const big = {+ name: "huge.jsonl",+ mimeType: "application/x-ndjson",+ buffer: Buffer.alloc(14 * 1024 * 1024 + 1, 0x20),+ };+ await pick(row, big);+ await expect(row.getByRole("alert")).toHaveText(TOO_LARGE_REFUSED);+ await expect(page.getByRole("region", { name: "通知" }).getByRole("button")).toHaveCount(0);+ expect(uploads).toHaveLength(0);++ // And a file that is small enough still lands, with the sentence of the last attempt gone.+ const landed = page.waitForResponse(isImport);+ await pick(row, traceFile(fresh, "session-b.jsonl"));+ expect((await landed).status(), "import after a refused file").toBe(200);+ await expect(row.getByRole("alert")).toHaveCount(0);+ expect(uploads).toHaveLength(1);+ expect(await importedIds(page.request, projectId)).toContain(fresh);+});diff --git a/packages/web/src/features/settings/trace-import-row.tsx b/packages/web/src/features/settings/trace-import-row.tsxindex 218a7179..68aad42e 100644--- a/packages/web/src/features/settings/trace-import-row.tsx+++ b/packages/web/src/features/settings/trace-import-row.tsx@@ -16,14 +16,20 @@* The row sits beside the CLI-sessions filter because both decide what the conversation* list holds. Export is deliberately not here: a Trace is downloaded from the conversation* it belongs to, in the chat's Trace panel.+ *+ * A refused import says why in this row rather than in a toast: the import writes nothing on+ * failure, so the three controls stay exactly as they were, and picking a file again is the+ * retry — the sentence belongs to the row that just did nothing, not to a notification that+ * dismisses itself over it (7.64, the same rule the write refusals follow).*/import { useEffect, useState } from "react";import type { ChangeEvent } from "react";import type { AgentSummary, ProjectSummary } from "@adelie/server/api";-import { HiddenFileInput, PrefRow, Select, UploadIcon, toastError, toastSuccess } from "@adelie/ui";+import { HiddenFileInput, PrefRow, Select, UploadIcon, toastSuccess } from "@adelie/ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";-import { apiErrorText } from "../../lib/api-error";+import { refusalText } from "../../lib/api-error";+import { toneInk } from "../../lib/tone";import { agentDisplayName, projectDisplayName, useProject } from "../../state/project";import { useSessions } from "../../state/sessions";@@ -32,6 +38,19 @@ const MAX_TRACE_BYTES = 14 * 1024 * 1024;/** A whole-Session bundle is several shards in one file, so it gets the server's larger ceiling. */const MAX_TRACE_BUNDLE_BYTES = 48 * 1024 * 1024;+/**+ * The sentence a picked file draws before any of it is read, or `null` when it may be read.+ *+ * Which ceiling applies is decided by the file, the same way the server decides it: a `.json`+ * bundle may be several shards' worth, a `.jsonl` Trace file is one shard. Judged on the file+ * itself — its size, never its bytes — so a 40MB file is not read into memory to be told so.+ */+export function traceImportSizeRefusal(fileName: string, sizeBytes: number): string | null {+ const bundle = fileName.toLowerCase().endsWith(".json");+ if (sizeBytes <= (bundle ? MAX_TRACE_BUNDLE_BYTES : MAX_TRACE_BYTES)) return null;+ return bundle ? S.settings.importTraceBundleTooLarge : S.settings.importTraceTooLarge;+}+/*** The Projects the row offers, and the one it is on. The import route answers anyone but the* Project's owner with 403, so a Project the viewer is only a member of is left out rather than@@ -63,6 +82,11 @@ export function TraceImportRow() {const [pickedAgent, setPickedAgent] = useState("");const [agents, setAgents] = useState<readonly AgentSummary[]>([]);const [importing, setImporting] = useState(false);+ /**+ * Why the last attempt was refused, drawn under the pickers until the next one starts. One+ * sentence at a time, like the import itself: the row has one pick and one destination.+ */+ const [refusal, setRefusal] = useState<string | null>(null);/** Destination Project, derived like the Agent below: only owned Projects are offered at all. */const { projects: ownedProjects, projectId } = traceImportTargets(@@ -113,8 +137,8 @@ export function TraceImportRow() {if (projectId === currentProject?.projectId) await reload();toastSuccess(S.settings.importTraceDone(target));} catch (e: unknown) {- // Transient action failure → toast (the app's one notification rule).- toastError(apiErrorText(e));+ // Kept on the row rather than toasted: nothing was written, and the pick below is the retry.+ setRefusal(refusalText(e));} finally {setImporting(false);}@@ -125,11 +149,13 @@ export function TraceImportRow() {// Reset before reading so re-picking the same file fires change again.e.target.value = "";if (!file || agentId === "") return;+ // Another attempt: the sentence about the last one is stale from this moment on.+ setRefusal(null);// Which ceiling applies is decided by the file, the same way the server decides it: a// `.json` bundle may be several shards' worth, a `.jsonl` Trace file is one shard.- const bundle = file.name.toLowerCase().endsWith(".json");- if (file.size > (bundle ? MAX_TRACE_BUNDLE_BYTES : MAX_TRACE_BYTES)) {- toastError(bundle ? S.settings.importTraceBundleTooLarge : S.settings.importTraceTooLarge);+ const tooLarge = traceImportSizeRefusal(file.name, file.size);+ if (tooLarge !== null) {+ setRefusal(tooLarge);return;}const reader = new FileReader();@@ -137,7 +163,7 @@ export function TraceImportRow() {const url = reader.result as string;void runImport(url.slice(url.indexOf(",") + 1)); // strip the data:...;base64, prefix};- reader.onerror = () => toastError(S.common.unknownError);+ reader.onerror = () => setRefusal(S.common.unknownError);reader.readAsDataURL(file);};@@ -149,7 +175,10 @@ export function TraceImportRow() {<PrefRow label={S.settings.importTrace} info={S.settings.importTraceInfo}>{/* Each picker is boxed to a fixed width — a Select fills its container, and threefull-width controls would stack one per line. Long names truncate in the trigger.- The row still wraps at phone width, where three controls do not fit side by side. */}+ The row still wraps at phone width, where three controls do not fit side by side.+ The refusal takes a line of its own below them (`w-full` in the wrapping row): it is+ clamped to two lines with the whole of it on hover, because a server's reason (a+ Session id that is already here, a bundle that failed to parse) runs long. */}<div className="flex flex-wrap items-center justify-end gap-2"><div className="w-32"><Select@@ -199,6 +228,16 @@ export function TraceImportRow() {<UploadIcon size={14} />{importing ? S.settings.importTraceRunning : S.settings.importTracePick}</label>+ {refusal !== null && (+ <p+ role="alert"+ data-tooltip={S.common.refused(refusal)}+ data-tooltip-content="text"+ className={`line-clamp-2 w-full max-w-96 break-words text-right text-xs ${toneInk.danger}`}+ >+ {S.common.refused(refusal)}+ </p>+ )}</div></PrefRow>);diff --git a/packages/web/test/trace-import-row.test.ts b/packages/web/test/trace-import-row.test.tsnew file mode 100644index 00000000..7b9c2cb9--- /dev/null+++ b/packages/web/test/trace-import-row.test.ts@@ -0,0 +1,51 @@+/**+ * The Trace import row decides, from the picked file alone and before reading a byte of it, whether+ * it may be read: a `.jsonl` Trace file is one shard and answers to the 14MB ceiling, a whole-Session+ * `.json` bundle is several shards' worth and answers to the server's 48MB one. The two ceilings are+ * the route's (`MAX_TRACE_BYTES` / `MAX_TRACE_BUNDLE_BYTES` in `agent-traces.ts`), and getting them+ * the wrong way round would either refuse a bundle the server accepts or read 40MB into a request+ * body that is then answered with 400.+ *+ * vitest runs node-only here, so the rule is checked through the function the row's file pick calls+ * — the row itself needs a browser (a real `<input type="file">` and a FileReader).+ */+import { describe, expect, it } from "vitest";+import { traceImportSizeRefusal } from "../src/features/settings/trace-import-row";+import { S } from "../src/lib/strings";++const MB = 1024 * 1024;+const TRACE_CAP = 14 * MB;+const BUNDLE_CAP = 48 * MB;++describe("traceImportSizeRefusal (what the Trace import row reads)", () => {+ it("lets a Trace file through up to its own ceiling, and refuses one byte past it", () => {+ expect(traceImportSizeRefusal("session-a.jsonl", TRACE_CAP)).toBeNull();+ expect(traceImportSizeRefusal("session-a.jsonl", TRACE_CAP + 1)).toBe(+ S.settings.importTraceTooLarge,+ );+ });++ it("judges a whole-Session bundle by the larger ceiling, so 20MB of bundle is read", () => {+ expect(traceImportSizeRefusal("bundle.json", TRACE_CAP + 1)).toBeNull();+ expect(traceImportSizeRefusal("bundle.json", BUNDLE_CAP)).toBeNull();+ expect(traceImportSizeRefusal("bundle.json", BUNDLE_CAP + 1)).toBe(+ S.settings.importTraceBundleTooLarge,+ );+ });++ it("never gives a bundle's sentence to a Trace file: past both ceilings each says its own", () => {+ expect(traceImportSizeRefusal("session-a.jsonl", BUNDLE_CAP + 1)).toBe(+ S.settings.importTraceTooLarge,+ );+ expect(S.settings.importTraceTooLarge).not.toBe(S.settings.importTraceBundleTooLarge);+ });++ it("reads the extension the way the server does: case does not matter, and only .json is a bundle", () => {+ expect(traceImportSizeRefusal("Bundle.JSON", TRACE_CAP + 1)).toBeNull();+ expect(traceImportSizeRefusal("Trace.JSONL", TRACE_CAP + 1)).toBe(+ S.settings.importTraceTooLarge,+ );+ // A file the picker's accept list does not offer still gets a ceiling rather than a pass.+ expect(traceImportSizeRefusal("trace.txt", TRACE_CAP + 1)).toBe(S.settings.importTraceTooLarge);+ });+});