Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

perf(server,web,ui): 长会话与 Trace 文件打开不再卡(上游 b8862716 移植)

lmliheng819c31c10724
diff --git a/changelog/unreleased/2026-10-03-load-performance.md b/changelog/unreleased/2026-10-03-load-performance.md
new file mode 100644
index 00000000..7dc814d7
--- /dev/null
+++ b/changelog/unreleased/2026-10-03-load-performance.md
@@ -0,0 +1,55 @@
+# Long conversations and long Trace files open without stalling
+
+- **Date:** 2026-10-03
+- **Type:** fix
+- **Scope:** `web`, `server`, `docs`
+- **PR:** [#958](https://github.com/Prism-Shadow/penguin-harness/pull/958)
+
+[中文版](2026-10-03-load-performance.zh.md)
+
+A long conversation, and a long Trace file in the Trace panel, no longer stall the page while
+they load. The chat opens on fewer Tasks, a history page is bounded in bytes and carries its
+pictures as links, and the Trace panel reads one turn at a time instead of the whole file.
+
+## History window
+
+- A conversation opens on its newest 20 Q&A pairs (was 50), and each scroll to the top loads 20
+ more (was 50).
+- A windowed history page (`GET /api/sessions/:sessionId/messages` with `tailLimit` or `before`)
+ also stops before the Task that would take it past 4 MiB of serialized messages, but always
+ holds at least one Task. A page cut short carries its `before` cursor like any other.
+
+## Trace panel
+
+- Opening a Trace file requests its analysis, then the events of its newest turn only, by that
+ turn's message range (at most 1000 events per request), instead of every event in the file.
+ The newest turn opens expanded and is scrolled into view; the others stay collapsed with their
+ chips and read their own range the first time they are expanded.
+- The panel draws the newest 50 turn cards; an "N earlier turns" control above them draws 50
+ more per click.
+- A refresh during a run re-reads the analysis and only the expanded turns whose range moved,
+ keeping their rows on screen until the read lands; a new turn opens expanded only when the
+ newest one was open. A turn whose read failed shows the error in place of its rows and is
+ retried when reopened or on the next refresh.
+- The context ring reads the analysis' new `modelContextWindow` (the window in the file's head
+ `session_meta`), and 128k when an older server sends none.
+- A turn's events still carry their images inline as `data:` URLs, so a turn holding
+ screenshots can weigh megabytes; reading them by reference is left to a follow-up.
+
+## Trace events endpoint
+
+- The Trace event reads (`GET /api/projects/:projectId/agents/:agentId/traces/:sessionId/:index`
+ and `GET /api/sessions/:sessionId/traces/:index`) serve each page from a per-file line index
+ (record byte offsets, kept for 32 files and extended as a file grows) with one ranged read,
+ instead of parsing the whole file for every page.
+
+## Images by reference
+
+- A windowed history page replaces each PNG, JPEG, GIF or WebP `data:` URL of a main-session
+ record (a user's `image_url`, or an entry of a tool output's `images`) with
+ `/api/sessions/:sessionId/trace-image?file=<fileIndex>&ordinal=<ordinal>[&i=<k>]`. The new route
+ decodes that image from the Trace record and answers it with an immutable private cache.
+ Subagent messages, held inputs not yet in the Trace, other image types and the parameterless
+ full read keep their `data:` URLs.
+- The chat fetches these images from the machine the Session lives on, and only as they near the
+ viewport. An image the stream delivered inline while the page was being read still shows once.
diff --git a/changelog/unreleased/2026-10-03-load-performance.zh.md b/changelog/unreleased/2026-10-03-load-performance.zh.md
new file mode 100644
index 00000000..ebb78bb7
--- /dev/null
+++ b/changelog/unreleased/2026-10-03-load-performance.zh.md
@@ -0,0 +1,32 @@
+# 长对话与长 Trace 文件打开不再卡顿
+
+- **Date:** 2026-10-03
+- **Type:** fix
+- **Scope:** `web`, `server`, `docs`
+- **PR:** [#958](https://github.com/Prism-Shadow/penguin-harness/pull/958)
+
+[English](2026-10-03-load-performance.md)
+
+长对话以及 Trace 面板中的长 Trace 文件,加载时不再让页面卡住。对话打开时加载的 Task 更少,历史分页有字节上限、图片改为链接下发,Trace 面板按轮次逐个读取,不再读取整个文件。
+
+## 历史窗口
+
+- 打开对话时加载最新 20 个问答对(原为 50),每次滚动到顶部再加载 20 个(原为 50)。
+- 分窗读取的历史页(带 `tailLimit` 或 `before` 的 `GET /api/sessions/:sessionId/messages`)另受字节预算约束:加入下一个 Task 会使序列化后的消息超过 4 MiB 时即提前收口,但一页至少含一个 Task。提前收口的页同样带 `before` 游标。
+
+## Trace 面板
+
+- 打开 Trace 文件时先请求其分析结果,再按最新一轮的消息范围只读取该轮事件(每次请求至多 1000 条),不再读取文件中的全部事件。最新一轮默认展开并滚动到可见位置;其余轮次折叠、只显示统计标签,首次展开时才读取各自范围内的事件。
+- 面板渲染最新 50 个轮次卡片,其上方的「更早的 N 轮」每点一次再展示 50 轮。
+- 运行中刷新时重新请求分析结果,只重读范围有变化的已展开轮次,新结果到达前保留已显示的消息;仅当最新一轮处于展开状态时,新出现的一轮才自动展开。读取失败的轮次在消息位置显示错误,重新展开或下次刷新时重试。
+- 上下文圆环读取分析结果新增的 `modelContextWindow`(文件开头 `session_meta` 中的上下文窗口),旧版服务端未提供时按 128k 计。
+- 轮次事件中的图片仍以 `data:` URL 内联下发,含截图的一轮可能达数 MB;改为按引用读取留待后续。
+
+## Trace 事件接口
+
+- Trace 事件读取(`GET /api/projects/:projectId/agents/:agentId/traces/:sessionId/:index` 与 `GET /api/sessions/:sessionId/traces/:index`)每页由按文件维护的行索引(记录的字节偏移,最多缓存 32 个文件,文件增长时增量扩展)一次范围读取得到,不再每页解析整个文件。
+
+## 图片按引用下发
+
+- 分窗历史页把主会话记录中的 PNG、JPEG、GIF、WebP `data:` URL(用户的 `image_url`,或工具输出 `images` 中的一项)替换为 `/api/sessions/:sessionId/trace-image?file=<fileIndex>&ordinal=<ordinal>[&i=<k>]`。新路由从 Trace 记录解码该图片,以不可变的私有缓存返回。子会话消息、尚未写入 Trace 的暂存输入、其他图片类型以及无参数的全量读取仍保留 `data:` URL。
+- 对话从 Session 所在的机器获取这些图片,且只在图片接近视口时才加载。读取历史页期间经流式通道内联到达的图片,仍只显示一次。
diff --git a/packages/docs/content/chat.en.md b/packages/docs/content/chat.en.md
index 15453ef2..18bde9d8 100644
--- a/packages/docs/content/chat.en.md
+++ b/packages/docs/content/chat.en.md
@@ -68,7 +68,7 @@ Limits apply at two moments:
- When you pick or drop a file: a file over the per-file size (100MB by default) or an image over 20MB is refused before anything is read, and the message names the limit in force.
- When you send: a message carries at most 20 files and 120MB in total by default. Over that, the send fails with "Too many files attached to one message." or "The request is too large."
-An admin can change both sizes under [Settings › Upload limits](/settings#upload-limits). The 20MB cap for images placed inline does not follow them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every Session resume.
+An admin can change both sizes under [Settings › Upload limits](/settings#upload-limits). The 20MB cap for images placed inline does not follow them: an inline image enters the conversation and the Trace, where its size is paid again on every Session resume.
On send, attached files are written into the Session's scratchpad, which is deleted with the Session. The conversation shows an "Attached files" notice; the file contents never enter the conversation, and the model opens each file by path with its file tools. On a model without image input, images are saved to the scratchpad the same way and passed as file paths, and a hint above the composer says so.
@@ -220,7 +220,7 @@ The fork is a new Session with the same agent, model, Workspace and approval mod
### Older messages
-A conversation opens on its latest 50 turns. Scroll near the top to load 50 more; your reading position stays in place. If loading fails, select "Failed to load earlier messages — click to retry". Once nothing older remains, "Beginning of conversation" marks the start. Turn numbers and header statistics count from the start of the conversation, so they match a full load.
+A conversation opens on its latest 20 turns. Scroll near the top to load 20 more; your reading position stays in place. A turn with a very large output can make one load hold fewer turns. Pictures load as they scroll into view. If loading fails, select "Failed to load earlier messages — click to retry". Once nothing older remains, "Beginning of conversation" marks the start. Turn numbers and header statistics count from the start of the conversation, so they match a full load.
To return to the newest message, select **Jump to latest**. In a longer conversation, ticks in the left margin mark each exchange: point at a tick to preview it, and select it to jump there. Where the margin has no room, such as on a phone, an **Outline** button in the toolbar lists the same exchanges.
@@ -388,7 +388,7 @@ On a Mac, ⌘ takes the place of Ctrl in Ctrl+S and in the Ctrl+Alt rows other t
| Attachments per message | 20 files |
| Attachment size | 100MB per file and 120MB per message by default; set by an admin under [Upload limits](/settings#upload-limits) |
| Shortcuts | 3 per user; name up to 40 characters, prompt up to 4000 |
-| History | The latest 50 turns on opening, then 50 more per load |
+| History | The latest 20 turns on opening, then 20 more per load; at most 4 MiB of messages per load, but always at least one turn |
| Conversation list | 10 conversations at a time per group or folder; 10 groups per page |
| Send to background | Offered after a call has run for 10 seconds |
| Retry countdown | Shown for waits of 2s or more |
diff --git a/packages/docs/content/chat.zh.md b/packages/docs/content/chat.zh.md
index be36aa64..122e9587 100644
--- a/packages/docs/content/chat.zh.md
+++ b/packages/docs/content/chat.zh.md
@@ -68,7 +68,7 @@ Session 创建后,Workspace 就锁定了;模型仍然可以换,见[切换
- 选择或拖入文件时:超过单个文件大小上限(默认 100MB)的文件,或超过 20MB 的图片,会在读取之前被拒绝,提示中写明当前生效的上限。
- 发送时:一条消息默认最多 20 个文件、合计 120MB,超出时发送失败,提示「一条消息附加的文件过多。」或「请求体过大。」
-管理员可以在[设置 › 上传限制](/settings#上传限制)中修改这两个大小。嵌入对话的图片另有 20MB 上限,不随它们变化:这类图片会进入对话和 Trace,此后每次翻阅历史、每次恢复 Session,都要再付出一次它的体积。
+管理员可以在[设置 › 上传限制](/settings#上传限制)中修改这两个大小。嵌入对话的图片另有 20MB 上限,不随它们变化:这类图片会进入对话和 Trace,此后每次恢复 Session,都要再付出一次它的体积。
发送时,附件写入 Session 的 scratchpad,随 Session 一起删除。对话中显示一条「附加文件」提示;文件内容本身不进入对话,模型用文件工具按路径逐个读取。如果模型不支持图片输入,图片也会这样存进 scratchpad、以文件路径传给模型,输入框上方会给出提示。
@@ -220,7 +220,7 @@ Task 运行时输入了内容,发送按钮的行为取决于 + 菜单底部的
### 更早的消息
-打开对话时只加载最近 50 轮。滚动到顶部附近会再加载 50 轮,阅读位置保持不动;加载失败时,点击「更早的对话加载失败,点击重试」。没有更早的内容时,顶部显示「已是对话开头」。轮次编号和顶部统计都从对话开头算起,与一次加载全部的结果一致。
+打开对话时只加载最近 20 轮。滚动到顶部附近会再加载 20 轮,阅读位置保持不动;某一轮的输出特别大时,一次加载的轮数会少一些。图片随滚动进入视野时才加载。加载失败时,点击「更早的对话加载失败,点击重试」。没有更早的内容时,顶部显示「已是对话开头」。轮次编号和顶部统计都从对话开头算起,与一次加载全部的结果一致。
要回到最新消息,选择**回到最新消息**。对话较长时,左侧留白处有一列刻度,每个刻度对应一轮问答:指向刻度可以预览,点击即跳转。留白放不下时(例如在手机上),工具栏会出现**对话索引**按钮,列出同样的内容。
@@ -388,7 +388,7 @@ Task 运行时输入了内容,发送按钮的行为取决于 + 菜单底部的
| 每条消息的附件数 | 20 个文件 |
| 附件大小 | 默认单个文件 100MB、单条消息合计 120MB;管理员可在[上传限制](/settings#上传限制)中修改 |
| 快捷指令 | 每个用户 3 条;名称最多 40 个字符,Prompt 最多 4000 个字符 |
-| 历史消息 | 打开时加载最近 50 轮,之后每次加载 50 轮 |
+| 历史消息 | 打开时加载最近 20 轮,之后每次加载 20 轮;每次加载的消息最多 4 MiB,但至少一轮 |
| 对话列表 | 每个分组或折叠夹一次显示 10 条对话;每页 10 个分组 |
| 转入后台执行 | 调用运行满 10 秒后提供 |
| 重试倒计时 | 等待 2 秒及以上时显示 |
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index ca522dd4..f8d728f8 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -648,7 +648,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
| GET | `/usage/errors` | One page of the error detail table, newest first: → `{items, total, rows}` |
| DELETE | `/usage/errors` | Empties the error table for the current filter: → `{deleted}` (Project owner only) |
| GET | `/agents/:agentId/traces` | Trace files as a date → Session drill-down |
-| GET | `/agents/:agentId/traces/:sessionId/:index` | Reads Trace events (`offset` / `limit` pagination) |
+| GET | `/agents/:agentId/traces/:sessionId/:index` | Reads Trace events (`offset` / `limit` pagination, served from a per-file line index) |
| GET | `/agents/:agentId/traces/:sessionId/:index/analysis` | Trace performance analysis |
| GET | `/agents/:agentId/traces/:sessionId/:index/download` | Downloads the raw Trace file (JSONL attachment) |
| POST | `/agents/:agentId/traces/import` | Imports a Trace file: `{dataBase64}` → `{sessionId, index, date}` |
@@ -683,6 +683,7 @@ Two conventions apply to every route here. A Session the caller cannot access al
| PATCH | `/` | Updates the Session: `{approvalMode?, thinkingLevel?, archived?, title?}` |
| DELETE | `/` | Deletes the Session, with its Traces and scratch files |
| GET | `/messages` | The OmniMessage history, in full or as a window of Tasks |
+| GET | `/trace-image?file=&ordinal=[&i=]` | One image of a Trace record, as a windowed `/messages` page references it |
| POST | `/fork` | Forks an idle Session after a completed assistant reply: `{position: {fileIndex, ordinal}}` → `{session}` |
| GET | `/stream` | The SSE event stream; see [Streaming (SSE)](#streaming-sse) |
| GET | `/context` | What the current model context is made of, and where compaction will start |
@@ -690,7 +691,8 @@ Two conventions apply to every route here. A Session the caller cannot access al
- `GET /` returns the Session's info. Unlike the list rows, the single-Session response also carries `tracePath`, the absolute path of the latest Trace file. `orgId` marks a Session that company mode's caches own (a desk session, or a session contributing to one of that organization's tickets); it is absent on every ordinary Session, and the list route sets it too.
- `PATCH /` with `thinkingLevel` pins the level on this Session durably, from its very next LLM request. The thinking level is soft-limited: it can change mid-context, at the cost of the provider's cached context, which is why the level picker advises compacting first. The pinned level comes back as `SessionInfo.thinkingLevel`; when that is absent, no level was ever pinned and the agent config applies.
-- `GET /messages` without parameters returns the full OmniMessage history. `tailLimit=n` reads the newest n Task-aligned units instead, and `before=<cursor>&limit=n` reads the n units before a cursor. The two forms are exclusive, `n` is between 1 and 1000, and `limit` defaults to 200. The bundled Web App opens a conversation on its latest 50 turns and loads earlier ones as you scroll. A windowed response carries `page`, with the cursor for the next page (`before`), the number of turns before the window (`earlierTurns`), the cumulative stats before it (`prior`), and the model of the context the window starts in (`contextModel`): a Session can switch models between contexts, and a window that starts partway into one does not hold the `session_meta` that names its model. While a Task runs, the response also carries `live`; see [The live field on GET /messages](#the-live-field-on-get-messages).
+- `GET /messages` without parameters returns the full OmniMessage history. `tailLimit=n` reads the newest n Task-aligned units instead, and `before=<cursor>&limit=n` reads the n units before a cursor. The two forms are exclusive, `n` is between 1 and 1000, and `limit` defaults to 200. A window also stays within 4 MiB of serialized messages: it stops before the unit that would pass that, but always holds at least one, so it can hold fewer units than asked for and still carry a `before` cursor. The bundled Web App opens a conversation on its latest 20 turns and loads 20 more each time you scroll to the top. A windowed response carries `page`, with the cursor for the next page (`before`), the number of turns before the window (`earlierTurns`), the cumulative stats before it (`prior`), and the model of the context the window starts in (`contextModel`): a Session can switch models between contexts, and a window that starts partway into one does not hold the `session_meta` that names its model. While a Task runs, the response also carries `live`; see [The live field on GET /messages](#the-live-field-on-get-messages).
+- A windowed page serves images by reference. In each record that carries a `tracePosition`, a PNG, JPEG, GIF or WebP `data:` URL, whether a user's `image_url` or an entry of a tool output's `images`, is replaced by `/api/sessions/:sessionId/trace-image?file=<fileIndex>&ordinal=<ordinal>`, with `&i=<k>` for the k-th entry of `images`. That route answers the decoded image with its own type, `Cache-Control: private, max-age=31536000, immutable` and `X-Content-Type-Options: nosniff`. It returns 404 `trace_image_not_found` when the record holds no such image, and 400 for a missing or malformed parameter. Subagent messages, other image types and the full read keep their `data:` URLs.
- `GET /context` returns the parts the current model context is made of, plus `compactionThreshold`: the context size, in tokens, at which the Session's next request starts compaction. That threshold is the agent's `compaction.max_context_length`, capped by the room the model's context window leaves. It is `null` when compaction is disabled, when the agent's config cannot be read, or when the threshold is not below the window. The route reads the newest Trace file on every call, so the figures are a snapshot rather than a live counter.
- `GET /goal` returns `{goal}`, which is `null` if the Session never ran a goal, or otherwise `{objective, status, budget, used, rounds}`. `status` is `active`, `complete`, `blocked`, `budget_limited` or `aborted`, and a `budget` of -1 means unlimited. A goal lives only inside its run, so a goal that still reads as active while the Session is not running is reported as `aborted`. See [Goal mode](/goal-mode).
@@ -864,7 +866,7 @@ GET /preview/<token>/<relative path> (unauthenticated; the token is th
| Method | Path | Description |
| --- | --- | --- |
| GET | `/traces` | Lists this Session's Trace files |
-| GET | `/traces/:index` | Reads Trace events (paginated) |
+| GET | `/traces/:index` | Reads Trace events (paginated, served from a per-file line index) |
| GET | `/traces/:index/analysis` | Trace performance analysis |
## Messaging Bindings (Feishu, Telegram, QQ, WeChat)
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index fc9a7da1..50d1d3f6 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -648,7 +648,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| GET | `/usage/errors` | 错误详情表的一页,按时间倒序:→ `{items, total, rows}` |
| DELETE | `/usage/errors` | 按当前过滤条件清空错误表:→ `{deleted}`(仅限 Project 所有者) |
| GET | `/agents/:agentId/traces` | Trace 文件,按日期 → Session 逐级下钻 |
-| GET | `/agents/:agentId/traces/:sessionId/:index` | 读取 Trace 事件(`offset` / `limit` 分页) |
+| GET | `/agents/:agentId/traces/:sessionId/:index` | 读取 Trace 事件(`offset` / `limit` 分页,由按文件维护的行索引提供) |
| GET | `/agents/:agentId/traces/:sessionId/:index/analysis` | Trace 性能分析 |
| GET | `/agents/:agentId/traces/:sessionId/:index/download` | 下载原始 Trace 文件(JSONL 附件) |
| POST | `/agents/:agentId/traces/import` | 导入 Trace 文件:`{dataBase64}` → `{sessionId, index, date}` |
@@ -683,6 +683,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| PATCH | `/` | 更新 Session:`{approvalMode?, thinkingLevel?, archived?, title?}` |
| DELETE | `/` | 删除 Session,连同它的 Trace 和暂存文件 |
| GET | `/messages` | OmniMessage 历史,全量或按 Task 窗口 |
+| GET | `/trace-image?file=&ordinal=[&i=]` | Trace 记录中的一张图片,即分窗 `/messages` 页引用的图片 |
| POST | `/fork` | 在一条已完成的助手回复之后分叉空闲的 Session:`{position: {fileIndex, ordinal}}` → `{session}` |
| GET | `/stream` | SSE 事件流;见[流式传输(SSE)](#流式传输sse) |
| GET | `/context` | 当前模型上下文的组成,以及压缩将从哪里开始 |
@@ -690,7 +691,8 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
- `GET /` 返回 Session 的信息。与列表行不同,单个 Session 的响应还带 `tracePath`,即最新 Trace 文件的绝对路径。`orgId` 标记公司模式缓存持有的会话(工位会话,或这个组织某个工单的贡献会话);普通 Session 一律不带这个字段,列表路由同样会设置它。
- `PATCH /` 带 `thinkingLevel` 会把这个思考等级持久地固定到这个 Session,从下一次 LLM 请求开始生效。思考等级是软性限制:可以在上下文中途更改,代价是损失供应商已缓存的上下文,因此等级选择器会建议先压缩。固定后的等级以 `SessionInfo.thinkingLevel` 返回;没有这个字段说明从未固定等级,此时采用 Agent 配置。
-- `GET /messages` 不带参数时返回完整的 OmniMessage 历史。`tailLimit=n` 改为读取最新的 n 个按 Task 对齐的单元,`before=<cursor>&limit=n` 读取某个游标之前的 n 个单元。两种形式互斥,`n` 在 1 到 1000 之间,`limit` 默认为 200。内置 Web App 打开一段对话时先显示最近 50 轮,滚动时再加载更早的内容。窗口式响应带 `page`,包含下一页的游标(`before`)、窗口之前的轮数(`earlierTurns`)、此前累计的统计(`prior`),以及窗口起点所在上下文的模型(`contextModel`):Session 可以在上下文之间切换模型,而从某个上下文中途开始的窗口并不包含记录其模型的那条 `session_meta`。Task 运行期间,响应还会带 `live`;见 [GET /messages 上的 live 字段](#get-messages-上的-live-字段)。
+- `GET /messages` 不带参数时返回完整的 OmniMessage 历史。`tailLimit=n` 改为读取最新的 n 个按 Task 对齐的单元,`before=<cursor>&limit=n` 读取某个游标之前的 n 个单元。两种形式互斥,`n` 在 1 到 1000 之间,`limit` 默认为 200。窗口还受 4 MiB 的序列化大小约束:加入某个单元会超出时就在它之前收口,但至少包含一个单元,所以窗口的单元数可能少于请求的数量,此时同样带 `before` 游标。内置 Web App 打开一段对话时先显示最近 20 轮,每次滚动到顶部再加载 20 轮。窗口式响应带 `page`,包含下一页的游标(`before`)、窗口之前的轮数(`earlierTurns`)、此前累计的统计(`prior`),以及窗口起点所在上下文的模型(`contextModel`):Session 可以在上下文之间切换模型,而从某个上下文中途开始的窗口并不包含记录其模型的那条 `session_meta`。Task 运行期间,响应还会带 `live`;见 [GET /messages 上的 live 字段](#get-messages-上的-live-字段)。
+- 窗口式响应中的图片按引用下发。在带 `tracePosition` 的记录里,PNG、JPEG、GIF 或 WebP 的 `data:` URL(无论是用户的 `image_url`,还是工具输出 `images` 中的一项)会被替换为 `/api/sessions/:sessionId/trace-image?file=<fileIndex>&ordinal=<ordinal>`,`images` 的第 k 项再加 `&i=<k>`。这条路由返回解码后的图片,带图片自身的类型、`Cache-Control: private, max-age=31536000, immutable` 和 `X-Content-Type-Options: nosniff`。记录中没有对应图片时返回 404 `trace_image_not_found`,参数缺失或格式不对时返回 400。子 Agent 的消息、其他类型的图片以及全量读取都保留原来的 `data:` URL。
- `GET /context` 返回当前模型上下文的各个组成部分,外加 `compactionThreshold`:上下文达到多大(以 Token 计)时,Session 的下一个请求会开始压缩。这个阈值就是 Agent 的 `compaction.max_context_length`,上限不超过模型上下文窗口的剩余空间。压缩未启用、读不到 Agent 配置,或阈值不低于窗口时,这个值是 `null`。这条路由每次调用都读取最新的 Trace 文件,所以数值是快照,不是实时计数器。
- `GET /goal` 返回 `{goal}`:Session 从未跑过目标时为 `null`,否则为 `{objective, status, budget, used, rounds}`。`status` 取值为 `active`、`complete`、`blocked`、`budget_limited` 或 `aborted`,`budget` 为 -1 表示不限制。目标只存活在它的运行期间,所以 Session 已停止运行、目标却仍是 active 时,会报告为 `aborted`。见[目标模式](/goal-mode)。
@@ -864,7 +866,7 @@ GET /preview/<token>/<relative path> (unauthenticated; the token is th
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/traces` | 列出当前 Session 的 Trace 文件 |
-| GET | `/traces/:index` | 读取 Trace 事件(分页) |
+| GET | `/traces/:index` | 读取 Trace 事件(分页,由按文件维护的行索引提供) |
| GET | `/traces/:index/analysis` | Trace 性能分析 |
## 消息渠道绑定(飞书、Telegram、QQ、微信)
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index c85b0226..1b733dd9 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1856,7 +1856,10 @@ export interface MessagesLiveTail {
* only; the parameterless full read never carries it). A window is a run of whole
* message-bearing units — one unit = one Task in the Web reducer's sense, opened by a
* main-session user prompt — cut so that no pairing (tool_call/output), compaction span
- * or steering group ever splits across windows.
+ * or steering group ever splits across windows. Besides the unit count, a window stops
+ * before the unit that would take its serialized messages past 4 MiB, but always holds at
+ * least one unit; such a window carries `before` like any other, with fewer units than
+ * asked for.
*/
export interface MessagesPageInfo {
/**
@@ -1904,6 +1907,15 @@ export interface MessagesPageInfo {
/** Message history: the full messages and events from concatenating all of this Session's Trace files in order (excludes partial_*). */
export interface MessagesResponse {
+ /**
+ * On windowed requests, images are served by reference: in every record that carries a
+ * `tracePosition`, an inline PNG / JPEG / GIF / WebP `data:` URL — a user `image_url`, or
+ * an entry of a tool output's `images` — is replaced by
+ * `/api/sessions/<sessionId>/trace-image?file=<fileIndex>&ordinal=<ordinal>[&i=<k>]`
+ * (`i` = the index into `images`), an immutable, access-checked image response. Expanded
+ * subagent messages, held inputs not yet in the Trace, other image types and the
+ * parameterless full read keep their data URLs.
+ */
messages: HistoryMessage[];
/**
* Present only while the Session is running/compacting: the in-progress stream tail
@@ -2919,7 +2931,10 @@ export interface TraceEventsResponse {
events: OmniMessage[];
offset: number;
limit: number;
- /** Total line count of the file (basis for pagination). */
+ /**
+ * Record count of the file (basis for pagination), in the ordinals `tracePosition` and the
+ * analysis' `messageFrom` / `messageTo` use: malformed lines are not records.
+ */
total: number;
}
@@ -3239,6 +3254,13 @@ export interface TraceAnalysisResponse {
* scope every total here shares). Absent exactly when the turns carry no `cost`.
*/
cost?: number;
+ /**
+ * The model's context window as the file's head `session_meta` records it
+ * (`model_context_window`), for the context ring. The panel no longer reads every event, so the
+ * analysis carries it; absent when the head records none (an older server, or a file without
+ * one), and the panel then falls back as it always has.
+ */
+ modelContextWindow?: number | string;
requests: RequestSpan[];
/** Token / duration aggregated per Task (used directly by the Trace page's context ring and per-turn TPS). */
tasks: TraceTaskStats[];
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index c45c1a32..47aec411 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -44,6 +44,7 @@ import type {
import { compactionThresholdFor } from "../../services/context-breakdown.js";
import { decodeCursor } from "../../services/message-window.js";
import type { MessagesPageRequest } from "../../services/trace-service.js";
+import { withImagesByReference } from "../../services/trace-images.js";
import { PREVIEW_TOKEN_TTL_MS, resolvePreviewTarget } from "../../services/preview-token.js";
import type { AppEnv } from "../../auth/middleware.js";
import type { SessionRow } from "../../db/repos/sessions.js";
@@ -57,6 +58,7 @@ import {
optionalPagingQuery,
optionalString,
paginationQuery,
+ parseNonNegativeInt,
pathParam,
positiveIntParam,
readJson,
@@ -897,6 +899,40 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
});
});
+ // One image of one Trace record, the URL a windowed history page puts in place of an
+ // inline data URL (services/trace-images.ts). The record never changes, so the answer is
+ // immutable; only inert raster types are ever served (the page references nothing else).
+ app.get("/:sessionId/trace-image", async (c) => {
+ const row = resolveSession(c);
+ const intQuery = (name: string, min: number): number | undefined => {
+ const raw = c.req.query(name);
+ if (raw === undefined) return undefined;
+ const v = parseNonNegativeInt(raw);
+ if (v === null || v < min) {
+ throw badRequest(`${name} must be an integer of at least ${min}.`);
+ }
+ return v;
+ };
+ const fileIndex = intQuery("file", 1);
+ const ordinal = intQuery("ordinal", 0);
+ if (fileIndex === undefined || ordinal === undefined) {
+ throw badRequest("file and ordinal are required.");
+ }
+ const image = await deps.traceService.readTraceImage(
+ row.projectId,
+ row.agentId,
+ row.sessionId,
+ fileIndex,
+ ordinal,
+ intQuery("i", 0),
+ );
+ return c.body(new Uint8Array(image.bytes), 200, {
+ "content-type": image.mime,
+ "x-content-type-options": "nosniff",
+ "cache-control": "private, max-age=31536000, immutable",
+ });
+ });
+
app.get("/:sessionId/messages", async (c) => {
const row = resolveSession(c);
const page = messagesPageQuery(c);
@@ -959,8 +995,13 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
},
...(result.contextModel !== undefined ? { contextModel: result.contextModel } : {}),
};
+ // Images by reference, after the held inputs were merged: the dedup compares raw
+ // envelopes, and a held input carries its image inline exactly as its Trace copy does.
+ const messages = appendPendingInputs(result.messages, pendingInputs).map((m) =>
+ withImagesByReference(row.sessionId, m),
+ );
return c.json({
- messages: appendPendingInputs(result.messages, pendingInputs),
+ messages,
...(live !== undefined ? { live } : {}),
page: info,
} satisfies MessagesResponse);
diff --git a/packages/server/src/http/validate.ts b/packages/server/src/http/validate.ts
index 6cde4653..4a5c543a 100644
--- a/packages/server/src/http/validate.ts
+++ b/packages/server/src/http/validate.ts
@@ -50,7 +50,7 @@ export function requireValidId(c: Context, name: string): string {
* isSafeInteger (not isInteger) additionally rejects overlong runs like
* "99999999999999999999", which parse to an imprecise float (1e20).
*/
-function parseNonNegativeInt(raw: string): number | null {
+export function parseNonNegativeInt(raw: string): number | null {
if (!/^\d+$/.test(raw)) return null;
const v = Number.parseInt(raw, 10);
return Number.isSafeInteger(v) ? v : null;
diff --git a/packages/server/src/mechanisms/traces.ts b/packages/server/src/mechanisms/traces.ts
index b3f96f7f..0efa8d2f 100644
--- a/packages/server/src/mechanisms/traces.ts
+++ b/packages/server/src/mechanisms/traces.ts
@@ -162,6 +162,14 @@ export abstract class Traces {
offset: number,
limit: number,
): Promise<TraceEventsResponse>;
+ abstract readTraceImage(
+ projectId: string,
+ agentId: string,
+ sessionId: string,
+ fileIndex: number,
+ ordinal: number,
+ slot: number | undefined,
+ ): Promise<{ mime: string; bytes: Buffer }>;
abstract analyze(
projectId: string,
agentId: string,
diff --git a/packages/server/src/services/trace-images.ts b/packages/server/src/services/trace-images.ts
new file mode 100644
index 00000000..d06e82f5
--- /dev/null
+++ b/packages/server/src/services/trace-images.ts
@@ -0,0 +1,100 @@
+/**
+ * Images by reference on windowed history pages.
+ *
+ * A Trace stores images inline, as base64 `data:` URLs: the user's `image_url` records and
+ * the `images` of a tool output (a screenshot is ~1.5 MB of text). A windowed
+ * `GET /messages` page replaces each of them with the URL of the route that serves that
+ * one image from the Trace record, so a page costs its text and the browser fetches each
+ * picture as it draws it. The parameterless full read is left alone.
+ *
+ * URL: `/api/sessions/<sessionId>/trace-image?file=<fileIndex>&ordinal=<ordinal>[&i=<k>]`,
+ * where (file, ordinal) is the record's `tracePosition`; without `i` it names the record's
+ * `image_url`, with `i` the tool output's `images[k]`. A Trace record never changes, so the
+ * route answers it as immutable.
+ *
+ * Only raster types a browser renders inertly are referenced (the scratchpad route's
+ * allowlist): the route serves bytes on the app's own origin, and an `image/svg+xml` or
+ * `text/html` data URL served there would be a document, not a picture. Any other data URL
+ * stays inline, where it is as harmless as it always was.
+ */
+import type { ImageUrlPayload, OmniMessage, ToolCallOutputPayload } from "@lmliheng/penguin-core";
+import type { HistoryMessage, TracePosition } from "../api/types.js";
+
+/** Image types the trace-image route serves (core's own supported set). */
+const REFERENCED_IMAGE_MIMES: ReadonlySet<string> = new Set([
+ "image/png",
+ "image/jpeg",
+ "image/gif",
+ "image/webp",
+]);
+
+/** A base64 image data URL the route can serve: its type, and where its payload starts. */
+function referableImage(url: string): { mime: string; dataStart: number } | null {
+ if (!url.startsWith("data:")) return null;
+ const comma = url.indexOf(",");
+ if (comma < 0 || comma === url.length - 1) return null;
+ const header = url.slice("data:".length, comma).toLowerCase();
+ if (!header.endsWith(";base64")) return null;
+ const mime = header.slice(0, header.indexOf(";")).trim();
+ return REFERENCED_IMAGE_MIMES.has(mime) ? { mime, dataStart: comma + 1 } : null;
+}
+
+/** The route URL of one image slot of the record at `at` (`slot` = index into a tool output's `images`). */
+export function traceImageUrl(sessionId: string, at: TracePosition, slot?: number): string {
+ const query = `file=${at.fileIndex}&ordinal=${at.ordinal}${slot !== undefined ? `&i=${slot}` : ""}`;
+ return `/api/sessions/${encodeURIComponent(sessionId)}/trace-image?${query}`;
+}
+
+/**
+ * The message as a windowed page serves it: each referable image of a main-session record
+ * (one that carries its `tracePosition`) replaced by its route URL. Expanded subagent
+ * messages carry no position and stay inline. The input is never mutated; a message with
+ * nothing to replace is returned as is.
+ */
+export function withImagesByReference(sessionId: string, msg: HistoryMessage): HistoryMessage {
+ const at = msg.tracePosition;
+ if (at === undefined || msg.type !== "model_msg") return msg;
+ const kind = (msg.payload as { type?: string }).type;
+ if (kind === "image_url") {
+ const payload = msg.payload as ImageUrlPayload;
+ if (typeof payload.image_url !== "string" || referableImage(payload.image_url) === null) {
+ return msg;
+ }
+ return { ...msg, payload: { ...payload, image_url: traceImageUrl(sessionId, at) } };
+ }
+ if (kind === "tool_call_output") {
+ const payload = msg.payload as ToolCallOutputPayload;
+ if (!Array.isArray(payload.images)) return msg;
+ let replaced = false;
+ const images = payload.images.map((image, k) => {
+ if (typeof image !== "string" || referableImage(image) === null) return image;
+ replaced = true;
+ return traceImageUrl(sessionId, at, k);
+ });
+ if (replaced) return { ...msg, payload: { ...payload, images } };
+ }
+ return msg;
+}
+
+/**
+ * The decoded image in one slot of a Trace record: the user image of an `image_url` record
+ * (`slot` undefined) or a tool output's `images[slot]`. Null when that slot holds no image
+ * the route serves — the same test the page applied before it handed out the URL.
+ */
+export function traceRecordImage(
+ record: OmniMessage,
+ slot: number | undefined,
+): { mime: string; bytes: Buffer } | null {
+ if (record.type !== "model_msg") return null;
+ const p = record.payload as { type?: string; image_url?: unknown; images?: unknown };
+ let url: unknown;
+ if (slot === undefined) {
+ url = p.type === "image_url" ? p.image_url : undefined;
+ } else if (p.type === "tool_call_output" && Array.isArray(p.images)) {
+ url = (p.images as unknown[])[slot];
+ }
+ if (typeof url !== "string") return null;
+ const image = referableImage(url);
+ if (image === null) return null;
+ return { mime: image.mime, bytes: Buffer.from(url.slice(image.dataStart), "base64") };
+}
diff --git a/packages/server/src/services/trace-line-index.ts b/packages/server/src/services/trace-line-index.ts
new file mode 100644
index 00000000..a38e2938
--- /dev/null
+++ b/packages/server/src/services/trace-line-index.ts
@@ -0,0 +1,223 @@
+/**
+ * Per-file record offsets for Trace JSONL, so a page of events costs one ranged read
+ * instead of a parse of the whole file.
+ *
+ * The events endpoint used to read and parse the whole shard for every page it served: a
+ * 25 MB shard walked in pages of 1000 was parsed fourteen times per panel open. Here each
+ * file version is scanned once (the scan does parse every line, to decide which ones are
+ * records), and every later page reads only the bytes of the records it returns.
+ *
+ * Ordinals equal `readTraceTolerant`'s, which is what `tracePosition` and the analysis'
+ * `messageFrom`/`messageTo` are counted in: a line is a record iff its trimmed text is
+ * non-empty and parses as JSON. A malformed middle line is skipped, as `parseTraceLines`
+ * skips it. A final segment with no `\n` yet is a record exactly when it parses, as the
+ * tolerant reader counts it; such a segment is never taken as scanned, so a crash-torn
+ * tail that the writer later heals (with a leading `\n`, see core's `probeTornTail`) is
+ * re-read and becomes the skipped middle line it then is.
+ *
+ * Versions: a file that only grew (same inode, larger size, mtime not earlier) is scanned
+ * from where the last scan stopped; anything else (truncation, replacement, an in-place
+ * rewrite of the same size) is scanned again from the start. The newest
+ * `TRACE_LINE_INDEX_MAX_FILES` files are kept.
+ */
+import fs from "node:fs/promises";
+import type { OmniMessage } from "@lmliheng/penguin-core";
+
+/** How many files keep their index (least recently used is dropped first). */
+export const TRACE_LINE_INDEX_MAX_FILES = 32;
+
+const NEWLINE = 0x0a;
+
+/** One file version's record offsets. */
+export interface TraceLineIndexEntry {
+ ino: number;
+ size: number;
+ mtimeMs: number;
+ /** Byte offset of each record's first byte; index = the record's ordinal. */
+ starts: number[];
+ /** One past each record's last byte (its `\n`, or the file's end for an unterminated last record). */
+ ends: number[];
+ /** Bytes scanned for good: one past the last `\n` seen. An unterminated tail lies beyond it. */
+ scanned: number;
+ /** The last record is an unterminated tail, re-read on the next growth. */
+ provisionalTail: boolean;
+}
+
+export interface TraceLineIndexOptions {
+ maxFiles?: number;
+ /** Test observability: every byte range read from disk, as [start, end). */
+ observeRead?: (path: string, start: number, end: number) => void;
+}
+
+/** Whether bytes [from, to) of `buf` hold one Trace record (the tolerant reader's rule). */
+function isRecord(buf: Buffer, from: number, to: number): boolean {
+ const text = buf.toString("utf8", from, to).trim();
+ if (text === "") return false;
+ try {
+ JSON.parse(text);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export class TraceLineIndex {
+ private readonly maxFiles: number;
+ private readonly observeRead: ((path: string, start: number, end: number) => void) | undefined;
+ /** Insertion order is recency: a hit moves its entry to the end. */
+ private readonly entries = new Map<string, TraceLineIndexEntry>();
+ /** Per-path refresh chain, so concurrent callers share one scan of a version. */
+ private readonly queues = new Map<string, Promise<unknown>>();
+
+ constructor(opts: TraceLineIndexOptions = {}) {
+ this.maxFiles = Math.max(1, opts.maxFiles ?? TRACE_LINE_INDEX_MAX_FILES);
+ this.observeRead = opts.observeRead;
+ }
+
+ /** The index for the file as it is now: built on first sight, extended over appended bytes only. */
+ async ensure(path: string): Promise<TraceLineIndexEntry> {
+ const previous = this.queues.get(path) ?? Promise.resolve();
+ const run = previous.catch(() => {}).then(() => this.refresh(path));
+ this.queues.set(path, run);
+ try {
+ return await run;
+ } finally {
+ if (this.queues.get(path) === run) this.queues.delete(path);
+ }
+ }
+
+ /**
+ * Records [offset, offset + limit) of the file, in file order, read with one ranged read;
+ * `total` is the file's record count. An offset at or past the end yields no events.
+ */
+ async readRange(
+ path: string,
+ offset: number,
+ limit: number,
+ ): Promise<{ events: OmniMessage[]; total: number }> {
+ for (let attempt = 0; ; attempt++) {
+ const entry = await this.ensure(path);
+ const total = entry.starts.length;
+ const from = Math.min(Math.max(0, offset), total);
+ const to = Math.min(total, from + Math.max(0, limit));
+ if (from >= to) return { events: [], total };
+ // Copied before the read: a concurrent refresh may extend the arrays meanwhile.
+ const starts = entry.starts.slice(from, to);
+ const ends = entry.ends.slice(from, to);
+ const base = starts[0]!;
+ const buf = await this.readBytes(path, base, ends[ends.length - 1]!);
+ const events: OmniMessage[] = [];
+ try {
+ for (let i = 0; i < starts.length; i++) {
+ const text = buf.toString("utf8", starts[i]! - base, ends[i]! - base).trim();
+ events.push(JSON.parse(text) as OmniMessage);
+ }
+ } catch (err) {
+ // The bytes under a scanned record no longer parse: the file was replaced between the
+ // stat and the read. Forget it and index the new file once; a second miss is real.
+ this.entries.delete(path);
+ if (attempt > 0) throw err;
+ continue;
+ }
+ return { events, total };
+ }
+ }
+
+ private async refresh(path: string): Promise<TraceLineIndexEntry> {
+ const stat = await fs.stat(path);
+ let entry = this.entries.get(path);
+ const grownOnly =
+ entry !== undefined &&
+ stat.ino === entry.ino &&
+ stat.size >= entry.size &&
+ stat.mtimeMs >= entry.mtimeMs &&
+ (stat.size > entry.size || stat.mtimeMs === entry.mtimeMs);
+ if (entry === undefined || !grownOnly) {
+ entry = {
+ ino: stat.ino,
+ size: 0,
+ mtimeMs: stat.mtimeMs,
+ starts: [],
+ ends: [],
+ scanned: 0,
+ provisionalTail: false,
+ };
+ await this.scan(path, entry, stat.size);
+ } else if (stat.size > entry.size) {
+ if (!(await this.scan(path, entry, stat.size))) {
+ // The byte before the scanned point is no longer a newline: not an append.
+ entry = {
+ ino: stat.ino,
+ size: 0,
+ mtimeMs: stat.mtimeMs,
+ starts: [],
+ ends: [],
+ scanned: 0,
+ provisionalTail: false,
+ };
+ await this.scan(path, entry, stat.size);
+ }
+ }
+ entry.mtimeMs = stat.mtimeMs;
+ this.entries.delete(path);
+ this.entries.set(path, entry);
+ while (this.entries.size > this.maxFiles) {
+ this.entries.delete(this.entries.keys().next().value!);
+ }
+ return entry;
+ }
+
+ /**
+ * Scans bytes [entry.scanned, size) into `entry`. Returns false, leaving `entry` untouched,
+ * when the byte just before `scanned` is not the newline the last scan ended on.
+ */
+ private async scan(path: string, entry: TraceLineIndexEntry, size: number): Promise<boolean> {
+ const from = entry.scanned;
+ // One byte of overlap re-checks the newline the previous scan ended on.
+ const readFrom = from > 0 ? from - 1 : 0;
+ const buf = await this.readBytes(path, readFrom, size);
+ let pos = from - readFrom;
+ if (pos === 1 && buf[0] !== NEWLINE) return false;
+ if (entry.provisionalTail) {
+ entry.starts.pop();
+ entry.ends.pop();
+ entry.provisionalTail = false;
+ }
+ for (;;) {
+ const nl = buf.indexOf(NEWLINE, pos);
+ if (nl < 0) break;
+ if (isRecord(buf, pos, nl)) {
+ entry.starts.push(readFrom + pos);
+ entry.ends.push(readFrom + nl + 1);
+ }
+ pos = nl + 1;
+ }
+ entry.scanned = readFrom + pos;
+ if (pos < buf.length && isRecord(buf, pos, buf.length)) {
+ entry.starts.push(readFrom + pos);
+ entry.ends.push(readFrom + buf.length);
+ entry.provisionalTail = true;
+ }
+ entry.size = readFrom + buf.length;
+ return true;
+ }
+
+ /** Bytes [start, end) of the file; fewer when the file is shorter than that now. */
+ private async readBytes(path: string, start: number, end: number): Promise<Buffer> {
+ this.observeRead?.(path, start, end);
+ const length = Math.max(0, end - start);
+ const buf = Buffer.allocUnsafe(length);
+ const fh = await fs.open(path, "r");
+ try {
+ let filled = 0;
+ while (filled < length) {
+ const { bytesRead } = await fh.read(buf, filled, length - filled, start + filled);
+ if (bytesRead === 0) break;
+ filled += bytesRead;
+ }
+ return filled === length ? buf : buf.subarray(0, filled);
+ } finally {
+ await fh.close();
+ }
+ }
+}
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 39f77288..fca177cd 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -76,6 +76,8 @@ import type {
import { buildContextBreakdown, emptyContextBreakdown } from "./context-breakdown.js";
import { sessionIdCreatedAt } from "./session-service.js";
import { TraceIndexService, traceFilePath } from "./trace-index.js";
+import { TraceLineIndex } from "./trace-line-index.js";
+import { traceRecordImage, withImagesByReference } from "./trace-images.js";
import { Component, Use } from "@lmliheng/penguin-core/kernel";
import type { Paths } from "../hmr/capabilities.js";
import type { TraceIndex, TraceIndexStore, Traces } from "../mechanisms/traces.js";
@@ -90,6 +92,13 @@ const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;
*/
const IMPORT_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
+/**
+ * A windowed history page stops adding units once its serialized size (UTF-8, images by
+ * reference) would pass this, but never holds fewer than one unit: the unit count alone does
+ * not bound a page, since one Task can carry hundreds of tool outputs.
+ */
+export const MESSAGES_PAGE_MAX_BYTES = 4 * 1024 * 1024;
+
/** Recursion depth cap for sub-session expansion (run_subagent depth is already constrained by the SDK; this is just a defensive backstop against cycles). */
const MAX_SUBAGENT_DEPTH = 4;
@@ -173,6 +182,7 @@ export type MessagesPageRequest =
/** A windowed history read's result (route maps it onto MessagesResponse.page). */
export interface MessagesPageResult {
+ /** The window's records with their `tracePosition`, images still inline (the route references them). */
messages: OmniMessage[];
/** Cursor of the window's first unit; absent = the window reaches the beginning. */
before?: string;
@@ -292,6 +302,11 @@ export class TraceService implements Traces {
* newest shard and vice versa). Production wiring leaves it unset.
*/
observeShardRead?: (path: string) => void;
+ /**
+ * Record offsets per Trace file (trace-line-index.ts): the events endpoint and the image
+ * route read only the records they serve. Tests wire their own to observe the reads.
+ */
+ private lineIndex = new TraceLineIndex();
/**
* All of this Session's Trace files (sorted by index ascending), served from the
@@ -545,6 +560,12 @@ export class TraceService implements Traces {
* (plus, once ever per old shard, the prefix-cache backfill above). Subagent
* pointers are expanded exactly as the full path expands them, but only within the
* window: children referenced by older windows load when those windows do.
+ *
+ * Two limits bound a window: at most `limit` units, and at most
+ * MESSAGES_PAGE_MAX_BYTES of serialized messages, measured with images by reference
+ * (the route applies that rewrite after merging the held inputs). The newest unit
+ * always joins, however large; a window the budget cut short carries the cursor of its
+ * first unit like any other. A child's expanded size is not counted.
*/
async readMessagesPage(
projectId: string,
@@ -604,36 +625,77 @@ export class TraceService implements Traces {
boundaries = [...shardBoundaries, ...boundaries];
}
- // Window start: the last `limit` units, or the very beginning (preamble included)
- // when the whole remaining history fits — then there is no `before` cursor.
- let start: { pos: number; ordinal: number };
- let before: string | undefined;
- let prior: WindowPriorStats;
- if (boundaries.length > req.limit) {
- const wb = boundaries[boundaries.length - req.limit]!;
- start = { pos: wb.pos, ordinal: wb.ordinal };
- before = encodeCursor({ fileIndex: files[wb.pos]!.index, ordinal: wb.ordinal });
- prior = wb.stats;
- } else {
- start = { pos: 0, ordinal: 0 };
- prior = initialScanState().totals;
- }
-
- const windowRaw: HistoryMessage[] = [];
- for (let pos = start.pos; pos <= endPos; pos++) {
+ // The widest window the unit count allows: the last `limit` units, or the very
+ // beginning (preamble included) when the whole remaining history holds no more.
+ type Boundary = (typeof boundaries)[number];
+ const reachesStart = boundaries.length <= req.limit;
+ const units = reachesStart ? boundaries : boundaries.slice(boundaries.length - req.limit);
+ const widest = reachesStart ? { pos: 0, ordinal: 0 } : units[0]!;
+
+ const spanRaw: HistoryMessage[] = [];
+ /** Where each candidate start lies in spanRaw, oldest first; a null boundary = the beginning. */
+ const starts: Array<{ at: number; boundary: Boundary | null }> = reachesStart
+ ? [{ at: 0, boundary: null }]
+ : [];
+ let nextUnit = 0;
+ for (let pos = widest.pos; pos <= endPos; pos++) {
const messages = shardMessages.get(pos) ?? (await this.readShard(files[pos]!.path));
- const from = pos === start.pos ? start.ordinal : 0;
+ const from = pos === widest.pos ? widest.ordinal : 0;
const to =
pos === endPos && endOrdinal !== null
? Math.min(endOrdinal, messages.length)
: messages.length;
for (let i = from; i < to; i++) {
- windowRaw.push({
+ const unit = units[nextUnit];
+ if (unit !== undefined && unit.pos === pos && unit.ordinal === i) {
+ // A unit opening the very first record IS the beginning: no cursor precedes it.
+ if (starts.at(-1)?.at !== spanRaw.length) {
+ starts.push({ at: spanRaw.length, boundary: unit });
+ }
+ nextUnit += 1;
+ }
+ spanRaw.push({
...messages[i]!,
tracePosition: { fileIndex: files[pos]!.index, ordinal: i },
});
}
}
+
+ // Byte budget: newest first, a unit joins while the page stays within it; the first one
+ // always joins. Sized as the route serves it, images by reference (trace-images.ts).
+ let chosen = starts.length - 1;
+ let pageBytes = 0;
+ for (let k = starts.length - 1; k >= 0; k--) {
+ const unitEnd = k + 1 < starts.length ? starts[k + 1]!.at : spanRaw.length;
+ let unitBytes = 0;
+ for (let i = starts[k]!.at; i < unitEnd; i++) {
+ unitBytes += Buffer.byteLength(
+ JSON.stringify(withImagesByReference(sessionId, spanRaw[i]!)),
+ "utf8",
+ );
+ }
+ if (k < starts.length - 1 && pageBytes + unitBytes > MESSAGES_PAGE_MAX_BYTES) break;
+ pageBytes += unitBytes;
+ chosen = k;
+ }
+
+ // The window starts at the chosen unit; anything before it gets a `before` cursor.
+ let start: { pos: number; ordinal: number };
+ let before: string | undefined;
+ let prior: WindowPriorStats;
+ const startBoundary = starts[chosen]?.boundary ?? null;
+ if (startBoundary !== null) {
+ start = { pos: startBoundary.pos, ordinal: startBoundary.ordinal };
+ before = encodeCursor({
+ fileIndex: files[startBoundary.pos]!.index,
+ ordinal: startBoundary.ordinal,
+ });
+ prior = startBoundary.stats;
+ } else {
+ start = { pos: 0, ordinal: 0 };
+ prior = initialScanState().totals;
+ }
+ const windowRaw = spanRaw.slice(starts[chosen]?.at ?? 0);
const expanded = await this.expandMessages(projectId, windowRaw, ctx);
// The start shard was read for the window above, so its head is on hand.
const startMeta = shardMessages.get(start.pos)?.find(isSessionMeta);
@@ -869,7 +931,11 @@ export class TraceService implements Traces {
return out;
}
- /** Reads events from the Trace file at the given index, paginated by line (for loading large files in pages). */
+ /**
+ * Reads records [offset, offset + limit) of the Trace file at the given index, in the
+ * tolerant reader's ordinals. Served from the file's line index: one ranged read per page,
+ * not a parse of the whole file.
+ */
async readEvents(
projectId: string,
agentId: string,
@@ -878,13 +944,34 @@ export class TraceService implements Traces {
offset: number,
limit: number,
): Promise<TraceEventsResponse> {
- const messages = await this.readFileByIndex(projectId, agentId, sessionId, index);
- return {
- events: messages.slice(offset, offset + limit),
- offset,
- limit,
- total: messages.length,
- };
+ const file = await this.locateByIndex(projectId, agentId, sessionId, index);
+ const { events, total } = await this.lineIndex.readRange(file.path, offset, limit);
+ return { events, offset, limit, total };
+ }
+
+ /**
+ * One image of one Trace record, decoded: the `image_url` of the record at
+ * (`fileIndex`, `ordinal`), or its tool output's `images[slot]`. This is what a windowed
+ * history page's image URL names (trace-images.ts). 404 `trace_image_not_found` when the
+ * file, the record or the slot holds no image the route serves.
+ */
+ async readTraceImage(
+ projectId: string,
+ agentId: string,
+ sessionId: string,
+ fileIndex: number,
+ ordinal: number,
+ slot: number | undefined,
+ ): Promise<{ mime: string; bytes: Buffer }> {
+ const notFound = () =>
+ new HttpError(404, "trace_image_not_found", "This Trace record holds no such image.");
+ const files = await this.locateAll(projectId, agentId, sessionId);
+ const file = files.find((f) => f.index === fileIndex);
+ if (file === undefined) throw notFound();
+ const { events } = await this.lineIndex.readRange(file.path, ordinal, 1);
+ const image = events[0] !== undefined ? traceRecordImage(events[0], slot) : null;
+ if (image === null) throw notFound();
+ return image;
}
/**
@@ -896,11 +983,8 @@ export class TraceService implements Traces {
*/
private async filePricing(
projectId: string,
- messages: OmniMessage[],
+ meta: OmniMessage | undefined,
): Promise<{ provider: string; modelId: string; rates: TieredRates } | null> {
- const meta = messages.find(
- (m) => isSessionMeta(m) && (m.origin === undefined || m.origin.length === 0),
- );
if (meta === undefined) return null;
const { provider, model_id: modelId } = meta.payload as {
provider?: unknown;
@@ -920,7 +1004,18 @@ export class TraceService implements Traces {
index: number,
): Promise<TraceAnalysisResponse> {
const messages = await this.readFileByIndex(projectId, agentId, sessionId, index);
- const pricing = await this.filePricing(projectId, messages);
+ // The file's head: the main session's first `session_meta`.
+ const meta = messages.find(
+ (m) => isSessionMeta(m) && (m.origin === undefined || m.origin.length === 0),
+ );
+ const pricing = await this.filePricing(projectId, meta);
+ const headWindow = (meta?.payload as { model_context_window?: unknown } | undefined)
+ ?.model_context_window;
+ const modelContextWindow =
+ (typeof headWindow === "number" && Number.isFinite(headWindow)) ||
+ (typeof headWindow === "string" && headWindow !== "")
+ ? headWindow
+ : undefined;
const requests: RequestSpan[] = [];
let openRequest: RequestSpan | null = null;
@@ -1461,6 +1556,7 @@ export class TraceService implements Traces {
apiMs,
toolMs,
...(cost !== undefined ? { cost } : {}),
+ ...(modelContextWindow !== undefined ? { modelContextWindow } : {}),
requests,
tasks,
toolCalls,
diff --git a/packages/server/test/messages-page.test.ts b/packages/server/test/messages-page.test.ts
index 93775fe8..06866dc6 100644
--- a/packages/server/test/messages-page.test.ts
+++ b/packages/server/test/messages-page.test.ts
@@ -11,6 +11,14 @@
* shard-read discipline (an old-window request never reads the newest shard and vice
* versa, once the per-shard prefix cache is primed), and the no-params full read
* staying byte-identical with no `page` envelope.
+ *
+ * The byte budget (MESSAGES_PAGE_MAX_BYTES):
+ * - Given a newest unit larger than the budget, the page holds that unit alone and a cursor,
+ * and the page before it continues exactly where it stopped.
+ * - Given units that together pass the budget, they join newest-first until the next one
+ * would pass it, and the cut page equals a unit-count cut at the same place (cursor,
+ * prior stats, messages) — even when the whole history is within the unit count.
+ * - Given units carrying screenshots, an image counts as its reference URL, not its bytes.
*/
import fs from "node:fs/promises";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -36,6 +44,7 @@ import {
} from "@lmliheng/penguin-core/markers";
import type { OmniMessage, SessionMetaPayload, TokenCounts } from "@lmliheng/penguin-core";
import { decodeCursor, encodeCursor } from "../src/services/message-window.js";
+import { MESSAGES_PAGE_MAX_BYTES } from "../src/services/trace-service.js";
import type { TraceService } from "../src/services/trace-service.js";
import { makeTempRoot, makeTraceHarness, writeTraceFile } from "./helpers.js";
@@ -77,6 +86,32 @@ function turn(mm: number, n: number, sessionTotal: number): OmniMessage[] {
];
}
+/**
+ * One Task whose tool output carries `outputChars` characters of text, or as many characters
+ * of base64 in one PNG screenshot when `image` is set.
+ */
+function heavyTurn(mm: number, n: number, outputChars: number, image = false): OmniMessage[] {
+ const t = (s: string) => `2026-07-20T10:${String(mm).padStart(2, "0")}:${s}Z`;
+ const output = image
+ ? toolCallOutput({
+ output: "screenshot",
+ toolCallId: `t${n}`,
+ images: [`data:image/png;base64,${"A".repeat(outputChars)}`],
+ })
+ : toolCallOutput({ output: "x".repeat(outputChars), toolCallId: `t${n}` });
+ return [
+ at(t("00.000"), userText(`q${n}`)),
+ at(t("01.000"), requestBegin()),
+ at(t("02.000"), toolCall({ name: "exec", arguments: "{}", toolCallId: `t${n}` })),
+ at(t("03.000"), requestEnd("completed")),
+ at(t("04.000"), output),
+ at(t("05.000"), requestBegin()),
+ at(t("06.000"), assistantText(`a${n}`)),
+ at(t("07.000"), requestEnd("completed")),
+ at(t("07.500"), tokenUsage(counts(1000 * n), counts(100 + n))),
+ ];
+}
+
const textOf = (m: OmniMessage): string | undefined => (m.payload as { text?: string }).text;
const userTexts = (ms: OmniMessage[]): string[] =>
ms
@@ -654,6 +689,64 @@ describe("messages windowed reads", () => {
expect(tail.messages).toEqual(await service.readMessages(P, A, S));
});
+ it("a newest unit over the byte budget comes alone with a cursor, and the page before continues there", async () => {
+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [
+ sessionMeta(metaPayload()),
+ ...turn(0, 1, 1000),
+ ...turn(1, 2, 2000),
+ ...heavyTurn(2, 3, MESSAGES_PAGE_MAX_BYTES + 1),
+ ]);
+ const tail = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 50 });
+ expect(userTexts(tail.messages)).toEqual(["q3"]);
+ expect(tail.before).toBeDefined();
+ expect(tail.prior.turns).toBe(2);
+
+ const rest = await service.readMessagesPage(P, A, S, {
+ kind: "before",
+ cursor: decodeCursor(tail.before!)!,
+ limit: 50,
+ });
+ expect(userTexts(rest.messages)).toEqual(["q1", "q2"]);
+ expect(rest.before).toBeUndefined();
+ expect([...rest.messages, ...tail.messages]).toEqual(await service.readMessages(P, A, S));
+ });
+
+ it("units join newest-first until the next would pass the budget; the cut equals a unit-count cut there", async () => {
+ const unitChars = Math.ceil(MESSAGES_PAGE_MAX_BYTES * 0.35);
+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [
+ sessionMeta(metaPayload()),
+ ...heavyTurn(0, 1, unitChars),
+ ...heavyTurn(1, 2, unitChars),
+ ...heavyTurn(2, 3, unitChars),
+ ]);
+ // Three units are within the count but not the budget: two fit.
+ const cut = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 50 });
+ expect(userTexts(cut.messages)).toEqual(["q2", "q3"]);
+ expect(cut).toEqual(await service.readMessagesPage(P, A, S, { kind: "tail", limit: 2 }));
+
+ const first = await service.readMessagesPage(P, A, S, {
+ kind: "before",
+ cursor: decodeCursor(cut.before!)!,
+ limit: 50,
+ });
+ expect(userTexts(first.messages)).toEqual(["q1"]);
+ expect(first.before).toBeUndefined();
+ expect([...first.messages, ...cut.messages]).toEqual(await service.readMessages(P, A, S));
+ });
+
+ it("a screenshot costs its reference, not its bytes, against the budget", async () => {
+ const imageChars = Math.ceil(MESSAGES_PAGE_MAX_BYTES * 0.4);
+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [
+ sessionMeta(metaPayload()),
+ ...heavyTurn(0, 1, imageChars, true),
+ ...heavyTurn(1, 2, imageChars, true),
+ ...heavyTurn(2, 3, imageChars, true),
+ ]);
+ const tail = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 50 });
+ expect(userTexts(tail.messages)).toEqual(["q1", "q2", "q3"]);
+ expect(tail.before).toBeUndefined();
+ });
+
it("names the model of the context a window starts in: the session_meta heading that shard, which the window does not hold", async () => {
// A Session that switched models: shard 1 on m1, closed by the switch's compaction; shard 2
// on another provider's m2, opened with its summary and continued for two turns.
diff --git a/packages/server/test/messages-pending-input.test.ts b/packages/server/test/messages-pending-input.test.ts
index 5e8b7a6f..f01ffa3c 100644
--- a/packages/server/test/messages-pending-input.test.ts
+++ b/packages/server/test/messages-pending-input.test.ts
@@ -9,6 +9,8 @@
* (full and tail reads alike) exactly once, and both holds end at the first request_begin,
* while the run is still going — a hold outliving the tail window would re-append the input.
* - An input already persisted with a Trace position is not served twice.
+ * - A held image whose Trace copy has landed is served once on a windowed page, by reference:
+ * the dedup compares the inline copies, and only then is the Trace copy's image referenced.
* - A run aborted mid-bootstrap keeps its holds, so a reload still sees the message; the next
* run appends its own input and drops the stale connect pair.
*/
@@ -178,6 +180,46 @@ describe("GET /messages serves the running task's pending inputs", () => {
await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
});
+ it("serves a held image whose Trace copy has landed once, by reference", async () => {
+ const png =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
+ const res = await api.post(`/api/sessions/${SID}/tasks`, {
+ input: [
+ { type: "text", text: "see this" },
+ { type: "image_url", imageUrl: png },
+ ],
+ });
+ expect(res.status).toBe(202);
+ await waitFor(() => t.deps.manager.pendingBootstrap(SID).length === 1);
+ await writeTraceFile(t.root, PROJECT, "default_agent", "2026-08-15", SID, 1, [
+ sessionMeta({
+ session_id: SID,
+ provider: "custom",
+ model_id: "m1",
+ model_context_window: 10_000,
+ system_prompt: "test",
+ agent_state: "/tmp/agent-state",
+ workspace: "/tmp/w",
+ }),
+ ...t.deps.manager.pendingInputs(SID),
+ ]);
+
+ const tail = (await (
+ await api.get(`/api/sessions/${SID}/messages?tailLimit=10`)
+ ).json()) as MessagesResponse;
+ const images = tail.messages.filter(
+ (m) => (m.payload as { type?: string }).type === "image_url",
+ );
+ expect(images.map((m) => (m.payload as { image_url: string }).image_url)).toEqual([
+ `/api/sessions/${SID}/trace-image?file=1&ordinal=2`,
+ ]);
+
+ releaseBootstrap();
+ await waitFor(() => t.deps.manager.pendingInputs(SID).length === 0);
+ releaseRequest();
+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");
+ });
+
it("keeps the holds after a run aborted mid-bootstrap (no request_begin): a reload still sees the message; the next run appends", async () => {
const SID2 = uniqueSessionId();
// First run: connect aborted before any request (the core cancels the bootstrap and
diff --git a/packages/server/test/trace-image.test.ts b/packages/server/test/trace-image.test.ts
new file mode 100644
index 00000000..38e755e3
--- /dev/null
+++ b/packages/server/test/trace-image.test.ts
@@ -0,0 +1,169 @@
+/**
+ * Images by reference on windowed history pages, and the route that serves them,
+ * `GET /api/sessions/:sessionId/trace-image?file=&ordinal=[&i=]`.
+ *
+ * - Given a Trace holding a user image and a tool output with two screenshots, a windowed
+ * page carries route URLs in their place, and each URL answers exactly that image's bytes
+ * with its type, an immutable private cache and nosniff.
+ * - The parameterless full read still carries every data URL.
+ * - An image type the route does not serve (SVG) stays inline on the windowed page.
+ * - A caller without access to the Session gets 404 session_not_found and an anonymous one
+ * 401; neither gets the bytes.
+ * - A record without an image, a slot past the end, an ordinal past the end and an unknown
+ * file answer 404 trace_image_not_found; missing or malformed parameters answer 400.
+ */
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import {
+ assistantText,
+ imageUrlMessage,
+ requestBegin,
+ requestEnd,
+ sessionMeta,
+ toolCall,
+ toolCallOutput,
+ userText,
+} from "@lmliheng/penguin-core";
+import type { OmniMessage } from "@lmliheng/penguin-core";
+import type { HistoryMessage, MessagesResponse } from "../src/api/types.js";
+import { sessionRow, uniqueSessionId } from "./fixtures/session.js";
+import { apiClient, createTestApp, provisionUser, writeTraceFile } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+const PROJECT = "imager-default_project";
+
+const PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
+ "base64",
+);
+const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46]);
+const SVG = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>');
+const dataUrl = (mime: string, bytes: Buffer) => `data:${mime};base64,${bytes.toString("base64")}`;
+
+type Payload = { type?: string; text?: string; image_url?: string; images?: string[] };
+const payloadOf = (m: OmniMessage) => m.payload as Payload;
+
+describe("images by reference", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let outsider: ReturnType<typeof apiClient>;
+ let SID: string;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ api = apiClient(t.app, (await provisionUser(t.app, "imager")).cookie);
+ outsider = apiClient(t.app, (await provisionUser(t.app, "outsider")).cookie);
+ SID = uniqueSessionId();
+ t.deps.sessionsRepo.insert(sessionRow(SID, { projectId: PROJECT }));
+ await writeTraceFile(t.root, PROJECT, "default_agent", "2026-09-01", SID, 1, [
+ sessionMeta({
+ session_id: SID,
+ provider: "custom",
+ model_id: "m1",
+ model_context_window: 10_000,
+ system_prompt: "sp",
+ agent_state: "/tmp/a",
+ workspace: "/tmp/w",
+ }),
+ userText("look at these"), // 1
+ imageUrlMessage(dataUrl("image/png", PNG)), // 2
+ imageUrlMessage(dataUrl("image/svg+xml", SVG)), // 3
+ requestBegin(), // 4
+ toolCall({ name: "browser_screenshot", arguments: "{}", toolCallId: "t1" }), // 5
+ toolCallOutput({
+ output: "two shots",
+ toolCallId: "t1",
+ images: [dataUrl("image/jpeg", JPEG), dataUrl("image/png", PNG)],
+ }), // 6
+ assistantText("done"), // 7
+ requestEnd("completed"), // 8
+ ]);
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+
+ const tailPage = async (): Promise<HistoryMessage[]> => {
+ const res = await api.get(`/api/sessions/${SID}/messages?tailLimit=20`);
+ expect(res.status).toBe(200);
+ return ((await res.json()) as MessagesResponse).messages;
+ };
+ const errorCode = async (res: Response) =>
+ ((await res.json()) as { error: { code: string } }).error.code;
+
+ it("a windowed page carries URLs that answer each image's bytes, immutable and typed", async () => {
+ const messages = await tailPage();
+ const userImage = payloadOf(messages[2]!);
+ const output = payloadOf(messages.find((m) => payloadOf(m).type === "tool_call_output")!);
+ expect(userImage.image_url).toBe(`/api/sessions/${SID}/trace-image?file=1&ordinal=2`);
+ expect(output.images).toEqual([
+ `/api/sessions/${SID}/trace-image?file=1&ordinal=6&i=0`,
+ `/api/sessions/${SID}/trace-image?file=1&ordinal=6&i=1`,
+ ]);
+
+ const served = [
+ [userImage.image_url!, "image/png", PNG],
+ [output.images![0]!, "image/jpeg", JPEG],
+ [output.images![1]!, "image/png", PNG],
+ ] as const;
+ for (const [url, mime, bytes] of served) {
+ const res = await api.get(url);
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe(mime);
+ expect(res.headers.get("cache-control")).toBe("private, max-age=31536000, immutable");
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");
+ expect(Buffer.from(await res.arrayBuffer()).equals(bytes)).toBe(true);
+ }
+ });
+
+ it("the full read keeps every image inline", async () => {
+ const res = await api.get(`/api/sessions/${SID}/messages`);
+ const { messages } = (await res.json()) as MessagesResponse;
+ expect(payloadOf(messages[2]!).image_url).toBe(dataUrl("image/png", PNG));
+ expect(payloadOf(messages[6]!).images).toEqual([
+ dataUrl("image/jpeg", JPEG),
+ dataUrl("image/png", PNG),
+ ]);
+ });
+
+ it("an image type the route does not serve stays inline, and its slot is not served", async () => {
+ const messages = await tailPage();
+ expect(payloadOf(messages[3]!).image_url).toBe(dataUrl("image/svg+xml", SVG));
+ const res = await api.get(`/api/sessions/${SID}/trace-image?file=1&ordinal=3`);
+ expect(res.status).toBe(404);
+ expect(await errorCode(res)).toBe("trace_image_not_found");
+ });
+
+ it("a caller without access, or without a sign-in, gets no bytes", async () => {
+ const url = `/api/sessions/${SID}/trace-image?file=1&ordinal=2`;
+ const denied = await outsider.get(url);
+ expect(denied.status).toBe(404);
+ expect(await errorCode(denied)).toBe("session_not_found");
+ const anonymous = await t.app.request(url);
+ expect(anonymous.status).toBe(401);
+ });
+
+ it.each([
+ ["a record without an image", "file=1&ordinal=1"],
+ ["a user image asked for as a tool slot", "file=1&ordinal=2&i=0"],
+ ["a tool output asked for without a slot", "file=1&ordinal=6"],
+ ["a slot past the end", "file=1&ordinal=6&i=2"],
+ ["an ordinal past the end", "file=1&ordinal=99"],
+ ["an unknown file", "file=2&ordinal=2"],
+ ])("%s answers 404 trace_image_not_found", async (_case, query) => {
+ const res = await api.get(`/api/sessions/${SID}/trace-image?${query}`);
+ expect(res.status).toBe(404);
+ expect(await errorCode(res)).toBe("trace_image_not_found");
+ });
+
+ it.each([
+ ["no file", "ordinal=2"],
+ ["no ordinal", "file=1"],
+ ["file 0", "file=0&ordinal=2"],
+ ["a negative ordinal", "file=1&ordinal=-1"],
+ ["a non-numeric slot", "file=1&ordinal=6&i=x"],
+ ["a path in file", "file=..%2F1&ordinal=2"],
+ ])("%s answers 400", async (_case, query) => {
+ const res = await api.get(`/api/sessions/${SID}/trace-image?${query}`);
+ expect(res.status).toBe(400);
+ });
+});
diff --git a/packages/server/test/trace-line-index.test.ts b/packages/server/test/trace-line-index.test.ts
new file mode 100644
index 00000000..2cd46898
--- /dev/null
+++ b/packages/server/test/trace-line-index.test.ts
@@ -0,0 +1,210 @@
+/**
+ * The Trace line index (services/trace-line-index.ts): the events endpoint's pages, served by
+ * ranged reads instead of a parse of the whole file per page.
+ *
+ * - Given a file with blank lines, a CRLF line, a malformed middle line and a crash-torn
+ * tail, every page holds exactly the records `readTraceTolerant` returns at those
+ * ordinals, and `total` is its record count.
+ * - Given a last record whose newline has not landed yet, it is counted as the tolerant
+ * reader counts it, and keeps its ordinal once the writer appends after it.
+ * - Given a torn tail the writer later heals with a leading newline, the torn line stays out
+ * and the healed record takes the next ordinal, both before and after.
+ * - Paging through a file reads the whole file once, then only the bytes of each page.
+ * - Concurrent first reads of one file share that one scan.
+ * - An appended file is followed by reading only the appended bytes, never its prefix again.
+ * - A truncated file, a file replaced by another, and a same-size rewrite are indexed anew.
+ * - Only the most recently used files keep their index: an evicted file is scanned again.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { readTraceTolerant, userText } from "@lmliheng/penguin-core";
+import type { OmniMessage } from "@lmliheng/penguin-core";
+import { TraceLineIndex } from "../src/services/trace-line-index.js";
+import { makeTempRoot } from "./helpers.js";
+
+const line = (msg: OmniMessage): string => `${JSON.stringify(msg)}\n`;
+const texts = (events: OmniMessage[]): string[] =>
+ events.map((e) => (e.payload as { text: string }).text);
+
+describe("trace line index", () => {
+ let dir: string;
+ let file: string;
+ let reads: Array<{ path: string; start: number; end: number }>;
+ let index: TraceLineIndex;
+
+ const bytesRead = () => reads.reduce((sum, r) => sum + (r.end - r.start), 0);
+ /** Every page of `size` the index serves, concatenated, and the totals it reported. */
+ const allPages = async (size: number) => {
+ const events: OmniMessage[] = [];
+ const totals = new Set<number>();
+ for (let offset = 0; ; offset += size) {
+ const page = await index.readRange(file, offset, size);
+ totals.add(page.total);
+ events.push(...page.events);
+ if (page.events.length < size) break;
+ }
+ return { events, totals: [...totals] };
+ };
+
+ beforeEach(async () => {
+ dir = await makeTempRoot();
+ file = path.join(dir, "s_001.jsonl");
+ reads = [];
+ index = new TraceLineIndex({
+ observeRead: (p, start, end) => reads.push({ path: p, start, end }),
+ });
+ });
+ afterEach(async () => {
+ await fs.rm(dir, { recursive: true, force: true });
+ });
+
+ it.each([1, 2, 3, 1000])(
+ "pages of %i hold exactly the tolerant reader's records, skipping damage the way it does",
+ async (size) => {
+ await fs.writeFile(
+ file,
+ [
+ line(userText("m0")),
+ "\n",
+ " \n",
+ line(userText("m1")).replace("\n", "\r\n"),
+ '{"timestamp":"2026-07-05T10:00:00.000Z","type":"model_msg","payl\n',
+ line(userText("m2")),
+ "not json at all\n",
+ line(userText("m3")),
+ '{"timestamp":"2026-07-05T10:00:0',
+ ].join(""),
+ );
+ const expected = await readTraceTolerant(file);
+ expect(texts(expected)).toEqual(["m0", "m1", "m2", "m3"]);
+
+ const { events, totals } = await allPages(size);
+ expect(events).toEqual(expected);
+ expect(totals).toEqual([expected.length]);
+ },
+ );
+
+ it("a last record whose newline has not landed is counted, and keeps its ordinal after the next append", async () => {
+ await fs.writeFile(file, line(userText("a")) + JSON.stringify(userText("b")));
+ expect(texts((await index.readRange(file, 0, 10)).events)).toEqual(
+ texts(await readTraceTolerant(file)),
+ );
+ expect((await index.readRange(file, 0, 10)).total).toBe(2);
+
+ await fs.appendFile(file, `\n${line(userText("c"))}`);
+ const after = await index.readRange(file, 0, 10);
+ expect(texts(after.events)).toEqual(["a", "b", "c"]);
+ expect(after.events).toEqual(await readTraceTolerant(file));
+ });
+
+ it("a torn tail stays out before and after the writer heals it, and the healed record follows", async () => {
+ await fs.writeFile(file, line(userText("a")) + '{"timestamp":"2026-07-05T1');
+ const before = await index.readRange(file, 0, 10);
+ expect(before.events).toEqual(await readTraceTolerant(file));
+ expect(before.total).toBe(1);
+
+ // The writer's heal: a leading newline turns the torn line into a malformed middle line.
+ await fs.appendFile(file, `\n${line(userText("b"))}`);
+ const after = await index.readRange(file, 0, 10);
+ expect(after.events).toEqual(await readTraceTolerant(file));
+ expect(texts(after.events)).toEqual(["a", "b"]);
+ });
+
+ it("paging through a file reads it whole once, then only each page's bytes", async () => {
+ const records = Array.from({ length: 30 }, (_, i) => line(userText(`m${i}`)));
+ await fs.writeFile(file, records.join(""));
+ const size = (await fs.stat(file)).size;
+
+ await allPages(7);
+ // One full scan, then every record exactly once across the pages.
+ expect(bytesRead()).toBe(size + size);
+ expect(reads.filter((r) => r.start === 0 && r.end === size)).toHaveLength(1);
+
+ reads = [];
+ const again = await index.readRange(file, 10, 5);
+ expect(texts(again.events)).toEqual(["m10", "m11", "m12", "m13", "m14"]);
+ expect(bytesRead()).toBe(records.slice(10, 15).join("").length);
+ });
+
+ it("concurrent first reads of one file share one scan", async () => {
+ await fs.writeFile(
+ file,
+ Array.from({ length: 20 }, (_, i) => line(userText(`m${i}`))).join(""),
+ );
+ const size = (await fs.stat(file)).size;
+ const pages = await Promise.all(
+ [0, 5, 10, 15].map((offset) => index.readRange(file, offset, 5)),
+ );
+ expect(pages.map((p) => texts(p.events)[0])).toEqual(["m0", "m5", "m10", "m15"]);
+ // One scan, plus four pages of a quarter of the file each.
+ expect(bytesRead()).toBe(size + size);
+ });
+
+ it("an appended file is followed by reading only the appended bytes", async () => {
+ const head = Array.from({ length: 10 }, (_, i) => line(userText(`m${i}`))).join("");
+ await fs.writeFile(file, head);
+ await index.readRange(file, 0, 1);
+
+ reads = [];
+ const tail = line(userText("m10")) + line(userText("m11"));
+ await fs.appendFile(file, tail);
+ const page = await index.readRange(file, 10, 5);
+ expect(texts(page.events)).toEqual(["m10", "m11"]);
+ expect(page.total).toBe(12);
+ // The scan starts one byte before the old end (re-checking the newline it ended on).
+ const scan = reads[0]!;
+ expect(scan.start).toBe(head.length - 1);
+ expect(reads.every((r) => r.start >= head.length - 1)).toBe(true);
+ });
+
+ it("a truncated, a replaced and a same-size rewritten file are indexed anew", async () => {
+ await fs.writeFile(file, [line(userText("aa")), line(userText("bb"))].join(""));
+ expect((await index.readRange(file, 0, 10)).total).toBe(2);
+
+ // Truncated to its first record.
+ await fs.writeFile(file, line(userText("aa")));
+ expect(texts((await index.readRange(file, 0, 10)).events)).toEqual(["aa"]);
+
+ // Replaced by another file (a rename onto the path: a new inode), longer than before.
+ const other = path.join(dir, "other.jsonl");
+ await fs.writeFile(
+ other,
+ [line(userText("x")), line(userText("y")), line(userText("z"))].join(""),
+ );
+ await fs.rename(other, file);
+ expect(texts((await index.readRange(file, 0, 10)).events)).toEqual(["x", "y", "z"]);
+
+ // Rewritten in place with the same size and a later mtime.
+ await fs.writeFile(
+ file,
+ [line(userText("p")), line(userText("q")), line(userText("r"))].join(""),
+ );
+ const later = new Date(Date.now() + 60_000);
+ await fs.utimes(file, later, later);
+ expect(texts((await index.readRange(file, 0, 10)).events)).toEqual(["p", "q", "r"]);
+ });
+
+ it("only the most recently used files keep their index", async () => {
+ index = new TraceLineIndex({
+ maxFiles: 2,
+ observeRead: (p, start, end) => reads.push({ path: p, start, end }),
+ });
+ const files = ["a", "b", "c"].map((name) => path.join(dir, `${name}.jsonl`));
+ for (const f of files) await fs.writeFile(f, line(userText("one")) + line(userText("two")));
+ const size = (await fs.stat(files[0]!)).size;
+ /** Whole-file reads: scans (a page here is a single record, never the whole file). */
+ const scans = (f: string) =>
+ reads.filter((r) => r.path === f && r.start === 0 && r.end === size);
+
+ await index.readRange(files[0]!, 0, 1);
+ await index.readRange(files[1]!, 0, 1);
+ await index.readRange(files[0]!, 0, 1); // a is now the most recent
+ await index.readRange(files[2]!, 0, 1); // evicts b
+ reads = [];
+ await index.readRange(files[0]!, 0, 1);
+ await index.readRange(files[1]!, 0, 1);
+ expect(scans(files[0]!)).toHaveLength(0);
+ expect(scans(files[1]!)).toHaveLength(1);
+ });
+});
diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.ts
index 99826bfd..fb38312d 100644
--- a/packages/server/test/trace-service.test.ts
+++ b/packages/server/test/trace-service.test.ts
@@ -1,7 +1,7 @@
/**
* Unit tests for the Trace service: multi-file history concatenation, file
- * listing, pagination, performance-analysis derivation, and Agent-level
- * drill-down browsing.
+ * listing, pagination (following a growing file), performance-analysis derivation
+ * (including the head's context window), and Agent-level drill-down browsing.
*/
import fs from "node:fs/promises";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
@@ -156,6 +156,28 @@ describe("trace-service", () => {
expect((notFound as { status: number }).status).toBe(404);
});
+ it("paginated line reads follow a file the running Task appends to", async () => {
+ const file = await writeTraceFile(root, P, A, "2026-07-05", S, 1, [
+ userText("m0"),
+ userText("m1"),
+ ]);
+ expect((await service.readEvents(P, A, S, 1, 0, 10)).total).toBe(2);
+ await fs.appendFile(file, `${JSON.stringify(userText("m2"))}\n`, "utf8");
+ const grown = await service.readEvents(P, A, S, 1, 1, 10);
+ expect(grown.total).toBe(3);
+ expect(grown.events.map((e) => (e.payload as { text: string }).text)).toEqual(["m1", "m2"]);
+ });
+
+ it("the analysis carries the context window its file's head names, and none when the head names none", async () => {
+ await writeTraceFile(root, P, A, "2026-07-05", S, 1, [
+ sessionMeta(metaPayload({ model_context_window: 200_000 })),
+ userText("hi"),
+ ]);
+ await writeTraceFile(root, P, A, "2026-07-05", S, 2, [userText("no head")]);
+ expect((await service.analyze(P, A, S, 1)).modelContextWindow).toBe(200_000);
+ expect((await service.analyze(P, A, S, 2)).modelContextWindow).toBeUndefined();
+ });
+
it("performance analysis: Request pairing, tool durations, reconnect / compaction counts, Token trend", async () => {
await writeTraceFile(root, P, A, "2026-07-05", S, 1, [
sessionMeta(metaPayload()),
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 48ecf969..eb5eecd9 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -1223,8 +1223,13 @@ function analyze(history: readonly OmniMessage[]): TraceAnalysisResponse {
(sum, t) => sum + (t.startTs ? Math.max(0, Date.parse(t.endTs) - Date.parse(t.startTs)) : 0),
0,
);
+ // The context ring's bound, read off the file's head session_meta as the server does.
+ const head = history.find((m) => m.type === "session_meta")?.payload;
+ const contextWindow =
+ head !== undefined && "model_context_window" in head ? head.model_context_window : undefined;
return {
elapsedMs,
+ ...(contextWindow !== undefined ? { modelContextWindow: contextWindow } : {}),
apiMs: tasks.reduce((sum, t) => sum + t.llmMs, 0),
toolMs: tasks.reduce((sum, t) => sum + t.toolMs, 0),
cost: tasks.reduce((sum, t) => sum + (t.cost ?? 0), 0),
diff --git a/packages/ui/src/components/chat/message-bubble/message-bubble.tsx b/packages/ui/src/components/chat/message-bubble/message-bubble.tsx
index ccb79415..08998021 100644
--- a/packages/ui/src/components/chat/message-bubble/message-bubble.tsx
+++ b/packages/ui/src/components/chat/message-bubble/message-bubble.tsx
@@ -122,7 +122,11 @@ export function MessageBubble({
}
}
-/** An image the person sent, in its bubble (`bubble`) or among a steer's (`chip`, smaller). */
+/**
+ * An image the person sent, in its bubble (`bubble`) or among a steer's (`chip`, smaller). It
+ * loads lazily: a transcript's images can be fetched by reference, one request each, and only
+ * the ones scrolled near need to arrive.
+ */
export function MessageImage({
src,
alt,
@@ -136,6 +140,7 @@ export function MessageImage({
<ZoomableImage
src={src}
alt={alt}
+ lazy
className={
size === "bubble"
? "max-h-48 max-w-full rounded-control"
diff --git a/packages/ui/src/components/chat/tool-call-card/tool-call-card.tsx b/packages/ui/src/components/chat/tool-call-card/tool-call-card.tsx
index 55487680..a4ce99bf 100644
--- a/packages/ui/src/components/chat/tool-call-card/tool-call-card.tsx
+++ b/packages/ui/src/components/chat/tool-call-card/tool-call-card.tsx
@@ -73,7 +73,7 @@ export interface ToolCallCardProps {
output?: string;
/** The output is still arriving: a caret follows it. */
outputStreaming?: boolean;
- /** Images the call returned, shown as thumbnails that zoom when pressed. */
+ /** Images the call returned, shown as thumbnails that zoom when pressed (fetched lazily, as they near the viewport). */
images?: { srcs: readonly string[]; alt: string };
/** Always shown below the details, whatever the collapsed state (a subagent's row). */
footer?: ReactNode;
@@ -215,6 +215,7 @@ export function ToolCallCard({
key={i}
src={src}
alt={images.alt}
+ lazy
className="max-h-40 max-w-full rounded-md border border-line"
/>
))}
diff --git a/packages/ui/src/components/overlays/lightbox/lightbox.tsx b/packages/ui/src/components/overlays/lightbox/lightbox.tsx
index 4cebe748..2a2a7e2f 100644
--- a/packages/ui/src/components/overlays/lightbox/lightbox.tsx
+++ b/packages/ui/src/components/overlays/lightbox/lightbox.tsx
@@ -65,6 +65,7 @@ export function ZoomableImage({
alt,
className,
closeLabel,
+ lazy = false,
}: {
src: string;
alt: string;
@@ -72,12 +73,14 @@ export function ZoomableImage({
className?: string;
/** The lightbox's close glyph's accessible name; defaults to the interface's word for "close". */
closeLabel?: string;
+ /** Fetch the thumbnail only as it nears the viewport (a long list of fetched images, e.g. a transcript's). */
+ lazy?: boolean;
}) {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" className="block cursor-zoom-in" onClick={() => setOpen(true)}>
- <img src={src} alt={alt} className={className} />
+ <img src={src} alt={alt} className={className} loading={lazy ? "lazy" : undefined} />
</button>
<Lightbox
open={open}
diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsx
index c9b93109..9ad2de47 100644
--- a/packages/web/src/features/chat/message-item.tsx
+++ b/packages/web/src/features/chat/message-item.tsx
@@ -21,6 +21,7 @@ import { S } from "../../lib/strings";
import { useLocale } from "../../state/locale";
import { formatMessageTime } from "../../lib/format";
import { splitAttachments } from "../../lib/attachments";
+import { routedUrl } from "../../lib/session-machines";
import type { ChatItem, ReconnectItem } from "../../lib/omni/stream-model";
import { MessageFilesCard } from "./message-files-card";
import { MemoryChangesCard } from "./memory-changes-card";
@@ -265,7 +266,9 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
images: steerImages,
files: steerFiles,
} = splitAttachments(item.text);
- const shown = [...steerImages, ...(item.images ?? [])];
+ // A steer's own images can be a history page's Trace references: routed to the
+ // Session's machine like the user_image below.
+ const shown = [...steerImages, ...(item.images ?? []).map(routedUrl)];
return (
<MessageRow spacing="steer">
<MessageBubble
@@ -289,10 +292,13 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo
);
}
case "user_image":
+ // Inline bytes live, or a windowed history page's reference to the Trace record
+ // (`/api/sessions/<id>/trace-image?…`), which the browser must fetch from the machine
+ // the Session lives on.
return (
<MessageRow>
<MessageBubble variant="image">
- <MessageImage src={item.imageUrl} alt={S.chat.imageAlt} />
+ <MessageImage src={routedUrl(item.imageUrl)} alt={S.chat.imageAlt} />
</MessageBubble>
<SentMessageMeta atMs={item.atMs} />
</MessageRow>
diff --git a/packages/web/src/features/chat/tool-call-card.tsx b/packages/web/src/features/chat/tool-call-card.tsx
index cb889afe..efc62a29 100644
--- a/packages/web/src/features/chat/tool-call-card.tsx
+++ b/packages/web/src/features/chat/tool-call-card.tsx
@@ -18,6 +18,7 @@ import type { RunState, ToolCallDuration } from "@lmliheng/penguin-ui";
import { S } from "../../lib/strings";
import { toolDisplayName } from "../../lib/tool-alias";
import { stripAnsi } from "../../lib/strip-ansi";
+import { routedUrl } from "../../lib/session-machines";
import { approvalKey } from "../../lib/omni/stream-model";
import type { ToolCallItem } from "../../lib/omni/stream-model";
import { useTheme } from "../../state/theme";
@@ -424,8 +425,10 @@ export function SessionToolCall({ item, ctx }: { item: ToolCallItem; ctx: Stream
output={output}
outputStreaming={item.outputStreaming}
images={
+ // Inline bytes live, or a windowed history page's Trace references, which the browser
+ // must fetch from the machine the Session lives on.
item.images && item.images.length > 0
- ? { srcs: item.images, alt: S.chat.toolImageAlt }
+ ? { srcs: item.images.map(routedUrl), alt: S.chat.toolImageAlt }
: undefined
}
// A bound subagent: a shortcut row into the subagents panel, shown whatever the card's
diff --git a/packages/web/src/features/traces/trace-events-loader.ts b/packages/web/src/features/traces/trace-events-loader.ts
deleted file mode 100644
index 8fa29480..00000000
--- a/packages/web/src/features/traces/trace-events-loader.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * Sequential pager for a Trace file's events (pure — unit-tested in test/trace-events-loader.test.ts).
- *
- * The events endpoint is paginated and its `limit` is capped server-side, while the analysis
- * beside it describes the WHOLE file: every round carries a `messageFrom`/`messageTo` index
- * range, so a view that fetched one page only had nothing to show for any round whose range
- * started past that page — the last rounds of a long file, the compaction round among them.
- * The walk here is what closes that gap: it keeps asking for the next page until the file is
- * covered, reporting each page as it arrives so the first one is on screen while the rest load.
- *
- * Pages are fetched one at a time rather than in parallel: the file is read from disk in order,
- * the next offset is only known from the page before it (a page may come back short), and a
- * reader looking at round one does not benefit from round nine's page racing it.
- */
-import type { TraceEventsResponse } from "@lmliheng/penguin-server/api";
-
-/**
- * Hard stop on the number of requests one walk may make. With the endpoint's 1000-event page
- * this covers a 500,000-event file, far past any Trace a Session produces (files rotate on
- * compaction), so the cap is only ever reached by a server that stops making progress — a page
- * that reports a `total` it never delivers would otherwise loop for as long as the view is open.
- */
-export const MAX_TRACE_EVENT_PAGES = 500;
-
-/**
- * Events per request: the largest `limit` the events endpoint accepts (it rejects anything
- * above 1000), so a file is covered in the fewest round trips the server allows.
- */
-export const TRACE_EVENT_PAGE_SIZE = 1000;
-
-/** Cancellation handed to a walk by its caller; flipped by a React effect's cleanup. */
-export interface TraceEventsSignal {
- cancelled: boolean;
-}
-
-export interface LoadTraceEventPagesOptions {
- /** Events per request. The endpoint rejects a `limit` above its own maximum, so pass TRACE_EVENT_PAGE_SIZE. */
- pageSize: number;
- /** Called once per fetched page, in file order, for the caller to render. */
- onPage: (page: TraceEventsResponse) => void;
- /** When its `cancelled` turns true the walk stops and reports nothing further. */
- signal?: TraceEventsSignal;
-}
-
-/**
- * Walk a Trace file's events from its start, reporting every page through `onPage`.
- *
- * The next offset is the end of what has actually been delivered (`offset + events.length`),
- * never `offset + pageSize`: the last page of a file is short, and any page the server answers
- * with fewer events than were asked for must not leave a hole behind it either. The walk ends
- * when that offset reaches the LATEST page's `total` — read per page, so a file appended to
- * while the walk runs is followed to its new end rather than cut at the length it had when the
- * first page was served.
- *
- * A page carrying no events also ends the walk, whatever its `total` claims: a file truncated
- * under the reader cannot be paged any further, and continuing would re-request the same offset
- * forever. Cancellation is checked on both sides of every await — after one, so a page that
- * arrives for a view that is gone is not rendered into it; before the next, so no further
- * request is issued once the caller has stopped caring about the answer.
- *
- * Rejections are not caught: the caller decides what a failed page means for what is already on
- * screen. Pages reported before it stand.
- *
- * Resolves with the `total` of the LAST page it reported — the walk's final word on how long the
- * file is, which a caller holding pages from an earlier walk uses to drop whatever sits past the
- * end. A walk that reported no page at all (cancelled before its first) resolves with 0, so the
- * caller must consult its own cancellation before acting on the number.
- */
-export async function loadTraceEventPages(
- fetchPage: (offset: number, limit: number) => Promise<TraceEventsResponse>,
- opts: LoadTraceEventPagesOptions,
-): Promise<number> {
- let offset = 0;
- let total = 0;
- // Read through a call, not inline: the flag flips while a page is in flight, and an inline
- // check narrows it to `false` for the rest of the loop body, so the post-await check would
- // compare a type the checker believes cannot be `true`.
- const cancelled = (): boolean => opts.signal?.cancelled === true;
- for (let page = 0; page < MAX_TRACE_EVENT_PAGES; page++) {
- if (cancelled()) return total;
- const res = await fetchPage(offset, opts.pageSize);
- if (cancelled()) return total;
- opts.onPage(res);
- total = res.total;
- if (res.events.length === 0) return total;
- offset += res.events.length;
- if (offset >= res.total) return total;
- }
- return total;
-}
diff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsx
index a65feae0..e8d45a38 100644
--- a/packages/web/src/features/traces/trace-file-view.tsx
+++ b/packages/web/src/features/traces/trace-file-view.tsx
@@ -7,6 +7,12 @@
* output, showing both usage ratio and composition, with exact numbers on
* hover), followed by that round's execution timeline and all of its messages.
*
+ * Loading is per round: opening a file reads only its analysis — every number on the panel and
+ * every round's message index range — and the file's newest round is open, read and scrolled into view. The other
+ * rounds show their chips collapsed; opening one reads that round's range alone
+ * (trace-rounds.ts). Round cards are drawn from the newest end, TRACE_ROUNDS_PAGE at a time,
+ * behind an "earlier rounds" control, so a file of thousands of rounds is still a short list.
+ *
* Token usage here is **broken down by category** rather than given as one
* lump sum (a total alone doesn't show where the money went): this round's
* input (with the portion that was a **cache hit** in parentheses, target
@@ -18,12 +24,13 @@
* so the file's total is what the toolbar shows for the same requests.
*
* Task attribution: model segments/tool spans carry their own taskIndex
- * (computed by the server), and messages fall into a Task's time range by
- * timestamp. Timeline ↔ message linked highlighting: hovering either side
+ * (computed by the server), and a round's messages are the events in its
+ * server-given index range. Timeline ↔ message linked highlighting: hovering either side
* highlights the other (only one bar / one message lights up at a time);
* clicking a bar scrolls to the corresponding message and pins the highlight for PIN_MS.
*/
-import { useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import type { RefObject } from "react";
import type { OmniMessage } from "@lmliheng/penguin-core/omnimessage";
import type {
TraceAnalysisResponse,
@@ -57,8 +64,19 @@ import {
} from "../../lib/format";
import { STAT_ICONS } from "../../lib/stat-icons";
import { resolveContextWindow } from "../../lib/context";
+import { toneInk } from "../../lib/tone";
import { useTheme } from "../../state/theme";
-import { TRACE_EVENT_PAGE_SIZE, loadTraceEventPages } from "./trace-events-loader";
+import type { Currency } from "../../state/theme";
+import {
+ TRACE_ROUNDS_PAGE,
+ expandedAfterAnalysis,
+ loadRoundEvents,
+ revealAfterAnalysis,
+ roundSpan,
+ roundsToRead,
+ visibleRounds,
+} from "./trace-rounds";
+import type { RoundRange, TraceEventsSignal } from "./trace-rounds";
import { TimelineChart } from "./timeline-chart";
import type { TraceHighlight } from "./timeline-chart";
import { EventRow } from "./trace-event-row";
@@ -90,20 +108,21 @@ interface Buckets {
}
const zeroBuckets = (): Buckets => ({ cacheRead: 0, cacheWrite: 0, output: 0 });
-interface TaskData {
- taskIndex: number;
+/** A round's timeline as the analysis gives it: everything a card draws without reading events. */
+interface TaskTimeline {
segments: TraceModelSegment[];
spans: TraceToolSpan[];
otherSpans: TraceOtherSpan[];
- messages: OmniMessage[];
- toolCalls: number;
- durationMs: number;
}
-const msOf = (ts: string): number => {
- const n = Date.parse(ts);
- return Number.isFinite(n) ? n : 0;
-};
+/**
+ * One round's events as the view holds them, tagged with the range they were read for — a
+ * refresh compares that range with the fresh analysis to find the round that grew. `rows` are
+ * the round's own messages: a subagent's messages (`origin` set) are not this file's rounds.
+ */
+export type RoundEntry =
+ | (RoundRange & { status: "loaded"; rows: OmniMessage[] })
+ | (RoundRange & { status: "failed"; error: string });
/** How long the target message row stays pinned highlighted after a bar-click jump (milliseconds). */
const PIN_MS = 2500;
@@ -111,6 +130,30 @@ const PIN_MS = 2500;
/** Unique key for a message row (also the DOM scroll anchor). */
const rowKeyOf = (taskIndex: number, i: number): string => `${taskIndex}-${i}`;
+const isMainSession = (msg: OmniMessage): boolean => !(msg.origin && msg.origin.length > 0);
+
+/** Identity of the range a read was issued for, so a read the analysis has since moved past is dropped. */
+const rangeKey = (r: RoundRange): string => `${r.messageFrom}:${r.messageTo}`;
+
+/**
+ * The **first** message row at that instant among the open rounds' read rows; a bar-initiated
+ * highlight/jump uses this to hit only one row.
+ */
+function firstRowKeyAt(
+ rounds: ReadonlyMap<number, RoundEntry>,
+ expanded: ReadonlySet<number>,
+ ts: string,
+): string | null {
+ const open = [...expanded].sort((a, b) => a - b);
+ for (const ti of open) {
+ const entry = rounds.get(ti);
+ if (entry?.status !== "loaded") continue;
+ const i = entry.rows.findIndex((m) => m.timestamp === ts);
+ if (i >= 0) return rowKeyOf(ti, i);
+ }
+ return null;
+}
+
/**
* One row of the global summary: name on the left, value on the right
* (tabular-nums right-aligned → values line up column-wise across rows, easy to compare at a glance).
@@ -203,6 +246,37 @@ function durationSplit(apiMs: number, toolMs: number): string {
)}${S.chat.statParenClose}`;
}
+/** A file's analysis and what it decided: the view's state per file, reset on a switch to another file. */
+export interface FileState {
+ analysis: TraceAnalysisResponse | null;
+ /** Open rounds, by taskIndex. Held beside the analysis: a fresh analysis decides which new round opens. */
+ expanded: ReadonlySet<number>;
+ /**
+ * The round the latest analysis asks to scroll into view: the newest one on the analysis that
+ * opened the file, null on every refresh. The view scrolls when this becomes non-null.
+ */
+ reveal: number | null;
+}
+
+/** What the view shows before a file's analysis lands, and after a switch to another file. */
+export const EMPTY_FILE: FileState = { analysis: null, expanded: new Set(), reveal: null };
+
+/** The view's state once an analysis of its file lands, from the state it held before. */
+export function fileAfterAnalysis(prev: FileState, analysis: TraceAnalysisResponse): FileState {
+ const previous = prev.analysis?.tasks ?? null;
+ return {
+ analysis,
+ expanded: expandedAfterAnalysis(previous, analysis.tasks, prev.expanded),
+ reveal: revealAfterAnalysis(previous, analysis.tasks),
+ };
+}
+
+/** `rounds` without its failed reads: a refresh retries them. The same map when there are none. */
+function withoutFailures(rounds: ReadonlyMap<number, RoundEntry>): ReadonlyMap<number, RoundEntry> {
+ if (![...rounds.values()].some((e) => e.status === "failed")) return rounds;
+ return new Map([...rounds].filter(([, e]) => e.status !== "failed"));
+}
+
export function TraceFileView({
projectId,
agentId,
@@ -227,11 +301,10 @@ export function TraceFileView({
onHighlight: (h: TraceHighlight | null) => void;
}) {
const { currency } = useTheme();
- const [analysis, setAnalysis] = useState<TraceAnalysisResponse | null>(null);
- const [events, setEvents] = useState<OmniMessage[]>([]);
- const [total, setTotal] = useState(0);
+ const [file, setFile] = useState<FileState>(EMPTY_FILE);
+ const [rounds, setRounds] = useState<ReadonlyMap<number, RoundEntry>>(new Map());
+ const [shownRounds, setShownRounds] = useState(TRACE_ROUNDS_PAGE);
const [error, setError] = useState<string | null>(null);
- const [collapsed, setCollapsed] = useState<ReadonlySet<number>>(new Set());
/** Message row pinned highlighted after a bar-click jump; auto-clears when its timer fires (independent of hover highlighting, and can stack with it). */
const [pinnedRow, setPinnedRow] = useState<string | null>(null);
const rootRef = useRef<HTMLDivElement>(null);
@@ -244,185 +317,225 @@ export function TraceFileView({
[],
);
- // Switching to a DIFFERENT file clears the view — back to the skeleton, with the collapsed
- // rounds and the pinned row forgotten because they name rounds this file does not have.
- // Reset during render (React's documented "adjust state when a prop changes" pattern), which
- // is what keeps it out of the load effect below: that effect also runs for a REFRESH of the
- // file already on screen, and blanking there would flash a skeleton, drop the highlight and
- // reopen every round card the user collapsed, several times per run.
+ // Switching to a DIFFERENT file clears the view — back to the skeleton, with the open
+ // rounds, the read rounds, the revealed earlier rounds and the pinned row forgotten because
+ // they name rounds this file does not have. Reset during render (React's documented "adjust
+ // state when a prop changes" pattern), which is what keeps it out of the load effect below:
+ // that effect also runs for a REFRESH of the file already on screen, and blanking there
+ // would flash a skeleton, drop the highlight and close every round the reader opened.
const fileKey = `${projectId}/${agentId}/${sessionId}/${index}`;
const [renderedFileKey, setRenderedFileKey] = useState(fileKey);
if (renderedFileKey !== fileKey) {
setRenderedFileKey(fileKey);
- setAnalysis(null);
- setEvents([]);
+ setFile(EMPTY_FILE);
+ setRounds(new Map());
+ setShownRounds(TRACE_ROUNDS_PAGE);
setError(null);
- setCollapsed(new Set());
setPinnedRow(null);
}
- // Load the file, and re-load it whenever the panel's signal moves. Results overwrite what is
- // on screen in place — an in-flight refresh keeps the current content readable, and its
- // outcome is what clears or sets the error, since nothing was cleared up front.
- //
- // The events are paged through to the END of the file, not fetched once: the analysis
- // describes every round by index range, so a round whose messages sit past the first page
- // would render an empty message list. Each page lands at its own offset, so a long file is
- // readable from its start while the rest of it arrives, and a REFRESH of a file already on
- // screen updates the list in place instead of shrinking it back to one page per settled turn.
+ // Round reads belong to the file they were issued for: switching files (or unmounting)
+ // cancels them all, and the registry of reads in flight starts over with the new file.
+ const fileSignal = useRef<TraceEventsSignal>({ cancelled: false });
+ const inflight = useRef(new Map<number, string>());
useEffect(() => {
const signal = { cancelled: false };
- const fail = (err: unknown) => {
- if (!signal.cancelled) setError(apiErrorText(err));
- };
- // The error is cleared only once BOTH halves of the first load have landed: cleared on
- // either one alone, a failure on one side would be wiped by the other side's success.
- let haveAnalysis = false;
- let haveFirstPage = false;
- const clearErrorWhenBothLanded = () => {
- if (haveAnalysis && haveFirstPage) setError(null);
+ fileSignal.current = signal;
+ inflight.current = new Map();
+ return () => {
+ signal.cancelled = true;
};
+ }, [fileKey]);
+
+ // Load the analysis, and re-load it whenever the panel's signal moves. It overwrites what is
+ // on screen in place — an in-flight refresh keeps the current content readable, and its
+ // outcome is what clears or sets the error, since nothing was cleared up front. No event is
+ // read here: the rounds to read follow from the analysis (the effect below).
+ useEffect(() => {
+ const signal = { cancelled: false };
api
.getAgentTraceAnalysis(projectId, agentId, sessionId, index)
.then((a) => {
if (signal.cancelled) return;
- setAnalysis(a);
- haveAnalysis = true;
- clearErrorWhenBothLanded();
- })
- .catch(fail);
- loadTraceEventPages(
- (offset, limit) =>
- api.getAgentTraceEvents(projectId, agentId, sessionId, index, offset, limit),
- {
- pageSize: TRACE_EVENT_PAGE_SIZE,
- signal,
- onPage: (page) => {
- // `total` comes from the latest page: the file is appended to while the Session runs.
- setTotal(page.total);
- // The page is spliced in AT ITS OFFSET rather than replacing or appending: a refresh
- // re-walks a file already on screen (the panel re-reads on every settled turn), and
- // a first page that replaced the list would drop a 2500-event file back to 1000 rows
- // and empty its later rounds for a moment, once per turn. A file SWITCH starts from
- // an empty list instead — the renderedFileKey reset above — so nothing is spliced
- // into another file's rows.
- setEvents((prev) => {
- const next = prev.slice();
- next.splice(page.offset, page.events.length, ...page.events);
- return next;
- });
- haveFirstPage = true;
- clearErrorWhenBothLanded();
- },
- },
- )
- .then((loaded) => {
- // The completed walk's last word on the file's length: rows past it are an earlier
- // walk's leftovers, from a file that came back shorter than it was read as before.
- if (!signal.cancelled) {
- setEvents((prev) => (prev.length > loaded ? prev.slice(0, loaded) : prev));
- }
+ setFile((prev) => fileAfterAnalysis(prev, a));
+ setRounds(withoutFailures);
+ setError(null);
})
- .catch(fail);
+ .catch((err: unknown) => {
+ if (!signal.cancelled) setError(apiErrorText(err));
+ });
return () => {
signal.cancelled = true;
};
}, [projectId, agentId, sessionId, index, reloadSignal]);
+ // Read the open rounds that need it: a round opened for the first time, and an open round
+ // whose range the latest analysis moved (the running round, which grows every turn). A
+ // re-read keeps the rows already on screen until it lands. A round being read for the same
+ // range is not asked for twice, and a read the analysis has since moved past is dropped when
+ // it lands — the newer read is the one that counts.
+ const { analysis, expanded } = file;
+ useEffect(() => {
+ if (analysis === null) return;
+ const signal = fileSignal.current;
+ for (const round of roundsToRead(analysis.tasks, shownRounds, expanded, rounds)) {
+ const range: RoundRange = {
+ taskIndex: round.taskIndex,
+ messageFrom: round.messageFrom,
+ messageTo: round.messageTo,
+ };
+ const key = rangeKey(range);
+ if (inflight.current.get(range.taskIndex) === key) continue;
+ inflight.current.set(range.taskIndex, key);
+ const land = (entry: RoundEntry) => {
+ if (signal.cancelled || inflight.current.get(range.taskIndex) !== key) return;
+ inflight.current.delete(range.taskIndex);
+ setRounds((prev) => new Map(prev).set(range.taskIndex, entry));
+ };
+ loadRoundEvents(
+ (offset, limit) =>
+ api.getAgentTraceEvents(projectId, agentId, sessionId, index, offset, limit),
+ range,
+ { signal },
+ )
+ .then((events) => land({ ...range, status: "loaded", rows: events.filter(isMainSession) }))
+ .catch((err: unknown) => land({ ...range, status: "failed", error: apiErrorText(err) }));
+ }
+ }, [analysis, expanded, shownRounds, rounds, projectId, agentId, sessionId, index]);
+
+ // Opening a file brings its open newest round into view: it is the last card, under the
+ // summary and the collapsed rounds drawn before it, so without this the panel opens on
+ // everything but the round it just opened. The card's top goes to the top of the panel, so
+ // its body — still being read — unfolds below it without moving it. Instant, not smooth: a
+ // smooth scroll would sweep past every card above it. Only the analysis that opened the file
+ // sets `reveal`; a refresh clears it, so a settled turn never moves the reader's scroll.
+ const reveal = file.reveal;
+ useLayoutEffect(() => {
+ if (reveal === null) return;
+ rootRef.current?.querySelector(`[data-round="${reveal}"]`)?.scrollIntoView({ block: "start" });
+ }, [reveal]);
+
+ // The error takes the whole view only while there is nothing to take it from: this re-reads
+ // on every settled turn now, so a blip mid-read would otherwise blank a file the user is in
+ // the middle of. With a file already rendered the failure is a line above it.
+ if (error !== null && analysis === null)
+ return <p className={`text-xs ${toneInk.danger}`}>{error}</p>;
+ if (!analysis) return <Skeleton className="h-40" />;
+
+ const toggle = (ti: number) => {
+ setFile((prev) => {
+ const next = new Set(prev.expanded);
+ if (next.has(ti)) next.delete(ti);
+ else next.add(ti);
+ return { ...prev, expanded: next };
+ });
+ // A failed read is not kept: closing and reopening the round is how it is retried.
+ setRounds((prev) => {
+ if (prev.get(ti)?.status !== "failed") return prev;
+ const next = new Map(prev);
+ next.delete(ti);
+ return next;
+ });
+ };
+
+ /** Click a bar: scroll to the corresponding message row and pin the highlight — the mouse moving away afterward shouldn't clear it, so this is stored separately from hover highlighting. */
+ const jumpTo = (ts: string) => {
+ const rk = firstRowKeyAt(rounds, expanded, ts);
+ if (rk === null) return;
+ setPinnedRow(rk);
+ // The target row may have just re-rendered from the highlight; wait for this frame to commit before scrolling.
+ requestAnimationFrame(() => {
+ rootRef.current
+ ?.querySelector(`[data-trace-row="${rk}"]`)
+ ?.scrollIntoView({ block: "center", behavior: "smooth" });
+ });
+ if (pinTimer.current) clearTimeout(pinTimer.current);
+ pinTimer.current = setTimeout(() => setPinnedRow(null), PIN_MS);
+ };
+
+ return (
+ <TraceFileBody
+ rootRef={rootRef}
+ analysis={analysis}
+ currency={currency}
+ expanded={expanded}
+ rounds={rounds}
+ shownRounds={shownRounds}
+ error={error}
+ highlight={highlight}
+ pinnedRow={pinnedRow}
+ onHighlight={onHighlight}
+ onToggle={toggle}
+ onShowEarlier={() => setShownRounds((n) => n + TRACE_ROUNDS_PAGE)}
+ onJump={jumpTo}
+ />
+ );
+}
+
+/**
+ * The file as drawn from what the view holds: the analysis, which rounds are open, which have
+ * been read. Separate from the loading so it renders to static markup with a given state.
+ */
+export function TraceFileBody({
+ rootRef,
+ analysis,
+ currency,
+ expanded,
+ rounds,
+ shownRounds,
+ error,
+ highlight,
+ pinnedRow,
+ onHighlight,
+ onToggle,
+ onShowEarlier,
+ onJump,
+}: {
+ rootRef?: RefObject<HTMLDivElement | null>;
+ analysis: TraceAnalysisResponse;
+ currency: Currency;
+ expanded: ReadonlySet<number>;
+ rounds: ReadonlyMap<number, RoundEntry>;
+ /** How many of the newest round cards are drawn. */
+ shownRounds: number;
+ /** A refresh that failed: what is drawn is the last read that succeeded. */
+ error: string | null;
+ highlight: TraceHighlight | null;
+ pinnedRow: string | null;
+ onHighlight: (h: TraceHighlight | null) => void;
+ onToggle: (taskIndex: number) => void;
+ onShowEarlier: () => void;
+ onJump: (ts: string) => void;
+}) {
// Cost is not priced here: the analysis carries each round's cost (and the file's), priced by
// the server with the cost center's own rule — the Project's current rates for the file's
// model, at the tier each Request's timestamp fell in — so what this file adds up to is what
// the conversation toolbar shows for the same requests. An unpriced model (or a legacy head
// naming no provider) simply carries no cost, and formatMoney renders that as a dash.
- // Session context window (the upper bound for each round's donut ring): read once from session_meta, falling back to 128000 if unconfigured.
- const contextMax = useMemo(() => {
- const meta = events.find((m) => m.type === "session_meta");
- return resolveContextWindow(
- meta
- ? (meta.payload as { model_context_window?: number | string }).model_context_window
- : undefined,
- );
- }, [events]);
-
- const { tasks, global, statsByTask, globalLlmMs } = useMemo(() => {
- const g = { buckets: zeroBuckets(), toolCalls: 0 };
- const empty = new Map<number, TraceTaskStats>();
- if (!analysis)
- return {
- tasks: [] as TaskData[],
- global: g,
- statsByTask: empty,
- globalLlmMs: 0,
- };
-
- // A round's duration range always comes from the server (analysis.tasks,
- // computed over the whole file; the start is that round's first
- // request_begin). For a degenerate round with no Request, startTs is an
- // empty string → no range is built, and the duration counts as 0.
- const boundsByTask = new Map<number, { min: number; max: number }>();
- for (const t of analysis.tasks) {
- const min = Date.parse(t.startTs);
- const max = Date.parse(t.endTs);
- if (Number.isFinite(min) && Number.isFinite(max)) {
- boundsByTask.set(t.taskIndex, { min, max });
- }
- }
+ // Session context window (the upper bound for each round's donut ring): the analysis reads it
+ // off the file's head session_meta; an older server sends none, and the ring falls back to 128000.
+ const contextMax = resolveContextWindow(analysis.modelContextWindow);
- const map = new Map<number, TaskData>();
- const ensure = (ti: number): TaskData => {
- let d = map.get(ti);
+ const { timelines, global, globalLlmMs } = useMemo(() => {
+ const g = { buckets: zeroBuckets(), toolCalls: analysis.toolSpans.length };
+ const byTask = new Map<number, TaskTimeline>();
+ const ensure = (ti: number): TaskTimeline => {
+ let d = byTask.get(ti);
if (!d) {
- const b = boundsByTask.get(ti);
- d = {
- taskIndex: ti,
- segments: [],
- spans: [],
- otherSpans: [],
- messages: [],
- toolCalls: 0,
- durationMs: b ? Math.max(0, b.max - b.min) : 0,
- };
- map.set(ti, d);
+ d = { segments: [], spans: [], otherSpans: [] };
+ byTask.set(ti, d);
}
return d;
};
- for (const t of analysis.tasks) ensure(t.taskIndex); // empty rounds still need to appear in the list
for (const s of analysis.modelSegments) ensure(s.taskIndex).segments.push(s);
- for (const s of analysis.toolSpans) {
- const d = ensure(s.taskIndex);
- d.spans.push(s);
- d.toolCalls += 1;
- }
+ for (const s of analysis.toolSpans) ensure(s.taskIndex).spans.push(s);
// Non-tool auxiliary phases (MCP connect); pre-otherSpans analysis payloads (cached
// responses) may omit the field.
for (const s of analysis.otherSpans ?? []) ensure(s.taskIndex).otherSpans.push(s);
- // Message attribution: **by the server-given index range**, never guessed
- // from timestamps. The same millisecond can be crowded with "the previous
- // round's last reply, compaction_begin, the compaction prompt, the next
- // round's request_begin" — splitting by a time boundary can't tell them
- // apart, and this round's reply would get misattributed to the next
- // round (the server already knows this message-by-message from its
- // sequential scan, no need to re-guess it here).
- // events is only used to populate the message list (a list view that
- // names its loading progress at the bottom); no **numeric value** is ever
- // derived from it: the pages arrive one after another, so aggregating over
- // events would undercount Token/cost for as long as a long Trace is still loading.
- const taskOfIndex = (k: number): number | null => {
- for (const t of analysis.tasks) {
- if (k >= t.messageFrom && k <= t.messageTo) return t.taskIndex;
- }
- return null;
- };
- for (let i = 0; i < events.length; i++) {
- const msg = events[i]!;
- if (msg.origin && msg.origin.length > 0) continue; // sub-session messages don't enter this file's grouping
- const ti = taskOfIndex(i); // events is paged from the file's start, so i IS the index within the file
- if (ti !== null) ensure(ti).messages.push(msg);
- }
- g.toolCalls = analysis.toolSpans.length;
// Numeric values always come from analysis.tasks, computed by the server
- // over **the whole file**. Note the differing conventions:
+ // over **the whole file** — never from the events, which are read one
+ // open round at a time. Note the differing conventions:
// - context: a **snapshot** (usage at that round's last non-compaction Request), not an accumulated value;
// - tokens: this round's **throughput** (sum across Requests), used for
// Token / cost; `tokens.output` doubles as the TPS numerator;
@@ -430,72 +543,34 @@ export function TraceFileView({
// The global summary and the per-round cards below share **the same
// scope** (including compaction rounds): every global figure is the sum
// across rounds, and they must add up.
- const statsByTask = new Map(analysis.tasks.map((t) => [t.taskIndex, t]));
for (const t of analysis.tasks) {
g.buckets.cacheRead += t.tokens.cacheRead;
g.buckets.cacheWrite += t.tokens.cacheWrite;
g.buckets.output += t.tokens.output;
}
const gLlm = analysis.tasks.reduce((s, t) => s + t.llmMs, 0);
- const tasks = [...map.values()].sort((a, b) => a.taskIndex - b.taskIndex);
- return { tasks, global: g, statsByTask, globalLlmMs: gLlm };
- }, [analysis, events]);
+ return { timelines: byTask, global: g, globalLlmMs: gLlm };
+ }, [analysis]);
- // The error takes the whole view only while there is nothing to take it from: this re-reads
- // on every settled turn now, so a blip mid-read would otherwise blank a file the user is in
- // the middle of. With a file already rendered the failure is a line above it (below).
- if (error !== null && analysis === null)
- return <p className="text-xs text-red-600 dark:text-red-400">{error}</p>;
- if (!analysis) return <Skeleton className="h-40" />;
+ const shown = useMemo(() => visibleRounds(analysis.tasks, shownRounds), [analysis, shownRounds]);
+ const earlier = analysis.tasks.length - shown.length;
// Duration is likewise "the sum across rounds" computed by the server over
// the whole file (including compaction rounds, same scope as the per-round
- // display below): events is paginated, so subtracting first from last
- // would truncate a long Trace's duration (a 90s span where the first 1000 events only cover the first 30s → showing 30s).
+ // display below).
const globalMs = analysis.elapsedMs;
- const toggle = (ti: number) =>
- setCollapsed((prev) => {
- const next = new Set(prev);
- if (next.has(ti)) next.delete(ti);
- else next.add(ti);
- return next;
- });
-
- /** The **first** message row at that instant; a bar-initiated highlight/jump uses this to hit only one row. */
- const firstRowKeyAt = (ts: string): string | null => {
- for (const t of tasks) {
- const i = t.messages.findIndex((m) => m.timestamp === ts);
- if (i >= 0) return rowKeyOf(t.taskIndex, i);
- }
- return null;
- };
-
// Target row for hover highlighting: use the highlight's own rowKey (from a
// message row) if it has one; otherwise, with only ts (from a bar), take the first row.
const hoveredRow =
- highlight?.rowKey ?? (highlight?.ts !== undefined ? firstRowKeyAt(highlight.ts) : null);
-
- /** Click a bar: scroll to the corresponding message row and pin the highlight — the mouse moving away afterward shouldn't clear it, so this is stored separately from hover highlighting. */
- const jumpTo = (ts: string) => {
- const rk = firstRowKeyAt(ts);
- if (rk === null) return;
- setPinnedRow(rk);
- // The target row may have just re-rendered from the highlight; wait for this frame to commit before scrolling.
- requestAnimationFrame(() => {
- rootRef.current
- ?.querySelector(`[data-trace-row="${rk}"]`)
- ?.scrollIntoView({ block: "center", behavior: "smooth" });
- });
- if (pinTimer.current) clearTimeout(pinTimer.current);
- pinTimer.current = setTimeout(() => setPinnedRow(null), PIN_MS);
- };
+ highlight?.rowKey ??
+ (highlight?.ts !== undefined ? firstRowKeyAt(rounds, expanded, highlight.ts) : null);
return (
<div ref={rootRef} className="space-y-4">
{/* A re-read that failed: what follows is the last read that succeeded, so it may be a
turn or two behind. */}
- {error !== null && <p className="text-xs text-red-600 dark:text-red-400">{error}</p>}
+ {error !== null && <p className={`text-xs ${toneInk.danger}`}>{error}</p>}
{/* Global summary: split into three groups by nature (count / Token
usage / duration·cost·TPS), separated by vertical rules — a dozen
metrics laid out in one row would read as a blur of digits; grouping lets you spot the kind you want at a glance. */}
@@ -509,14 +584,13 @@ export function TraceFileView({
<div className="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-3">
{/* Counts */}
<div>
- {/* Rounds = number of cards below (a compaction round counts as
- a round too): the global summary and the per-round display
- below share **the same scope** — every figure is the sum
- across rounds and must add up. The average is exactly the two
- rows above it divided, tool calls ÷ rounds, so it holds that
- same scope and a reader can check the division by eye — a
- denominator that skipped compaction rounds would no longer
- match the round count printed here. */}
+ {/* Rounds = every round in the file (a compaction round counts as
+ a round too), drawn or not: the global summary and the per-round
+ cards share **the same scope** — every figure is the sum across
+ rounds and must add up. The average is exactly the two rows above
+ it divided, tool calls ÷ rounds, so it holds that same scope and a
+ reader can check the division by eye — a denominator that skipped
+ compaction rounds would no longer match the round count printed here. */}
<SummaryRow label={S.traces.tasksLabel} value={String(analysis.tasks.length)} />
<SummaryRow label={S.traces.toolCalls} value={String(global.toolCalls)} />
<SummaryRow
@@ -556,29 +630,51 @@ export function TraceFileView({
</div>
</Card>
+ {/* The rounds before the drawn ones: each click draws the next page of them above. */}
+ {earlier > 0 && (
+ <button
+ type="button"
+ data-slot="earlier"
+ onClick={onShowEarlier}
+ className="w-full rounded-md py-1 text-center text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-gray-800/60 dark:hover:text-gray-200"
+ >
+ {S.traces.earlierRounds(earlier)}
+ </button>
+ )}
+
{/* Grouped by Task */}
- {tasks.map((t) => {
- const open = !collapsed.has(t.taskIndex);
+ {shown.map((st) => {
+ const open = expanded.has(st.taskIndex);
+ const timeline = timelines.get(st.taskIndex);
+ // A round's duration range always comes from the server (computed over
+ // the whole file; the start is that round's first request_begin). For a
+ // degenerate round with no Request, startTs is an empty string → the
+ // duration counts as 0.
+ const startMs = Date.parse(st.startTs);
+ const endMs = Date.parse(st.endTs);
+ const durationMs =
+ Number.isFinite(startMs) && Number.isFinite(endMs) ? Math.max(0, endMs - startMs) : 0;
// This round's convention as computed by the server over the whole
// file: ctx = context snapshot at the end of this round (last
// non-compaction Request), tokens = this round's throughput (used
// for Token and cost, output doubles as the TPS numerator), llmMs = the TPS denominator.
- const st = statsByTask.get(t.taskIndex);
- const ctx = st?.context;
- const tokens = st?.tokens ?? zeroBuckets();
+ const ctx = st.context;
+ const tokens = st.tokens;
const compactionBadge = compactionBadgeLabel(st);
return (
- <Card key={t.taskIndex} padding="none">
+ // `data-round` is what a file's first open scrolls to; the margin keeps the card off
+ // the panel's top edge once it is there.
+ <Card key={st.taskIndex} padding="none" data-round={st.taskIndex} className="scroll-mt-3">
<button
type="button"
data-slot="head"
- onClick={() => toggle(t.taskIndex)}
+ onClick={() => onToggle(st.taskIndex)}
aria-expanded={open}
className="flex w-full items-center gap-2 bg-gray-50 px-3 py-2 text-left transition-colors duration-150 hover:bg-gray-100 dark:bg-gray-900 dark:hover:bg-gray-800/60"
>
<Chevron open={open} size={13} className="text-gray-400" />
<span className="shrink-0 text-sm font-semibold">
- {S.traces.task(t.taskIndex + 1)}
+ {S.traces.task(st.taskIndex + 1)}
</span>
{/* Compaction rounds are explicitly flagged: their Token /
cost / duration / TPS count toward the global summary just
@@ -597,12 +693,12 @@ export function TraceFileView({
>
<StatChip
glyph={STAT_ICONS.toolCalls}
- value={String(t.toolCalls)}
+ value={String(timeline?.spans.length ?? 0)}
label={S.traces.toolCalls}
/>
{/* Token usage broken down by category: this round's input
(parenthesized portion is the cache hit) + this round's
- output. Uses the server's this-round throughput tokens (whole file, including compaction), not computed from truncated events. */}
+ output. Uses the server's this-round throughput tokens (whole file, including compaction). */}
<InputChip buckets={tokens} />
<StatChip
glyph={STAT_ICONS.output}
@@ -611,17 +707,17 @@ export function TraceFileView({
/>
<StatChip
glyph={STAT_ICONS.cost}
- value={formatMoney(st?.cost ?? null, currency)}
+ value={formatMoney(st.cost ?? null, currency)}
label={`${S.common.cost}(${currency})`}
/>
<StatChip
glyph={STAT_ICONS.elapsed}
- value={humanizeDuration(t.durationMs)}
- label={`${S.chat.statElapsed}${durationSplit(st?.llmMs ?? 0, st?.toolMs ?? 0)}`}
+ value={humanizeDuration(durationMs)}
+ label={`${S.chat.statElapsed}${durationSplit(st.llmMs, st.toolMs)}`}
/>
<StatChip
glyph={STAT_ICONS.tps}
- value={formatTps(computeTps(tokens.output, st?.llmMs ?? 0))}
+ value={formatTps(computeTps(tokens.output, st.llmMs))}
label={S.chat.statTps}
/>
</div>
@@ -631,7 +727,7 @@ export function TraceFileView({
title). The exact figures are given by the chips on the
left; the ring is only a peripheral hint of the usage
ratio, hence its small size. It's fed the snapshot ctx
- rather than the accumulated t.buckets — the latter
+ rather than the accumulated tokens — the latter
recounts the history each round carries forward, so a few
rounds of tool calls alone could fill the ring. A pure compaction Task has no snapshot and draws no ring. */}
{ctx && (
@@ -654,54 +750,99 @@ export function TraceFileView({
{open && (
<div data-slot="body" className="space-y-3 p-3">
- {/* This round's timeline */}
- {(t.segments.length > 0 || t.spans.length > 0 || t.otherSpans.length > 0) && (
- <div className="rounded-md border border-gray-100 p-2 dark:border-gray-800/60">
- <p className="mb-1.5 text-xs font-medium text-gray-500">{S.traces.timeline}</p>
- <TimelineChart
- segments={t.segments}
- toolSpans={t.spans}
- otherSpans={t.otherSpans}
- highlight={highlight}
- onHighlight={onHighlight}
- onJump={jumpTo}
- hideTaskLabel
- />
- </div>
- )}
+ {/* This round's timeline: drawn from the analysis, so it is there before the messages are read. */}
+ {timeline !== undefined &&
+ (timeline.segments.length > 0 ||
+ timeline.spans.length > 0 ||
+ timeline.otherSpans.length > 0) && (
+ <div className="rounded-md border border-gray-100 p-2 dark:border-gray-800/60">
+ <p className="mb-1.5 text-xs font-medium text-gray-500">
+ {S.traces.timeline}
+ </p>
+ <TimelineChart
+ segments={timeline.segments}
+ toolSpans={timeline.spans}
+ otherSpans={timeline.otherSpans}
+ highlight={highlight}
+ onHighlight={onHighlight}
+ onJump={onJump}
+ hideTaskLabel
+ />
+ </div>
+ )}
{/* This round's messages */}
- <div>
- <p className="mb-1.5 text-xs font-medium text-gray-500">
- {S.traces.messages}({t.messages.length})
- </p>
- {t.messages.length === 0 ? (
- <p className="text-xs text-gray-400">{S.common.none}</p>
- ) : (
- <ul className="divide-y divide-gray-100 rounded-md border border-gray-200 dark:divide-gray-800/60 dark:border-gray-800">
- {t.messages.map((msg, i) => {
- const rk = rowKeyOf(t.taskIndex, i);
- return (
- <EventRow
- key={i}
- msg={msg}
- rowKey={rk}
- matched={rk === hoveredRow || rk === pinnedRow}
- onHighlight={(h) => onHighlight(h)}
- />
- );
- })}
- </ul>
- )}
- </div>
+ <RoundMessages
+ round={st}
+ entry={rounds.get(st.taskIndex)}
+ hoveredRow={hoveredRow}
+ pinnedRow={pinnedRow}
+ onHighlight={onHighlight}
+ />
</div>
)}
</Card>
);
})}
+ </div>
+ );
+}
- {events.length < total && (
- <p className="text-xs text-gray-400">{S.traces.loadingNote(events.length, total)}</p>
+/**
+ * An open round's messages: its rows once read, a placeholder while the first read is out,
+ * and the failure in their place when it did not come back. A re-read of a round already read
+ * keeps the rows on screen until it lands.
+ */
+function RoundMessages({
+ round,
+ entry,
+ hoveredRow,
+ pinnedRow,
+ onHighlight,
+}: {
+ round: TraceTaskStats;
+ entry: RoundEntry | undefined;
+ hoveredRow: string | null;
+ pinnedRow: string | null;
+ onHighlight: (h: TraceHighlight | null) => void;
+}) {
+ // Before the read lands the count is the range's, known from the analysis alone.
+ const count = entry?.status === "loaded" ? entry.rows.length : roundSpan(round);
+ return (
+ <div>
+ <p className="mb-1.5 text-xs font-medium text-gray-500">
+ {S.traces.messages}({count})
+ </p>
+ {entry === undefined ? (
+ count === 0 ? (
+ <p className="text-xs text-gray-400">{S.common.none}</p>
+ ) : (
+ <div role="status" aria-busy="true" className="space-y-1.5">
+ <span className="sr-only">{S.traces.roundLoading}</span>
+ {Array.from({ length: Math.min(3, count) }, (_, i) => (
+ <Skeleton key={i} className="h-7 w-full" />
+ ))}
+ </div>
+ )
+ ) : entry.status === "failed" ? (
+ <p className={`text-xs ${toneInk.danger}`}>{entry.error}</p>
+ ) : entry.rows.length === 0 ? (
+ <p className="text-xs text-gray-400">{S.common.none}</p>
+ ) : (
+ <ul className="divide-y divide-gray-100 rounded-md border border-gray-200 dark:divide-gray-800/60 dark:border-gray-800">
+ {entry.rows.map((msg, i) => {
+ const rk = rowKeyOf(round.taskIndex, i);
+ return (
+ <EventRow
+ key={i}
+ msg={msg}
+ rowKey={rk}
+ matched={rk === hoveredRow || rk === pinnedRow}
+ onHighlight={(h) => onHighlight(h)}
+ />
+ );
+ })}
+ </ul>
)}
</div>
);
diff --git a/packages/web/src/features/traces/trace-panel.tsx b/packages/web/src/features/traces/trace-panel.tsx
index 77ba8bb2..d2a219c5 100644
--- a/packages/web/src/features/traces/trace-panel.tsx
+++ b/packages/web/src/features/traces/trace-panel.tsx
@@ -89,7 +89,7 @@ export function TracePanel({
// "whatever activeTraceFile falls back to" — the newest file, re-resolved on every
// re-list — so a compaction shard appearing mid-run would move a reader who never
// clicked a pill onto the new file, remounting the view below onto a different index
- // and taking its collapsed rounds, pinned row and scroll position with it. Pinned,
+ // and taking its open rounds, pinned row and scroll position with it. Pinned,
// only a pill click moves the selection.
setFileIndex((cur) => cur ?? sorted[0]?.index ?? null);
setError(null);
diff --git a/packages/web/src/features/traces/trace-rounds.ts b/packages/web/src/features/traces/trace-rounds.ts
new file mode 100644
index 00000000..d7ddec1d
--- /dev/null
+++ b/packages/web/src/features/traces/trace-rounds.ts
@@ -0,0 +1,176 @@
+/**
+ * Which rounds the Trace file view draws and reads (pure — unit-tested in
+ * test/trace-rounds.test.ts).
+ *
+ * The analysis describes the WHOLE file — every figure on the panel and every round's
+ * `messageFrom`/`messageTo` index range — in one request. The events behind a round are read
+ * only when that round is open, and only that round's range: a long Session's file is tens of
+ * megabytes and thousands of rounds, and reading or drawing all of it at once is what stalled
+ * the panel. Round cards are drawn a page at a time from the newest end, so the list itself
+ * stays a bounded number of heads however long the file is.
+ */
+import type { OmniMessage } from "@lmliheng/penguin-core/omnimessage";
+import type { TraceEventsResponse } from "@lmliheng/penguin-server/api";
+
+/** Round cards drawn per step: the panel opens on the newest this many, and each "earlier" click adds this many more. */
+export const TRACE_ROUNDS_PAGE = 50;
+
+/**
+ * Events per request: the largest `limit` the events endpoint accepts (it rejects anything
+ * above 1000), so a round is read in the fewest round trips the server allows.
+ */
+export const TRACE_EVENT_PAGE_SIZE = 1000;
+
+/** A round as the analysis places it in the file: its inclusive event index range. */
+export interface RoundRange {
+ taskIndex: number;
+ messageFrom: number;
+ messageTo: number;
+}
+
+/** Cancellation handed to a read by its caller; flipped when the view moves to another file or unmounts. */
+export interface TraceEventsSignal {
+ cancelled: boolean;
+}
+
+/**
+ * How many events a round's range holds. A round the analysis gave no message (its range left
+ * at -1, or inverted) holds none and is never read.
+ */
+export function roundSpan(range: RoundRange): number {
+ if (range.messageFrom < 0 || range.messageTo < range.messageFrom) return 0;
+ return range.messageTo - range.messageFrom + 1;
+}
+
+/**
+ * The rounds the panel draws: the newest `shown` of `tasks`, oldest first. The analysis lists
+ * rounds in file order already; they are sorted here anyway, on a copy, so the card order never
+ * depends on how the server happened to build the list.
+ */
+export function visibleRounds<T extends RoundRange>(tasks: readonly T[], shown: number): T[] {
+ const sorted = [...tasks].sort((a, b) => a.taskIndex - b.taskIndex);
+ return sorted.slice(Math.max(0, sorted.length - Math.max(0, shown)));
+}
+
+/**
+ * Read one round's events, in file order, within `[messageFrom, messageTo]`, at most
+ * TRACE_EVENT_PAGE_SIZE per request — `ceil(span / 1000)` requests for a round the server
+ * answers in full, none for an empty round.
+ *
+ * The next offset is the end of what actually arrived, never `offset + limit`, so a page the
+ * server answers short leaves no hole. The read stops early, with what it has, on a page that
+ * carries no events or once it reaches the page's `total`: the analysis reads a record that is
+ * still being appended a moment before the events endpoint counts it, and a range that runs
+ * past the file's end must not loop asking for it. Events past `messageTo` in a page are
+ * dropped, so the result never leaks into the next round.
+ *
+ * Cancellation is checked on both sides of every await, and a cancelled read resolves with
+ * whatever it had: the caller checks its own signal before using the result. Rejections are not
+ * caught — the caller decides what a failed round shows.
+ */
+export async function loadRoundEvents(
+ fetchPage: (offset: number, limit: number) => Promise<TraceEventsResponse>,
+ range: RoundRange,
+ opts: { signal?: TraceEventsSignal } = {},
+): Promise<OmniMessage[]> {
+ const events: OmniMessage[] = [];
+ if (roundSpan(range) === 0) return events;
+ // Read through a call, not inline: the flag flips while a page is in flight, and an inline
+ // check would narrow it to `false` for the rest of the loop body.
+ const cancelled = (): boolean => opts.signal?.cancelled === true;
+ let offset = range.messageFrom;
+ while (offset <= range.messageTo) {
+ if (cancelled()) return events;
+ const limit = Math.min(TRACE_EVENT_PAGE_SIZE, range.messageTo - offset + 1);
+ const page = await fetchPage(offset, limit);
+ if (cancelled()) return events;
+ const taken = page.events.slice(0, range.messageTo - offset + 1);
+ if (taken.length === 0) return events;
+ events.push(...taken);
+ offset += taken.length;
+ if (offset >= page.total) return events;
+ }
+ return events;
+}
+
+/**
+ * The expanded rounds whose cached range no longer matches the fresh analysis — in practice the
+ * round still running, which grows with every settled turn. Only these are re-read on a
+ * refresh; a collapsed round keeps its cache untouched until it is opened again, and a round the
+ * cache does not hold is a first read, not a stale one.
+ */
+export function staleRounds(
+ cached: ReadonlyMap<number, RoundRange>,
+ fresh: readonly RoundRange[],
+ expanded: ReadonlySet<number>,
+): number[] {
+ const stale: number[] = [];
+ for (const round of fresh) {
+ if (!expanded.has(round.taskIndex)) continue;
+ const held = cached.get(round.taskIndex);
+ if (held === undefined) continue;
+ if (held.messageFrom !== round.messageFrom || held.messageTo !== round.messageTo) {
+ stale.push(round.taskIndex);
+ }
+ }
+ return stale;
+}
+
+/**
+ * The rounds to read now: of the drawn rounds, the open ones the cache does not hold yet and the
+ * open ones whose cached range the analysis has since moved. A collapsed round is never read,
+ * nor is an open one scrolled out of the drawn window — opening or revealing it is what reads it.
+ */
+export function roundsToRead<T extends RoundRange>(
+ tasks: readonly T[],
+ shown: number,
+ expanded: ReadonlySet<number>,
+ cached: ReadonlyMap<number, RoundRange>,
+): T[] {
+ const open = visibleRounds(tasks, shown).filter((t) => expanded.has(t.taskIndex));
+ const stale = new Set(staleRounds(cached, open, expanded));
+ return open.filter((t) => !cached.has(t.taskIndex) || stale.has(t.taskIndex));
+}
+
+/** The newest round's taskIndex, or null for a file with no round yet. */
+function newestRound(rounds: readonly RoundRange[]): number | null {
+ let newest: number | null = null;
+ for (const r of rounds) if (newest === null || r.taskIndex > newest) newest = r.taskIndex;
+ return newest;
+}
+
+/**
+ * The expanded set once an analysis lands. A file seen for the first time (`previous` null, or
+ * a file that had no round yet) opens on its newest round only. On a refresh the reader's
+ * choices stand, and a round that appeared since arrives collapsed — unless the round that was
+ * newest before it is open: a reader following the run keeps following it, so the new newest
+ * round opens beside it.
+ */
+export function expandedAfterAnalysis(
+ previous: readonly RoundRange[] | null,
+ fresh: readonly RoundRange[],
+ expanded: ReadonlySet<number>,
+): ReadonlySet<number> {
+ const freshNewest = newestRound(fresh);
+ const previousNewest = previous === null ? null : newestRound(previous);
+ if (previousNewest === null) return new Set(freshNewest === null ? [] : [freshNewest]);
+ if (freshNewest === null || freshNewest === previousNewest || !expanded.has(previousNewest)) {
+ return expanded;
+ }
+ return new Set([...expanded, freshNewest]);
+}
+
+/**
+ * The round to scroll into view once an analysis lands: on the analysis that opens the file
+ * (the same one expandedAfterAnalysis opens on its newest round), that newest round — the last
+ * card drawn, below up to TRACE_ROUNDS_PAGE − 1 collapsed ones. Null on every refresh after it,
+ * including one that opens a new round for a reader following the run: a settled turn never
+ * moves the reader's scroll.
+ */
+export function revealAfterAnalysis(
+ previous: readonly RoundRange[] | null,
+ fresh: readonly RoundRange[],
+): number | null {
+ if (previous !== null && newestRound(previous) !== null) return null;
+ return newestRound(fresh);
+}
diff --git a/packages/web/src/lib/omni/stream-controller.ts b/packages/web/src/lib/omni/stream-controller.ts
index 422b3716..d3635d34 100644
--- a/packages/web/src/lib/omni/stream-controller.ts
+++ b/packages/web/src/lib/omni/stream-controller.ts
@@ -83,16 +83,16 @@ export type MessagesPageQuery =
/**
* Initial (tail) window size, in message-bearing units — one unit = one Task, opened by
- * a user prompt (the server's cut rule; see MessagesPageInfo). 50 is what a reader
- * actually looks at when a conversation opens: the rest of a long Session streams in on
- * scroll (see loadOlder). Anything much larger stops being a window at all — at 200 the
- * tail covered nearly every real Session, so every open still read, shipped and rendered
- * the whole transcript, tool output included.
+ * a user prompt (the server's cut rule; see MessagesPageInfo). A conversation opens on its
+ * newest 20 Q&A pairs, the user's call: the rest of a long Session streams in on scroll
+ * (see loadOlder). The count bounds what the page renders, not what it weighs — one Task
+ * can run hundreds of tool calls — so the server also cuts a page at its byte budget, and
+ * a page may then hold fewer units than asked for while still carrying `before`.
*/
-export const TAIL_UNITS = 50;
+export const TAIL_UNITS = 20;
-/** Scroll-up backfill window size: one more tail's worth per prepend, so each stays snappy. */
-export const OLDER_UNITS = 50;
+/** Scroll-up backfill window size: each scroll to the top adds 20 more Q&A pairs. */
+export const OLDER_UNITS = 20;
/**
* Item-id space reserved per prepended window. The live model numbers its items upward
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index 62774394..7e1c73d0 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -2109,11 +2109,43 @@ function bindSubagent(model: StreamModel, sessionId: string, sub: StreamModel):
// Overlap dedup (connect-first + dedup)
// ---------------------------------------------------------------------------
-/** Disk-only transport metadata must not make an otherwise identical SSE envelope look new. */
+/** Stands in for an image's content inside a dedup key (see dedupKey). */
+const IMAGE_IN_KEY = "<image>";
+
+/**
+ * An image slot's value as the dedup key sees it: inline bytes (`data:`) and a history page's
+ * reference to the same Trace record (`/api/sessions/<id>/trace-image?…`) are one image; any
+ * other address (a web URL) is kept, since it is the same string in both copies anyway.
+ */
+function imageInKey(value: unknown): unknown {
+ if (typeof value !== "string") return value;
+ return value.startsWith("data:") || /^\/api\/sessions\/[^/?#]+\/trace-image\?/.test(value)
+ ? IMAGE_IN_KEY
+ : value;
+}
+
+/**
+ * The envelope a history copy and its SSE copy share. Disk-only transport metadata
+ * (`tracePosition`) must not make an otherwise identical SSE envelope look new, and neither
+ * may an image's form: a windowed history page carries a user `image_url` and a tool output's
+ * `images` by reference while the stream carries the bytes, and an SSE copy that escaped the
+ * overlap dedup would draw the person's image twice. Two images of one prompt may then share a
+ * key (same timestamp); that is harmless, since a history read holds a prompt whole (the server
+ * appends held inputs the Trace lacks), so each stream copy has its own history copy to match.
+ */
function dedupKey(msg: OmniMessage): string {
const { tracePosition: _tracePosition, ...envelope } = msg as OmniMessage & {
tracePosition?: TracePosition;
};
+ if (msg.type === "model_msg") {
+ const p = msg.payload as { type?: string; image_url?: unknown; images?: unknown };
+ if (p.type === "image_url") {
+ return JSON.stringify({ ...envelope, payload: { ...p, image_url: imageInKey(p.image_url) } });
+ }
+ if (p.type === "tool_call_output" && Array.isArray(p.images)) {
+ return JSON.stringify({ ...envelope, payload: { ...p, images: p.images.map(imageInKey) } });
+ }
+ }
return JSON.stringify(envelope);
}
diff --git a/packages/web/src/lib/session-machines.ts b/packages/web/src/lib/session-machines.ts
index 433c04f7..b3327e1c 100644
--- a/packages/web/src/lib/session-machines.ts
+++ b/packages/web/src/lib/session-machines.ts
@@ -15,6 +15,7 @@
* displays them, and a stale entry surviving a reload would route a call at a machine that
* may no longer own — or may no longer have — that Session.
*/
+import { apiUrl } from "./server-context";
/** sessionId → the machine it lives on. Absent = this server. */
const owners = new Map<string, string>();
@@ -61,3 +62,15 @@ export function machineForPath(path: string): string | null {
const sessionId = sessionIdInPath(path);
return sessionId === null ? null : machineForSession(sessionId);
}
+
+/**
+ * A server-absolute URL the BROWSER follows itself (an `<img src>`), routed by the same rule.
+ * No request passes through the fetch wrapper for the rule to act on, so the owner's proxy
+ * prefix has to be in the URL: a windowed history page names each Trace image as
+ * `/api/sessions/<id>/trace-image?…`, which for a Session on a machine only that machine can
+ * answer. Anything that is not a Session path (a `data:` URL, an http(s) address, a URL already
+ * re-rooted onto a machine) comes back unchanged.
+ */
+export function routedUrl(url: string): string {
+ return apiUrl(url, machineForPath(url));
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 1b94b00e..43892981 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -3736,8 +3736,10 @@ export const en: Strings = {
globalSummary: "Overall",
tasksLabel: "Turns",
messages: "Messages",
- /** Shown while the file's remaining pages are still being fetched; gone once every message is on screen. */
- loadingNote: (shown: number, total: number) => `Loaded ${shown} / ${total} messages…`,
+ /** The control above the drawn round cards: how many earlier rounds are not drawn yet; a click draws the next page of them. */
+ earlierRounds: (n: number) => (n === 1 ? "1 earlier turn" : `${n} earlier turns`),
+ /** Spoken by an open round's placeholder while its messages are being read. */
+ roundLoading: "Reading this turn's messages",
zoom: "Zoom",
zoomReset: "Double-click to reset zoom",
zoomOut: "Zoom out",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 753b993a..29628964 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -3776,8 +3776,10 @@ export const zh = {
globalSummary: "全局统计",
tasksLabel: "轮次",
messages: "消息",
- /** Shown while the file's remaining pages are still being fetched; gone once every message is on screen. */
- loadingNote: (shown: number, total: number) => `已载入 ${shown} / ${total} 条消息…`,
+ /** The control above the drawn round cards: how many earlier rounds are not drawn yet; a click draws the next page of them. */
+ earlierRounds: (n: number) => `更早的 ${n} 轮`,
+ /** Spoken by an open round's placeholder while its messages are being read. */
+ roundLoading: "正在读取本轮消息",
zoom: "缩放",
zoomReset: "双击复位缩放",
zoomOut: "缩小",
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index c70b1ef0..70653e2e 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -5,6 +5,11 @@
* keeps localDecisions), approval re-delivery keyed by origin composite key + missing
* card backfill, the local answer time an optimistic resolveApproval stamps, and history
* load failure/retry.
+ *
+ * Windowed history: a conversation opens on its newest 20 Q&A pairs and each scroll to the top
+ * asks for 20 more; a page the server cut short at its byte budget still offers the history
+ * before it; a user image the page carries by reference and the stream's inline copy of it
+ * draw one picture.
*/
import { describe, expect, it } from "vitest";
import {
@@ -12,6 +17,7 @@ import {
assistantText,
compactionBegin,
compactionEnd,
+ imageUrlMessage,
partialText,
partialToolCallOutput,
sessionMeta,
@@ -32,7 +38,12 @@ import type {
import { OLDER_UNITS, TAIL_UNITS, createStreamController } from "../src/lib/omni/stream-controller";
import type { MessagesPageQuery, StreamController } from "../src/lib/omni/stream-controller";
import { approvalKey, findToolCard } from "../src/lib/omni/stream-model";
-import type { AssistantTextItem, TaskStatsItem, ToolCallItem } from "../src/lib/omni/stream-model";
+import type {
+ AssistantTextItem,
+ TaskStatsItem,
+ ToolCallItem,
+ UserImageItem,
+} from "../src/lib/omni/stream-model";
/** Override a message timestamp (constructor defaults to the current time). */
function at<M extends OmniMessage>(msg: M, ts: string): M {
@@ -556,6 +567,73 @@ describe("windowed history: tail-first load + scroll-up backfill", () => {
at(tokenUsage(counts(400), counts(400)), "2026-07-04T00:00:04.000Z"),
];
+ it("a conversation opens on its newest 20 Q&A pairs, and each scroll to the top asks for 20 more", async () => {
+ const h = createHarness();
+ const p = h.controller.load();
+ h.controller.handleServer({ type: "task_state", state: "idle" });
+ h.resolveLoad(HISTORY_TASK, undefined, null, pageInfo({ before: "2:10", earlierTurns: 40 }));
+ await p;
+ const first = h.controller.loadOlder();
+ h.resolveLoad(OLD_TURN, undefined, null, pageInfo({ before: "1:30", earlierTurns: 20 }));
+ await first;
+ const second = h.controller.loadOlder();
+ h.resolveLoad(OLD_TURN, undefined, null, pageInfo({ earlierTurns: 0 }));
+ await second;
+ // The Q&A-pair counts the server is asked for: what the person sees first and per scroll.
+ expect(h.pageArgs).toEqual([
+ { kind: "tail", limit: 20 },
+ { kind: "before", cursor: "2:10", limit: 20 },
+ { kind: "before", cursor: "1:30", limit: 20 },
+ ]);
+ expect(h.controller.older.hasMore).toBe(false);
+ });
+
+ it("a page the server cut short of its limit still offers the history before it, on both ends", async () => {
+ const h = createHarness();
+ const p = h.controller.load();
+ h.controller.handleServer({ type: "task_state", state: "idle" });
+ // One unit where twenty were asked for: the byte budget cut the tail, and its cursor says so.
+ h.resolveLoad(HISTORY_TASK, undefined, null, pageInfo({ before: "2:40", earlierTurns: 30 }));
+ await p;
+ expect(h.controller.older).toEqual({ hasMore: true, loading: false, error: null });
+ // A backfill cut short the same way keeps the way back open at its own cursor.
+ const first = h.controller.loadOlder();
+ h.resolveLoad(OLD_TURN, undefined, null, pageInfo({ before: "2:12", earlierTurns: 29 }));
+ await first;
+ expect(h.controller.older.hasMore).toBe(true);
+ expect(h.controller.outlineOffset).toBe(29);
+ const second = h.controller.loadOlder();
+ expect(h.pageArgs[2]).toEqual({ kind: "before", cursor: "2:12", limit: OLDER_UNITS });
+ h.resolveLoad(OLD_TURN, undefined, null, pageInfo({ earlierTurns: 0 }));
+ await second;
+ expect(h.controller.older.hasMore).toBe(false);
+ });
+
+ it("a user image the page carries by reference and the stream's inline copy of it draw one picture", async () => {
+ const h = createHarness();
+ const p = h.controller.load();
+ const bytes = "data:image/png;base64,iVBORw0KGgo=";
+ const ref = "/api/sessions/s1/trace-image?file=2&ordinal=8";
+ const prompt = at(userText("what is this?"), "2026-07-05T00:00:00.000Z");
+ const sent = at(imageUrlMessage(bytes), "2026-07-05T00:00:00.000Z");
+ // The stream delivered the image while the page was being read: the buffered copy has its bytes.
+ h.controller.handleOmni(prompt, "e1-1");
+ h.controller.handleOmni(sent, "e1-2");
+ h.controller.handleServer({ type: "task_state", state: "idle" });
+ // The page's copies: positioned Trace records, the image's bytes replaced by its route URL.
+ const pagePrompt = { ...prompt, tracePosition: { fileIndex: 2, ordinal: 7 } };
+ const pageImage = {
+ ...sent,
+ payload: { ...sent.payload, image_url: ref },
+ tracePosition: { fileIndex: 2, ordinal: 8 },
+ };
+ h.resolveLoad([pagePrompt, pageImage, ...HISTORY_TASK.slice(1)], undefined, null, pageInfo());
+ await p;
+ const images = h.controller.model.items.filter((i) => i.kind === "user_image");
+ expect(images.map((i) => (i as UserImageItem).imageUrl)).toEqual([ref]);
+ expect(h.controller.model.items.filter((i) => i.kind === "user_text")).toHaveLength(1);
+ });
+
it("initial load requests the TAIL window and seeds the prior stats into the tracker", async () => {
const h = createHarness();
const p = h.controller.load();
diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.ts
index b67eb17e..51098191 100644
--- a/packages/web/test/stream-model.test.ts
+++ b/packages/web/test/stream-model.test.ts
@@ -27,8 +27,10 @@
* - Elapsed time survives a reload mid-run and never leaks the local clock.
* - Tool cards are found at any depth by origin chain, and an approval key tells apart the
* same call id under different origins.
- * - Overlap dedup matches identical envelopes in its window (Trace positions ignored) and
- * discards the matching in-flight fragment, nested ones included.
+ * - Overlap dedup matches identical envelopes in its window (Trace positions ignored, an
+ * image's inline bytes and its history reference taken as one) and discards the matching
+ * in-flight fragment, nested ones included; an image history does not hold is never
+ * taken for one it does.
* - Thinking and tool durations cover generation and execution, minus approval waits; aborts
* and idle close running cards.
* - A repeated tool_call_id opens a new card and closes the superseded one.
@@ -2371,6 +2373,55 @@ describe("overlap dedup (contract §7.2)", () => {
expect(isDuplicate(buildDedupIndex([history]), live)).toBe(true);
});
+ it("an image a history page carries by reference matches the stream's inline copy of the same record", () => {
+ const bytes = "data:image/png;base64,iVBORw0KGgo=";
+ const ref = (query: string) => `/api/sessions/s1/trace-image?${query}`;
+ const userImage = at(imageUrlMessage(bytes), "2026-07-05T00:00:00.000Z");
+ const shot = at(
+ toolCallOutput({ output: "two shots", toolCallId: "c1", images: [bytes, bytes] }),
+ "2026-07-05T00:00:04.000Z",
+ );
+ // The page's copies: positioned Trace records whose images became route URLs.
+ const pageImage = {
+ ...userImage,
+ payload: { ...userImage.payload, image_url: ref("file=1&ordinal=4") },
+ tracePosition: { fileIndex: 1, ordinal: 4 },
+ };
+ const pageShot = {
+ ...shot,
+ payload: {
+ ...shot.payload,
+ images: [ref("file=1&ordinal=6&i=0"), ref("file=1&ordinal=6&i=1")],
+ },
+ tracePosition: { fileIndex: 1, ordinal: 6 },
+ };
+ const page = buildDedupIndex([pageImage, pageShot]);
+ expect(isDuplicate(page, userImage)).toBe(true);
+ expect(isDuplicate(page, shot)).toBe(true);
+ });
+
+ it("an image the history does not hold is never taken for one it does", () => {
+ const bytes = "data:image/png;base64,iVBORw0KGgo=";
+ const held = at(imageUrlMessage(bytes), "2026-07-05T00:00:00.000Z");
+ const page = buildDedupIndex([
+ {
+ ...held,
+ payload: { ...held.payload, image_url: "/api/sessions/s1/trace-image?file=1&ordinal=4" },
+ },
+ ]);
+ // The same picture sent again later is a new message.
+ expect(isDuplicate(page, at(imageUrlMessage(bytes), "2026-07-05T00:01:00.000Z"))).toBe(false);
+ // Web addresses are compared as written: a different picture at the same moment stays apart.
+ const web = (url: string) => at(imageUrlMessage(url), "2026-07-05T00:00:00.000Z");
+ expect(
+ isDuplicate(buildDedupIndex([web("https://a.test/1.png")]), web("https://a.test/2.png")),
+ ).toBe(false);
+ // A tool output with one more image than history's copy is not that copy.
+ const out = (images: string[]) =>
+ at(toolCallOutput({ output: "shot", toolCallId: "c1", images }), "2026-07-05T00:00:04.000Z");
+ expect(isDuplicate(buildDedupIndex([out([bytes])]), out([bytes, bytes]))).toBe(false);
+ });
+
it("a full message hitting dedup discards the matching in-flight fragment (discardFragmentFor)", () => {
const m = createStreamModel();
// History already contains the full message.
diff --git a/packages/web/test/trace-events-loader.test.ts b/packages/web/test/trace-events-loader.test.ts
deleted file mode 100644
index 78581cfe..00000000
--- a/packages/web/test/trace-events-loader.test.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-/**
- * The Trace file view's event pager (features/traces/trace-events-loader.ts). The walk must
- * cover the WHOLE file: the analysis attributes messages to rounds by index range, so an event
- * never fetched is a round that renders an empty message list.
- *
- * - A 2500-event file is paged in three requests, every page reported in file order; the walk
- * advances by what a page delivered, not by what it asked for.
- * - A file appended to while the walk runs is followed to its new end.
- * - The walk ends on a page with no events, however long the file claims to be; it reports and
- * requests nothing more once cancelled (a page arriving after the cancel is dropped); a walk
- * that never finishes is capped.
- * - It resolves with the last page's total, the walk's final word on the file's length.
- */
-import { describe, expect, it } from "vitest";
-import type { OmniMessage } from "@lmliheng/penguin-core/omnimessage";
-import type { TraceEventsResponse } from "@lmliheng/penguin-server/api";
-import {
- MAX_TRACE_EVENT_PAGES,
- loadTraceEventPages,
-} from "../src/features/traces/trace-events-loader";
-
-/** One synthetic event, identified by its index so a page's slice can be checked exactly. */
-const event = (i: number): OmniMessage => ({
- timestamp: "2026-09-12T00:00:00.000Z",
- type: "model_msg",
- payload: { type: "text", role: "assistant", text: `m${i}` },
-});
-
-const textsOf = (events: readonly OmniMessage[]): string[] =>
- events.map((m) => (m.payload as { text: string }).text);
-
-const expectedTexts = (from: number, count: number): string[] =>
- Array.from({ length: count }, (_, i) => `m${from + i}`);
-
-/**
- * A fake events endpoint over a file of `size` synthetic events.
- *
- * `state.size` is what the file can actually deliver and `state.total` what it reports, held
- * apart so a truncated file (a `total` above what comes back) can be staged. `serverLimit` caps
- * how many events a page comes back with — a server answering with fewer than were asked for —
- * and `onFetch` is the hook the growing-file, truncation and cancellation cases use to change
- * the file between two pages.
- */
-function fakeFile(
- size: number,
- opts: { serverLimit?: number; onFetch?: (call: number) => void } = {},
-) {
- const state = { size, total: size };
- const calls: { offset: number; limit: number }[] = [];
- const pages: TraceEventsResponse[] = [];
- const fetchPage = (offset: number, limit: number): Promise<TraceEventsResponse> => {
- calls.push({ offset, limit });
- opts.onFetch?.(calls.length);
- const capped = Math.min(limit, opts.serverLimit ?? limit);
- const events: OmniMessage[] = [];
- for (let i = offset; i < Math.min(offset + capped, state.size); i++) events.push(event(i));
- return Promise.resolve({ events, offset, limit: capped, total: state.total });
- };
- return {
- state,
- calls,
- pages,
- fetchPage,
- onPage: (page: TraceEventsResponse) => pages.push(page),
- };
-}
-
-describe("loadTraceEventPages", () => {
- it("pages a 2500-event file in three requests, reporting every page in file order", async () => {
- const f = fakeFile(2500);
- await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
-
- expect(f.calls).toEqual([
- { offset: 0, limit: 1000 },
- { offset: 1000, limit: 1000 },
- { offset: 2000, limit: 1000 },
- ]);
- expect(f.pages.map((p) => p.offset)).toEqual([0, 1000, 2000]);
- expect(f.pages.map((p) => p.events.length)).toEqual([1000, 1000, 500]);
- expect(textsOf(f.pages[0]!.events)).toEqual(expectedTexts(0, 1000));
- expect(textsOf(f.pages[1]!.events)).toEqual(expectedTexts(1000, 1000));
- expect(textsOf(f.pages[2]!.events)).toEqual(expectedTexts(2000, 500));
- // Concatenated, the pages are the file — nothing dropped, nothing repeated.
- expect(textsOf(f.pages.flatMap((p) => p.events))).toEqual(expectedTexts(0, 2500));
- });
-
- it("advances by what a page delivered, not by the page size it asked for", async () => {
- // Whatever cuts a page short, the next offset follows the events that arrived rather than
- // the number asked for, so no event is skipped between two pages.
- const f = fakeFile(500, { serverLimit: 200 });
- await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
-
- expect(f.calls.map((c) => c.offset)).toEqual([0, 200, 400]);
- expect(textsOf(f.pages.flatMap((p) => p.events))).toEqual(expectedTexts(0, 500));
- });
-
- it("follows a file that was appended to while the walk was running", async () => {
- // The Session keeps writing: the file grows by 600 events after the second page was served.
- const f = fakeFile(2500, {
- onFetch: (call) => {
- if (call === 2) {
- f.state.size = 3100;
- f.state.total = 3100;
- }
- },
- });
- await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
-
- // A walk pinned to the FIRST page's total would have stopped at 2500, three pages in.
- expect(f.calls.map((c) => c.offset)).toEqual([0, 1000, 2000, 3000]);
- expect(f.pages.map((p) => p.total)).toEqual([2500, 3100, 3100, 3100]);
- expect(textsOf(f.pages.flatMap((p) => p.events))).toEqual(expectedTexts(0, 3100));
- });
-
- it("ends the walk on a page with no events, however long the file claims to be", async () => {
- // A file truncated under the reader: `total` still says 3000, nothing comes back past 1000.
- const f = fakeFile(3000, {
- onFetch: (call) => {
- if (call === 2) f.state.size = 1000;
- },
- });
- await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
-
- expect(f.calls.map((c) => c.offset)).toEqual([0, 1000]);
- expect(f.pages.map((p) => p.events.length)).toEqual([1000, 0]);
- expect(f.pages[1]!.total).toBe(3000);
- });
-
- it("stops without reporting or requesting anything more once it is cancelled", async () => {
- const signal = { cancelled: false };
- const f = fakeFile(4000);
- await loadTraceEventPages(f.fetchPage, {
- pageSize: 1000,
- signal,
- onPage: (page) => {
- f.onPage(page);
- // The view is gone — the file switched, or the panel unmounted — mid-walk.
- signal.cancelled = true;
- },
- });
-
- expect(f.calls).toEqual([{ offset: 0, limit: 1000 }]);
- expect(f.pages).toHaveLength(1);
- });
-
- it("does not report a page that arrived after the walk was cancelled", async () => {
- // The flag is flipped by a React effect's cleanup, which runs while a page is IN FLIGHT —
- // not from inside `onPage`. Checked only before each request, the walk would still splice
- // this page into a view that has already moved to another Trace file.
- const signal = { cancelled: false };
- const calls: number[] = [];
- const pages: TraceEventsResponse[] = [];
- let deliver!: (page: TraceEventsResponse) => void;
- const walk = loadTraceEventPages(
- (offset) => {
- calls.push(offset);
- return new Promise<TraceEventsResponse>((resolve) => {
- deliver = resolve;
- });
- },
- { pageSize: 1000, signal, onPage: (page) => pages.push(page) },
- );
-
- // The view switched files while the first page was still out; the page lands afterwards.
- signal.cancelled = true;
- deliver({ events: [event(0)], offset: 0, limit: 1000, total: 2500 });
-
- // Nothing rendered, nothing requested beyond the page already out, and the 0 tells the
- // caller it has no answer about the file's length.
- await expect(walk).resolves.toBe(0);
- expect(pages).toEqual([]);
- expect(calls).toEqual([0]);
- });
-
- it("caps a walk that never finishes, rather than requesting for as long as the view is open", async () => {
- // A server reporting a total it never delivers: one event per page, forever.
- const f = fakeFile(Number.MAX_SAFE_INTEGER, { serverLimit: 1 });
- await loadTraceEventPages(f.fetchPage, { pageSize: 1000, onPage: f.onPage });
-
- expect(f.calls).toHaveLength(MAX_TRACE_EVENT_PAGES);
- });
-
- it("resolves with the last page's total, the walk's final word on the file's length", async () => {
- // The caller truncates to this number, so an earlier walk's rows cannot outlive a file
- // that came back shorter than it was read as before.
- const plain = fakeFile(2500);
- await expect(
- loadTraceEventPages(plain.fetchPage, { pageSize: 1000, onPage: plain.onPage }),
- ).resolves.toBe(2500);
-
- const grown = fakeFile(2500, {
- onFetch: (call) => {
- if (call === 2) {
- grown.state.size = 3100;
- grown.state.total = 3100;
- }
- },
- });
- await expect(
- loadTraceEventPages(grown.fetchPage, { pageSize: 1000, onPage: grown.onPage }),
- ).resolves.toBe(3100);
-
- // Cancelled before any page was reported, there is no answer to give: 0, which the caller
- // must not act on — it checks its own cancellation first.
- const gone = fakeFile(2500);
- await expect(
- loadTraceEventPages(gone.fetchPage, {
- pageSize: 1000,
- signal: { cancelled: true },
- onPage: gone.onPage,
- }),
- ).resolves.toBe(0);
- expect(gone.calls).toEqual([]);
- });
-});
diff --git a/packages/web/test/trace-file-view.test.ts b/packages/web/test/trace-file-view.test.ts
new file mode 100644
index 00000000..3d631d12
--- /dev/null
+++ b/packages/web/test/trace-file-view.test.ts
@@ -0,0 +1,258 @@
+/**
+ * The Trace file view as drawn (features/traces/trace-file-view.tsx, `TraceFileBody`): what a
+ * long file puts on screen once its analysis is in and its newest round is read. Rendered to
+ * static markup, so each scenario hands the view the state it would hold.
+ *
+ * - A 1200-round file draws at most 50 round heads, and the rows of exactly one round — the
+ * open newest one.
+ * - The rounds not drawn sit behind an "earlier rounds" control that names how many there are;
+ * one step draws 50 more; a file of fewer than 50 rounds has no such control.
+ * - A collapsed round draws no rows, even when its events are held from an earlier opening.
+ * - An open round whose read is still out draws a placeholder and no rows; one whose read
+ * failed says so in place of its rows.
+ * - Each round's context ring is bounded by the file's context window, and by 128k when the
+ * analysis (from an older server) carries none.
+ * - Opening a file asks once to scroll its newest round into view — the open round drawn last —
+ * and no refresh after it asks again, not even one that opens a new round for a reader
+ * following the run.
+ */
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+import type { OmniMessage } from "@lmliheng/penguin-core/omnimessage";
+import type { TraceAnalysisResponse, TraceTaskStats } from "@lmliheng/penguin-server/api";
+import {
+ EMPTY_FILE,
+ TraceFileBody,
+ fileAfterAnalysis,
+} from "../src/features/traces/trace-file-view";
+import type { FileState, RoundEntry } from "../src/features/traces/trace-file-view";
+import { TRACE_ROUNDS_PAGE } from "../src/features/traces/trace-rounds";
+import { humanizeTokens } from "../src/lib/format";
+import { S } from "../src/lib/strings";
+
+/** Events per synthetic round: a prompt, a request, thinking, a tool call and its output, a reply… */
+const PER_ROUND = 11;
+
+const iso = (ms: number): string => new Date(Date.UTC(2026, 9, 1) + ms).toISOString();
+
+function round(k: number): TraceTaskStats {
+ return {
+ taskIndex: k,
+ messageFrom: k * PER_ROUND,
+ messageTo: (k + 1) * PER_ROUND - 1,
+ startTs: iso(k * 60_000),
+ endTs: iso(k * 60_000 + 20_000),
+ context: { cacheRead: 30_000, cacheWrite: 2_000, output: 1_000 },
+ tokens: { cacheRead: 30_000, cacheWrite: 2_000, output: 1_000 },
+ llmMs: 12_000,
+ toolMs: 5_000,
+ };
+}
+
+function analysisOf(rounds: number, extra: Partial<TraceAnalysisResponse> = {}) {
+ const tasks = Array.from({ length: rounds }, (_, k) => round(k));
+ const newest = rounds - 1;
+ const analysis: TraceAnalysisResponse = {
+ elapsedMs: rounds * 20_000,
+ apiMs: rounds * 12_000,
+ toolMs: rounds * 5_000,
+ requests: [],
+ tasks,
+ toolCalls: [],
+ // The newest round has a timeline, as a real one does.
+ modelSegments: [
+ {
+ kind: "thinking",
+ startTs: iso(newest * 60_000),
+ endTs: iso(newest * 60_000 + 4_000),
+ taskIndex: newest,
+ },
+ ],
+ toolSpans: [],
+ otherSpans: [],
+ reconnectCount: 0,
+ compactionCount: 0,
+ usageTrend: [],
+ ...extra,
+ };
+ return analysis;
+}
+
+/** A round's events as read: one row per event in its range. */
+function readRound(r: TraceTaskStats): RoundEntry {
+ const rows: OmniMessage[] = [];
+ for (let i = r.messageFrom; i <= r.messageTo; i++) {
+ rows.push({
+ timestamp: iso(r.taskIndex * 60_000 + (i - r.messageFrom) * 1000),
+ type: "model_msg",
+ payload: { type: "text", role: "assistant", text: `event ${i}` },
+ });
+ }
+ return {
+ taskIndex: r.taskIndex,
+ messageFrom: r.messageFrom,
+ messageTo: r.messageTo,
+ status: "loaded",
+ rows,
+ };
+}
+
+function render(opts: {
+ analysis: TraceAnalysisResponse;
+ expanded: number[];
+ rounds?: RoundEntry[];
+ shownRounds?: number;
+}): string {
+ return renderToStaticMarkup(
+ createElement(TraceFileBody, {
+ analysis: opts.analysis,
+ currency: "USD",
+ expanded: new Set(opts.expanded),
+ rounds: new Map((opts.rounds ?? []).map((e) => [e.taskIndex, e])),
+ shownRounds: opts.shownRounds ?? TRACE_ROUNDS_PAGE,
+ error: null,
+ highlight: null,
+ pinnedRow: null,
+ onHighlight: () => {},
+ onToggle: () => {},
+ onShowEarlier: () => {},
+ onJump: () => {},
+ }),
+ );
+}
+
+const count = (html: string, re: RegExp): number => [...html.matchAll(re)].length;
+const heads = (html: string): number => count(html, /data-slot="head"/g);
+const earlierControls = (html: string): number => count(html, /data-slot="earlier"/g);
+/** The rounds whose rows are on screen, by taskIndex (a row's key is `<taskIndex>-<i>`). */
+const rowGroups = (html: string): number[] => [
+ ...new Set([...html.matchAll(/data-trace-row="(\d+)-\d+"/g)].map((m) => Number(m[1]))),
+];
+const rows = (html: string): number => count(html, /data-trace-row="/g);
+
+describe("a long Trace file", () => {
+ const analysis = analysisOf(1200);
+ const newest = analysis.tasks[1199]!;
+
+ it("draws at most 50 round heads, and the rows of the one open round", () => {
+ const html = render({ analysis, expanded: [1199], rounds: [readRound(newest)] });
+
+ expect(heads(html)).toBeLessThanOrEqual(50);
+ expect(rowGroups(html)).toEqual([1199]);
+ expect(rows(html)).toBe(PER_ROUND);
+ });
+
+ it("puts the rounds not drawn behind one control that names them, and a step draws 50 more", () => {
+ const first = render({ analysis, expanded: [1199], rounds: [readRound(newest)] });
+ expect(earlierControls(first)).toBe(1);
+ expect(first).toContain(S.traces.earlierRounds(1150));
+
+ const stepped = render({
+ analysis,
+ expanded: [1199],
+ rounds: [readRound(newest)],
+ shownRounds: 2 * TRACE_ROUNDS_PAGE,
+ });
+ expect(heads(stepped)).toBe(100);
+ expect(stepped).toContain(S.traces.earlierRounds(1100));
+ });
+
+ it("a file of fewer rounds than a page has no earlier-rounds control", () => {
+ const html = render({ analysis: analysisOf(30), expanded: [29] });
+ expect(heads(html)).toBe(30);
+ expect(earlierControls(html)).toBe(0);
+ });
+
+ it("a collapsed round draws no rows, even with its events held from an earlier opening", () => {
+ const html = render({ analysis, expanded: [], rounds: [readRound(newest)] });
+
+ expect(rows(html)).toBe(0);
+ expect(html).not.toContain('aria-expanded="true"');
+ });
+
+ it("an open round still being read draws a placeholder and no rows", () => {
+ const html = render({ analysis, expanded: [1199] });
+
+ expect(rows(html)).toBe(0);
+ expect(html).toContain('role="status"');
+ expect(html).toContain(S.traces.roundLoading);
+ });
+
+ it("an open round whose read failed says so in place of its rows", () => {
+ const failed: RoundEntry = {
+ taskIndex: 1199,
+ messageFrom: newest.messageFrom,
+ messageTo: newest.messageTo,
+ status: "failed",
+ error: "The Trace file could not be read.",
+ };
+ const html = render({ analysis, expanded: [1199], rounds: [failed] });
+
+ expect(rows(html)).toBe(0);
+ expect(html).toContain("The Trace file could not be read.");
+ });
+});
+
+describe("the context ring", () => {
+ const used = humanizeTokens(30_000 + 2_000 + 1_000);
+ /** The first round's ring, read by its accessible name. */
+ const ringOf = (html: string): string => {
+ const start = html.indexOf(`aria-label="${S.chat.contextUsage} `);
+ return start < 0 ? "" : html.slice(start, html.indexOf('"', start + 12));
+ };
+
+ it("is bounded by the file's context window", () => {
+ const html = render({ analysis: analysisOf(3, { modelContextWindow: 200_000 }), expanded: [] });
+ expect(ringOf(html)).toContain(`${used}/${humanizeTokens(200_000)}`);
+ });
+
+ it("falls back to 128k when the analysis carries no window", () => {
+ const html = render({ analysis: analysisOf(3), expanded: [] });
+ expect(ringOf(html)).toContain(`${used}/${humanizeTokens(128_000)}`);
+ });
+});
+
+describe("opening a file", () => {
+ /** The view's state after each analysis in turn, from a file it has not shown yet. */
+ const statesAfter = (...analyses: TraceAnalysisResponse[]): FileState[] => {
+ const states: FileState[] = [];
+ let state = EMPTY_FILE;
+ for (const a of analyses) {
+ state = fileAfterAnalysis(state, a);
+ states.push(state);
+ }
+ return states;
+ };
+ /** The scroll requests a run of analyses makes: the view scrolls whenever `reveal` is set. */
+ const scrollRequests = (states: FileState[]): number[] =>
+ states.flatMap((s) => (s.reveal === null ? [] : [s.reveal]));
+
+ it("scrolls the open newest round into view once, on the first analysis only", () => {
+ const states = statesAfter(
+ analysisOf(1200),
+ // A turn settles inside the newest round, then a new round starts: both are refreshes.
+ analysisOf(1200),
+ analysisOf(1201),
+ );
+
+ expect(scrollRequests(states)).toEqual([1199]);
+ // The refresh still follows the run: the reader was on the newest round, so the new one opens.
+ expect([...states[2]!.expanded].sort((a, b) => a - b)).toEqual([1199, 1200]);
+ });
+
+ it("the round it scrolls to is the last card drawn, and the open one", () => {
+ const [opened] = statesAfter(analysisOf(1200));
+ const html = render({ analysis: opened!.analysis!, expanded: [...opened!.expanded] });
+
+ const drawn = [...html.matchAll(/data-round="(\d+)"/g)].map((m) => Number(m[1]));
+ expect(drawn.at(-1)).toBe(opened!.reveal);
+ const lastCard = html.slice(html.lastIndexOf("data-round="));
+ expect(lastCard).toContain('aria-expanded="true"');
+ expect(count(html, /aria-expanded="true"/g)).toBe(1);
+ });
+
+ it("a file with no round yet scrolls nowhere until its first round appears", () => {
+ expect(scrollRequests(statesAfter(analysisOf(0), analysisOf(0), analysisOf(1)))).toEqual([0]);
+ });
+});
diff --git a/packages/web/test/trace-rounds.test.ts b/packages/web/test/trace-rounds.test.ts
new file mode 100644
index 00000000..cc376ef1
--- /dev/null
+++ b/packages/web/test/trace-rounds.test.ts
@@ -0,0 +1,246 @@
+/**
+ * Which rounds the Trace panel draws and reads (features/traces/trace-rounds.ts). A long
+ * Session's file is thousands of rounds and tens of megabytes; the panel stays fast only while
+ * what it draws and what it reads are bounded by what the reader opened.
+ *
+ * - A 1200-round file draws its newest 50 round cards, oldest first; one "earlier" step draws
+ * the newest 100; a file shorter than a page draws all of it.
+ * - Reading a round asks for its own index range only, in ceil(span / 1000) requests, and gets
+ * back exactly that range in file order; an empty round asks for nothing.
+ * - A page answered short is followed from where it ended; a range that runs past the file's end
+ * or meets a page with no events stops instead of asking again; a cancelled read asks no more.
+ * - Opening a file reads its newest round and nothing in any collapsed round.
+ * - A refresh re-reads only the open rounds that grew; a collapsed round that grew is left
+ * alone until it is opened.
+ * - A file opens on its newest round only; a refresh keeps the reader's choices, and a new round
+ * opens only when the reader was following the newest one.
+ */
+import { describe, expect, it } from "vitest";
+import type { OmniMessage } from "@lmliheng/penguin-core/omnimessage";
+import type { TraceEventsResponse } from "@lmliheng/penguin-server/api";
+import {
+ TRACE_EVENT_PAGE_SIZE,
+ TRACE_ROUNDS_PAGE,
+ expandedAfterAnalysis,
+ loadRoundEvents,
+ roundsToRead,
+ staleRounds,
+ visibleRounds,
+} from "../src/features/traces/trace-rounds";
+import type { RoundRange } from "../src/features/traces/trace-rounds";
+
+/** One synthetic event, identified by its index in the file so a read's slice can be checked exactly. */
+const event = (i: number): OmniMessage => ({
+ timestamp: "2026-10-02T00:00:00.000Z",
+ type: "model_msg",
+ payload: { type: "text", role: "assistant", text: `m${i}` },
+});
+
+const textsOf = (events: readonly OmniMessage[]): string[] =>
+ events.map((m) => (m.payload as { text: string }).text);
+
+const indexes = (from: number, to: number): string[] =>
+ Array.from({ length: to - from + 1 }, (_, i) => `m${from + i}`);
+
+/** `n` consecutive rounds of `perRound` events each, round k covering [k·perRound, (k+1)·perRound − 1]. */
+function roundsOf(n: number, perRound: number): RoundRange[] {
+ return Array.from({ length: n }, (_, k) => ({
+ taskIndex: k,
+ messageFrom: k * perRound,
+ messageTo: (k + 1) * perRound - 1,
+ }));
+}
+
+/**
+ * A fake events endpoint over a file of `size` events, recording every request. `serverLimit`
+ * caps how many events a page comes back with; `total` is what pages report as the file's length.
+ */
+function fakeFile(size: number, opts: { serverLimit?: number; total?: number } = {}) {
+ const calls: { offset: number; limit: number }[] = [];
+ const fetchPage = (offset: number, limit: number): Promise<TraceEventsResponse> => {
+ calls.push({ offset, limit });
+ const capped = Math.min(limit, opts.serverLimit ?? limit);
+ const events: OmniMessage[] = [];
+ for (let i = offset; i < Math.min(offset + capped, size); i++) events.push(event(i));
+ return Promise.resolve({ events, offset, limit: capped, total: opts.total ?? size });
+ };
+ return { calls, fetchPage };
+}
+
+describe("visibleRounds", () => {
+ const file = roundsOf(1200, 11);
+
+ it("a 1200-round file draws its newest 50 rounds, oldest first", () => {
+ const drawn = visibleRounds(file, TRACE_ROUNDS_PAGE);
+ expect(drawn).toHaveLength(50);
+ expect(drawn.map((r) => r.taskIndex)).toEqual(Array.from({ length: 50 }, (_, i) => 1150 + i));
+ });
+
+ it("one earlier step draws the newest 100", () => {
+ const drawn = visibleRounds(file, 2 * TRACE_ROUNDS_PAGE);
+ expect(drawn).toHaveLength(100);
+ expect(drawn[0]!.taskIndex).toBe(1100);
+ expect(drawn[99]!.taskIndex).toBe(1199);
+ });
+
+ it("a file shorter than a page draws all of it, in round order whatever order it came in", () => {
+ const shuffled = [...roundsOf(3, 4)].reverse();
+ expect(visibleRounds(shuffled, TRACE_ROUNDS_PAGE).map((r) => r.taskIndex)).toEqual([0, 1, 2]);
+ });
+});
+
+describe("loadRoundEvents", () => {
+ it.each([1, 999, 1000, 1001, 2500])(
+ "a round of %i events is read in ceil(span / 1000) requests, all inside its range",
+ async (span) => {
+ const range = { taskIndex: 7, messageFrom: 1300, messageTo: 1300 + span - 1 };
+ const f = fakeFile(10_000);
+ const events = await loadRoundEvents(f.fetchPage, range);
+
+ expect(f.calls).toHaveLength(Math.ceil(span / TRACE_EVENT_PAGE_SIZE));
+ for (const c of f.calls) {
+ expect(c.limit).toBeLessThanOrEqual(TRACE_EVENT_PAGE_SIZE);
+ expect(c.offset).toBeGreaterThanOrEqual(range.messageFrom);
+ expect(c.offset + c.limit - 1).toBeLessThanOrEqual(range.messageTo);
+ }
+ // Exactly the round, in file order: nothing from the rounds on either side of it.
+ expect(textsOf(events)).toEqual(indexes(range.messageFrom, range.messageTo));
+ },
+ );
+
+ it("an empty round asks for nothing", async () => {
+ const f = fakeFile(100);
+ await expect(
+ loadRoundEvents(f.fetchPage, { taskIndex: 0, messageFrom: -1, messageTo: -1 }),
+ ).resolves.toEqual([]);
+ expect(f.calls).toEqual([]);
+ });
+
+ it("a page answered short is followed from where it ended, leaving no hole", async () => {
+ const f = fakeFile(1000, { serverLimit: 200 });
+ const events = await loadRoundEvents(f.fetchPage, {
+ taskIndex: 0,
+ messageFrom: 100,
+ messageTo: 549,
+ });
+
+ expect(f.calls.map((c) => c.offset)).toEqual([100, 300, 500]);
+ expect(textsOf(events)).toEqual(indexes(100, 549));
+ });
+
+ it("a range running past the file's end stops at the end instead of asking again", async () => {
+ // The analysis counted a record the events endpoint does not serve yet (mid-append).
+ const f = fakeFile(1000);
+ const events = await loadRoundEvents(f.fetchPage, {
+ taskIndex: 0,
+ messageFrom: 990,
+ messageTo: 1004,
+ });
+
+ expect(f.calls).toHaveLength(1);
+ expect(textsOf(events)).toEqual(indexes(990, 999));
+ });
+
+ it("a page with no events ends the read, however long the file claims to be", async () => {
+ // Truncated under the reader: the total still says 3000, nothing comes back past 1000.
+ const f = fakeFile(1000, { total: 3000 });
+ const events = await loadRoundEvents(f.fetchPage, {
+ taskIndex: 0,
+ messageFrom: 1500,
+ messageTo: 2600,
+ });
+
+ expect(f.calls).toHaveLength(1);
+ expect(events).toEqual([]);
+ });
+
+ it("a read cancelled while a page is out asks for nothing more", async () => {
+ const signal = { cancelled: false };
+ const f = fakeFile(10_000);
+ const read = loadRoundEvents(
+ (offset, limit) => {
+ // The view moved to another file while this page was in flight.
+ signal.cancelled = true;
+ return f.fetchPage(offset, limit);
+ },
+ { taskIndex: 0, messageFrom: 0, messageTo: 2999 },
+ { signal },
+ );
+
+ await read;
+ expect(f.calls).toHaveLength(1);
+ });
+});
+
+describe("roundsToRead", () => {
+ it("opening a 1200-round file reads its newest round and nothing in any collapsed round", async () => {
+ const file = roundsOf(1200, 11);
+ const expanded = expandedAfterAnalysis(null, file, new Set());
+ const toRead = roundsToRead(file, TRACE_ROUNDS_PAGE, expanded, new Map());
+ expect(toRead.map((r) => r.taskIndex)).toEqual([1199]);
+
+ const f = fakeFile(1200 * 11);
+ for (const round of toRead) await loadRoundEvents(f.fetchPage, round);
+ // One request, inside the newest round: no collapsed round's events were asked for.
+ expect(f.calls).toEqual([{ offset: 1199 * 11, limit: 11 }]);
+ });
+
+ it("an open round already read is not read again, and an open round not drawn is not read", () => {
+ const file = roundsOf(200, 5);
+ const cached = new Map<number, RoundRange>([[199, file[199]!]]);
+ // Round 3 was opened, then 50 newer rounds pushed it out of the drawn window.
+ const expanded = new Set([3, 199]);
+ expect(roundsToRead(file, TRACE_ROUNDS_PAGE, expanded, cached)).toEqual([]);
+ // Revealing it is what reads it.
+ expect(roundsToRead(file, 200, expanded, cached).map((r) => r.taskIndex)).toEqual([3]);
+ });
+});
+
+describe("staleRounds", () => {
+ it("a refresh re-reads only the open rounds that grew", () => {
+ const range = (taskIndex: number, messageFrom: number, messageTo: number): RoundRange => ({
+ taskIndex,
+ messageFrom,
+ messageTo,
+ });
+ const cached = new Map<number, RoundRange>([
+ [0, range(0, 0, 9)],
+ [1, range(1, 10, 19)],
+ [2, range(2, 20, 29)],
+ ]);
+ const fresh = [
+ range(0, 0, 9),
+ range(1, 10, 19),
+ // The round that was running: it grew.
+ range(2, 20, 41),
+ // New since, never read: a first read, not a stale one.
+ range(3, 42, 50),
+ ];
+ // Open and unchanged, open and grown, open and new: only the grown one is re-read.
+ expect(staleRounds(cached, fresh, new Set([0, 2, 3]))).toEqual([2]);
+ // The same growth on a collapsed round is left alone until the round is opened.
+ expect(staleRounds(cached, fresh, new Set([0, 1, 3]))).toEqual([]);
+ });
+});
+
+describe("expandedAfterAnalysis", () => {
+ it("a file opens on its newest round only", () => {
+ expect([...expandedAfterAnalysis(null, roundsOf(1200, 3), new Set())]).toEqual([1199]);
+ // A file with no round yet opens nothing, and its first round opens when it appears.
+ expect([...expandedAfterAnalysis(null, [], new Set())]).toEqual([]);
+ expect([...expandedAfterAnalysis([], roundsOf(1, 3), new Set())]).toEqual([0]);
+ });
+
+ it("a refresh keeps what the reader opened and closed", () => {
+ const before = roundsOf(5, 3);
+ // The newest round (4) was closed by the reader and two older ones opened.
+ expect([...expandedAfterAnalysis(before, roundsOf(5, 3), new Set([1, 2]))]).toEqual([1, 2]);
+ });
+
+ it("a new round opens when the reader was following the newest one, and stays closed otherwise", () => {
+ const before = roundsOf(5, 3);
+ const after = roundsOf(6, 3);
+ expect([...expandedAfterAnalysis(before, after, new Set([4]))].sort()).toEqual([4, 5]);
+ expect([...expandedAfterAnalysis(before, after, new Set([2]))]).toEqual([2]);
+ });
+});
diff --git a/packages/web/test/transcript-images.test.ts b/packages/web/test/transcript-images.test.ts
new file mode 100644
index 00000000..48530b29
--- /dev/null
+++ b/packages/web/test/transcript-images.test.ts
@@ -0,0 +1,92 @@
+/**
+ * The pictures in a conversation, where the browser fetches them from (react-dom/server static
+ * markup, node env, no DOM). A windowed history page carries each Trace image by reference
+ * (`/api/sessions/<id>/trace-image?…`), and the browser follows an `<img src>` itself, with no
+ * request for the fetch wrapper's routing rule to act on.
+ *
+ * - Given a Session that lives on another machine, an image the page names by reference is
+ * fetched from that machine, and only as it nears the viewport.
+ * - Given a Session on this server, the reference is fetched here, as written.
+ * - Given a steering message's image on a machine's Session, it is fetched from that machine.
+ * - An image that arrived inline (live, or a subagent's) renders from its own bytes.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { MessageStream } from "../src/features/chat/message-stream";
+import type { StreamRenderContext } from "../src/features/chat/message-stream";
+import type { ChatItem } from "../src/lib/omni/stream-model";
+import { forgetSessionMachines, rememberSessionMachine } from "../src/lib/session-machines";
+import { LocaleProvider } from "../src/state/locale";
+import { stubLocalStorage } from "./helpers/storage";
+
+beforeEach(() => {
+ stubLocalStorage().setItem("penguin.lang", "en");
+});
+afterEach(() => forgetSessionMachines());
+
+const ctx: StreamRenderContext = {
+ pendingApprovals: new Map(),
+ onApprove: async () => {},
+ origin: [],
+ taskRunning: false,
+};
+
+/** The `<img>` tags a stream of these items renders. */
+function imgTags(items: ChatItem[]): string[] {
+ const html = renderToStaticMarkup(
+ createElement(
+ LocaleProvider,
+ null,
+ createElement(MessageStream, { items, version: 1, ctx, onAddExcerpt: () => {} }),
+ ),
+ );
+ return html.match(/<img\b[^>]*>/g) ?? [];
+}
+
+const ref = (sessionId: string) => `/api/sessions/${sessionId}/trace-image?file=2&amp;ordinal=8`;
+
+describe("transcript images", () => {
+ it("a referenced image of a Session on another machine is fetched from that machine, lazily", () => {
+ rememberSessionMachine("s-remote", "M1");
+ const tags = imgTags([
+ {
+ kind: "user_image",
+ id: 1,
+ imageUrl: "/api/sessions/s-remote/trace-image?file=2&ordinal=8",
+ },
+ ]);
+ expect(tags).toHaveLength(1);
+ expect(tags[0]).toContain(`src="/server/M1${ref("s-remote")}"`);
+ expect(tags[0]).toContain('loading="lazy"');
+ });
+
+ it("a referenced image of a Session on this server is fetched here, as written", () => {
+ const tags = imgTags([
+ { kind: "user_image", id: 1, imageUrl: "/api/sessions/s-local/trace-image?file=2&ordinal=8" },
+ ]);
+ expect(tags[0]).toContain(`src="${ref("s-local")}"`);
+ });
+
+ it("a steering message's image on a machine's Session is fetched from that machine", () => {
+ rememberSessionMachine("s-remote", "M1");
+ const tags = imgTags([
+ { kind: "user_text", id: 1, text: "start" },
+ {
+ kind: "user_steering",
+ id: 2,
+ text: "look at this too",
+ images: ["/api/sessions/s-remote/trace-image?file=2&ordinal=8"],
+ },
+ ]);
+ expect(tags).toHaveLength(1);
+ expect(tags[0]).toContain(`src="/server/M1${ref("s-remote")}"`);
+ });
+
+ it("an image that arrived inline renders from its own bytes", () => {
+ rememberSessionMachine("s-remote", "M1");
+ const bytes = "data:image/png;base64,iVBORw0KGgo=";
+ const tags = imgTags([{ kind: "user_image", id: 1, imageUrl: bytes }]);
+ expect(tags[0]).toContain(`src="${bytes}"`);
+ });
+});