A local-first multi-agent app development platform, built on PenguinHarness
Remove the standalone Trace page; Trace import moves to System settings (#462)
Yaowei Zhengb90f5aa76534
diff --git a/changelog/unreleased/2026-08-25-remove-traces-page.md b/changelog/unreleased/2026-08-25-remove-traces-page.mdnew file mode 100644index 00000000..60d2734a--- /dev/null+++ b/changelog/unreleased/2026-08-25-remove-traces-page.md@@ -0,0 +1,63 @@+# The standalone Trace page is gone; a Trace is read where it was produced++- **Date:** 2026-08-25+- **Type:** change+- **Scope:** `web`, `docs`+- **PR:** [#462](https://github.com/Prism-Shadow/penguin-harness/pull/462)++[中文版](2026-08-25-remove-traces-page.zh.md)++[Keeping one entry point for reading a Trace](2026-08-23-trace-one-entry-point.md) removed the three+in-app links to `/traces` and left the page itself in place, reachable by URL. It is now removed+outright: reading a Trace happens in a conversation's Trace panel, which is the only way in.++## Details++- The `/traces` route and page are deleted, along with the Trace-file tree that only it rendered+ (its lazy per-Agent loading, its Workspace/Agent grouping toggle, and its own group paging).+ An existing `/traces?sessionId=…` link no longer resolves.+- **Importing a Trace moved to System settings → General**, below the CLI-sessions filter — the one+ capability that lived nowhere else. Choose the destination Project and Agent, then pick a `.jsonl`+ file; the pick is the confirmation, and the toast names where it landed.+- Both halves of the destination are picked, where the old dialog asked only for the Agent. The+ endpoint is per-Agent because a Trace file's own `session_meta` cannot name a local Agent — its+ `agent_state` path belongs to the machine that exported it. The Project is asked for because the+ settings dialog does not show which one is open, every other row in it belonging to the account or+ the server; inheriting it silently would land an import in whichever Project the sidebar happened+ to have selected. A Trace can therefore also be imported into a Project other than the open one —+ the conversation list refreshes only when the destination IS the open one, since that is the only+ list on screen.+- **An imported Trace now becomes a listed conversation.** The import registered the Trace file and+ nothing else, so the imported Session existed only on disk: the conversation list is served from+ the sessions table, and the row appeared only with "show CLI sessions" on — the filter for+ Sessions this server never created, which an explicitly imported file is not. The import now+ indexes the Session too (`client: web`), carrying the model reference, Workspace and title from+ the file's own `session_meta`, so it shows up in the sidebar as soon as the list refreshes.+- **A duplicate session id is rejected across the whole install**, not just the receiving Agent. A+ session id is the identity everywhere — the sessions table keys on it, the frontend dedupes rows+ by it, `/chat/:sessionId` routes by it — so importing the same Trace under a second Agent used to+ "succeed" into a Session nothing could own: no row could sit beside the existing one, and the list+ folded the two into one conversation, leaving that group's count one above the rows it could ever+ show. It is now a 409 `trace_session_exists`, as it always was within one Agent.+- Exporting is unchanged and stays with the file it downloads: the Trace panel's export link on the+ selected file.+- The panel itself is untouched — same file view, performance timeline and event list, scoped to the+ open conversation.+- The server's Trace APIs are unchanged, the per-Agent listing endpoint included: it is documented+ surface, and only the Web App's use of it went away.+- `Select` now forwards `aria-label` to its trigger, the way a native select honours one — the+ settings row's Agent picker carries its name there, since the row's own label names the action+ rather than the control.++## Existing data++Traces imported **before** this change carry no Session row, so they stay as they were: visible only+with "show CLI sessions" on. No migration is offered because none is possible — a Trace with no+Session row is indistinguishable from a CLI-created one, and adopting every such Session would+promote genuine CLI Sessions along with them. To pull an old import into the list, delete its Trace+file and import it again.++## Known gap++The landing page's feature grid still shows a capture of the removed page. The copy describes the+capability, which the Trace panel still provides; the screenshot is re-captured at release time.diff --git a/changelog/unreleased/2026-08-25-remove-traces-page.zh.md b/changelog/unreleased/2026-08-25-remove-traces-page.zh.mdnew file mode 100644index 00000000..b1f5baa4--- /dev/null+++ b/changelog/unreleased/2026-08-25-remove-traces-page.zh.md@@ -0,0 +1,30 @@+# 独立的 Trace 页已移除,轨迹在产生它的对话里阅读++- **Date:** 2026-08-25+- **Type:** change+- **Scope:** `web`, `docs`+- **PR:** [#462](https://github.com/Prism-Shadow/penguin-harness/pull/462)++[English](2026-08-25-remove-traces-page.md)++[会话轨迹只保留一个入口](2026-08-23-trace-one-entry-point.zh.md) 移除了应用内指向 `/traces` 的三处链接,但保留了页面本身,仍可通过 URL 进入。本次将其彻底移除:阅读轨迹只发生在对话的 Trace 面板中,这也是唯一的入口。++## 细节++- 删除 `/traces` 路由与页面,以及只有它渲染的 Trace 文件目录树(按 Agent 的惰性加载、工作区/Agent 分组开关,及其自有的分组翻页)。既有的 `/traces?sessionId=…` 链接不再可解析。+- **导入 Trace 移至「系统设置 → 通用」**,位于「显示 CLI 会话」下方——这是唯一别处没有的能力。选择目的地的 Project 与 Agent,再挑选 `.jsonl` 文件,挑选即确认;提示信息会点名它落到了哪里。+- 目的地的两个部分都需选择,而旧对话框只问 Agent。接口按 Agent 划分,因为轨迹文件自带的 `session_meta` 无法指认本机的 Agent,其中的 `agent_state` 路径属于导出它的那台机器;而 Project 之所以要问,是因为设置对话框并不显示当前打开的是哪一个——它的其余每一行都属于账号或服务器——若默默沿用,导入就会落到侧边栏碰巧选中的那个 Project 里。因此也可以导入到当前打开之外的 Project;只有目的地正是当前 Project 时才刷新会话列表,因为那是屏幕上唯一的那份列表。+- **导入的 Trace 现在会成为列表中的一个对话。**此前导入只登记轨迹文件、别无其他,导入的 Session 仅存在于磁盘上:会话列表由 sessions 表提供,因此该行只有在开启「显示 CLI 会话」后才出现——而那个开关是为本服务器从未创建过的 Session 准备的,用户显式导入的文件并不属于此列。现在导入会同时把 Session 写入索引(`client: web`),并从文件自带的 `session_meta` 中带出模型引用、工作区与标题,列表刷新后即出现在侧边栏中。+- **重复的 session id 在整个部署范围内被拒绝**,而不只是接收它的那个 Agent。session id 在各处都是身份标识——sessions 表以它为主键、前端按它去重、`/chat/:sessionId` 按它路由——因此把同一个 Trace 导入到第二个 Agent 此前会「成功」为一个无人能拥有的 Session:既无法在既有行旁再插入一行,列表又会把两者折叠成一个对话,于是该分组的计数比它所能显示的行数多出一个。现在返回 409 `trace_session_exists`,与单个 Agent 内一直以来的行为一致。+- 导出保持不变,并继续与它下载的文件待在一起:Trace 面板中针对所选文件的导出链接。+- 面板本身未作改动——同样的文件视图、性能时间线与事件列表,作用域为当前打开的对话。+- 服务端的 Trace 接口全部保持不变,按 Agent 的列表接口也在内:它是有文档的对外面,消失的只是 Web App 对它的使用。+- `Select` 现在会把 `aria-label` 透传到触发按钮,与原生 select 的行为一致——设置行中的 Agent 拾取器由此获得自己的名称,因为该行的标签命名的是动作而非控件。++## 存量数据++本次改动**之前**导入的 Trace 没有 Session 行,因此维持原状:仅在开启「显示 CLI 会话」时可见。不提供迁移,是因为迁移本身不可能——没有 Session 行的 Trace 与 CLI 创建的 Session 无法区分,若把所有这类 Session 一并收编,真正由 CLI 创建的会话也会被一起提升。若要把旧的导入拉回列表,删除其轨迹文件后重新导入即可。++## 已知欠缺++落地页的功能宫格仍展示着已移除页面的截图。文案描述的是能力,而这一能力仍由 Trace 面板提供;截图将在发布时重新采集。diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.mdindex aa1ce788..9ae6e8f0 100644--- a/packages/docs/content/sessions-and-traces.en.md+++ b/packages/docs/content/sessions-and-traces.en.md@@ -100,4 +100,4 @@ Each content message's opaque provider `fidelity` payload (thinking signatures,## Observability-Every approval decision (`approval_decision`), abort (`abort`), compaction (`compaction_begin` / `compaction_end`), and `token_usage` lands in the Trace as an event. The Web Trace view and the usage/cost statistics are both derived from this same data — there is no second source of truth; see the [Web App Guide](/web-app). The approval mechanism itself is covered in [Tools & Approval](/tools). Trace files can also be moved across deployments from the Web Traces page: any file can be exported (downloaded verbatim as JSONL) and imported back under an Agent — an import whose session id already exists under that Agent is rejected, so an imported file always becomes index 001 of a new Session.+Every approval decision (`approval_decision`), abort (`abort`), compaction (`compaction_begin` / `compaction_end`), and `token_usage` lands in the Trace as an event. The Web Trace view and the usage/cost statistics are both derived from this same data — there is no second source of truth; see the [Web App Guide](/web-app). The approval mechanism itself is covered in [Tools & Approval](/tools). Trace files can also be moved across deployments: a conversation's Trace panel exports the selected file (downloaded verbatim as JSONL), and System settings → General imports one back under an Agent — an import whose session id already exists under that Agent is rejected, so an imported file always becomes index 001 of a new Session.diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.mdindex 9ab8d85d..5364c117 100644--- a/packages/docs/content/sessions-and-traces.zh.md+++ b/packages/docs/content/sessions-and-traces.zh.md@@ -98,4 +98,4 @@ Web 的 `/model` 命令按 `/agent` 交接的方式换模型:选中模型只## 可观测性-每一次审批决策(`approval_decision`)、中断(`abort`)、压缩(`compaction_begin` / `compaction_end`)与 `token_usage` 都作为事件落入 Trace。Web 的 Trace 视图与用量、成本统计均由这同一份数据派生,不存在第二事实来源;见 [Web App 指南](/web-app)。审批机制本身见[工具与审批](/tools)。Trace 文件还可以在部署之间迁移:在 Web 轨迹观测页可将任意文件导出(按原样下载为 JSONL),也可导入到某个 Agent 下——若该 Agent 已存在同名 Session 则导入被拒绝,因此导入文件总是成为一个新 Session 的 001 号文件。+每一次审批决策(`approval_decision`)、中断(`abort`)、压缩(`compaction_begin` / `compaction_end`)与 `token_usage` 都作为事件落入 Trace。Web 的 Trace 视图与用量、成本统计均由这同一份数据派生,不存在第二事实来源;见 [Web App 指南](/web-app)。审批机制本身见[工具与审批](/tools)。Trace 文件还可以在部署之间迁移:在对话的 Trace 面板中可将选中的文件导出(按原样下载为 JSONL),在系统设置的「常规」页可导入到某个 Agent 下——若该 Agent 已存在同名 Session 则导入被拒绝,因此导入文件总是成为一个新 Session 的 001 号文件。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 11ee8c6c..d64bf77e 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -116,10 +116,6 @@ A per-Project model table grouped by provider. Models can be added and edited: i- Two things a chart cannot draw. A bucket with **no rate** — an entity that made no request in it, or a bucket with no cache traffic — has its line carried across at the top of the axis so the stroke stays continuous; the hover table prints a dash there, never a percentage, and a real 0% (requests were made and all of them failed) still prints 0%. A bucket that recorded **nothing at all** is not plotted: every chart drops it and packs the rest left to right, so all four share one x axis that skips the quiet intervals and carries a break mark at each skip. Emptiness is judged per bucket, never per entity — an interval anything ran in stays, with the entities that were idle in it showing their zeros and dashes;- A server error panel: summary stats plus an errors table paged at a fixed page size (no scrolling).-## Trace Browser (/traces)--Drill down Agent → date → Session → Trace file. Per-turn cards show a context-occupancy donut and a cache breakdown, alongside a lane-based execution timeline and the full event list. For the storage model, see [Sessions and Traces](/sessions-and-traces).-## Benchmark (/benchmark)Read-only scoreboards per Benchmark: switch the metric (score / cost / duration), drill into each Case's runs, and jump to the linked Session and Trace. Works together with the [Self-Improvement](/self-improvement) workflow.@@ -132,7 +128,7 @@ The rail is grouped. **Personal** holds preferences that belong to the signed-in### General-Personal. **Language** (Chinese / English / follow the browser) and the **display currency** for prices (USD / CNY; storage is always USD — conversion happens only at the edge of the screen). **Show CLI sessions** (default off): off, the conversation list holds only Sessions created in the Web App and is served straight from the database; on, the Trace directories are scanned too and CLI-created Sessions are listed alongside them. Stored per user, and the Trace browser follows the same preference.+Personal. **Language** (Chinese / English / follow the browser) and the **display currency** for prices (USD / CNY; storage is always USD — conversion happens only at the edge of the screen). **Show CLI sessions** (default off): off, the conversation list holds only Sessions created in the Web App and is served straight from the database; on, the Trace directories are scanned too and CLI-created Sessions are listed alongside them. Stored per user. **Import Trace**: choose the destination Project and Agent, upload a `.jsonl` Trace exported from another install, and it becomes a conversation of that Agent. Both halves are asked for: the endpoint is per-Agent because a Trace file cannot name a local Agent of its own, and the Project because this dialog does not show which one is open — which also means a Trace can go to a Project other than the open one. Exporting is the other direction of the same road and lives with the file it downloads, in a conversation's Trace panel.### Appearancediff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex baca1d99..a360bc7e 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -115,10 +115,6 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,- 有两种情况图画不出来。**没有比率**的桶——该对象在这个桶里一次请求都没发,或该桶没有缓存流量——折线沿坐标轴顶部横穿过去,只为让线保持连续;悬停表格在该处显示「—」而非百分比,而真正的 0%(发了请求且全部失败)仍然显示 0%。**什么都没记录**的桶一律不画:四张图都丢弃它、把其余的从左往右依次排开,因此共用同一条会跳过空闲区间的横轴,跳过处画有断轴标记。空与不空按桶判断、绝不按单个对象判断——只要有任何对象在这个区间跑过,桶就保留,当时空闲的对象在该列显示 0 与「—」;- 服务端错误面板:汇总统计 + 异常明细表,按固定页大小分页(不滚动)。-## Trace 浏览(/traces)--按 Agent → 日期 → Session → Trace 文件逐级下钻。每回合卡片展示上下文占用环形图与缓存构成,并提供泳道式执行时间线与完整事件列表。Trace 的存储模型见 [Session 与 Trace](/sessions-and-traces)。-## Benchmark(/benchmark)只读展示各 Benchmark 的评分板,可切换指标(得分 / 费用 / 耗时),下钻查看每个 Case 的多次运行结果,并跳转到关联的 Session 与 Trace。配合[自我进化](/self-improvement)工作流使用。@@ -131,7 +127,7 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,### 通用-个人设置。**语言**(中文 / English / 跟随浏览器)与价格的**显示币种**(USD / CNY;存储始终为美元,换算只发生在显示层)。**显示 CLI 会话**(默认关):关闭时会话列表只列出在 Web 端创建的 Session,直接由数据库返回;开启后会额外扫描轨迹目录,把 CLI 创建的会话一并列出。按用户存储,轨迹观测页遵循同一偏好。+个人设置。**语言**(中文 / English / 跟随浏览器)与价格的**显示币种**(USD / CNY;存储始终为美元,换算只发生在显示层)。**显示 CLI 会话**(默认关):关闭时会话列表只列出在 Web 端创建的 Session,直接由数据库返回;开启后会额外扫描轨迹目录,把 CLI 创建的会话一并列出。按用户存储。**导入 Trace**:选择目的地的 Project 与 Agent,上传从其他部署导出的 `.jsonl` 轨迹文件,它会成为该 Agent 的一个会话。两者都需要选择:接口按 Agent 划分,因为轨迹文件自身无法指认本机的 Agent;Project 则是因为本对话框不显示当前打开的是哪一个——这也意味着可以导入到当前打开之外的 Project。导出是同一条路的反方向,与它下载的文件待在一起,位于对话的 Trace 面板中。### 外观diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex fec20dbb..9d1ecd79 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -71,6 +71,7 @@ import type {WindowPriorStats,} from "./message-window.js";import { buildContextBreakdown, emptyContextBreakdown } from "./context-breakdown.js";+import { sessionIdCreatedAt } from "./session-service.js";import { TraceIndexService, traceFilePath } from "./trace-index.js";const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;@@ -213,6 +214,10 @@ function subagentPointer(msg: OmniMessage): string | null {*/export interface TraceSessionIndex {listByAgent(projectId: string, agentId: string): SessionRow[];+ /** One row by id, from anywhere in the install — the import path's uniqueness check (see importTraceFile). Optional, like the index itself: narrow tests stub only what they read. */+ findById?(sessionId: string): SessionRow | null;+ /** Registers an imported Trace as a Session of the receiving Agent (see importTraceFile); optional for the same reason. */+ insertOrIgnore?(row: SessionRow): void;}/** TraceService wiring (the trace-file index is required: every listing/locating path serves from it — no directory walks). */@@ -1587,9 +1592,16 @@ export class TraceService {new HttpError(409,"trace_session_exists",- `This Agent already has a Session with id ${sessionId}; a duplicate Trace cannot be imported.`,+ `A Session with id ${sessionId} already exists here; a duplicate Trace cannot be imported.`,);+ // A Session id is the identity everywhere — the sessions table keys on it, the frontend+ // dedupes rows by it, and /chat/:sessionId routes by it — so the check spans the whole+ // install, not just the receiving Agent. Importing the same Trace under a second Agent+ // used to "succeed" into a Session nothing could own: no row could be inserted beside+ // the existing one, and the list folded the two into a single conversation, leaving a+ // group's count one above the rows it could ever show.if ((await this.locateAll(projectId, agentId, sessionId)).length > 0) throw duplicate();+ if (this.deps.sessions?.findById?.(sessionId)) throw duplicate();const ts = Date.parse(first.timestamp);const date = formatLocalDate(Number.isNaN(ts) ? new Date() : new Date(ts));const index = 1;@@ -1618,6 +1630,47 @@ export class TraceService {sizeBytes: Buffer.byteLength(body, "utf8"),records,});+ this.indexImportedSession(projectId, agentId, sessionId);return { sessionId, index, date };}++ /**+ * Registers an imported Trace as a **Session of the receiving Agent**, from the facts the+ * registration above just head-read (no second parse).+ *+ * Without this the import produced a Trace file and nothing else: the conversation list is+ * served straight from the sessions table, so an imported Trace stayed invisible unless+ * "show CLI sessions" was on — that filter adopts Sessions this server never created, and+ * a file the user deliberately imported is not one of those. Hence `client: "web"`: an+ * imported conversation is a conversation of this install.+ *+ * `approvalMode` is backfilled with the default (a Trace does not record it), and the+ * origin is recorded in the shared registry so the row lands in the right sidebar+ * category. Facts too old or too broken to name a model are skipped rather than inserted+ * half-formed — the Trace file itself is already written and readable either way.+ */+ private indexImportedSession(projectId: string, agentId: string, sessionId: string): void {+ const sessions = this.deps.sessions;+ if (!sessions) return;+ const facts = this.deps.index.repo.getSession(sessionId);+ if (!facts?.metaRead || facts.provider === null || facts.modelId === null) return;+ if (facts.source !== null) this.deps.sources?.set(sessionId, facts.source);+ const createdAt = sessionIdCreatedAt(sessionId) ?? facts.firstTs ?? new Date().toISOString();+ sessions.insertOrIgnore?.({+ sessionId,+ projectId,+ agentId,+ provider: facts.provider,+ modelId: facts.modelId,+ workspace: facts.workspace,+ approvalMode: "allow-all",+ title: facts.title,+ client: "web",+ hasTrace: true,+ createdAt,+ // Nothing has run here yet: the imported conversation reads as last-active when it+ // was created, until it is resumed on this install.+ lastActiveAt: createdAt,+ });+ }}diff --git a/packages/server/test/trace-import-export.test.ts b/packages/server/test/trace-import-export.test.tsindex 38d99fcc..23bda1ae 100644--- a/packages/server/test/trace-import-export.test.ts+++ b/packages/server/test/trace-import-export.test.ts@@ -2,15 +2,17 @@* Trace file export/import integration tests:* export serves the raw JSONL verbatim as an attachment (any member); import validates the* uploaded content (parseable JSONL, leading session_meta, filename-safe session_id) and- * always stores it as index 1 of a new Session — a session id the Agent already has is- * rejected with 409 trace_session_exists — and the file is then browsable through the- * existing tree/detail endpoints. Import is owner-only, mirroring the Agent snapshot import.+ * always stores it as index 1 of a new Session — a session id that exists ANYWHERE in the+ * install is rejected with 409 trace_session_exists — the imported file becomes a listed+ * Session of the receiving Agent, and is browsable through the existing tree/detail+ * endpoints. Import is owner-only, mirroring the Agent snapshot import.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import type { OmniMessage, SessionMetaPayload } from "@prismshadow/penguin-core";import type {AgentTracesResponse,ProjectCreateResponse,+ SessionsResponse,TraceEventsResponse,TraceImportResponse,} from "../src/api/types.js";@@ -169,6 +171,56 @@ describe("trace-import-export", () => {expect(await (await owner.get(`${base()}/${SID}/1/download`)).text()).toBe(toContent(original));});+ it("import: the file becomes a Session of the receiving Agent, listed without the CLI filter", async () => {+ // An imported Trace IS a conversation of this install, not a foreign artefact: it has to+ // appear in the conversation list, which is served from the sessions table. Registering+ // only the Trace file left it visible solely under "show CLI sessions" — the filter for+ // Sessions this server never created.+ expect(+ (await owner.post(`${base()}/import`, { dataBase64: b64(toContent(sampleTrace(SID))) }))+ .status,+ ).toBe(200);+ const listed = (await (+ await owner.get(`/api/projects/${projectId}/agents/default_agent/sessions?counts=1`)+ ).json()) as SessionsResponse;+ expect(listed.sessions.map((x) => x.sessionId)).toEqual([SID]);+ expect(listed.counts?.active).toBe(1);+ // Carried over from the file's own session_meta, so the row is a usable conversation+ // rather than a stub: model reference, Workspace, and the Trace it was imported from.+ const row = listed.sessions[0]!;+ expect(row.provider).toBe("custom");+ expect(row.modelId).toBe("m");+ expect(row.workspace).toBe("/tmp/w");+ expect(row.hasTrace).toBe(true);+ // Its Workspace group knows it too — the per-Workspace share the sidebar counts a group by.+ expect(listed.workspaceCounts?.["/tmp/w"]?.active).toBe(1);+ });++ it("import: a session id that exists anywhere in the install → 409, whichever Agent holds it", async () => {+ // A session id is the identity everywhere: the sessions table keys on it, the frontend+ // dedupes rows by it. Importing the same Trace under a SECOND Agent used to pass the+ // per-Agent check and produce a Session nothing could own — no row could sit beside the+ // existing one, so a group's count stood one above the rows it could ever show.+ expect(+ (await owner.post(`${base()}/import`, { dataBase64: b64(toContent(sampleTrace(SID))) }))+ .status,+ ).toBe(200);+ expect(+ (await owner.post(`/api/projects/${projectId}/agents`, { agentId: "second", name: "Second" }))+ .status,+ ).toBe(201);+ const res = await owner.post(`/api/projects/${projectId}/agents/second/traces/import`, {+ dataBase64: b64(toContent(sampleTrace(SID))),+ });+ expect(res.status).toBe(409);+ expect(await errorCode(res)).toBe("trace_session_exists");+ // Nothing was written for the second Agent.+ const tree = (await (+ await owner.get(`/api/projects/${projectId}/agents/second/traces`)+ ).json()) as AgentTracesResponse;+ expect(tree.dates).toEqual([]);+ });+it("import: concurrent imports of the same new session id — exactly one wins", async () => {// Whichever request loses is rejected either by the pre-check (locateAll) or by the// exclusive `wx` write (EEXIST → the same 409), so the observable outcome isdiff --git a/packages/web/e2e/chat.spec.mjs b/packages/web/e2e/chat.spec.mjsindex b11e595a..f62e517e 100644--- a/packages/web/e2e/chat.spec.mjs+++ b/packages/web/e2e/chat.spec.mjs@@ -217,14 +217,17 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })await msgCopy.click();expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("Help me set up @theme");- // --- traces --- (scope to <main>; the global sidebar also lists the session title)- await page.goto(`${BASE}/traces`);+ // --- traces --- the dock's Trace panel is the only way to read a Trace. It opens on+ // THIS conversation's newest file, so there is no tree to drill down. The bottom dock,+ // to leave the right one closed for the files block below; scope to <main> (which holds+ // the docks) since the global sidebar also lists the session title.+ await page.getByTestId("dock-toggle-bottom").click();+ const bottomDock = page.locator("[data-testid='dock'][data-position='bottom']");+ await bottomDock.getByTestId("dock-pick-trace").click();const main = page.locator("main");- // Auto-generated title should appear in the traces tree (agents default-expanded).- const titleNode = main.getByText("Configure Tailwind theme").first();- await expect(titleNode).toBeVisible();- await titleNode.click();- await expect(main.getByText("轨迹观测").first()).toBeVisible();+ await expect(main.locator('[data-tab-id="trace"][data-active="true"]')).toBeVisible();+ // The file pills name the Session's own Trace files, newest first.+ await expect(main.getByText("Trace 文件").first()).toBeVisible();// Legend shows the 5 fixed categories (tool-exec renamed).await expect(main.getByText("工具调用执行").first()).toBeVisible();await expect(main.getByText("模型回复").first()).toBeVisible();@@ -261,6 +264,8 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })await expect(seg).toBeVisible();await seg.hover();await expect(main.locator("button.bg-amber-50").first()).toBeVisible();+ // Put the dock away: the files block below opens the right dock from a closed state.+ await page.getByTestId("dock-toggle-bottom").click();// --- files: HTML preview (isolated separate-origin iframe, scripts + storage) + path hidden ---// run.sh binds 127.0.0.1 and the spec browses on localhost, so previewIsolated=true and thediff --git a/packages/web/e2e/compaction.spec.mjs b/packages/web/e2e/compaction.spec.mjsindex cf87400a..a6c9575e 100644--- a/packages/web/e2e/compaction.spec.mjs+++ b/packages/web/e2e/compaction.spec.mjs@@ -126,15 +126,17 @@ test("compaction mid-turn: the reply's stats line is still reachable by hoveringawait expect(banner).toHaveAttribute("aria-expanded", "false");await expect(card.getByText(summaryLine)).toHaveCount(0);- // —— Trace page ——+ // —— Trace panel ——// Compaction is its own round: the user round's elapsed time and TPS don't include compaction// (matching the chat page's convention), and the compaction round has **its own TPS** (how- // fast the summary was generated), not a "—".- await page.goto(`${BASE}/traces`);+ // fast the summary was generated), not a "—". The panel opens on this conversation's own+ // Trace file, so the rounds are on screen with nothing to drill into.+ await page.getByTestId("dock-toggle-bottom").click();+ await page+ .locator("[data-testid='dock'][data-position='bottom']")+ .getByTestId("dock-pick-trace")+ .click();const main = page.locator("main");- const node = main.getByText(/Configure|新对话/).first();- await expect(node).toBeVisible();- await node.click();await expect(main.getByText("第 1 轮")).toBeVisible();await expect(main.getByText("第 2 轮")).toBeVisible();const roundRows = main.locator("button").filter({ hasText: /第 \d 轮/ });diff --git a/packages/web/e2e/layout.spec.mjs b/packages/web/e2e/layout.spec.mjsindex 10ec145e..16c4d1bf 100644--- a/packages/web/e2e/layout.spec.mjs+++ b/packages/web/e2e/layout.spec.mjs@@ -828,7 +828,7 @@ test("layout: no page grows the document (absolute descendants stay in their scr// A short viewport puts the second Agent's node below the fold with a handful of Sessions// instead of dozens — the same geometry a full-height window reaches with a longer list.await page.setViewportSize({ width: 1440, height: 420 });- const paths = ["/traces", "/chat", "/agents", "/agents/default_agent", "/skills", "/models"];+ const paths = ["/chat", "/agents", "/agents/default_agent", "/skills", "/models"];const grewBy = (p) =>p.evaluate(() => {const de = document.documentElement;diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 90d0827b..761927fc 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -21,7 +21,6 @@ import type {AgentSkillsResponse,AgentVaultConfigDto,AgentsResponse,- AgentTracesResponse,ApprovalDecisionRequest,AuthLoginRequest,AuthResponse,@@ -397,30 +396,6 @@ export const kernelUpdateAgentConfig = (projectId: string, agentId: string) =>{ method: "POST" },);-/**- * Optional paging (absent = the legacy full date-grouped response): pages Session groups- * newest-first; a paged response answers with `sessions` (titles + category/workspace),- * `totalSessions`, and per-category `counts` / `workspaceCounts`. `category` filters to- * one sidebar bucket (paging applies within it, mirroring the sessions list); `cli`- * includes CLI-origin Sessions (the "show CLI sessions" preference, default off — same- * parameter convention as listSessions). The Trace page requests `limit+1` per page to- * detect "has more" (splitPage).- */-export const getAgentTraces = (- projectId: string,- agentId: string,- paging?: { offset: number; limit: number; category?: SessionCategory; cli?: boolean },-) =>- apiFetch<AgentTracesResponse>(- `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/traces${- paging- ? `?limit=${paging.limit}&offset=${paging.offset}` +- (paging.category ? `&category=${paging.category}` : "") +- (paging.cli ? "&cli=1" : "")- : ""- }`,- );-// Session ---------------------------------------------------------------------/**diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex 01fe9f26..7b26bdfc 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -78,9 +78,8 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {};/** Page entries (rail positions 3-7): same routes, same labels as the pinned nav.- Traces is not among them: the Trace panel lives in the chat toolbar's panel switcher- now, and the /traces browsing page stays addressable by URL (plus the Benchmark- page's per-run Session links). */+ Traces is not among them: reading a Trace happens in the chat toolbar's panel+ switcher, which is the only place it happens. */const pages: ReadonlyArray<{ to: string; label: string; icon: string }> = [{ to: "/agents", label: S.nav.agents, icon: NAV_ICONS.agents },{ to: "/skills", label: S.nav.skills, icon: NAV_ICONS.skills },diff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsxindex d748f655..c1b78f91 100644--- a/packages/web/src/components/ui/group-list.tsx+++ b/packages/web/src/components/ui/group-list.tsx@@ -1,10 +1,10 @@/**- * Shared building blocks of the grouped Session lists (the chat sidebar and the Trace- * page's directory tree render the same structure — group header, collapsed lazy- * folders, "More" rows, the Workspace/Agent grouping toggle). Extracted verbatim from- * sidebar.tsx's inner closures so the two surfaces cannot drift apart visually: the- * markup and classes here ARE the sidebar's; callers pass the state the closures used- * to capture.+ * Building blocks of the chat sidebar's grouped Session list — group header, collapsed+ * lazy folders, the reveal/collapse rows, the group pager. Extracted from sidebar.tsx's+ * inner closures, which is why the markup and classes here ARE the sidebar's and callers+ * pass the state those closures used to capture. The Trace page's directory tree used to+ * render the same structure from here; that page is gone, so this is now one surface's+ * vocabulary kept in one file rather than a contract between two.*/import type { DragEvent as ReactDragEvent, ReactNode } from "react";import { S } from "../../lib/strings";@@ -47,19 +47,6 @@ export const REORDER_ICON = "m21 16-4 4-4-4M17 20V4M3 8l4-4 4 4M7 4v16";/** Grouping mode of a Session list (persisted; Workspace is the default). */export type GroupMode = "workspace" | "agent" | "time";-/**- * The grouping modes a Trace-file tree can offer. Its rows are trace files keyed by- * Session id and carry no activity timestamp, so there is nothing to cut time buckets- * on; a stored "time" preference reads there as the Workspace grouping it falls back to- * (treeGroupMode), and its two-icon toggle offers exactly these two.- */-export type TreeGroupMode = "workspace" | "agent";--/** The nearest mode a Trace-file tree supports (see TreeGroupMode). */-export function treeGroupMode(mode: GroupMode): TreeGroupMode {- return mode === "agent" ? "agent" : "workspace";-}-/*** Leading glyph per grouping mode — the one place these are chosen, read by both the* two-icon toggle below and the sidebar's list-options menu, so a row and its toggle can@@ -112,42 +99,6 @@ export function storeGroupMode(mode: GroupMode): void {localStorage.setItem(GROUP_MODE_KEY, mode);}-/** The two-icon Workspace/Agent grouping toggle (the Trace tree's mode switch — see TreeGroupMode). */-export function GroupModeToggle({- value,- onChange,-}: {- value: TreeGroupMode;- onChange: (mode: TreeGroupMode) => void;-}) {- return (- <div className="flex items-center gap-0.5">- {(- [- { value: "workspace", icon: GROUP_MODE_ICONS.workspace, label: S.chat.groupByWorkspace },- { value: "agent", icon: GROUP_MODE_ICONS.agent, label: S.chat.groupByAgent },- ] as const- ).map((opt) => (- <button- key={opt.value}- type="button"- title={opt.label}- aria-label={opt.label}- aria-pressed={value === opt.value}- onClick={() => onChange(opt.value)}- className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-md transition-colors duration-150 ${- value === opt.value- ? "bg-gray-200/70 text-gray-700 dark:bg-gray-800 dark:text-gray-200"- : "text-gray-400 hover:bg-gray-200/50 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800/70 dark:hover:text-gray-300"- }`}- >- <Icon d={opt.icon} size={14} />- </button>- ))}- </div>- );-}-/** Row class of folder toggles and "More" rows (the sidebar's folderClass). */export const FOLDER_ROW_CLASS ="flex w-full items-center gap-1 rounded px-1.5 py-1 text-left text-[11px] font-medium text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 dark:text-gray-500 dark:hover:bg-gray-800/50";diff --git a/packages/web/src/components/ui/select.tsx b/packages/web/src/components/ui/select.tsxindex 4cdc395f..42068ef0 100644--- a/packages/web/src/components/ui/select.tsx+++ b/packages/web/src/components/ui/select.tsx@@ -61,6 +61,10 @@ export function Select({value,onChange,disabled,+ // Forwarded like a native select would: a control with no visible `label` (one sitting in+ // an already-labelled settings row, say) still has to name itself to a screen reader, and+ // the selected option's text says what is chosen, not what is being chosen.+ "aria-label": ariaLabel,}: SelectProps) {const options = parseOptions(children);const current = String(value ?? "");@@ -90,6 +94,7 @@ export function Select({disabled={disabled}aria-haspopup="listbox"aria-expanded={open}+ {...(ariaLabel !== undefined ? { "aria-label": ariaLabel } : {})}aria-required={required || undefined}aria-invalid={error ? true : undefined}aria-describedby={error ? errorId : undefined}diff --git a/packages/web/src/features/settings/general-section.tsx b/packages/web/src/features/settings/general-section.tsxindex 86fe428e..59defc2e 100644--- a/packages/web/src/features/settings/general-section.tsx+++ b/packages/web/src/features/settings/general-section.tsx@@ -13,6 +13,7 @@ import { useTheme } from "../../state/theme";import type { Currency } from "../../state/theme";import { useSessions } from "../../state/sessions";import { PrefRow } from "./setting-row";+import { TraceImportRow } from "./trace-import-row";export function GeneralSection() {const { lang, setLang } = useLocale();@@ -42,6 +43,8 @@ export function GeneralSection() {<PrefRow label={S.settings.showCliSessions} info={S.settings.showCliSessionsInfo}><Switch checked={showCliSessions} onChange={setShowCliSessions} /></PrefRow>+ {/* Beside the filter above: both rows decide what the conversation list holds. */}+ <TraceImportRow /></div>);}diff --git a/packages/web/src/features/settings/trace-import-row.tsx b/packages/web/src/features/settings/trace-import-row.tsxnew file mode 100644index 00000000..e66692d5--- /dev/null+++ b/packages/web/src/features/settings/trace-import-row.tsx@@ -0,0 +1,172 @@+/**+ * Trace import (System settings → General): a `.jsonl` Trace exported from another install+ * becomes a conversation of the chosen Agent.+ *+ * Both halves of the destination are picked here, Project included. The endpoint is+ * per-Agent and a Trace file cannot name one: its `session_meta` carries an `agent_state`+ * path belonging to the machine that exported it. The Project is asked for rather than+ * inherited because this dialog does not show which one is current — every other row in it+ * belongs to the account or the server — and an import that silently landed in whichever+ * Project the sidebar happened to have selected would be a hard mistake to notice. It also+ * means a Trace can be imported into a Project other than the open one.+ *+ * 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.+ */+import { useEffect, useState } from "react";+import type { ChangeEvent } from "react";+import type { AgentSummary } from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { HiddenFileInput } from "../../components/ui/hidden-file-input";+import { UploadIcon } from "../../components/ui/icons";+import { Select } from "../../components/ui/select";+import { toastError, toastSuccess } from "../../components/ui/toast";+import { agentDisplayName, projectDisplayName, useProject } from "../../state/project";+import { useSessions } from "../../state/sessions";+import { PrefRow } from "./setting-row";++/** Client-side pre-check before reading the picked file (the same cap as the server's import route). */+const MAX_TRACE_BYTES = 14 * 1024 * 1024;++export function TraceImportRow() {+ const { projects, currentProject } = useProject();+ const { reload } = useSessions();+ /** Explicit picks; "" means "not chosen yet", which resolves to the defaults below. */+ const [pickedProject, setPickedProject] = useState("");+ const [pickedAgent, setPickedAgent] = useState("");+ const [agents, setAgents] = useState<readonly AgentSummary[]>([]);+ const [importing, setImporting] = useState(false);++ /** Destination Project: the explicit pick, else the open one (which may still be resolving). */+ const projectId =+ pickedProject !== ""+ ? pickedProject+ : (currentProject?.projectId ?? projects[0]?.projectId ?? "");+ /**+ * Destination Agent, derived rather than stored: a pick that the selected Project has no+ * Agent for falls back on its own, so switching Project cannot leave a stale id behind.+ */+ const agentId = agents.some((a) => a.agentId === pickedAgent)+ ? pickedAgent+ : ((agents.find((a) => a.agentId === "default_agent") ?? agents[0])?.agentId ?? "");++ // The Agent list of whichever Project is selected — the Project context only holds the+ // open Project's, and this row can target any of them.+ useEffect(() => {+ if (projectId === "") return;+ let cancelled = false;+ void api+ .listAgents(projectId)+ .then((res) => {+ if (!cancelled) setAgents(res.agents);+ })+ .catch(() => {+ // Unreachable list: the row disables itself rather than offering an empty picker.+ if (!cancelled) setAgents([]);+ });+ return () => {+ cancelled = true;+ };+ }, [projectId]);++ const busy = importing || agentId === "";++ const runImport = async (dataBase64: string) => {+ if (projectId === "" || agentId === "") return;+ setImporting(true);+ try {+ await api.importAgentTrace(projectId, agentId, { dataBase64 });+ const project = projects.find((p) => p.projectId === projectId);+ const target = `${project ? projectDisplayName(project) : projectId} · ${+ agents.find((a) => a.agentId === agentId)?.name ?? agentId+ }`;+ // Only the open Project's conversation list is on screen behind the dialog; refresh it+ // so the imported Session is there, and let the toast name the destination either way.+ 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));+ } finally {+ setImporting(false);+ }+ };++ const onPickFile = (e: ChangeEvent<HTMLInputElement>) => {+ const file = e.target.files?.[0];+ // Reset before reading so re-picking the same file fires change again.+ e.target.value = "";+ if (!file || agentId === "") return;+ if (file.size > MAX_TRACE_BYTES) {+ toastError(S.settings.importTraceTooLarge);+ return;+ }+ const reader = new FileReader();+ reader.onload = () => {+ 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.readAsDataURL(file);+ };++ return (+ <PrefRow label={S.settings.importTrace} info={S.settings.importTraceInfo}>+ {/* Each picker is boxed to a fixed width — a Select fills its container, and three+ full-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. */}+ <div className="flex flex-wrap items-center justify-end gap-2">+ <div className="w-32">+ <Select+ size="sm"+ value={projectId}+ disabled={importing}+ onChange={(e) => {+ setPickedProject(e.target.value);+ // The new Project decides the Agent; `agentId` falls back until a pick lands in it.+ setPickedAgent("");+ }}+ aria-label={S.settings.importTraceProject}+ >+ {projects.map((p) => (+ <option key={p.projectId} value={p.projectId}>+ {projectDisplayName(p)}+ </option>+ ))}+ </Select>+ </div>+ <div className="w-32">+ <Select+ size="sm"+ value={agentId}+ disabled={busy}+ onChange={(e) => setPickedAgent(e.target.value)}+ aria-label={S.settings.importTraceAgent}+ >+ {agents.map((a) => (+ <option key={a.agentId} value={a.agentId}>+ {agentDisplayName(a)}+ </option>+ ))}+ </Select>+ </div>+ {/* The file pick doubles as the confirm action (button styling on a label, so the+ native picker opens without a detour). */}+ <label+ className={`inline-flex shrink-0 items-center justify-center gap-1 rounded-md border border-gray-300 px-3 py-1 text-sm font-medium transition-colors duration-150 dark:border-gray-700 ${+ busy+ ? "pointer-events-none opacity-60"+ : "cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"+ }`}+ >+ <HiddenFileInput accept=".jsonl" disabled={busy} onChange={onPickFile} />+ <UploadIcon size={14} />+ {importing ? S.settings.importTraceRunning : S.settings.importTracePick}+ </label>+ </div>+ </PrefRow>+ );+}diff --git a/packages/web/src/features/traces/trace-panel.tsx b/packages/web/src/features/traces/trace-panel.tsxindex 4b166705..fff30ac4 100644--- a/packages/web/src/features/traces/trace-panel.tsx+++ b/packages/web/src/features/traces/trace-panel.tsx@@ -1,10 +1,11 @@/**- * Trace panel — the current conversation's Trace files as a dock tab, reusing the traces- * page's file view (performance timeline + event list) scoped to one Session. The file- * pills page newest-first; the export link downloads the selected file raw. Cross-Session- * browsing stays on the /traces page, which no longer has a UI entry point of its own —- * this panel is the only way in from the app, and is the "what did this conversation do"- * view. The page is still reachable by URL, for shared links and its import/export controls.+ * Trace panel — the current conversation's Trace files as a dock tab, wrapping the shared+ * file view (performance timeline + event list) around one Session. The file pills page+ * newest-first; the export link downloads the selected file raw. This is the ONLY way to+ * read a Trace: the standalone cross-Session browsing page is gone, so a Trace is read+ * where it was produced, as the "what did this conversation do" view. Importing a Trace+ * from another install is the one thing that outlived the page — it moved to System+ * settings, beside the CLI-sessions filter.** Loading is gated on `active` (the dock keeps inactive tabs mounted): the listing is* fetched on the first show and re-fetched on every re-show, so a Task that finished whilediff --git a/packages/web/src/features/traces/trace-sessions.ts b/packages/web/src/features/traces/trace-sessions.tsdeleted file mode 100644index 073969bd..00000000--- a/packages/web/src/features/traces/trace-sessions.ts+++ /dev/null@@ -1,104 +0,0 @@-/**- * Pure Session-list logic for the Trace page (kept out of the components so it is unit- * testable): mapping either server response shape to the page's Session groups, and- * partitioning rows by their server-classified category.- */-import type { AgentTracesResponse, SessionCategory } from "@prismshadow/penguin-server/api";--/**- * Trace page sessions fetched per (group, category) page, and the per-group display cap- * step for active rows — the Trace-tree counterpart of the sidebar's SIDEBAR_PAGE_SIZE,- * deliberately larger: the sidebar is a narrow column, while the Trace tree is a- * full-height page column, so 10-row pages felt stingy there. Fetches use- * limit = TRACES_PAGE_SIZE + 1 (splitPage) exactly like the sidebar; folder pages use- * the same size, so every "More" on this page steps uniformly.- */-export const TRACES_PAGE_SIZE = 20;--/**- * Groups (Agents / Workspace groups) rendered per Trace page "page" (the sidebar's- * SIDEBAR_GROUP_PAGE_SIZE counterpart, modestly larger for the same reason as above);- * "more groups" raises it by one page — a pure display cap, data loading untouched.- */-export const TRACES_GROUP_PAGE_SIZE = 15;--export interface TraceFileRef {- index: number;- date: string;- sizeBytes: number;-}--export interface TraceSessionGroup {- sessionId: string;- /** Server-resolved display title (DB title or first-prompt fallback); absent for legacy responses / untitled Sessions. */- title?: string;- /**- * Server-classified sidebar category (the paged endpoint's bounded classification —- * the same value its filter and counts used, so rows and buckets can't disagree).- * Legacy responses carry no classification; the mapper defaults to "active".- */- category: SessionCategory;- /** Workspace path ("" = unknown → the merged temp group, same defensive rule as the sidebar's isTempWorkspace). */- workspace: string;- /** Sorted newest first (a higher index is newer) — the page's display order. */- files: TraceFileRef[];-}--/** A pooled row of the Trace tree: the group plus its owning Agent (the fetch that produced it). */-export interface TraceSessionRow extends TraceSessionGroup {- agentId: string;-}--/**- * Maps a listing response to Session groups, newest Session first. A paged response- * (`sessions` present) is already session-centric and server-ordered; a legacy full- * response is flattened from its date grouping (merging one Session's files across- * dates) and sorted by sessionId descending — ids embed a timestamp, so that is- * reverse chronological, matching the server's paged ordering.- */-export function toSessionGroups(data: AgentTracesResponse): TraceSessionGroup[] {- if (data.sessions) {- return data.sessions.map((s) => ({- sessionId: s.sessionId,- ...(s.title !== undefined ? { title: s.title } : {}),- category: s.category,- workspace: s.workspace,- files: [...s.files].sort((a, b) => b.index - a.index),- }));- }- const bySession = new Map<string, TraceFileRef[]>();- for (const d of data.dates) {- for (const s of d.sessions) {- const list = bySession.get(s.sessionId) ?? [];- for (const f of s.files) list.push({ index: f.index, date: d.date, sizeBytes: f.sizeBytes });- bySession.set(s.sessionId, list);- }- }- return [...bySession.entries()]- .sort((a, b) => b[0].localeCompare(a[0]))- .map(([sessionId, files]) => ({- sessionId,- category: "active" as const,- workspace: "",- files: files.sort((a, b) => b.index - a.index),- }));-}--/**- * Partition of one group's rows by their server-classified category — the Trace-side- * twin of session-grouping's partitionSessions (which derives the category client-side- * from SessionInfo; here the server field is authoritative, because it is what the- * per-category fetches and counts were computed from).- */-export function partitionTraceRows<T extends { category: SessionCategory }>(- rows: readonly T[],-): Record<SessionCategory, T[]> {- const parts: Record<SessionCategory, T[]> = {- active: [],- subagent: [],- schedule: [],- archived: [],- };- for (const r of rows) parts[r.category].push(r);- return parts;-}diff --git a/packages/web/src/features/traces/traces-page.tsx b/packages/web/src/features/traces/traces-page.tsxdeleted file mode 100644index 47343d73..00000000--- a/packages/web/src/features/traces/traces-page.tsx+++ /dev/null@@ -1,803 +0,0 @@-/**- * Trace browsing page. The left-side directory mirrors the chat sidebar's structure on- * the shared grouped-list building blocks (components/ui/group-list.tsx): the same two- * grouping modes behind the same persisted preference (by Workspace — the default — or- * by Agent), group bodies split into the active list plus the collapsed lazy- * subagent / scheduled / archived folders, and the same "More" paging rows. Data comes- * from the paginated traces endpoint (paged per (Agent, category), see use-trace-tree),- * honoring the same "show CLI sessions" preference as the sidebar (default off;- * subagent/schedule Sessions stay in their folders regardless of origin).- * Titles are server-resolved (DB title or first-prompt fallback) with the Sessions- * store overriding when it has a fresher one; raw session ids never render. The right- * side shows the selected Session's Trace files (paged, most recent first by default) +- * performance analysis (an execution timeline) + an event timeline.- */-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import type { ChangeEvent } from "react";-import { useSearchParams } from "react-router";-import type { SessionCategory, SessionCategoryCounts } from "@prismshadow/penguin-server/api";-import * as api from "../../api/endpoints";-import { S } from "../../lib/strings";-import { apiErrorText } from "../../lib/api-error";-import { useDocumentTitle } from "../../lib/use-document-title";-import { formatBytes } from "../../lib/format";-import {- FOLDER_CATEGORIES,- aggregateWorkspaceCounts,- groupSessionsByWorkspace,- pinnedFirst,-} from "../../lib/session-grouping";-import type { FolderCategory } from "../../lib/session-grouping";-import { agentDisplayName, useProject } from "../../state/project";-import { AgentAvatar } from "../../components/ui/agent-avatar";-import {- FOLDER_ICON,- FOLDER_OPEN_ICON,- FolderSection,- GroupHeader,- GroupModeToggle,- Icon,- MoreRow,- initialGroupMode,- storeGroupMode,- treeGroupMode,-} from "../../components/ui/group-list";-import type { TreeGroupMode } from "../../components/ui/group-list";-import { HiddenFileInput } from "../../components/ui/hidden-file-input";-import { DownloadIcon, UploadIcon } from "../../components/ui/icons";-import { Modal } from "../../components/ui/modal";-import { Select } from "../../components/ui/select";-import { toastError } from "../../components/ui/toast";-import { Truncated } from "../../components/ui/truncated";-import { useSessions } from "../../state/sessions";-import { EmptyState } from "../../components/ui/empty-state";-import { SkeletonList } from "../../components/ui/skeleton";-import { TraceFileView } from "./trace-file-view";-import type { TraceHighlight } from "./timeline-chart";-import {- TRACES_GROUP_PAGE_SIZE,- TRACES_PAGE_SIZE,- partitionTraceRows,- toSessionGroups,-} from "./trace-sessions";-import type { TraceFileRef, TraceSessionRow } from "./trace-sessions";-import { useTraceTree } from "./use-trace-tree";-import { ICON_SIZE } from "../../lib/icon-scale";--/**- * Import file size cap, mirroring the server's route-side limit (agent-traces.ts).- * Checked on the raw picked file before it is read: base64-encoding an oversized- * pick and uploading it just to receive the server's 400 would materialize and- * send many times the cap for nothing.- */-const MAX_TRACE_BYTES = 14 * 1024 * 1024;--/** File pills rendered before the "+N" overflow control expands them (a long Session can hold dozens of compaction shards). */-const FILE_PILL_CAP = 10;--/** Open-state key of a collapsed folder inside a group ("\0" never appears in Agent ids or Workspace paths — the sidebar's composite). */-const folderKey = (groupKey: string, category: FolderCategory) => `${category}\0${groupKey}`;--interface Selection {- /** Details go through the Agent-level endpoint (not dependent on the sessions table's tracking), so the owning Agent must be carried along. */- agentId: string;- sessionId: string;- /** Server-resolved title of the selected group (the header still prefers a fresher store title). */- title?: string;- files: TraceFileRef[];-}--export function TracesPage() {- useDocumentTitle(S.traces.title);- const { currentProject, agents, agentsLoading } = useProject();- // showCliSessions: the traces tree follows the same per-user "show CLI sessions"- // preference as the sidebar (default off) — CLI-origin Sessions are excluded- // server-side from the listing, counts and workspace groups until it is enabled.- // A deep link to a CLI Session still resolves while the preference is off: the- // selection fallback (selectFromFull) uses the unfiltered legacy endpoint, so the- // Session opens in the right pane without appearing in the tree.- const { byAgent, showCliSessions } = useSessions();- const projectId = currentProject?.projectId ?? null;- const tree = useTraceTree(projectId, showCliSessions);- // ?agentId= deep link: forces agent grouping for this visit (the target must be a visible,- // expanded group) WITHOUT overwriting the stored preference; only the target Agent defaults to- // expanded. Nothing in the app produces these URLs any more — they arrive from links shared- // while the Agents page still had a Trace entry point, so they have to keep resolving.- const [searchParams] = useSearchParams();- const focusAgentId = searchParams.get("agentId");- // ?sessionId= deep link: auto-selects once the target Agent's Session list is ready. The- // evaluation center's Run rows used to produce these; they now show the Session id as text.- const focusSessionId = searchParams.get("sessionId");- // Grouping mode: the same persisted preference as the chat sidebar- // (penguin.sidebarGroupMode) so the two surfaces always group alike, narrowed to the- // two this tree can offer — its rows are Trace files keyed by Session id and carry no- // activity timestamp, so the sidebar's time buckets have nothing here to cut on and- // read as the Workspace grouping they fall back to (treeGroupMode).- const [modePref, setModePref] = useState<TreeGroupMode>(() => treeGroupMode(initialGroupMode()));- const groupMode: TreeGroupMode = focusAgentId !== null ? "agent" : modePref;- const [selection, setSelection] = useState<Selection | null>(null);- const [fileIndex, setFileIndex] = useState<number | null>(null);- /** Rendered groups cap (the sidebar's group paging pattern: raised a page per "more groups" click; reset per Project and on a mode switch). */- const [groupCap, setGroupCap] = useState(TRACES_GROUP_PAGE_SIZE);- /** Per-group display cap for active rows (keyed by group key; absent = TRACES_PAGE_SIZE). "More" raises it a page at a time. */- const [groupCaps, setGroupCaps] = useState<ReadonlyMap<string, number>>(new Map());- /**- * Agent-mode open groups; null = the default (only the deep-link target / first- * Agent expands — expanding all of them fanned out one directory scan per Agent).- * Materialized on the first manual toggle.- */- const [openAgentGroups, setOpenAgentGroups] = useState<ReadonlySet<string> | null>(null);- /** Workspace-mode collapsed groups (expanded by default, like the sidebar — their data is already pooled). */- const [collapsedWsGroups, setCollapsedWsGroups] = useState<ReadonlySet<string>>(new Set());- /** Expanded folders (subagent / scheduled / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */- const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set());- /** "More" rows with a fetch in flight, keyed `${category}\0${groupKey}` (disable + loading text). */- const [pendingLoads, setPendingLoads] = useState<ReadonlySet<string>>(new Set());- /** Import dialog open state and its target Agent (the endpoint is per-Agent, so the page-level button asks which one). */- const [importOpen, setImportOpen] = useState(false);- const [importAgentId, setImportAgentId] = useState("");- /** Agent whose Trace import is in flight (the header button disables and reads "importing"). */- const [importingAgent, setImportingAgent] = useState<string | null>(null);- /** File-pill overflow expanded for the current selection. */- const [showAllFiles, setShowAllFiles] = useState(false);- // Linked highlighting between the trace observation view and the event list (keyed by tool_call_id).- const [highlight, setHighlight] = useState<TraceHighlight | null>(null);- /** Session to auto-select once the refreshed list arrives (the import response's sessionId). */- const importedSession = useRef<{ agentId: string; sessionId: string } | null>(null);-- const setGroupMode = (mode: TreeGroupMode) => {- storeGroupMode(mode);- setModePref(mode);- // The two modes have unrelated group lists: restart the reveal window.- setGroupCap(TRACES_GROUP_PAGE_SIZE);- };-- // Clear the selection and per-Project view state when switching Project.- useEffect(() => {- setSelection(null);- setFileIndex(null);- setGroupCap(TRACES_GROUP_PAGE_SIZE);- setGroupCaps(new Map());- setOpenAgentGroups(null);- setCollapsedWsGroups(new Set());- setOpenFolders(new Set());- }, [projectId]);-- // Clear the linked highlight when switching Session / Trace file.- useEffect(() => {- setHighlight(null);- }, [selection, fileIndex]);-- // Collapse the file-pill overflow when switching Session (picking a pill must not re-collapse the row it lives in).- useEffect(() => {- setShowAllFiles(false);- }, [selection]);-- /**- * sessionId -> freshest store title (live session_title pushes land in the Sessions- * store first). Memoized Map: a per-row `.find` would re-scan the store list on- * every render of every row.- */- const storeTitles = useMemo(() => {- const m = new Map<string, string>();- for (const list of byAgent.values()) {- for (const s of list) if (s.title !== undefined) m.set(s.sessionId, s.title);- }- return m;- }, [byAgent]);-- /** Display title: store title (freshest) -> server-resolved title -> default. Raw session ids never render as text. */- const titleOf = useCallback(- (sessionId: string, serverTitle?: string): string =>- storeTitles.get(sessionId) ?? serverTitle ?? S.chat.defaultSessionTitle,- [storeTitles],- );-- /** agentId → display name (row hint tooltips in workspace mode). */- const agentNameById = useMemo(- () => new Map(agents.map((a) => [a.agentId, agentDisplayName(a)])),- [agents],- );-- // The ?agentId= focus target is pinned first so the deep link stays visible above the- // group cap (the sidebar's pinnedFirst, with the deep link as the pinned set).- const orderedAgents = useMemo(- () =>- pinnedFirst(agents, (a) => a.agentId, new Set(focusAgentId === null ? [] : [focusAgentId])),- [agents, focusAgentId],- );-- /** Agent-mode effective open set: the deep-link target / first Agent until the user toggles. */- const effectiveOpenAgents = useMemo(() => {- if (openAgentGroups !== null) return openAgentGroups;- const first = focusAgentId ?? orderedAgents[0]?.agentId;- return new Set(first === undefined ? [] : [first]);- }, [openAgentGroups, focusAgentId, orderedAgents]);-- const toggleAgentGroup = (agentId: string) => {- const next = new Set(effectiveOpenAgents);- if (next.has(agentId)) next.delete(agentId);- else next.add(agentId);- setOpenAgentGroups(next);- };-- const toggleWsGroup = (key: string) => {- setCollapsedWsGroups((prev) => {- const next = new Set(prev);- if (next.has(key)) next.delete(key);- else next.add(key);- return next;- });- };-- // Agent mode loads lazily: only rendered-and-expanded groups fetch their first page.- const ensureFirstFor = tree.ensureFirstFor;- useEffect(() => {- if (!projectId || groupMode !== "agent") return;- const visible = orderedAgents- .slice(0, groupCap)- .map((a) => a.agentId)- .filter((id) => effectiveOpenAgents.has(id));- if (visible.length > 0) ensureFirstFor(visible);- }, [projectId, groupMode, orderedAgents, groupCap, effectiveOpenAgents, ensureFirstFor]);-- // Workspace mode needs every Agent's first active page to group by Workspace at all:- // fetched in parallel (one paged request per Agent), like the sidebar's reload fans- // out over the sessions API.- useEffect(() => {- if (!projectId || groupMode !== "workspace" || agents.length === 0) return;- ensureFirstFor(agents.map((a) => a.agentId));- }, [projectId, groupMode, agents, ensureFirstFor]);-- /** Workspace groups from the pooled rows; the sessionId doubles as the chronological sort key groupSessionsByWorkspace needs (ids embed the creation timestamp). */- const workspaceGroups = useMemo(- () => groupSessionsByWorkspace(tree.allRows.map((r) => ({ ...r, createdAt: r.sessionId }))),- [tree.allRows],- );- /** Workspace-mode per-group exact server totals (folded from the per-Agent per-Workspace counts). */- const workspaceGroupCounts = useMemo(- () => aggregateWorkspaceCounts(tree.workspaceCountsByAgent),- [tree.workspaceCountsByAgent],- );-- const select = useCallback((row: TraceSessionRow) => {- setSelection({- agentId: row.agentId,- sessionId: row.sessionId,- ...(row.title !== undefined ? { title: row.title } : {}),- files: row.files,- });- setFileIndex(row.files[0]?.index ?? null);- }, []);-- /**- * Selects a Session that isn't in the loaded pages (a deep link to, or re-import of,- * an old Session): one legacy full fetch resolves its files. That is the pre-paging- * cost of the whole tree, but for a single Agent and only on this path; a miss stays- * silent, like an in-list miss.- */- const selectFromFull = useCallback(- (agentId: string, sessionId: string) => {- if (!projectId) return;- api- .getAgentTraces(projectId, agentId)- .then((data) => {- const target = toSessionGroups(data).find((g) => g.sessionId === sessionId);- if (target) select({ ...target, agentId });- })- .catch(() => {});- },- [projectId, select],- );-- // The Session deep link is applied only once: it selects the target as soon as the- // target Agent's first page is ready (falling back to a full fetch when the target- // sorts beyond it or lives in a folder category); after that, the user's manual- // switches are never pulled back by the deep-link parameter.- const focusApplied = useRef(false);- useEffect(() => {- if (focusApplied.current || !focusSessionId || !focusAgentId) return;- if (!tree.isLoadedFor(focusAgentId, "active")) return;- focusApplied.current = true;- const target = tree.rowsByAgent.get(focusAgentId)?.find((g) => g.sessionId === focusSessionId);- if (target) select(target);- else selectFromFull(focusAgentId, focusSessionId);- }, [tree, focusSessionId, focusAgentId, select, selectFromFull]);-- // Post-import selection: once the refreshed list is in, select the imported Session —- // an import always creates a new Session whose only file is the imported one, so the- // default file pick is the imported file. A re-imported OLD session id can sort beyond- // the refreshed first page; the full-fetch fallback still selects it.- useEffect(() => {- const pendingImport = importedSession.current;- if (pendingImport === null) return;- const rows = tree.rowsByAgent.get(pendingImport.agentId);- if (rows === undefined) return;- importedSession.current = null;- const target = rows.find((g) => g.sessionId === pendingImport.sessionId);- if (target) select(target);- else selectFromFull(pendingImport.agentId, pendingImport.sessionId);- }, [tree, select, selectFromFull]);-- const runImport = async (agentId: string, dataBase64: string) => {- if (!projectId) return;- setImportingAgent(agentId);- try {- const res = await api.importAgentTrace(projectId, agentId, { dataBase64 });- // Refresh the Agent's pages; the effect watching the tree then jumps to the- // imported Session. The group also expands so the selection is visible.- importedSession.current = { agentId, sessionId: res.sessionId };- if (!effectiveOpenAgents.has(agentId)) toggleAgentGroup(agentId);- await tree.refreshAgent(agentId);- } catch (e: unknown) {- // Transient action failure → toast (the app's one notification rule; a- // rejected import isn't a state of the tree, unlike the inline load error).- toastError(apiErrorText(e));- } finally {- setImportingAgent(null);- }- };-- const onPickFile = (e: ChangeEvent<HTMLInputElement>) => {- const agentId = importAgentId;- const file = e.target.files?.[0];- // Reset before reading so re-picking the same file fires change again.- e.target.value = "";- if (!file || agentId === "") return;- if (file.size > MAX_TRACE_BYTES) {- toastError(S.traces.fileTooLarge);- return;- }- // Picking a file IS the confirmation: close the dialog and run the import (the- // header button shows the in-flight state; failures toast as before).- setImportOpen(false);- const reader = new FileReader();- reader.onload = () => {- const url = reader.result as string;- void runImport(agentId, url.slice(url.indexOf(",") + 1)); // strip the data:...;base64, prefix- };- reader.onerror = () => toastError(S.common.unknownError);- reader.readAsDataURL(file);- };-- /** Opens the import dialog, defaulting the target to the deep-linked / first Agent. */- const openImport = () => {- setImportAgentId(focusAgentId ?? orderedAgents[0]?.agentId ?? "");- setImportOpen(true);- };-- /** In-flight key of one group's category "More" (folderKey shares the same composite for folder categories). */- const loadKey = (groupKey: string, category: SessionCategory) => `${category}\0${groupKey}`;-- /** loadMoreFor with an in-flight marker for the triggering "More" row (disable + loading text). */- const trackedLoadMore = (groupKey: string, category: SessionCategory, agentIds: string[]) => {- const key = loadKey(groupKey, category);- setPendingLoads((prev) => new Set(prev).add(key));- void tree.loadMoreFor(agentIds, category).finally(() => {- setPendingLoads((prev) => {- const next = new Set(prev);- next.delete(key);- return next;- });- });- };-- /**- * Open/close a group's folder. A folder's content is loaded on demand: the first- * expand fetches its category's first page for every contributing Agent that hasn't- * been asked yet (already-loaded rows stay put — re-expanding never refetches; the- * folder's own "More" row does the paging from there).- */- const toggleFolder = (groupKey: string, category: FolderCategory, agentIds: string[]) => {- const key = folderKey(groupKey, category);- const opening = !openFolders.has(key);- setOpenFolders((prev) => {- const next = new Set(prev);- if (opening) next.add(key);- else next.delete(key);- return next;- });- if (opening) {- const unloaded = agentIds.filter((id) => !tree.isLoadedFor(id, category));- if (unloaded.length > 0) void tree.loadMoreFor(unloaded, category);- }- };-- /** Session rows shared by both modes; withAgentHint adds a small Agent avatar per row (workspace mode, where the group no longer names the Agent). */- const renderRows = (rows: TraceSessionRow[], withAgentHint: boolean) => (- <ul className="space-y-0.5">- {rows.map((r) => {- const active = selection?.sessionId === r.sessionId;- const hint = agentNameById.get(r.agentId) ?? r.agentId;- return (- <li key={r.sessionId}>- <button- type="button"- onClick={() => select(r)}- className={`flex w-full items-center gap-1.5 rounded-md px-2.5 py-1.5 text-left transition-colors duration-150 ${- active- ? "bg-gray-200/70 dark:bg-gray-800"- : "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"- }`}- >- {withAgentHint && (- <span title={hint} className="flex shrink-0 items-center">- <AgentAvatar id={r.agentId} name={hint} size={14} className="rounded" />- <span className="sr-only">{hint}</span>- </span>- )}- <Truncated- text={titleOf(r.sessionId, r.title)}- className={`min-w-0 flex-1 text-sm ${- active- ? "font-medium text-gray-900 dark:text-gray-100"- : "text-gray-700 dark:text-gray-300"- }`}- />- <span className="shrink-0 font-mono text-[11px] text-gray-400">{r.files.length}</span>- </button>- </li>- );- })}- </ul>- );-- /**- * Lazy folder inside a group (the sidebar's renderFolder shape): exists only while- * the group's own exact server share is non-zero, the label shows that share, and- * "More" shows only while loaded rows fall short of it.- */- const renderFolder = (- groupKey: string,- category: FolderCategory,- parts: Record<SessionCategory, TraceSessionRow[]>,- withAgentHint: boolean,- agentIds: string[],- totals: SessionCategoryCounts | undefined,- ) => {- const rows = parts[category];- // Loaded rows win a disagreement with the totals (counts refresh on the next fetch).- const total = Math.max(totals?.[category] ?? 0, rows.length);- if (total === 0) return null;- const more = rows.length < total && agentIds.some((id) => tree.hasMoreFor(id, category));- return (- <FolderSection- key={category}- label={S.chat.folderGroups[category](total)}- open={openFolders.has(folderKey(groupKey, category))}- onToggle={() => toggleFolder(groupKey, category, agentIds)}- more={more}- pending={pendingLoads.has(loadKey(groupKey, category))}- onMore={() => trackedLoadMore(groupKey, category, agentIds)}- >- {renderRows(rows, withAgentHint)}- </FolderSection>- );- };-- /** Active-list "More": reveal one more page of already-loaded active rows AND fetch the next active server page for every Agent that still has one. */- const showMore = (groupKey: string, agentIds: string[]) => {- setGroupCaps((prev) => {- const next = new Map(prev);- next.set(groupKey, (prev.get(groupKey) ?? TRACES_PAGE_SIZE) + TRACES_PAGE_SIZE);- return next;- });- if (agentIds.length > 0) trackedLoadMore(groupKey, "active", agentIds);- };-- /**- * Expanded group body shared by both modes (the sidebar's renderGroupBody shape):- * active rows (display-capped; "More" reveals and loads further active-only pages —- * the folders below never feed it) + the collapsed-by-default subagent / scheduled /- * archived folders, each loading on first expand and paging on its own. Rows are- * partitioned by their server-classified category (partitionTraceRows).- */- const renderGroupBody = (- groupKey: string,- rows: TraceSessionRow[],- withAgentHint: boolean,- totals: SessionCategoryCounts | undefined,- agentsFor: (category: SessionCategory) => string[],- emptyText: string,- ) => {- const parts = partitionTraceRows(rows);- const cap = groupCaps.get(groupKey) ?? TRACES_PAGE_SIZE;- const shownActive = parts.active.slice(0, cap);- const activeAgents = agentsFor("active");- const activeTotal = Math.max(totals?.active ?? 0, parts.active.length);- const hasMore =- parts.active.length > cap ||- (parts.active.length < activeTotal &&- activeAgents.some((id) => tree.hasMoreFor(id, "active")));- const folders = FOLDER_CATEGORIES.map((category) =>- renderFolder(groupKey, category, parts, withAgentHint, agentsFor(category), totals),- );- const empty = parts.active.length === 0 && folders.every((f) => f === null);- const activePending = pendingLoads.has(loadKey(groupKey, "active"));- return (- <>- {empty ? (- <p className="px-2.5 py-1 text-xs text-gray-400 dark:text-gray-600">{emptyText}</p>- ) : (- renderRows(shownActive, withAgentHint)- )}- {/* Load/reveal more (kept adjacent to the active list it extends, above the folders) */}- {hasMore && (- <MoreRow- label={S.chat.loadMore}- pending={activePending}- onClick={() => showMore(groupKey, activeAgents)}- className="mt-0.5"- />- )}- {folders}- </>- );- };-- if (!projectId) return null;-- const activeFile =- selection === null- ? null- : (selection.files.find((f) => f.index === fileIndex) ?? selection.files[0] ?? null);- const visibleFiles =- selection === null || showAllFiles ? null : selection.files.slice(0, FILE_PILL_CAP);-- /** Workspace mode is still fanning out its first pages and has nothing pooled yet. */- const wsLoading =- tree.allRows.length === 0 && agents.some((a) => tree.isPendingFor(a.agentId, "active"));-- return (- <div className="flex h-full flex-col md:flex-row">- {/* Directory tree (≥md left column; <md top collapsible area).- relative: a scroller is its own containing block — the invariant and the failure it- prevents are documented in styles.css; this is where it first bit (an Agent node past- the fold put its import control's absolutely positioned box at a document-level- offset, growing the document). */}- <aside className="relative max-h-52 shrink-0 overflow-y-auto border-b border-gray-200 bg-gray-50 px-1 py-2 md:max-h-none md:w-72 md:border-b-0 md:border-r dark:border-gray-800 dark:bg-gray-900">- <div className="flex items-center justify-between px-3 pb-1">- <p className="text-xs font-bold uppercase tracking-wide text-gray-500">- {S.traces.title}- </p>- <div className="flex items-center gap-0.5">- {/* Page-level Trace import (owner-only; moved here from the per-Agent group- headers): one button beside the grouping toggle, matching its control- height; the dialog then asks which Agent receives the file. */}- {currentProject?.role === "owner" && (- <button- type="button"- title={importingAgent !== null ? S.traces.importing : S.traces.importTrace}- aria-label={importingAgent !== null ? S.traces.importing : S.traces.importTrace}- disabled={importingAgent !== null}- onClick={openImport}- className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors duration-150 hover:bg-gray-200/50 hover:text-gray-700 disabled:opacity-60 dark:text-gray-500 dark:hover:bg-gray-800/70 dark:hover:text-gray-300"- >- <UploadIcon size={14} />- </button>- )}- {/* Hidden while an ?agentId= deep link forces agent grouping: a toggle showing- the (possibly different) stored preference would look broken. */}- {focusAgentId === null && <GroupModeToggle value={modePref} onChange={setGroupMode} />}- </div>- </div>- {agentsLoading || (groupMode === "workspace" && wsLoading) ? (- <SkeletonList rows={4} />- ) : groupMode === "agent" ? (- <>- {orderedAgents.slice(0, groupCap).map((a) => {- const open = effectiveOpenAgents.has(a.agentId);- const name = agentDisplayName(a);- const error = tree.errorByAgent.get(a.agentId);- const loaded = tree.isLoadedFor(a.agentId, "active");- return (- <div key={a.agentId} className="pt-2.5">- <GroupHeader- open={open}- onToggle={() => toggleAgentGroup(a.agentId)}- icon={- <AgentAvatar- id={a.agentId}- name={name}- size={18}- className="shrink-0 rounded"- />- }- label={name}- uppercase- />- {open && (- <div className="anim-fade">- {/* Load failure of the tree itself stays inline (the one-notification-rule keeps load states with their content, not in a disappearing toast). */}- {error !== undefined && (- <p className="px-2.5 py-1 text-xs text-red-500">{error}</p>- )}- {!loaded && error === undefined && (- <p className="px-2.5 py-1 text-xs text-gray-400">{S.common.loading}</p>- )}- {loaded &&- renderGroupBody(- a.agentId,- tree.rowsByAgent.get(a.agentId) ?? [],- false,- tree.countsByAgent.get(a.agentId),- () => [a.agentId],- S.traces.empty,- )}- </div>- )}- </div>- );- })}- {orderedAgents.length > groupCap && (- <MoreRow- label={S.chat.moreGroups(orderedAgents.length - groupCap)}- onClick={() => setGroupCap((c) => c + TRACES_GROUP_PAGE_SIZE)}- className="mt-1"- />- )}- </>- ) : workspaceGroups.length === 0 ? (- <p className="px-2.5 pt-3 text-xs text-gray-400 dark:text-gray-600">- {S.chat.noSessions}- </p>- ) : (- <>- {workspaceGroups.slice(0, groupCap).map((group) => {- const collapsed = collapsedWsGroups.has(group.key);- const parts = partitionTraceRows(group.sessions);- /** This group's exact server share (per-Workspace fold) and its per-category fetch fan-out. */- const counts = workspaceGroupCounts.get(group.key);- const contributingAgents = [...new Set(group.sessions.map((s) => s.agentId))];- const agentsFor = (category: SessionCategory) => [- ...new Set([...(counts?.agents[category] ?? []), ...contributingAgents]),- ];- return (- <div key={group.key} className="pt-2.5">- <GroupHeader- open={!collapsed}- onToggle={() => toggleWsGroup(group.key)}- icon={- /* Folder opens and closes with the group */- <span className="shrink-0 text-gray-400 dark:text-gray-500">- <Icon d={collapsed ? FOLDER_ICON : FOLDER_OPEN_ICON} size={15} />- </span>- }- label={group.temp ? S.chat.tempWorkspaces : group.label}- count={Math.max(counts?.totals.active ?? 0, parts.active.length)}- {...(group.fullPath !== null ? { title: group.fullPath } : {})}- />- {/* A workspace group can span Agents: the group body fans folder loads and- "More" out per category to the Agents whose share of THIS group is- non-zero (plus the Agents already contributing loaded rows). */}- {collapsed- ? null- : renderGroupBody(- group.key,- group.sessions,- true,- counts?.totals,- agentsFor,- S.chat.noSessions,- )}- </div>- );- })}- {workspaceGroups.length > groupCap && (- <MoreRow- label={S.chat.moreGroups(workspaceGroups.length - groupCap)}- onClick={() => setGroupCap((c) => c + TRACES_GROUP_PAGE_SIZE)}- className="mt-1"- />- )}- </>- )}- </aside>-- <section className="min-w-0 flex-1 overflow-y-auto p-3 md:p-4">- {selection && activeFile ? (- <div className="mx-auto max-w-4xl space-y-4">- {/* Header: Session title + Trace file pagination (newest first) */}- <div className="flex flex-wrap items-center gap-2">- <p className="min-w-0 flex-1 truncate text-sm font-semibold">- {titleOf(selection.sessionId, selection.title)}- </p>- <div className="flex flex-wrap items-center gap-1">- <span className="mr-1 text-xs text-gray-400">{S.traces.filesTitle}</span>- {(visibleFiles ?? selection.files).map((f) => (- <button- key={f.index}- type="button"- onClick={() => setFileIndex(f.index)}- title={`${f.date} · ${formatBytes(f.sizeBytes)}`}- className={`rounded-md border px-2 py-0.5 font-mono text-xs transition-colors duration-150 ${- f.index === activeFile.index- ? "border-gray-400 bg-gray-200/70 font-semibold text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"- : "border-gray-200 text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"- }`}- >- #{String(f.index).padStart(3, "0")}- </button>- ))}- {/* Overflow control: reveals the remaining pills (styled like an inactive pill). */}- {visibleFiles !== null && selection.files.length > FILE_PILL_CAP && (- <button- type="button"- title={S.chat.loadMore}- aria-label={S.chat.loadMore}- onClick={() => setShowAllFiles(true)}- className="rounded-md border border-gray-200 px-2 py-0.5 font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"- >- +{selection.files.length - FILE_PILL_CAP}- </button>- )}- </div>- </div>- <div className="flex flex-wrap items-center gap-2">- {/* Date · size only — the session id stays in the data (selection, deep links) but never renders as text. */}- <p className="min-w-0 flex-1 truncate font-mono text-xs text-gray-400">- {activeFile.date} · {formatBytes(activeFile.sizeBytes)}- </p>- {/* Raw-file download for the selected Trace file (same styling as the inactive file pills). */}- <a- href={api.agentTraceDownloadUrl(- projectId,- selection.agentId,- selection.sessionId,- activeFile.index,- )}- download- className="inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"- >- <DownloadIcon size={ICON_SIZE.rowLead} />- {S.traces.exportFile}- </a>- </div>-- <TraceFileView- projectId={projectId}- agentId={selection.agentId}- sessionId={selection.sessionId}- index={activeFile.index}- highlight={highlight}- onHighlight={setHighlight}- />- </div>- ) : (- <EmptyState title={S.traces.selectSession} />- )}- </section>-- {/* Import dialog: the endpoint is per-Agent (the file's own session_meta cannot- name a local Agent — its agent_state path belongs to the exporting machine),- so the page-level button asks which Agent receives the file. Picking a file- confirms and starts the import; everything downstream (validation, 409 on a- duplicate session id, refresh + auto-select of the imported Session) is the- unchanged runImport flow. */}- <Modal open={importOpen} title={S.traces.importTrace} onClose={() => setImportOpen(false)}>- <div className="space-y-4">- <Select- label={S.traces.importAgent}- value={importAgentId}- onChange={(e) => setImportAgentId(e.target.value)}- >- {agents.map((a) => (- <option key={a.agentId} value={a.agentId}>- {agentDisplayName(a)}- </option>- ))}- </Select>- <div className="flex justify-end">- {/* File pick doubles as the confirm action (primary-button styling on a label- so the native picker opens without a detour). */}- <label className="inline-flex cursor-pointer items-center justify-center gap-1 rounded-md border border-[var(--accent-bg)] bg-[var(--accent-bg)] px-3 py-1.5 text-sm font-medium text-[var(--accent-fg)] transition-opacity hover:opacity-90">- <HiddenFileInput accept=".jsonl" onChange={onPickFile} />- <UploadIcon size={14} />- {S.traces.importPickFile}- </label>- </div>- </div>- </Modal>- </div>- );-}diff --git a/packages/web/src/features/traces/use-trace-tree.ts b/packages/web/src/features/traces/use-trace-tree.tsdeleted file mode 100644index 8cb3a500..00000000--- a/packages/web/src/features/traces/use-trace-tree.ts+++ /dev/null@@ -1,324 +0,0 @@-/**- * Data layer of the Trace page's directory tree — the traces-endpoint twin of the- * sessions store (state/sessions.tsx): paged per (Agent, category) against- * GET .../traces with limit+1 pages (splitPage), pooling rows by sessionId. Later- * fetches overwrite pooled rows: the server's bounded classification refines as its- * head-read caches warm up, and an overwrite moves a row into its true category- * bucket. Per-category totals and per-Workspace counts ride along on every paged- * response (no separate counts request).- */-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import type { SessionCategory, SessionCategoryCounts } from "@prismshadow/penguin-server/api";-import * as api from "../../api/endpoints";-import { apiErrorText } from "../../lib/api-error";-import { FOLDER_CATEGORIES, splitPage } from "../../lib/session-grouping";-import { TRACES_PAGE_SIZE, toSessionGroups } from "./trace-sessions";-import type { TraceSessionRow } from "./trace-sessions";--/** Page-state key of one (Agent, category) pair ("\0" never appears in Agent ids). */-const pairKey = (agentId: string, category: SessionCategory) => `${agentId}\0${category}`;--/** One pair's paging cursor (same convention as the sessions store: `fetched` counts rows consumed from the server's category stream). */-interface PagePosition {- hasMore: boolean;- fetched: number;-}--/** One fetched page, ready to merge. */-interface FetchedPage {- agentId: string;- category: SessionCategory;- items: TraceSessionRow[];- hasMore: boolean;- counts?: SessionCategoryCounts;- workspaceCounts?: Readonly<Record<string, SessionCategoryCounts>>;-}--export interface TraceTree {- /** agentId → its pooled rows (every fetched category), newest first by sessionId. */- rowsByAgent: ReadonlyMap<string, TraceSessionRow[]>;- /** All pooled rows (workspace-mode grouping input). */- allRows: TraceSessionRow[];- /** agentId → per-category totals over ALL of the Agent's Trace session groups. */- countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;- /** agentId → the same totals broken down by Workspace path (workspace-mode group headers). */- workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;- /** agentId → active-first-page load failure (inline tree error, mirroring the load-state-with-content rule). */- errorByAgent: ReadonlyMap<string, string>;- isLoadedFor: (agentId: string, category: SessionCategory) => boolean;- /** Whether the pair's active-first-page fetch is in flight (skeleton/loading states). */- isPendingFor: (agentId: string, category: SessionCategory) => boolean;- /** Whether the server still holds unfetched groups of a category — an unloaded pair answers from the counts. */- hasMoreFor: (agentId: string, category: SessionCategory) => boolean;- /** Fetches the active first page (+ counts) for each given Agent that has none yet (idempotent; safe to call from render effects). */- ensureFirstFor: (agentIds: string[]) => void;- /** Fetches a category's first page for each given unloaded Agent (skipped unless its counts hold anything) and the next page for each loaded one with more. */- loadMoreFor: (agentIds: string[], category: SessionCategory) => Promise<void>;- /** Drops and refetches one Agent's loaded pairs (post-import refresh), keeping open folders populated. */- refreshAgent: (agentId: string) => Promise<void>;-}--/**- * @param includeCli Mirror of the user's "show CLI sessions" preference: appended to- * every paged fetch (`cli=1`); flipping it resets and refetches the whole tree under- * the new filter, like the sessions store does.- */-export function useTraceTree(projectId: string | null, includeCli = false): TraceTree {- /** sessionId → pooled row (the newest fetch wins — see module doc). */- const [rows, setRows] = useState<ReadonlyMap<string, TraceSessionRow>>(new Map());- const [pageState, setPageState] = useState<ReadonlyMap<string, PagePosition>>(new Map());- const [countsByAgent, setCountsByAgent] = useState<ReadonlyMap<string, SessionCategoryCounts>>(- new Map(),- );- const [workspaceCountsByAgent, setWorkspaceCountsByAgent] = useState<- ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>- >(new Map());- const [errorByAgent, setErrorByAgent] = useState<ReadonlyMap<string, string>>(new Map());- const [pending, setPending] = useState<ReadonlySet<string>>(new Set());- // Generation counter: a Project switch invalidates in-flight responses.- const gen = useRef(0);- // Synchronous in-flight guard: ensureFirstFor runs from render effects, which can- // double-fire (StrictMode) before the async state update lands.- const inflight = useRef(new Set<string>());- const pageStateRef = useRef(pageState);- pageStateRef.current = pageState;- const countsRef = useRef(countsByAgent);- countsRef.current = countsByAgent;-- // Project switch / CLI-preference flip: drop everything (rows / cursors / counts are- // Project- and filter-scoped) — consumers' ensure effects then refetch under the new state.- useEffect(() => {- gen.current += 1;- inflight.current.clear();- const emptyPages = new Map<string, PagePosition>();- pageStateRef.current = emptyPages;- setRows(new Map());- setPageState(emptyPages);- setCountsByAgent(new Map());- setWorkspaceCountsByAgent(new Map());- setErrorByAgent(new Map());- setPending(new Set());- }, [projectId, includeCli]);-- const fetchPage = useCallback(- async (- pid: string,- agentId: string,- category: SessionCategory,- offset: number,- ): Promise<FetchedPage> => {- const res = await api.getAgentTraces(pid, agentId, {- offset,- limit: TRACES_PAGE_SIZE + 1,- category,- ...(includeCli ? { cli: true } : {}),- });- const page = splitPage(toSessionGroups(res), TRACES_PAGE_SIZE);- return {- agentId,- category,- items: page.items.map((g) => ({ ...g, agentId })),- hasMore: page.hasMore,- ...(res.counts !== undefined ? { counts: res.counts } : {}),- ...(res.workspaceCounts !== undefined ? { workspaceCounts: res.workspaceCounts } : {}),- };- },- [includeCli],- );-- /** Merges fetched pages: rows overwrite by sessionId, cursors advance, counts refresh to the newest response. */- const applyPages = useCallback((pages: FetchedPage[], resetPairsOf?: string) => {- setRows((prev) => {- const next = new Map(prev);- if (resetPairsOf !== undefined) {- for (const [sid, row] of prev) if (row.agentId === resetPairsOf) next.delete(sid);- }- for (const p of pages) for (const row of p.items) next.set(row.sessionId, row);- return next;- });- setPageState((prev) => {- const next = new Map(prev);- if (resetPairsOf !== undefined) {- for (const key of prev.keys()) if (key.startsWith(`${resetPairsOf}\0`)) next.delete(key);- }- for (const p of pages) {- const key = pairKey(p.agentId, p.category);- next.set(key, {- hasMore: p.hasMore,- fetched:- (resetPairsOf === undefined ? (prev.get(key)?.fetched ?? 0) : 0) + p.items.length,- });- }- return next;- });- for (const p of pages) {- if (p.counts) {- setCountsByAgent((prev) => new Map(prev).set(p.agentId, p.counts!));- }- if (p.workspaceCounts) {- setWorkspaceCountsByAgent((prev) => new Map(prev).set(p.agentId, p.workspaceCounts!));- }- }- }, []);-- const ensureFirstFor = useCallback(- (agentIds: string[]) => {- if (!projectId) return;- const targets = [...new Set(agentIds)].filter((agentId) => {- const key = pairKey(agentId, "active");- return !pageStateRef.current.has(key) && !inflight.current.has(key);- });- if (targets.length === 0) return;- const g = gen.current;- for (const agentId of targets) inflight.current.add(pairKey(agentId, "active"));- setPending((prev) => {- const next = new Set(prev);- for (const agentId of targets) next.add(pairKey(agentId, "active"));- return next;- });- setErrorByAgent((prev) => {- if (!targets.some((id) => prev.has(id))) return prev;- const next = new Map(prev);- for (const id of targets) next.delete(id);- return next;- });- void Promise.all(- targets.map(async (agentId) => {- try {- return await fetchPage(projectId, agentId, "active", 0);- } catch (e: unknown) {- if (g === gen.current) {- setErrorByAgent((prev) => new Map(prev).set(agentId, apiErrorText(e)));- }- return null;- }- }),- ).then((results) => {- for (const agentId of targets) inflight.current.delete(pairKey(agentId, "active"));- setPending((prev) => {- const next = new Set(prev);- for (const agentId of targets) next.delete(pairKey(agentId, "active"));- return next;- });- if (g !== gen.current) return;- applyPages(results.filter((r) => r !== null));- });- },- [projectId, fetchPage, applyPages],- );-- const loadMoreFor = useCallback(- async (agentIds: string[], category: SessionCategory) => {- if (!projectId) return;- const targets = [...new Set(agentIds)].filter((agentId) => {- const position = pageStateRef.current.get(pairKey(agentId, category));- if (position === undefined) return (countsRef.current.get(agentId)?.[category] ?? 0) > 0;- return position.hasMore;- });- if (targets.length === 0) return;- const g = gen.current;- const results = await Promise.all(- targets.map(async (agentId) => {- const offset = pageStateRef.current.get(pairKey(agentId, category))?.fetched ?? 0;- try {- return await fetchPage(projectId, agentId, category, offset);- } catch {- // Transient failure: leave the pair's state untouched (still unloaded /- // still has-more), so the affordance stays and the user can retry —- // the sessions store's convention.- return null;- }- }),- );- if (g !== gen.current) return;- applyPages(results.filter((r) => r !== null));- },- [projectId, fetchPage, applyPages],- );-- /** Post-import refresh: refetch the Agent's active first page plus every folder category already loaded (an open folder must not blank). */- const refreshAgent = useCallback(- async (agentId: string) => {- if (!projectId) return;- const categories: SessionCategory[] = [- "active",- ...FOLDER_CATEGORIES.filter((cat) => pageStateRef.current.has(pairKey(agentId, cat))),- ];- const g = gen.current;- const results = await Promise.all(- categories.map(async (category) => {- try {- return await fetchPage(projectId, agentId, category, 0);- } catch {- return null;- }- }),- );- if (g !== gen.current) return;- applyPages(- results.filter((r) => r !== null),- agentId,- );- },- [projectId, fetchPage, applyPages],- );-- const isLoadedFor = useCallback(- (agentId: string, category: SessionCategory) => pageState.has(pairKey(agentId, category)),- [pageState],- );-- const isPendingFor = useCallback(- (agentId: string, category: SessionCategory) => pending.has(pairKey(agentId, category)),- [pending],- );-- const hasMoreFor = useCallback(- (agentId: string, category: SessionCategory) => {- const position = pageState.get(pairKey(agentId, category));- if (position !== undefined) return position.hasMore;- // Unloaded pair: anything the counts report is by definition still unfetched.- return (countsByAgent.get(agentId)?.[category] ?? 0) > 0;- },- [pageState, countsByAgent],- );-- return useMemo<TraceTree>(() => {- const rowsByAgent = new Map<string, TraceSessionRow[]>();- for (const row of rows.values()) {- const list = rowsByAgent.get(row.agentId);- if (list) list.push(row);- else rowsByAgent.set(row.agentId, [row]);- }- // sessionId embeds the creation timestamp: sorting by it descending is the same- // newest-first order the server pages with.- for (const list of rowsByAgent.values()) {- list.sort((a, b) => b.sessionId.localeCompare(a.sessionId));- }- const allRows = [...rowsByAgent.values()].flat();- return {- rowsByAgent,- allRows,- countsByAgent,- workspaceCountsByAgent,- errorByAgent,- isLoadedFor,- isPendingFor,- hasMoreFor,- ensureFirstFor,- loadMoreFor,- refreshAgent,- };- }, [- rows,- countsByAgent,- workspaceCountsByAgent,- errorByAgent,- isLoadedFor,- isPendingFor,- hasMoreFor,- ensureFirstFor,- loadMoreFor,- refreshAgent,- ]);-}diff --git a/packages/web/src/lib/nav-group-collapse.ts b/packages/web/src/lib/nav-group-collapse.tsindex 9460f79a..56db876c 100644--- a/packages/web/src/lib/nav-group-collapse.ts+++ b/packages/web/src/lib/nav-group-collapse.ts@@ -17,9 +17,8 @@* Page entries of the collapsible nav group, in rendered order. Each key names its* route (`/<key>`), its S.nav label, and its NAV_ICONS glyph — the sidebar derives* its nav rows from this manifest, so the covered range is pinned here (and in the- * unit tests) rather than duplicated. Traces is deliberately absent: the Trace panel- * lives in the chat toolbar's panel switcher, and the /traces browsing page stays- * addressable by URL (the Benchmark page's per-run Session links still point at it).+ * unit tests) rather than duplicated. Traces is deliberately absent: reading a Trace+ * happens in the chat toolbar's panel switcher, which is the only place it happens.*/export const NAV_GROUP_KEYS = ["agents", "skills", "models", "usage", "benchmark"] as const;export type NavGroupKey = (typeof NAV_GROUP_KEYS)[number];diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 15c64ba8..810c9f1a 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -91,6 +91,16 @@ export const en: Strings = {showCliSessions: "Show CLI sessions",showCliSessionsInfo:"Off, the conversation list holds only Sessions created in the Web App and is served straight from the database. On, the Trace directories are scanned too and CLI-created Sessions are listed alongside them. Applies to this account only.",+ /** Trace import (below the CLI-sessions filter): the two pickers' accessible names, the pick-a-file action, and its outcomes. */+ importTrace: "Import Trace",+ importTraceInfo:+ "Upload a .jsonl Trace exported from another install and it becomes a conversation of the chosen Agent. Both halves of the destination are picked here: the endpoint is per-Agent — a Trace file's own session_meta cannot name a local Agent, since its agent_state path belongs to the machine that exported it — and the Project is asked for because this dialog does not show which one is open, which also means a Trace can go to a Project other than the open one. Exporting happens in a conversation's Trace panel.",+ importTraceProject: "Import into project",+ importTraceAgent: "Import into agent",+ importTracePick: "Choose file",+ importTraceRunning: "Importing…",+ importTraceDone: (target: string) => `Trace imported into ${target}`,+ importTraceTooLarge: "The file exceeds the 14MB limit.",/** Admin-only sub-page (server-global); its explanation is disclosed at the pane heading. */proxyTitle: "Proxy options",proxyInfo:@@ -1555,8 +1565,6 @@ Scenarios:/** Visible label on the Memory panel's header link (not a tooltip-only glyph): says what the click does and where it lands. */openAgentMemory: "Manage in agent settings",memoryShowMore: (n: number) => `Show ${n} more`,- /** Reveal the next page of the Trace page's group tree; n = groups still hidden. */- moreGroups: (n: number) => `More groups (${n})`,/** Sidebar group pagination (#139): the pager's step buttons and the "2/5" readout's accessible name. */prevGroupPage: "Previous groups",nextGroupPage: "Next groups",@@ -1814,8 +1822,8 @@ Scenarios:`Page ${page} / ${pages} · ${total} total`,},+ /** The Trace panel's own view of a Trace file (trace-file-view / timeline-chart); the standalone browsing page these once also served is gone. */traces: {- title: "Traces",timeline: "Execution timeline",laneLLM: "Model",kindThinking: "thinking",@@ -1839,25 +1847,16 @@ Scenarios:linkHint:"Hover a timeline segment or event row to cross-highlight, click a segment to jump to its message; legend highlights its kind; drag the bar below to pan/zoom",filesTitle: "Trace files",- selectSession: "Select a Session on the left",toolCalls: "Tool calls",taskInput: "Input tokens this turn",taskOutput: "Output tokens this turn",cacheHit: "Cache hits",hitRate: "Hit rate",compactions: "compactions",- empty: "No Traces for this agent",inProgress: "in progress",systemPrompt: "System prompt",toolDefs: (n: number) => `Tool definitions (${n})`,exportFile: "Export",- importTrace: "Import Trace",- /** Import dialog: which Agent receives the file (the endpoint is per-Agent). */- importAgent: "Import into Agent",- importPickFile: "Choose file",- importing: "Importing…",- /** Client-side pre-check before reading the picked file (same cap as the server's import route). */- fileTooLarge: "The file exceeds the 14MB limit.",},benchmark: {diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex a1c0cc44..c27cab14 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -99,6 +99,16 @@ export const zh = {showCliSessions: "显示 CLI 会话",showCliSessionsInfo:"关闭时会话列表只列出在 Web 端创建的会话,直接由数据库返回;开启后会额外扫描轨迹目录,把 CLI 创建的会话一并列出。仅影响当前账号。",+ /** Trace import (below the CLI-sessions filter): the two pickers' accessible names, the pick-a-file action, and its outcomes. */+ importTrace: "导入 Trace",+ importTraceInfo:+ "上传从其他部署导出的 .jsonl 轨迹文件,它会成为所选 Agent 的一个会话。目的地的两个部分都在这里选择:导入接口按 Agent 划分——轨迹文件自带的 session_meta 无法指认本机的 Agent,其中的 agent_state 路径属于导出它的那台机器——而 Project 需要明确指定,因为本对话框不显示当前是哪一个,也因此可以导入到当前打开之外的 Project。导出在对话的 Trace 面板中进行。",+ importTraceProject: "导入到 Project",+ importTraceAgent: "导入到 Agent",+ importTracePick: "选择文件",+ importTraceRunning: "导入中…",+ importTraceDone: (target: string) => `轨迹已导入到 ${target}`,+ importTraceTooLarge: "文件超过 14MB 上限。",/** Admin-only sub-page (server-global); its explanation is disclosed at the pane heading. */proxyTitle: "代理选项",proxyInfo: "服务器全局设置,保存后立即生效,无需重启。回环地址始终直连。",@@ -1514,8 +1524,6 @@ Benchmark:/** Visible label on the Memory panel's header link (not a tooltip-only glyph): says what the click does and where it lands. */openAgentMemory: "在 Agent 设置中管理",memoryShowMore: (n: number) => `显示其余 ${n} 条`,- /** Reveal the next page of the Trace page's group tree; n = groups still hidden. */- moreGroups: (n: number) => `更多分组(${n})`,/** Sidebar group pagination (#139): the pager's step buttons and the "2/5" readout's accessible name. */prevGroupPage: "上一页分组",nextGroupPage: "下一页分组",@@ -1771,8 +1779,8 @@ Benchmark:`第 ${page} / ${pages} 页 · 共 ${total} 条`,},+ /** The Trace panel's own view of a Trace file (trace-file-view / timeline-chart); the standalone browsing page these once also served is gone. */traces: {- title: "轨迹观测",timeline: "执行时间线",laneLLM: "模型",kindThinking: "思考",@@ -1796,26 +1804,17 @@ Benchmark:linkHint:"鼠标移到时间线段或消息行即可联动高亮,点击时间线段跳转到对应消息;图例可高亮同类;拖动下方滑块平移/缩放",filesTitle: "Trace 文件",- selectSession: "在左侧选择一个 Session",toolCalls: "工具调用",taskInput: "本轮输入 tokens",taskOutput: "本轮输出 tokens",cacheHit: "命中缓存",hitRate: "命中率",compactions: "压缩次数",- /** The round-card badge reuses `chat.compactionTitle`, which names the mode (压缩 / 清空), so the Trace page and the conversation cannot drift apart; there is deliberately no Trace-local copy of that word. */- empty: "该 Agent 暂无 Trace",+ /** The round-card badge reuses `chat.compactionTitle`, which names the mode (压缩 / 清空), so the Trace view and the conversation cannot drift apart; there is deliberately no Trace-local copy of that word. */inProgress: "进行中",systemPrompt: "系统提示词",toolDefs: (n: number) => `工具定义(${n})`,exportFile: "导出",- importTrace: "导入 Trace",- /** Import dialog: which Agent receives the file (the endpoint is per-Agent). */- importAgent: "导入到 Agent",- importPickFile: "选择文件",- importing: "导入中…",- /** Client-side pre-check before reading the picked file (same cap as the server's import route). */- fileTooLarge: "文件超过 14MB 上限。",},benchmark: {diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsxindex 80c87135..25bce148 100644--- a/packages/web/src/router.tsx+++ b/packages/web/src/router.tsx@@ -15,7 +15,6 @@ import { AgentSettingsPage } from "./features/agents/agent-settings-page";import { SkillsPage } from "./features/skills/skills-page";import { ModelsPage } from "./features/models/models-page";import { UsagePage } from "./features/usage/usage-page";-import { TracesPage } from "./features/traces/traces-page";import { BenchmarkPage } from "./features/benchmark/benchmark-page";import { TerminalPage } from "./features/terminal/terminal-page";@@ -73,7 +72,6 @@ export function AppRouter() {<Route path="/skills" element={<SkillsPage />} /><Route path="/models" element={<ModelsPage />} /><Route path="/usage" element={<UsagePage />} />- <Route path="/traces" element={<TracesPage />} /><Route path="/benchmark" element={<BenchmarkPage />} />{/* System settings and user management live in the settings dialog now (seeSettingsDialog); their old routes fall through to the catch-all. */}diff --git a/packages/web/test/group-list.test.ts b/packages/web/test/group-list.test.tsindex 34aee36b..e9a0992d 100644--- a/packages/web/test/group-list.test.ts+++ b/packages/web/test/group-list.test.ts@@ -57,9 +57,9 @@ describe("list-options glyphs", () => {expect(SORT_MODE_ICONS).toEqual({ recent: CLOCK_ICON, manual: REORDER_ICON });});- it("is what the menu rows and the header toggle both actually render", () => {+ it("is what the list-options menu actually renders", () => {// The claim worth pinning is not the map's contents but that nothing re-picks an icon- // beside it: a hardcoded glyph at either call site is how the toggle and the menu would+ // beside it: a hardcoded glyph at a call site is how a row and the mode it names would// drift apart. Node-only suite, so this reads the sources (title-reveal.test.ts).const read = (p: string) =>readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), p), "utf8");@@ -68,8 +68,6 @@ describe("list-options glyphs", () => {expect(sidebar).toContain(`icon={GROUP_MODE_ICONS.${mode}}`);for (const mode of ["recent", "manual"] satisfies SessionSortMode[])expect(sidebar).toContain(`icon={SORT_MODE_ICONS.${mode}}`);- // The header toggle reads the same map rather than the raw constants.- expect(read("../src/components/ui/group-list.tsx")).toContain("GROUP_MODE_ICONS.workspace");});it("gives every row a glyph that differs, so an icon distinguishes rather than decorates", () => {diff --git a/packages/web/test/trace-sessions.test.ts b/packages/web/test/trace-sessions.test.tsdeleted file mode 100644index 6b3fbde5..00000000--- a/packages/web/test/trace-sessions.test.ts+++ /dev/null@@ -1,107 +0,0 @@-/**- * Trace page Session-list logic (pure): mapping both server response shapes to the- * page's Session groups, and partitioning rows by their server-classified category.- */-import { describe, expect, it } from "vitest";-import type { AgentTracesResponse } from "@prismshadow/penguin-server/api";-import { SIDEBAR_GROUP_PAGE_SIZE, SIDEBAR_PAGE_SIZE } from "../src/lib/session-grouping";-import {- TRACES_GROUP_PAGE_SIZE,- TRACES_PAGE_SIZE,- partitionTraceRows,- toSessionGroups,-} from "../src/features/traces/trace-sessions";-import type { TraceSessionRow } from "../src/features/traces/trace-sessions";--describe("trace page thresholds", () => {- it("stay larger than the sidebar's (full-height page column vs narrow sidebar), and bounded", () => {- expect(TRACES_PAGE_SIZE).toBeGreaterThan(SIDEBAR_PAGE_SIZE);- expect(TRACES_GROUP_PAGE_SIZE).toBeGreaterThan(SIDEBAR_GROUP_PAGE_SIZE);- // The fetch limit is TRACES_PAGE_SIZE + 1; the server caps limit at 1000.- expect(TRACES_PAGE_SIZE + 1).toBeLessThanOrEqual(1000);- });-});--const S1 = "session-2026-07-05-10-00-00-aabbccdd";-const S2 = "session-2026-07-06-09-00-00-11112222";--describe("toSessionGroups", () => {- it("paged response: server order kept, titles/classification carried, files re-sorted newest first", () => {- const res: AgentTracesResponse = {- dates: [],- sessions: [- {- sessionId: S2,- title: "标题",- category: "subagent",- workspace: "/ws/one",- files: [- { index: 1, date: "2026-07-06", sizeBytes: 10 },- { index: 2, date: "2026-07-07", sizeBytes: 20 },- ],- },- {- sessionId: S1,- category: "active",- workspace: "",- files: [{ index: 1, date: "2026-07-05", sizeBytes: 5 }],- },- ],- totalSessions: 12,- };- const groups = toSessionGroups(res);- expect(groups.map((g) => g.sessionId)).toEqual([S2, S1]);- expect(groups[0]!.title).toBe("标题");- expect(groups[0]!.category).toBe("subagent");- expect(groups[0]!.workspace).toBe("/ws/one");- expect(groups[0]!.files.map((f) => f.index)).toEqual([2, 1]); // newest first for display- expect(groups[1]!.title).toBeUndefined();- });-- it("legacy response: flattens date groups (merging a Session's files across dates), Sessions sorted by id descending, classification defaulted", () => {- const res: AgentTracesResponse = {- dates: [- {- date: "2026-07-06",- sessions: [- { sessionId: S2, files: [{ index: 1, sizeBytes: 1 }] },- { sessionId: S1, files: [{ index: 2, sizeBytes: 2 }] },- ],- },- { date: "2026-07-05", sessions: [{ sessionId: S1, files: [{ index: 1, sizeBytes: 3 }] }] },- ],- };- const groups = toSessionGroups(res);- expect(groups.map((g) => g.sessionId)).toEqual([S2, S1]);- // S1's files merged across both dates, each carrying its own date, newest first.- expect(groups[1]!.files).toEqual([- { index: 2, date: "2026-07-06", sizeBytes: 2 },- { index: 1, date: "2026-07-05", sizeBytes: 3 },- ]);- // No classification in the legacy shape: rows default to the active bucket / unknown workspace.- expect(groups[0]!.category).toBe("active");- expect(groups[0]!.workspace).toBe("");- });-});--describe("partitionTraceRows", () => {- it("splits rows by their server-classified category, preserving input order", () => {- const row = (sessionId: string, category: TraceSessionRow["category"]): TraceSessionRow => ({- sessionId,- category,- workspace: "",- files: [],- agentId: "a1",- });- const parts = partitionTraceRows([- row("s-4", "archived"),- row("s-3", "active"),- row("s-2", "subagent"),- row("s-1", "active"),- ]);- expect(parts.active.map((r) => r.sessionId)).toEqual(["s-3", "s-1"]);- expect(parts.subagent.map((r) => r.sessionId)).toEqual(["s-2"]);- expect(parts.schedule).toEqual([]);- expect(parts.archived.map((r) => r.sessionId)).toEqual(["s-4"]);- });-});