A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): fork sessions from completed replies (#297)
Yiru Donge5594d676eb4
diff --git a/changelog/unreleased/2026-08-15-session-fork.md b/changelog/unreleased/2026-08-15-session-fork.mdnew file mode 100644index 00000000..9ac4b703--- /dev/null+++ b/changelog/unreleased/2026-08-15-session-fork.md@@ -0,0 +1,23 @@+# Fork Sessions from completed replies++- **Date:** 2026-08-15+- **Type:** feat+- **Scope:** `web`, `server`, `docs`+- **PR:** [#297](https://github.com/Prism-Shadow/penguin-harness/pull/297)+- **Issue:** [#293](https://github.com/Prism-Shadow/penguin-harness/issues/293)++[中文版](2026-08-15-session-fork.zh.md)++Completed root assistant replies now have a **Fork** action beside Copy. The new Session keeps the same Project, Agent, model, Workspace, approval mode, and title while truncating its transcript at the selected completed Task.++Forks own independent Trace shards and a recursive scratchpad snapshot. Local image/file marker paths are rewritten to the new Session id, so attachments keep rendering after either Session is deleted. The server rejects forged or unsafe Trace positions and refuses to fork while the source is running or compacting.++## Fork asks before it duplicates++The fork action sits to the **right of the copy button**, and clicking it opens a confirmation dialog (the shared `ConfirmModal`) explaining that the conversation is duplicated into a new chat up to that reply. The fork request only fires on Confirm; plain copy stays an unconfirmed one-click action.++## Deleting a Session no longer re-fetches it++Deleting the conversation you are looking at — the normal way to discard a fork you just tried — left one `[http] session_not_found` record behind on every delete, visible in the Cost Center's error panel.++The chat page resolves a routed Session that is missing from the paged list with a direct lookup, which is right for a deep link but guaranteed to 404 for a row this client had just deleted. The Session list now tombstones ids it deletes, and that lookup consults the tombstones first and skips the request. The ordering between pruning the list and changing the route is deliberately no longer the mechanism: the list lives in a zustand store whose updates are not subject to React's transition lanes, so scheduling cannot sequence the two reliably.diff --git a/changelog/unreleased/2026-08-15-session-fork.zh.md b/changelog/unreleased/2026-08-15-session-fork.zh.mdnew file mode 100644index 00000000..3f532b96--- /dev/null+++ b/changelog/unreleased/2026-08-15-session-fork.zh.md@@ -0,0 +1,23 @@+# 从已完成的回复分叉会话++- **Date:** 2026-08-15+- **Type:** feat+- **Scope:** `web`, `server`, `docs`+- **PR:** [#297](https://github.com/Prism-Shadow/penguin-harness/pull/297)+- **Issue:** [#293](https://github.com/Prism-Shadow/penguin-harness/issues/293)++[English](2026-08-15-session-fork.md)++已完成的主线模型回复旁边新增了「分叉」操作。新建的 Session 沿用同一个 Project、Agent、模型、Workspace、审批模式和标题,历史则截断到所选的那个已完成 Task。++分叉出来的会话拥有独立的 Trace 分片和递归复制的 scratchpad 快照。本地图片与附件的标记路径会改写到新的 Session id 上,因此任意一侧的会话被删除后,附件仍然能正常显示。服务端会拒绝伪造或越界的 Trace 位置,并且在源会话运行中或压缩中时拒绝分叉。++## 分叉前先确认++分叉操作位于**复制按钮的右侧**,点击后先弹出确认框(复用共享的 `ConfirmModal`),说明该操作会把对话截至这条回复复制成一个新对话。只有点击确认才会真正发出分叉请求;复制本身仍然是不需要确认的一次点击。++## 删除会话不再回头请求它++删除当前正在查看的对话——也就是丢弃刚试过的分叉时最自然的做法——每次都会留下一条 `[http] session_not_found` 记录,在成本中心的错误面板里可以看到。++对话页在遇到「路由指向的会话不在已分页的列表里」时会直接发一次查询:这对深链接是对的,但对本客户端刚刚删掉的那一行来说,必然只会拿到 404。现在会话列表会为自己删除的 id 记下墓碑标记,那次查询会先检查墓碑并直接跳过请求。列表裁剪与路由切换之间的先后顺序有意不再作为修复手段:列表状态放在 zustand store 里,其更新不受 React transition 车道的约束,靠调度顺序无法可靠地排出先后。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 21049892..a3621140 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -184,6 +184,7 @@ The paths below omit the `/api/sessions/:sessionId` prefix. For the storage mode| PATCH | / | Update: `{approvalMode?, thinkingLevel?, archived?, title?}`. `thinkingLevel` pins the level on this Session (durable): every later run that carries no level of its own uses it instead of the Agent config's, and it comes back as `SessionInfo.thinkingLevel` (absent = never pinned) || DELETE | / | Delete the Session (along with its Traces and scratch files) || GET | /messages | Full OmniMessage history; while a Task runs the response also carries `live` (the in-progress stream tail, see below) |+| POST | /fork | Fork an idle Session through a completed assistant reply: `{position:{fileIndex,ordinal}}` → `{session}` || GET | /stream | SSE event stream (next section) || POST | /tasks | Start a Task: `{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202. With `queueIfBusy`, a busy session holds the input as a follow-up (`queued: true`) and auto-starts it as an ordinary next task once idle; `task_state` events report the queued count. `file` input parts are written to the Session scratchpad and handed to the model as `[attached file: <path>]` lines (see the request body below). With `goal: {budget?}` the input starts a goal loop instead: it must carry non-empty text (an image alone states no objective), any images it carries fold into the objective as scratchpad path lines whatever the model's vision, and `file` parts are refused — nothing folds them into a re-injected objective — see [Goal mode](/goal-mode) || POST | /steer | Mid-run steering: `{text, images?}` queues a message for the running Task (delivered between turns as a standalone `[user_steering]` user message, with its images right behind it) → 202; either field can carry the message on its own, but a request with neither is a 400; 409 `not_running` when no Task is in progress |@@ -214,7 +215,7 @@ The Trace stores only complete messages (streaming `partial_*` never reaches dis```tsinterface MessagesResponse {- messages: OmniMessage[];+ messages: (OmniMessage & { tracePosition?: { fileIndex: number; ordinal: number } })[];live?: {// The Session channel's most recently assigned SSE event id (`<epoch>-<seq>`):// every event published up to and including this id is already reflected in `fragments`.@@ -230,6 +231,8 @@ interface MessagesResponse {`cursor` and `fragments` are captured atomically before the trace read starts. A client using the connect-first pattern (below) applies them after history: when the cursor's epoch matches the epoch of the SSE events it has buffered, it drops every buffered **partial** event with seq ≤ cursor (their content is already accumulated inside `fragments`), feeds `fragments` through its normal reducer, then replays the rest of the buffer. Buffered **complete** messages are never dropped by the cursor — the regular overlap dedup decides for them. `live` is omitted while idle.+`tracePosition` is history-response metadata, not part of the persisted OmniMessage envelope. The Web App submits the final assistant record's immutable coordinate to `/fork`; the server validates that it closes a completed Task. A fork clones the retained Trace shards and snapshots the source scratchpad under the new Session id, rewriting system-generated local attachment markers so the fork remains usable if either Session is later deleted. Forks made from any reply in the same source Session share a persistent, language-neutral title sequence (`Source title (1)`, `Source title (2)`); deleting an older fork does not reuse its number. Running or compacting sources return 409.+Workspace files may be Agent-generated, so `GET /files/content` treats them as untrusted: every response carries `X-Content-Type-Options: nosniff`, and the rest of the headers depend on the two flags (`download=1` wins over `preview=1`):| Query | Content-Type | Content-Disposition | Content-Security-Policy |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 69612bc7..a311b0fe 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -184,6 +184,7 @@ Trace 下载对任意成员开放;导入仅限 owner(同 Agent 快照导入| PATCH | / | 更新:`{approvalMode?, thinkingLevel?, archived?, title?}`。`thinkingLevel` 将思考等级固定在该 Session 上并持久化:此后凡是自身未携带等级的运行都改用它,而不再回落到 Agent 配置;读取时由 `SessionInfo.thinkingLevel` 返回(缺省即从未固定) || DELETE | / | 删除 Session(连同 Trace 与暂存文件) || GET | /messages | 完整 OmniMessage 历史;Task 运行期间响应额外携带 `live`(进行中的流式尾部,见下) |+| POST | /fork | 从一条已完成的模型回复分叉空闲 Session:`{position:{fileIndex,ordinal}}` → `{session}` || GET | /stream | SSE 事件流(见下节) || POST | /tasks | 发起 Task:`{input: TaskInputPart[], thinkingLevel?, queueIfBusy?}` → 202。带 `queueIfBusy` 时,运行中的 Session 会把输入暂存为跟进消息(`queued: true`),空闲后按序自动作为普通 Task 发出;`task_state` 事件携带排队数。`file` 类型的输入会写入 Session scratchpad,以 `[attached file: <路径>]` 行交给模型(见下方请求体)。带 `goal: {budget?}` 时该输入转为发起目标循环:必须含非空文字(一张图说明不了目标),随行的图片一律折叠成 scratchpad 路径行写入目标文本、与模型是否支持视觉无关,而 `file` 会被拒绝——没有东西能把它折进每轮重注入的目标里——见[目标模式](/goal-mode) || POST | /steer | 运行中插话:`{text, images?}` 为运行中的 Task 排队一条消息(作为独立的 `[user_steering]` 用户消息随下一轮送达,图片紧随其后)→ 202;两个字段任一非空即可成消息,都为空则 400;无 Task 运行返回 409 `not_running` |@@ -214,7 +215,7 @@ Trace 只存完整消息(流式 `partial_*` 永远不落盘),所以仅靠```tsinterface MessagesResponse {- messages: OmniMessage[];+ messages: (OmniMessage & { tracePosition?: { fileIndex: number; ordinal: number } })[];live?: {// Session 通道最近分配的 SSE 事件 id(`<epoch>-<seq>`):// 截至该 id(含)发布的所有事件都已累积进 `fragments`。@@ -229,6 +230,8 @@ interface MessagesResponse {`cursor` 与 `fragments` 在 Trace 读取开始前原子采集。使用先连接模式(见下)的客户端在应用完历史后处理它们:当 cursor 的 epoch 与本连接已缓冲事件的 epoch 一致时,丢弃 seq ≤ cursor 的已缓冲 **partial** 事件(其内容已累积在 `fragments` 里),把 `fragments` 按正常归约路径喂入,再重放剩余缓冲。已缓冲的**完整**消息从不按 cursor 丢弃 —— 仍由常规重叠去重裁决。空闲时不携带 `live`。+`tracePosition` 只是历史响应元数据,不进入持久化 OmniMessage。Web App 将一轮最后一条模型文本的不可变坐标提交给 `/fork`,服务端再校验它确实闭合了一个完整 Task。分叉会克隆保留范围内的 Trace 分片,并把源 Session 的 scratchpad 快照到新 Session id 下;系统生成的本地附件路径同步改写,因此以后删除任一 Session 都不会破坏另一方。同一源 Session 在任意回复位置产生的分支共用持久编号,标题使用不依赖界面语言的后缀,依次为 `原标题 (1)`、`原标题 (2)`;删除旧分支不会复用编号。源 Session 正在运行或压缩时返回 409。+Workspace 文件可能由 Agent 生成,`GET /files/content` 一律按不可信内容处理:所有响应都带 `X-Content-Type-Options: nosniff`,其余响应头取决于两个开关(`download=1` 优先于 `preview=1`):| 查询参数 | Content-Type | Content-Disposition | Content-Security-Policy |diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex ad7c9b1b..147e5e66 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -42,7 +42,7 @@ There are four approval modes: `allow-all`, `deny-all`, `read-only` (only read-o- Model text renders token by token; thinking blocks are collapsible;- Tool cards expand to show arguments and output, with a live timer while running;- Subagents leave a full-width row in the stream, styled like the other collapsed step rows (agent avatar, name, short session id, running spinner, and an amber dot while one of their tool calls awaits approval); clicking it opens the agents side panel — a call graph of that row's Task on top (each node shows its elapsed time; click a node to switch) and the selected child's live conversation below — the child's own user prompts included — where nested tool cards and approvals work exactly as in the main chat. Panel visibility is task-scoped: sending a message that starts a new task closes it by default (entering a session starts closed too), and it comes back when you open it yourself or — on desktop — when the current task spawns a subagent (one auto-open per task; a manual close holds until the next task; never over an open files panel). Opening the panel from the toolbar, or switching sessions, shows the latest Task's graph; a row on an older turn brings back that turn's graph. The agents panel and the Workspace files panel never show together — opening one closes the other. Context compaction and the first-run MCP connect show a unified step row (the work-group header shell, sticky title bar included — running/success/failure only swap the icon and the one-line detail, with the wall time on the result; the MCP row leads with the discovered-tool count and names unavailable servers, and expands into one group per server — status, tool count and that server's connect time — each opening into its tool list or the failure detail);-- After each Task, a stats line shows tokens, TPS, elapsed time, and cost.+- After each Task, a stats line shows tokens, TPS, elapsed time, cost, copy, and a **Fork** action to the right of copy. Fork asks for confirmation first — it duplicates the conversation into a new chat — and only then opens a new Session at that completed assistant reply with the same Agent, model, Workspace, approval mode, and retained transcript. Forks from different replies in one source chat share an increasing, language-neutral title sequence (`Source title (1)`, `Source title (2)`). Its Trace and scratchpad are independent snapshots: local images/files keep rendering even after the source chat is deleted;### Header Stats and the Details Carddiff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 5de2caa6..d89751ce 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -42,7 +42,7 @@ penguin web- 模型文本逐 Token 渲染,思考块可折叠;- 工具卡片可展开查看参数与输出,执行中显示实时计时;- 子 Agent 在消息流中只留下一条通栏行,样式与其他折叠步骤行一致(头像、名称、短会话号、运行中转圈,子会话内有待审批时带琥珀色圆点);点击打开右侧智能体面板——上方是该行所属 Task 派生关系的调用图(节点上显示运行时长,点节点切换),下方是所选子会话的实时对话(含子会话自己的用户消息),嵌套工具卡片与审批与主对话完全一致;面板的显示以任务为界:发送消息开启新任务时默认关闭(进入会话时同样默认关闭),仅在手动打开、或(桌面端)当前任务派生子智能体时重新显示(每个任务自动打开一次,任务内手动关闭后保持关闭到下个任务,且不抢占已打开的工作区面板);从工具条打开面板或切换 Session 时默认展示最新 Task 的调用图,点旧轮次的行则回看那一轮的调用图;智能体面板与工作区面板不会同时显示,打开一个即关闭另一个;上下文压缩与首次 MCP 连接以统一样式的步骤行提示(与运行分组头同款外壳,含吸顶标题栏,连接中/成功/失败仅切换图标与单行详情,结果行含耗时;MCP 行主显发现的工具数并点名不可用的 Server,展开后按 Server 分组——每组一行状态、工具数与该 Server 的连接耗时,点开组内是工具列表或失败原因);-- 每个 Task 结束后显示统计行:Token 用量、TPS、耗时与费用。+- 每个 Task 结束后显示统计行:Token 用量、TPS、耗时、费用、复制以及位于复制按钮右侧的**分叉**操作。分叉会先弹出确认框(该操作会把对话复制为一个新对话),确认后才在该条已完成的模型回复处新建 Session,沿用 Agent、模型、Workspace、审批模式和保留范围内的历史;同一源对话从不同回复分叉时,标题使用不依赖界面语言的编号后缀,按 `原标题 (1)`、`原标题 (2)` 递增。新旧会话的 Trace 与 scratchpad 是独立快照,即使删除源对话,本地图片和附件仍可显示;### 头部统计与详情卡diff --git a/packages/docs/decisions/issue-293-session-fork.md b/packages/docs/decisions/issue-293-session-fork.mdnew file mode 100644index 00000000..555ec247--- /dev/null+++ b/packages/docs/decisions/issue-293-session-fork.md@@ -0,0 +1,113 @@+# Issue #293 — Session fork behavior and verification checklist++This document fixes the product contract before implementation. It is also the review checklist+for the PR: an item is checked only after an automated test or a captured browser result+proves it.++## Expected behavior++- [x] A **Fork** action appears beside the existing copy action under every completed root-session+ assistant turn.+- [x] Streaming replies, user messages, nested subagent replies, and turns without a completed+ assistant reply do not expose the action.+- [x] Clicking **Fork** creates a new Session for the same Project and Agent.+- [x] The fork keeps the source Session's model reference, Workspace, and approval mode. Its title+ is the current source title plus the language-neutral suffix ` (n)` (`(n)` when the source+ has no stored title).+- [x] All forks made directly from the same source Session share one increasing sequence, even when+ they are cut at different replies: `(1)`, `(2)`, `(3)`, and so on.+- [x] The forked transcript contains the source transcript through the selected completed turn,+ including its tool calls/results, and excludes every later turn.+- [ ] The source and fork can receive different follow-up Tasks without changing one another's+ Trace.+- [x] A successful fork is added to the Session list and opens immediately.+- [ ] While the request is in flight, the action cannot be triggered twice; a failure leaves the+ user in the source Session and shows the normal localized API error toast.++## Boundary behavior++### Trace cut and runtime state++- [x] The client sends a stable Trace position, not a display index, timestamp, or message text.+- [x] The server accepts only a position that identifies the final root assistant text record of a+ completed Task; a forged/stale/malformed position is rejected.+- [x] Forking is rejected while the source is running or compacting, even if another client calls+ the API directly.+- [ ] The cut never splits a request, tool-call/result pair, steering group, or compaction span.+- [x] A fork before a later automatic compaction excludes that compaction; a fork after compaction+ preserves the earlier display history while resuming from the selected shard's valid context.+- [x] Multi-shard Sessions clone every earlier shard and only the selected prefix of the final+ cloned shard, with the new Session id in every `session_meta` record.+- [ ] The fork is resumable after a server restart, not only through an in-memory runtime created by+ the fork request.++### Files, images, and paths++- [x] The source scratchpad is snapshotted into the fork's own scratchpad directory.+- [x] System-generated `[attached image: ...]` and `[attached file: ...]` paths that point at the+ source scratchpad are rewritten to the fork scratchpad in cloned user messages.+- [x] HTTP(S) image URLs and marker-shaped user text that does not point at the source scratchpad+ are left unchanged.+- [x] Vision-model images stored inline as data URLs remain byte-identical in the cloned Trace.+- [x] Forked attachment/image endpoints resolve through the new Session id and return the copied+ bytes.+- [x] Deleting the source Session does not remove or break the fork's copied files or images.+- [x] Deleting the fork removes only its own Trace and scratchpad; the source remains intact.+- [x] A missing source scratchpad is treated as an empty snapshot.+- [ ] A real copy/write failure rolls back the partially created fork.++### Access, lifecycle, and presentation++- [x] The existing Session access check protects the endpoint; a caller cannot fork a Session they+ cannot read.+- [x] Scheduled/subagent Sessions do not accidentally become scheduled/subagent runs; the fork is a+ normal user-created Session.+- [x] The fork is not archived even when the source is archived.+- [x] Source deletion, fork creation, and concurrent fork requests cannot overwrite an existing+ Trace or Session id.+- [x] Fork numbers are allocated atomically, persist across server restarts, and are not reused when+ an earlier fork is deleted; concurrent forks from one source receive distinct numbers.+- [x] Chinese and English labels/tooltips/error messages are present, keyboard focus works, and the+ action remains available on touch layouts where hover does not exist.++## Implementation outline++1. Attach an optional immutable Trace coordinate (`fileIndex`, `ordinal`) to root messages returned+ by the history API. Carry the last assistant record's coordinate into the turn footer.+2. Add `POST /api/sessions/:sessionId/fork` with that coordinate. Resolve the source row, require an+ idle Session, scan raw Trace records to validate that the coordinate is the final assistant reply+ of a completed Task, and choose the safe cut after its closing request records but before later+ compaction or user input.+3. Allocate a collision-resistant Session id, clone Trace shards through the cut, rewrite each+ shard's source `session_meta` with the new id and paths, clear scheduled/subagent provenance,+ and rewrite only recognized source-scratchpad attachment markers.+4. Snapshot the source scratchpad under the new id before exposing the Session. Do not create an+ in-memory runtime: the fork follows the ordinary load-and-resume path on its first Task.+5. In one database transaction, increment the source row's persistent `fork_count`, derive the+ numbered title, and insert the new Session row. Roll the counter back if insertion fails and+ clean up the cloned Trace/scratchpad on any caught failure.+6. Add the footer action, pending state, localized copy, Session-list insertion, and navigation.+7. Cover the checklist with focused core/server/web tests plus one browser flow. Store review+ screenshots under `pr-assets/issue-293/` and link them from the Draft PR.++## Review evidence++- Automated checks:+ - `pnpm typecheck`+ - `pnpm test` (all workspace packages)+ - `packages/server/test/session-fork.test.ts` (11 integration scenarios, including cross-position,+ deletion, no-title, concurrent numbering, and committed-row rollback after response failure)+ - `packages/web/test/stream-model.test.ts` (history-coordinate propagation and SSE dedup)+- Browser scenario: a deterministic two-turn Session with one image and one file was forked after+ the first reply. The fork opened immediately, excluded the second turn, retained both+ attachments, and still rendered the copied image after the source Session was deleted. A second+ browser pass forked the first reply, then the second reply, then the first reply again and observed+ the shared, language-neutral title sequence `(1)`, `(2)`, `(3)`.+- The browser evidence is summarized in the PR description without committing screenshot binaries+ to the repository.+- Known limitations / remaining verification:+ - Forking intentionally duplicates the retained scratchpad and therefore its disk usage.+ - The UI does not display parent/child lineage; both Sessions are ordinary independent entries.+ - A real provider-backed follow-up after a process restart and injected filesystem write failures+ remain unchecked above; the implementation deliberately creates no fork runtime and cleans up+ Trace/index/scratchpad state on every caught write or database failure.diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex e816f5cf..273fedfb 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -945,6 +945,26 @@ export interface SessionCreateResponse {session: SessionInfo;}+/** Immutable location of one record in a Session's append-only Trace. */+export interface TracePosition {+ /** Trace shard index (`001` on disk becomes `1`). */+ fileIndex: number;+ /** Zero-based record ordinal within the parsed shard. */+ ordinal: number;+}++/** History-only transport metadata; `tracePosition` is never persisted into Trace JSONL. */+export type HistoryMessage = OmniMessage & { tracePosition?: TracePosition };++export interface SessionForkRequest {+ /** The final root assistant text record of the completed Task to keep. */+ position: TracePosition;+}++export interface SessionForkResponse {+ session: SessionInfo;+}+export interface SessionResponse {session: SessionInfo;}@@ -1028,7 +1048,7 @@ 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 {- messages: OmniMessage[];+ messages: HistoryMessage[];/*** Present only while the Session is running/compacting: the in-progress stream tail* (open streaming fragments + the channel cursor they cover), so a client joiningdiff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.tsindex b182940f..a9ef2b4b 100644--- a/packages/server/src/db/database.ts+++ b/packages/server/src/db/database.ts@@ -29,6 +29,7 @@ export function openDatabase(dbPath: string): DatabaseSync {// schema.ts; drop entries only in a release allowed to break existing web.db files.ensureColumn(db, "sessions", "client", "TEXT");ensureColumn(db, "sessions", "has_trace", "INTEGER NOT NULL DEFAULT 0");+ ensureColumn(db, "sessions", "fork_count", "INTEGER NOT NULL DEFAULT 0");ensureColumn(db, "sessions", "thinking_level", "TEXT");ensureColumn(db, "auth_sessions", "via", "TEXT");ensureColumn(db, "trace_files", "page_stats", "TEXT");diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.tsindex db5525a9..8eac5b85 100644--- a/packages/server/src/db/repos/sessions.ts+++ b/packages/server/src/db/repos/sessions.ts@@ -81,6 +81,35 @@ export class SessionsRepo {this.runInsert("INSERT OR IGNORE", row);}+ /**+ * Allocate the source Session's next persistent fork number and insert its fork atomically.+ * Keeping both writes in one transaction prevents concurrent requests from sharing a number,+ * while retaining `fork_count` on the source means deleting an older fork never reuses it.+ */+ insertFork(sourceSessionId: string, row: SessionRow): SessionRow {+ this.db.exec("BEGIN IMMEDIATE");+ try {+ const source = this.db+ .prepare(+ `UPDATE sessions SET fork_count = fork_count + 1 WHERE session_id = ?+ RETURNING title, fork_count`,+ )+ .get(sourceSessionId) as { title: string | null; fork_count: number } | undefined;+ if (!source) throw new Error(`Source Session not found: ${sourceSessionId}`);++ const forkTitle = source.title+ ? `${source.title} (${source.fork_count})`+ : `(${source.fork_count})`;+ const forkRow = { ...row, title: forkTitle };+ this.runInsert("INSERT", forkRow);+ this.db.exec("COMMIT");+ return forkRow;+ } catch (err) {+ this.db.exec("ROLLBACK");+ throw err;+ }+ }+/*** The two inserts' shared column list and binding order (they differ only in conflict* handling). `last_active_at` defaults **in SQL** (`COALESCE(?, ?)` over the row's owndiff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.tsindex b170fbfb..3ff5ea3a 100644--- a/packages/server/src/db/schema.ts+++ b/packages/server/src/db/schema.ts@@ -57,6 +57,7 @@ CREATE TABLE IF NOT EXISTS sessions (archived_at TEXT, -- archive time; NULL=not archived (shown by default; archived ones move under "Archived")client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); NULL = legacy row, treated as webhas_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)+ fork_count INTEGER NOT NULL DEFAULT 0, -- monotonically allocated child-fork number for this source Session; never decremented when a fork is deletedlast_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfillcreated_at TEXT NOT NULL); -- the schedule/subagent SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); "client" is a different, DB-only axis (who created the row)diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 81bc7a38..eb251ba0 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -23,6 +23,7 @@ import type {ServerEvent,SessionCategory,SessionCreateResponse,+ SessionForkResponse,SessionProcessesResponse,SessionResponse,SessionsResponse,@@ -108,8 +109,14 @@ function pageLimit(raw: string, name: string): number {*/function appendPendingInputs(messages: OmniMessage[], pending: OmniMessage[]): OmniMessage[] {if (pending.length === 0) return messages;- const tail = new Set(messages.slice(-50).map((m) => JSON.stringify(m)));- const missing = pending.filter((m) => !tail.has(JSON.stringify(m)));+ const envelopeKey = (message: OmniMessage): string => {+ const { tracePosition: _tracePosition, ...envelope } = message as OmniMessage & {+ tracePosition?: unknown;+ };+ return JSON.stringify(envelope);+ };+ const tail = new Set(messages.slice(-50).map(envelopeKey));+ const missing = pending.filter((message) => !tail.has(envelopeKey(message)));return missing.length > 0 ? [...messages, ...missing] : messages;}@@ -536,6 +543,67 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {} satisfies SessionResponse);});+ app.post("/:sessionId/fork", async (c) => {+ const row = resolveSession(c);+ const body = (await readJson(c)) as Record<string, unknown>;+ const raw = body.position;+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {+ throw badRequest("position must be a Trace position object.");+ }+ const { fileIndex, ordinal } = raw as Record<string, unknown>;+ if (+ !Number.isSafeInteger(fileIndex) ||+ (fileIndex as number) < 1 ||+ !Number.isSafeInteger(ordinal) ||+ (ordinal as number) < 0+ ) {+ throw badRequest("position.fileIndex must be positive and position.ordinal non-negative.");+ }++ const fork = await deps.manager.atIdleBoundary(row.sessionId, () =>+ deps.traceService.forkSessionTrace(row.projectId, row.agentId, row.sessionId, {+ fileIndex: fileIndex as number,+ ordinal: ordinal as number,+ }),+ );+ const forkRow: SessionRow = {+ sessionId: fork.sessionId,+ projectId: row.projectId,+ agentId: row.agentId,+ provider: row.provider,+ modelId: row.modelId,+ workspace: row.workspace,+ approvalMode: row.approvalMode,+ // insertFork replaces this with the source's current title plus its persistent number.+ title: null,+ client: "web",+ hasTrace: true,+ lastActiveAt: fork.createdAt,+ createdAt: fork.createdAt,+ };+ try {+ const insertedForkRow = deps.sessionsRepo.insertFork(row.sessionId, forkRow);+ deps.sessionSources.set(fork.sessionId, null);+ return c.json(+ {+ session: await deps.sessionService.toInfo(insertedForkRow, true),+ } satisfies SessionForkResponse,+ 201,+ );+ } catch (err) {+ // insertFork commits before response shaping. If a later step fails (for example,+ // resolving SessionInfo), remove that committed row along with the cloned files so+ // the index cannot retain a Session whose Trace was rolled back.+ deps.sessionsRepo.deleteById(fork.sessionId);+ await deps.traceService.deleteSessionTraces(row.projectId, row.agentId, fork.sessionId);+ await fs.rm(+ path.join(scratchpadDir(deps.config.root, row.projectId, row.agentId), fork.sessionId),+ { recursive: true, force: true },+ );+ throw err;+ }+ });+app.delete("/:sessionId", async (c) => {const row = resolveSession(c);// Mark as being deleted and converge active runs (beginSessionDeletion): newdiff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex d5160154..16f7bc84 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -596,6 +596,23 @@ export class SessionManager {if (entry && !opts?.queueIfBusy) this.assertIdle(entry);}+ /**+ * Run a metadata operation at an idle Session boundary under the same mutex as Task and+ * compaction starts. Session fork uses this to snapshot an append-only Trace without a Task+ * beginning between its status check and final read. An uncached Session is idle by definition;+ * unlike startTask this path deliberately does not load a heavyweight runtime.+ */+ async atIdleBoundary<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {+ return this.withLock(sessionId, async () => {+ this.assertOpen();+ this.assertAgentNotDeleting(sessionId);+ this.assertSessionNotDeleting(sessionId);+ const entry = this.entries.get(sessionId);+ if (entry) this.assertIdle(entry);+ return operation();+ });+ }+/*** Start a Task: get-or-load → 409* mutual-exclusion check → publish the input messages first → drive run in thediff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex b5b92d30..921d9762 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -12,11 +12,19 @@*/import fs from "node:fs/promises";import path from "node:path";+import { randomUUID } from "node:crypto";import {+ attachedFileLine,+ attachedImageLine,isSessionMeta,+ matchAttachedFileLine,+ matchAttachedImageLine,+ modelVisiblePath,parseTraceLines,parseUserSteeringText,readTraceTolerant,+ resumeTrace,+ scratchpadDir,tracesDir,} from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";@@ -26,6 +34,8 @@ import type {RequestSpan,SessionCategory,SessionCategoryCounts,+ HistoryMessage,+ TracePosition,ToolCallSpan,TraceAnalysisResponse,TraceEventsResponse,@@ -71,6 +81,69 @@ const IMPORT_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;/** 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;+function forkSessionId(date: Date): string {+ const pad = (n: number) => String(n).padStart(2, "0");+ return `session-${formatLocalDate(date)}-${pad(date.getHours())}-${pad(date.getMinutes())}-${pad(date.getSeconds())}-${randomUUID().replaceAll("-", "").slice(0, 8)}`;+}++function isAssistantText(msg: OmniMessage): boolean {+ const p = msg.payload as { type?: string; role?: string; text?: unknown };+ return (+ msg.type === "model_msg" &&+ p.type === "text" &&+ p.role === "assistant" &&+ typeof p.text === "string" &&+ p.text.trim() !== ""+ );+}++function isTaskStartingUser(msg: OmniMessage): boolean {+ const p = msg.payload as { type?: string; role?: string; text?: unknown };+ if (msg.type !== "model_msg") return false;+ if (p.type === "image_url") return true;+ if (p.type !== "text" || p.role !== "user" || typeof p.text !== "string") return false;+ if (parseUserSteeringText(p.text) !== null) return false;+ return !p.text.startsWith("[context_summary]") && !p.text.startsWith("<context_summary>");+}++function rewriteForkText(text: string, sourceScratchpad: string, forkScratchpad: string): string {+ const source = modelVisiblePath(sourceScratchpad).replace(/\/$/, "");+ const target = modelVisiblePath(forkScratchpad).replace(/\/$/, "");+ const rewriteTarget = (value: string): string | null => {+ if (value === source) return target;+ if (value.startsWith(`${source}/`)) return `${target}${value.slice(source.length)}`;+ return null;+ };+ return text+ .split("\n")+ .map((line) => {+ const trimmed = line.trim();+ const image = matchAttachedImageLine(trimmed);+ if (image !== null) {+ const rewritten = rewriteTarget(image);+ return rewritten === null ? line : line.replace(trimmed, attachedImageLine(rewritten));+ }+ const file = matchAttachedFileLine(trimmed);+ if (file !== null) {+ const rewritten = rewriteTarget(file);+ return rewritten === null ? line : line.replace(trimmed, attachedFileLine(rewritten));+ }+ return line;+ })+ .join("\n");+}++function positioned(+ messages: readonly OmniMessage[],+ fileIndex: number,+ fromOrdinal = 0,+): HistoryMessage[] {+ return messages.map((msg, i) => ({+ ...msg,+ tracePosition: { fileIndex, ordinal: fromOrdinal + i },+ }));+}+interface LocatedFile {path: string;date: string;@@ -92,6 +165,11 @@ export interface MessagesPageResult {prior: WindowPriorStats;}+export interface ForkTraceResult {+ sessionId: string;+ createdAt: string;+}+/*** Per-request expansion context: `projectScanned` caps the miss-path force reconcile at* one per request; `ancestry` guards cycles; `raw` memoizes each child session's@@ -219,7 +297,7 @@ export class TraceService {projectId: string,agentId: string,sessionId: string,- ): Promise<OmniMessage[]> {+ ): Promise<HistoryMessage[]> {const ctx: ExpandCtx = {projectScanned: false,ancestry: new Set([sessionId]),@@ -229,7 +307,8 @@ export class TraceService {const files = await this.locateAll(projectId, agentId, sessionId);const out: OmniMessage[] = [];for (const file of files) {- out.push(...(await this.expandMessages(projectId, await this.readShard(file.path), ctx)));+ const raw = await this.readShard(file.path);+ out.push(...(await this.expandMessages(projectId, positioned(raw, file.index), ctx)));}return out;}@@ -482,7 +561,7 @@ export class TraceService {prior = initialScanState().totals;}- const windowRaw: OmniMessage[] = [];+ const windowRaw: HistoryMessage[] = [];for (let pos = start.pos; pos <= endPos; pos++) {const messages = shardMessages.get(pos) ?? (await this.readShard(files[pos]!.path));const from = pos === start.pos ? start.ordinal : 0;@@ -490,12 +569,190 @@ export class TraceService {pos === endPos && endOrdinal !== null? Math.min(endOrdinal, messages.length): messages.length;- for (let i = from; i < to; i++) windowRaw.push(messages[i]!);+ for (let i = from; i < to; i++) {+ windowRaw.push({+ ...messages[i]!,+ tracePosition: { fileIndex: files[pos]!.index, ordinal: i },+ });+ }}const expanded = await this.expandMessages(projectId, windowRaw, ctx);return { messages: expanded, ...(before !== undefined ? { before } : {}), prior };}+ /**+ * Clone a source Session through one completed root-assistant reply. The supplied position+ * names the reply record itself; this method validates it against raw Trace structure and+ * chooses the exclusive cut after the request's closing records but before a later Task or+ * compaction. Earlier shards stay intact so the fork renders the same history, while core+ * resumes from the selected shard exactly as it would after a restart.+ */+ async forkSessionTrace(+ projectId: string,+ agentId: string,+ sourceSessionId: string,+ position: TracePosition,+ ): Promise<ForkTraceResult> {+ const invalid = (message: string) => new HttpError(400, "invalid_fork_position", message);+ const files = await this.locateAll(projectId, agentId, sourceSessionId);+ const targetFilePos = files.findIndex((file) => file.index === position.fileIndex);+ if (targetFilePos < 0) throw invalid("The selected reply no longer exists in this Session.");++ const shards: OmniMessage[][] = [];+ for (let i = 0; i <= targetFilePos; i++) shards.push(await this.readShard(files[i]!.path));+ const targetShard = shards[targetFilePos]!;+ const target = targetShard[position.ordinal];+ if (!target || !isAssistantText(target)) {+ throw invalid("The fork position must identify a completed assistant reply.");+ }++ // A compaction's assistant summary is a real model message in Trace but never a visible+ // assistant reply. Reject a forged position inside that hidden span.+ let inCompaction = false;+ for (let filePos = 0; filePos <= targetFilePos; filePos++) {+ const messages = shards[filePos]!;+ const stop = filePos === targetFilePos ? position.ordinal : messages.length;+ for (let i = 0; i < stop; i++) {+ const p = messages[i]!.payload as { type?: string };+ if (messages[i]!.type === "event_msg" && p.type === "compaction_begin") {+ inCompaction = true;+ } else if (messages[i]!.type === "event_msg" && p.type === "compaction_end") {+ inCompaction = false;+ }+ }+ }+ if (inCompaction) throw invalid("A compaction summary cannot be used as a fork point.");++ let cutOrdinal = position.ordinal + 1;+ let completedRequest = false;+ for (let i = position.ordinal + 1; i < targetShard.length; i++) {+ const msg = targetShard[i]!;+ const p = msg.payload as { type?: string; status?: string };+ // The next user Task and housekeeping compaction both belong after the selected reply.+ if (isTaskStartingUser(msg) || (msg.type === "event_msg" && p.type === "compaction_begin")) {+ break;+ }+ // A Task may contain several assistant segments/requests. Only the final visible reply+ // gets a footer-level fork action; an intermediate segment is not a safe boundary.+ if (isAssistantText(msg)) {+ throw invalid("The selected record is not the final assistant reply of its Task.");+ }+ cutOrdinal = i + 1;+ if (msg.type === "event_msg" && p.type === "request_end") {+ if (p.status === "completed") completedRequest = true;+ else throw invalid("The selected assistant reply belongs to an incomplete request.");+ }+ }+ if (!completedRequest) throw invalid("The selected assistant reply has not completed yet.");++ const resumed = resumeTrace(targetShard.slice(0, cutOrdinal));+ if (+ resumed.contextClosed ||+ resumed.carryOver.length > 0 ||+ !resumed.history.some((message) => message === target)+ ) {+ throw invalid("The selected reply is not a complete resumable Task boundary.");+ }++ const firstMeta = shards.flat().find(isSessionMeta);+ if (!firstMeta) throw invalid("The source Trace has no session metadata.");++ const created = new Date();+ const createdAt = created.toISOString();+ const newSessionId = forkSessionId(created);+ const scratchpadRoot = scratchpadDir(this.root, projectId, agentId);+ const sourceScratchpad = path.join(scratchpadRoot, sourceSessionId);+ const forkScratchpad = path.join(scratchpadRoot, newSessionId);+ const written: string[] = [];++ const rewrite = (msg: OmniMessage): OmniMessage => {+ if (isSessionMeta(msg)) {+ const sourcePrompt = msg.payload.system_prompt;+ const sourceVisible = modelVisiblePath(sourceScratchpad);+ const forkVisible = modelVisiblePath(forkScratchpad);+ const payload = {+ ...msg.payload,+ session_id: newSessionId,+ system_prompt: sourcePrompt+ .split(sourceSessionId)+ .join(newSessionId)+ .split(sourceVisible)+ .join(forkVisible),+ };+ delete payload.source;+ return { ...msg, payload };+ }+ const p = msg.payload as { type?: string; role?: string; text?: unknown };+ if (+ msg.type === "model_msg" &&+ p.type === "text" &&+ p.role === "user" &&+ typeof p.text === "string"+ ) {+ return {+ ...msg,+ payload: {+ ...msg.payload,+ text: rewriteForkText(p.text, sourceScratchpad, forkScratchpad),+ },+ } as OmniMessage;+ }+ return msg;+ };++ try {+ // Snapshot the whole Session scratchpad: besides composer attachments it may contain+ // recovery archives or temporary files explicitly referenced by the retained history.+ try {+ const stat = await fs.stat(sourceScratchpad);+ if (stat.isDirectory()) {+ await fs.mkdir(scratchpadRoot, { recursive: true });+ await fs.cp(sourceScratchpad, forkScratchpad, {+ recursive: true,+ force: false,+ errorOnExist: true,+ });+ }+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;+ }++ for (let filePos = 0; filePos <= targetFilePos; filePos++) {+ const sourceFile = files[filePos]!;+ const sourceMessages = shards[filePos]!;+ const limit = filePos === targetFilePos ? cutOrdinal : sourceMessages.length;+ const records = sourceMessages.slice(0, limit).map(rewrite);+ if (!isSessionMeta(records[0]!)) {+ throw invalid(`Trace shard ${sourceFile.index} does not start with session metadata.`);+ }+ const dir = path.join(tracesDir(this.root, projectId, agentId), sourceFile.date);+ await fs.mkdir(dir, { recursive: true });+ const file = path.join(+ dir,+ `${newSessionId}_${String(sourceFile.index).padStart(3, "0")}.jsonl`,+ );+ const body = records.map((record) => JSON.stringify(record)).join("\n") + "\n";+ await fs.writeFile(file, body, { encoding: "utf8", flag: "wx" });+ written.push(file);+ this.deps.index.registerImportedFile({+ projectId,+ agentId,+ sessionId: newSessionId,+ fileIndex: sourceFile.index,+ date: sourceFile.date,+ sizeBytes: Buffer.byteLength(body, "utf8"),+ records,+ });+ }+ return { sessionId: newSessionId, createdAt };+ } catch (err) {+ await Promise.all(written.map((file) => fs.rm(file, { force: true }).catch(() => undefined)));+ await fs.rm(forkScratchpad, { recursive: true, force: true }).catch(() => undefined);+ this.deps.index.removeSession(projectId, agentId, newSessionId);+ throw err;+ }+ }+/** List of Trace files (index / date / size / mtime). */async listTraceFiles(projectId: string,diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.tsindex 0b1d9bc4..2bbdaccf 100644--- a/packages/server/test/db-upgrade.test.ts+++ b/packages/server/test/db-upgrade.test.ts@@ -88,6 +88,9 @@ describe("openDatabase column upgrade", () => {expect(legacy).not.toBeNull();expect(legacy!.client).toBeNull();expect(legacy!.hasTrace).toBe(false);+ expect(+ db.prepare("SELECT fork_count FROM sessions WHERE session_id = ?").get("session-legacy"),+ ).toEqual({ fork_count: 0 });// last_active_at is ALTERed in too; with no usage_records the backfill falls to created_at.expect(legacy!.lastActiveAt).toBe("2026-01-01T00:00:00.000Z");expect(repo.listByAgent("p1", "a1", { webOnly: true }).map((r) => r.sessionId)).toEqual([@@ -127,6 +130,7 @@ describe("openDatabase column upgrade", () => {const cols = db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[];expect(cols.filter((c) => c.name === "client")).toHaveLength(1);expect(cols.filter((c) => c.name === "has_trace")).toHaveLength(1);+ expect(cols.filter((c) => c.name === "fork_count")).toHaveLength(1);expect(cols.filter((c) => c.name === "last_active_at")).toHaveLength(1);} finally {db.close();diff --git a/packages/server/test/messages-pending-input.test.ts b/packages/server/test/messages-pending-input.test.tsindex 8ffbbf75..58afd78b 100644--- a/packages/server/test/messages-pending-input.test.ts+++ b/packages/server/test/messages-pending-input.test.ts@@ -17,12 +17,13 @@ import {mcpConnectBegin,mcpConnectEnd,requestBegin,+ sessionMeta,} from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";import type { MessagesResponse } from "../src/api/types.js";import type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";-import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";+import { apiClient, createTestApp, provisionUser, waitFor, writeTraceFile } from "./helpers.js";import type { TestApp } from "./helpers.js";const SID = "session-2026-08-10-10-00-00-eeff0002";@@ -154,6 +155,41 @@ describe("GET /messages serves the running task's pending inputs", () => {);});+ it("deduplicates a persisted pending input even when history adds a Trace position", async () => {+ const res = await api.post(`/api/sessions/${SID}/tasks`, {+ input: [{ type: "text", text: "positioned once" }],+ });+ expect(res.status).toBe(202);+ await waitFor(() => t.deps.manager.pendingBootstrap(SID).length === 1);+ const input = t.deps.manager.pendingInputs(SID)[0]!;+ await writeTraceFile(t.root, "pender-default_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",+ }),+ input,+ ]);++ const during = (await (await api.get(`/api/sessions/${SID}/messages`)).json()) as {+ messages: OmniMessage[];+ };+ expect(+ during.messages.filter(+ (message) => (message.payload as { text?: string }).text === "positioned once",+ ),+ ).toHaveLength(1);++ 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 = "session-2026-08-11-10-00-00-eeff0003";const row: SessionRow = {diff --git a/packages/server/test/session-fork.test.ts b/packages/server/test/session-fork.test.tsnew file mode 100644index 00000000..83622712--- /dev/null+++ b/packages/server/test/session-fork.test.ts@@ -0,0 +1,538 @@+import fs from "node:fs/promises";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ assistantText,+ compactionBegin,+ compactionEnd,+ imageUrlMessage,+ modelVisiblePath,+ requestBegin,+ requestEnd,+ scratchpadDir,+ sessionMeta,+ tokenUsage,+ tracesDir,+ userText,+} from "@prismshadow/penguin-core";+import type { OmniMessage, SessionMetaPayload, TokenCounts } from "@prismshadow/penguin-core";+import type {+ MessagesResponse,+ ProjectCreateResponse,+ SessionForkResponse,+} from "../src/api/types.js";+import { apiClient, createTestApp, provisionUser, writeTraceFile } from "./helpers.js";+import type { TestApp } from "./helpers.js";+import type { SessionRow } from "../src/db/repos/sessions.js";+import type { RuntimeSession } from "../src/runtime/session-manager.js";+import { waitFor } from "./helpers.js";++const SID = "session-2026-08-14-10-00-00-aabbcc01";++function counts(total: number): TokenCounts {+ return { cache_read: 0, cache_write: 0, output: total, total };+}++function at(timestamp: string, message: OmniMessage): OmniMessage {+ return { ...message, timestamp };+}++function parkingFakeSession(sessionId: string, until: Promise<void>): RuntimeSession {+ return {+ sessionId,+ toolPermission: () => "rw",+ generateTitle: async () => ({ title: null, usage: null }),+ compactability: () => "ok" as const,+ steer: () => false,+ skipReconnectWait: () => false,+ async *run() {+ await until;+ yield assistantText("done");+ },+ async *compact() {},+ };+}++describe("session fork", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;+ let projectId: string;+ let workspace: string;++ beforeEach(async () => {+ t = await createTestApp();+ const { cookie } = await provisionUser(t.app, "fork_owner");+ api = apiClient(t.app, cookie);+ const project = (await (+ await api.post("/api/projects", { projectId: "fork_owner-fork", name: "Fork project" })+ ).json()) as ProjectCreateResponse;+ projectId = project.project.projectId;+ workspace = path.join(t.root, "fork-workspace");+ await fs.mkdir(workspace, { recursive: true });+ });++ afterEach(async () => {+ await t.cleanup();+ });++ async function seedSource(): Promise<{ scratch: string; image: Buffer; row: SessionRow }> {+ const scratch = path.join(scratchpadDir(t.root, projectId, "default_agent"), SID);+ await fs.mkdir(scratch, { recursive: true });+ const image = Buffer.from("89504e470d0a1a0a", "hex");+ await fs.writeFile(path.join(scratch, "photo.png"), image);+ await fs.writeFile(path.join(scratch, "report.txt"), "source attachment", "utf8");+ await fs.mkdir(path.join(scratch, "truncated-tool-output"), { recursive: true });+ await fs.writeFile(+ path.join(scratch, "truncated-tool-output", "recovery.txt"),+ "recovery",+ "utf8",+ );++ const row: SessionRow = {+ sessionId: SID,+ projectId,+ agentId: "default_agent",+ provider: "custom",+ modelId: "fork-model",+ workspace,+ approvalMode: "always-ask",+ title: "Attachment discussion",+ client: "web",+ hasTrace: true,+ lastActiveAt: "2026-08-14T10:01:00.000Z",+ createdAt: "2026-08-14T10:00:00.000Z",+ };+ t.deps.sessionsRepo.insert(row);+ const meta: SessionMetaPayload = {+ session_id: SID,+ provider: "custom",+ model_id: "fork-model",+ model_context_window: 10_000,+ system_prompt: `Session ${SID}; scratchpad ${modelVisiblePath(scratch)}`,+ agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),+ workspace,+ source: "schedule",+ };+ await writeTraceFile(t.root, projectId, "default_agent", "2026-08-14", SID, 1, [+ at("2026-08-14T10:00:00.000Z", sessionMeta(meta)),+ at(+ "2026-08-14T10:00:01.000Z",+ userText(+ [+ "inspect these",+ `[attached image: ${modelVisiblePath(path.join(scratch, "photo.png"))}]`,+ `[attached file: ${modelVisiblePath(path.join(scratch, "report.txt"))}]`,+ "[attached image: https://example.com/remote.png]",+ "[attached file: /tmp/user-shaped-marker.txt]",+ ].join("\n"),+ ),+ ),+ at("2026-08-14T10:00:01.100Z", imageUrlMessage("data:image/png;base64,aW5saW5l")),+ at("2026-08-14T10:00:02.000Z", requestBegin()),+ at("2026-08-14T10:00:03.000Z", assistantText("first answer")),+ at("2026-08-14T10:00:04.000Z", requestEnd("completed")),+ at("2026-08-14T10:00:04.100Z", tokenUsage(counts(100), counts(100))),+ at("2026-08-14T10:01:01.000Z", userText("later question")),+ at("2026-08-14T10:01:02.000Z", requestBegin()),+ at("2026-08-14T10:01:03.000Z", assistantText("later answer")),+ at("2026-08-14T10:01:04.000Z", requestEnd("completed")),+ at("2026-08-14T10:01:04.100Z", tokenUsage(counts(200), counts(100))),+ ]);+ return { scratch, image, row };+ }++ it("forks through the selected reply, snapshots scratchpad, rewrites local markers, and survives source deletion", async () => {+ const { image } = await seedSource();+ expect((await api.patch(`/api/sessions/${SID}`, { archived: true })).status).toBe(200);+ const history = (await (+ await api.get(`/api/sessions/${SID}/messages`)+ ).json()) as MessagesResponse;+ const selected = history.messages.find(+ (message) => (message.payload as { text?: string }).text === "first answer",+ );+ expect(selected?.tracePosition).toEqual({ fileIndex: 1, ordinal: 4 });++ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: selected!.tracePosition,+ });+ expect(response.status).toBe(201);+ const { session } = (await response.json()) as SessionForkResponse;+ expect(session.sessionId).not.toBe(SID);+ expect(session).toMatchObject({+ provider: "custom",+ modelId: "fork-model",+ workspace,+ approvalMode: "always-ask",+ title: "Attachment discussion (1)",+ archived: false,+ hasTrace: true,+ });+ expect(session.source).toBeUndefined();++ const forked = (await (+ await api.get(`/api/sessions/${session.sessionId}/messages`)+ ).json()) as MessagesResponse;+ const texts = forked.messages+ .map((message) => (message.payload as { text?: string }).text)+ .filter((text): text is string => text !== undefined);+ expect(texts).toContain("first answer");+ expect(texts).not.toContain("later question");+ expect(texts).not.toContain("later answer");+ const forkUser = texts.find((text) => text.startsWith("inspect these"))!;+ expect(forkUser).toContain(`/scratchpad/${session.sessionId}/photo.png`);+ expect(forkUser).toContain(`/scratchpad/${session.sessionId}/report.txt`);+ expect(forkUser).toContain("https://example.com/remote.png");+ expect(forkUser).toContain("[attached file: /tmp/user-shaped-marker.txt]");+ expect(+ forked.messages.some(+ (message) =>+ (message.payload as { image_url?: string }).image_url ===+ "data:image/png;base64,aW5saW5l",+ ),+ ).toBe(true);+ const forkMeta = forked.messages.find((message) => message.type === "session_meta");+ expect((forkMeta?.payload as SessionMetaPayload).session_id).toBe(session.sessionId);+ expect((forkMeta?.payload as SessionMetaPayload).system_prompt).toContain(session.sessionId);+ expect((forkMeta?.payload as SessionMetaPayload).system_prompt).not.toContain(SID);++ const forkScratch = path.join(+ scratchpadDir(t.root, projectId, "default_agent"),+ session.sessionId,+ );+ expect(await fs.readFile(path.join(forkScratch, "report.txt"), "utf8")).toBe(+ "source attachment",+ );+ expect(+ await fs.readFile(path.join(forkScratch, "truncated-tool-output", "recovery.txt"), "utf8"),+ ).toBe("recovery");+ expect(+ Buffer.from(+ await (+ await api.get(`/api/sessions/${session.sessionId}/scratchpad/photo.png`)+ ).arrayBuffer(),+ ),+ ).toEqual(image);++ const disposableResponse = await api.post(`/api/sessions/${SID}/fork`, {+ position: selected!.tracePosition,+ });+ expect(disposableResponse.status).toBe(201);+ const disposable = (await disposableResponse.json()) as SessionForkResponse;+ expect(disposable.session.title).toBe("Attachment discussion (2)");+ expect((await api.delete(`/api/sessions/${disposable.session.sessionId}`)).status).toBe(204);+ expect(+ await fs.readFile(+ path.join(scratchpadDir(t.root, projectId, "default_agent"), SID, "report.txt"),+ "utf8",+ ),+ ).toBe("source attachment");++ expect((await api.delete(`/api/sessions/${SID}`)).status).toBe(204);+ expect(+ Buffer.from(+ await (+ await api.get(`/api/sessions/${session.sessionId}/scratchpad/photo.png`)+ ).arrayBuffer(),+ ),+ ).toEqual(image);+ expect((await api.get(`/api/sessions/${session.sessionId}`)).status).toBe(200);+ });++ it("shares one persistent number sequence across different reply positions", async () => {+ await seedSource();++ const first = (await (+ await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ })+ ).json()) as SessionForkResponse;+ const second = (await (+ await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 9 },+ })+ ).json()) as SessionForkResponse;+ expect(first.session.title).toBe("Attachment discussion (1)");+ expect(second.session.title).toBe("Attachment discussion (2)");++ expect((await api.delete(`/api/sessions/${first.session.sessionId}`)).status).toBe(204);+ const third = (await (+ await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ })+ ).json()) as SessionForkResponse;+ expect(third.session.title).toBe("Attachment discussion (3)");+ });++ it("uses a readable numbered fallback when the source has no title", async () => {+ await seedSource();+ t.deps.db.prepare("UPDATE sessions SET title = NULL WHERE session_id = ?").run(SID);++ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ });+ expect(response.status).toBe(201);+ const { session } = (await response.json()) as SessionForkResponse;+ expect(session.title).toBe("(1)");+ });++ it("removes the committed fork row and cloned files when response shaping fails", async () => {+ await seedSource();+ const toInfo = vi+ .spyOn(t.deps.sessionService, "toInfo")+ .mockRejectedValueOnce(new Error("response shaping failed"));++ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ });+ expect(response.status).toBe(500);++ const forkRow = toInfo.mock.calls[0]?.[0];+ expect(forkRow).toBeDefined();+ expect(t.deps.sessionsRepo.findById(forkRow!.sessionId)).toBeNull();+ await expect(+ fs.stat(path.join(scratchpadDir(t.root, projectId, "default_agent"), forkRow!.sessionId)),+ ).rejects.toMatchObject({ code: "ENOENT" });+ expect(+ await fs.readdir(path.join(tracesDir(t.root, projectId, "default_agent"), "2026-08-14")),+ ).toEqual([`${SID}_001.jsonl`]);++ // The allocation remains consumed so a transient failure cannot make a number mean+ // two different forks over time.+ toInfo.mockRestore();+ const retry = (await (+ await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ })+ ).json()) as SessionForkResponse;+ expect(retry.session.title).toBe("Attachment discussion (2)");+ });++ it("rejects a user-message coordinate rather than cutting an unsafe prefix", async () => {+ await seedSource();+ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 1 },+ });+ expect(response.status).toBe(400);+ expect(((await response.json()) as { error: { code: string } }).error.code).toBe(+ "invalid_fork_position",+ );+ });++ it("returns 409 while the source Session is running", async () => {+ const { row } = await seedSource();+ let release = () => {};+ const parked = new Promise<void>((resolve) => {+ release = resolve;+ });+ t.deps.manager.adopt(row, parkingFakeSession(SID, parked));+ await api.post(`/api/sessions/${SID}/tasks`, { input: [{ type: "text", text: "busy" }] });+ await waitFor(() => t.deps.manager.statusOf(SID) === "running");++ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ });+ expect(response.status).toBe(409);+ expect(((await response.json()) as { error: { code: string } }).error.code).toBe(+ "task_in_progress",+ );++ release();+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ });++ it("treats a missing scratchpad as empty and deleting the fork leaves the source intact", async () => {+ const { scratch } = await seedSource();+ await fs.rm(scratch, { recursive: true, force: true });++ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ });+ expect(response.status).toBe(201);+ const { session } = (await response.json()) as SessionForkResponse;+ expect((await api.delete(`/api/sessions/${session.sessionId}`)).status).toBe(204);++ const source = (await (+ await api.get(`/api/sessions/${SID}/messages`)+ ).json()) as MessagesResponse;+ expect(+ source.messages.some(+ (message) => (message.payload as { text?: string }).text === "later answer",+ ),+ ).toBe(true);+ expect((await api.get(`/api/sessions/${SID}`)).status).toBe(200);+ });++ it("clones completed earlier shards, cuts the selected shard, and exposes stable positions on a tail page", async () => {+ const { scratch } = await seedSource();+ const meta: SessionMetaPayload = {+ session_id: SID,+ provider: "custom",+ model_id: "fork-model",+ model_context_window: 10_000,+ system_prompt: `Session ${SID}; scratchpad ${modelVisiblePath(scratch)}`,+ agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),+ workspace,+ };+ const compaction = [+ at(+ "2026-08-14T10:01:05.000Z",+ compactionBegin({ reason: "context", mode: "summarize", context: 500, turns: 2 }),+ ),+ at("2026-08-14T10:01:05.100Z", requestBegin()),+ at("2026-08-14T10:01:05.200Z", assistantText("[summary]summary[/summary]")),+ at("2026-08-14T10:01:05.300Z", requestEnd("completed")),+ at(+ "2026-08-14T10:01:05.400Z",+ compactionEnd({ reason: "context", mode: "summarize", status: "completed" }),+ ),+ ];+ await fs.appendFile(+ path.join(tracesDir(t.root, projectId, "default_agent"), "2026-08-14", `${SID}_001.jsonl`),+ compaction.map((message) => JSON.stringify(message)).join("\n") + "\n",+ "utf8",+ );+ await writeTraceFile(t.root, projectId, "default_agent", "2026-08-14", SID, 2, [+ at("2026-08-14T10:01:05.000Z", sessionMeta(meta)),+ at("2026-08-14T10:01:06.000Z", userText("[context_summary]\nsummary\n[/context_summary]")),+ at("2026-08-14T10:01:07.000Z", userText("after compaction")),+ at("2026-08-14T10:01:08.000Z", requestBegin()),+ at("2026-08-14T10:01:09.000Z", assistantText("fork shard two")),+ at("2026-08-14T10:01:10.000Z", requestEnd("completed")),+ at("2026-08-14T10:01:10.100Z", tokenUsage(counts(300), counts(100))),+ at("2026-08-14T10:02:00.000Z", userText("excluded shard tail")),+ ]);++ const tail = (await (+ await api.get(`/api/sessions/${SID}/messages?tailLimit=2`)+ ).json()) as MessagesResponse;+ const selected = tail.messages.find(+ (message) => (message.payload as { text?: string }).text === "fork shard two",+ );+ expect(selected?.tracePosition).toEqual({ fileIndex: 2, ordinal: 4 });++ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: selected!.tracePosition,+ });+ expect(response.status).toBe(201);+ const { session } = (await response.json()) as SessionForkResponse;+ const forked = (await (+ await api.get(`/api/sessions/${session.sessionId}/messages`)+ ).json()) as MessagesResponse;+ const metas = forked.messages.filter((message) => message.type === "session_meta");+ expect(metas).toHaveLength(2);+ expect(+ metas.every(+ (message) => (message.payload as SessionMetaPayload).session_id === session.sessionId,+ ),+ ).toBe(true);+ expect(+ forked.messages.some(+ (message) => (message.payload as { text?: string }).text === "first answer",+ ),+ ).toBe(true);+ expect(+ forked.messages.some(+ (message) => (message.payload as { text?: string }).text === "fork shard two",+ ),+ ).toBe(true);+ expect(+ forked.messages.some(+ (message) => (message.payload as { text?: string }).text === "excluded shard tail",+ ),+ ).toBe(false);+ });++ it("rejects an intermediate assistant segment and a hidden compaction summary", async () => {+ await seedSource();+ const meta: SessionMetaPayload = {+ session_id: SID,+ provider: "custom",+ model_id: "fork-model",+ model_context_window: 10_000,+ system_prompt: `Session ${SID}`,+ agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),+ workspace,+ };+ await writeTraceFile(t.root, projectId, "default_agent", "2026-08-15", SID, 2, [+ at("2026-08-15T10:00:00.000Z", sessionMeta(meta)),+ at("2026-08-15T10:00:01.000Z", userText("tool task")),+ at("2026-08-15T10:00:02.000Z", requestBegin()),+ at("2026-08-15T10:00:03.000Z", assistantText("intermediate")),+ at("2026-08-15T10:00:04.000Z", requestEnd("completed")),+ at("2026-08-15T10:00:05.000Z", requestBegin()),+ at("2026-08-15T10:00:06.000Z", assistantText("final")),+ at("2026-08-15T10:00:07.000Z", requestEnd("completed")),+ at(+ "2026-08-15T10:00:08.000Z",+ compactionBegin({ reason: "context", mode: "summarize", context: 500, turns: 1 }),+ ),+ at("2026-08-15T10:00:09.000Z", requestBegin()),+ at("2026-08-15T10:00:10.000Z", assistantText("[summary]hidden[/summary]")),+ at("2026-08-15T10:00:11.000Z", requestEnd("completed")),+ at(+ "2026-08-15T10:00:12.000Z",+ compactionEnd({ reason: "context", mode: "summarize", status: "completed" }),+ ),+ ]);++ for (const ordinal of [3, 10]) {+ const response = await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 2, ordinal },+ });+ expect(response.status).toBe(400);+ expect(((await response.json()) as { error: { code: string } }).error.code).toBe(+ "invalid_fork_position",+ );+ }++ const beforeCompaction = await api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 2, ordinal: 6 },+ });+ expect(beforeCompaction.status).toBe(201);+ const { session } = (await beforeCompaction.json()) as SessionForkResponse;+ const forked = (await (+ await api.get(`/api/sessions/${session.sessionId}/messages`)+ ).json()) as MessagesResponse;+ expect(+ forked.messages.some(+ (message) =>+ message.type === "event_msg" &&+ (message.payload as { type?: string }).type === "compaction_begin",+ ),+ ).toBe(false);+ });++ it("gives concurrent forks unique Sessions without overwriting the source", async () => {+ await seedSource();+ const responses = await Promise.all(+ Array.from({ length: 4 }, () =>+ api.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ }),+ ),+ );+ expect(responses.every((response) => response.status === 201)).toBe(true);+ const sessions = await Promise.all(+ responses.map(async (response) => ((await response.json()) as SessionForkResponse).session),+ );+ const ids = sessions.map((session) => session.sessionId);+ expect(new Set(ids).size).toBe(ids.length);+ expect(sessions.map((session) => session.title).sort()).toEqual([+ "Attachment discussion (1)",+ "Attachment discussion (2)",+ "Attachment discussion (3)",+ "Attachment discussion (4)",+ ]);+ expect((await api.get(`/api/sessions/${SID}`)).status).toBe(200);+ });++ it("does not reveal the fork endpoint to a user without Project access", async () => {+ await seedSource();+ const { cookie } = await provisionUser(t.app, "fork_outsider");+ const outsider = apiClient(t.app, cookie);+ const response = await outsider.post(`/api/sessions/${SID}/fork`, {+ position: { fileIndex: 1, ordinal: 4 },+ });+ expect(response.status).toBe(404);+ });+});diff --git a/packages/web/e2e/README.md b/packages/web/e2e/README.mdindex 1d403bce..a4324c57 100644--- a/packages/web/e2e/README.md+++ b/packages/web/e2e/README.md@@ -1,10 +1,11 @@# Web E2E (Playwright)Browser end-to-end tests: chat (thinking + tool approval + tool execution + second-turn-reply), the iconified stats line (cost conversion / copy reply), Traces (per-Task timeline +-legend + hover-linked highlighting), Workspace file preview (sandboxed HTML rendering, path-hidden by default). The LLM is driven by `mock-llm.mjs` (a mock Anthropic Messages SSE-endpoint) — no network access.+reply), the iconified stats line (cost conversion / copy reply), Session fork (footer action+right of copy, confirm-gated, and no stray request after deleting the fork), Traces (per-Task+timeline + legend + hover-linked highlighting), Workspace file preview (sandboxed HTML+rendering, path hidden by default). The LLM is driven by `mock-llm.mjs` (a mock Anthropic+Messages SSE endpoint) — no network access.```shpnpm --filter @prismshadow/penguin-web test:e2e # build + start the server + run the testsdiff --git a/packages/web/e2e/session-fork.spec.mjs b/packages/web/e2e/session-fork.spec.mjsnew file mode 100644index 00000000..59881fe9--- /dev/null+++ b/packages/web/e2e/session-fork.spec.mjs@@ -0,0 +1,173 @@+/**+ * Session fork e2e: the reply footer's fork action (right of copy, confirm-gated) and the+ * delete-the-fork flow.+ *+ * - The fork button sits to the RIGHT of the copy button (review request), and clicking it+ * only opens the shared ConfirmModal — Cancel fires no fork request, Confirm creates the+ * fork and navigates to it. Copy itself stays a plain unconfirmed click.+ * - Deleting the fork must not ADD A SERVER ERROR RECORD. That is the acceptance criterion+ * the maintainer stated ("不应该多"), and it is asserted as a count taken before and after+ * the delete — not merely as "the UI looks right". Deleting the conversation you are+ * looking at is the normal way to discard a fork, and the chat page's deep-link lookup+ * used to re-fetch that just-deleted Session, so every fork deletion left one+ * `[http] session_not_found` row behind in the Cost Center's error panel.+ *+ * Runs as ADMIN deliberately: `/api/sessions/:sessionId` carries no `:projectId`, so the+ * recorder attributes its errors to no Project, and unattributed records are only visible to+ * admins. A regular member reads 0 either way, which would make this assertion vacuous.+ */+import { test, expect } from "@playwright/test";+import { login, ADMIN_ID, ADMIN_PASSWORD } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;++/** Total server-recorded errors visible to this (admin) context, including unattributed ones. */+async function errorRecordCount(page, projectId) {+ const res = await page.request.get(+ `${BASE}/api/projects/${projectId}/usage/errors?offset=0&limit=1`,+ );+ expect(res.ok(), "read error records").toBeTruthy();+ return (await res.json()).total;+}++test("fork from reply: button order + confirm gate + clean fork deletion", async ({ page }) => {+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);++ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;++ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();++ // Default approval mode (allow-all): the mock's turn-1 tool call auto-runs and turn 2+ // completes the reply, which is what makes the footer's fork action appear.+ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8" },+ })+ ).json();+ const sourceId = sess.session.sessionId;++ // Record every /api request (method + url + status) to prove which ids get re-fetched.+ const apiLog = [];+ page.on("request", (r) => {+ if (r.url().includes("/api/"))+ apiLog.push({ t: Date.now(), kind: "req", m: r.method(), url: r.url() });+ });+ page.on("response", (r) => {+ if (r.url().includes("/api/"))+ apiLog.push({ t: Date.now(), kind: "res", status: r.status(), url: r.url() });+ });++ await page.goto(`${BASE}/chat/${sourceId}`);+ const ta = page.getByPlaceholder(/输入消息/);+ await ta.waitFor();+ await ta.fill("Fork e2e message");+ await page.getByRole("button", { name: "发送" }).click();+ await expect(page.getByText("Command finished; the result looks as expected.")).toBeVisible({+ timeout: 30_000,+ });++ // Reveal the reply footer.+ await page.getByText("Command finished; the result looks as expected.").first().hover();+ const copyBtn = page.getByRole("button", { name: "复制回复" }).first();+ const forkBtn = page.getByRole("button", { name: "从这里分叉对话" }).first();+ await expect(copyBtn).toBeVisible();+ await expect(forkBtn).toBeVisible();++ // The fork action sits to the RIGHT of copy (review request).+ const [copyBox, forkBox] = await Promise.all([copyBtn.boundingBox(), forkBtn.boundingBox()]);+ expect(copyBox, "copy button rendered").not.toBeNull();+ expect(forkBox, "fork button rendered").not.toBeNull();+ expect(forkBox.x, "fork is right of copy").toBeGreaterThan(copyBox.x + copyBox.width - 1);++ // Copy stays a plain unconfirmed click: no dialog appears and the text lands on the clipboard.+ await copyBtn.click();+ await expect(page.getByRole("button", { name: "分叉", exact: true })).toHaveCount(0);+ expect(await page.evaluate(() => navigator.clipboard.readText())).toContain("Command finished");++ // Fork asks first: the click opens the confirm dialog and fires NO fork request by itself.+ await page.getByText("Command finished; the result looks as expected.").first().hover();+ await forkBtn.click();+ await expect(page.getByText("将把这段对话(截至这条回复)复制为一个新对话")).toBeVisible();+ // Cancel: dialog closes, still on the source chat, and no /fork request was made.+ await page.getByRole("button", { name: "取消" }).click();+ await expect(page.getByText("将把这段对话(截至这条回复)复制为一个新对话")).toHaveCount(0);+ expect(page.url()).toContain(sourceId);+ expect(+ apiLog.filter((e) => e.kind === "req" && /\/api\/sessions\/[^/]+\/fork$/.test(e.url)),+ "cancel fires no fork request",+ ).toHaveLength(0);++ // Confirm: the fork request fires and the app navigates to the new Session.+ await page.getByText("Command finished; the result looks as expected.").first().hover();+ await forkBtn.click();+ await page.getByRole("button", { name: "分叉", exact: true }).click();+ await page.waitForURL(+ (u) => /\/chat\/session-/.test(u.pathname) && !u.pathname.includes(sourceId),+ { timeout: 15_000 },+ );+ const forkId = decodeURIComponent(page.url().split("/chat/")[1]);+ expect(forkId).not.toBe(sourceId);+ // The fork carries the copied transcript.+ await expect(page.getByText("Command finished; the result looks as expected.")).toBeVisible();++ // Let the fork page settle (its per-session fetches all done) so the baseline below counts a+ // quiet system, and any record that appears afterwards is attributable to the delete.+ await page.waitForTimeout(2000);+ const errorsBefore = await errorRecordCount(page, projectId);++ // Delete the fork (it is the open chat — the standard try-then-discard fork flow).+ const sidebar = page.getByRole("complementary");+ const forkRow = sidebar.locator("li", { hasText: "(1)" }).first();+ await forkRow.hover();+ await forkRow.getByRole("button", { name: "对话选项" }).click();+ await page.getByRole("button", { name: "删除对话" }).click();+ const tDelete = Date.now();+ await page.getByRole("button", { name: "删除", exact: true }).click();++ // The app must land somewhere else and the fork row must be gone.+ await page.waitForURL((u) => !u.pathname.includes(forkId), { timeout: 15_000 });+ await expect(sidebar.locator("li", { hasText: "(1)" })).toHaveCount(0);+ // Generous window: a stray poll, an SSE reconnect or a late-settling effect all get time to+ // show themselves before the count below is taken.+ await page.waitForTimeout(5000);++ // THE acceptance criterion: deleting a fork adds no error record at all. Asserted first, and+ // as a count — a doomed request that got downgraded, reclassified or filtered out of the view+ // would still move this number, and it must not move.+ const errorsAfter = await errorRecordCount(page, projectId);+ expect(+ errorsAfter,+ `deleting a fork must add no server error record (before=${errorsBefore}, after=${errorsAfter})`,+ ).toBe(errorsBefore);++ // The two supporting facts, kept because they name the culprit when the count does move:+ // nothing may request the deleted id again, and nothing may 4xx at all.+ const strays = apiLog.filter(+ (e) => e.t >= tDelete && e.kind === "req" && e.m !== "DELETE" && e.url.includes(forkId),+ );+ expect(+ strays,+ `no follow-up requests for the deleted fork id: ${JSON.stringify(strays)}`,+ ).toHaveLength(0);+ const errors = apiLog.filter((e) => e.t >= tDelete && e.kind === "res" && e.status >= 400);+ expect(errors, `no error responses after fork deletion: ${JSON.stringify(errors)}`).toHaveLength(+ 0,+ );+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 7f7d3ab1..fad2509a 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -67,6 +67,8 @@ import type {SessionCategory,SessionCreateRequest,SessionCreateResponse,+ SessionForkRequest,+ SessionForkResponse,SessionPatchRequest,SessionResponse,SessionProcessesResponse,@@ -404,6 +406,12 @@ export const createSession = (projectId: string, agentId: string, body: SessionC{ method: "POST", body },);+export const forkSession = (sessionId: string, body: SessionForkRequest) =>+ apiFetch<SessionForkResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/fork`, {+ method: "POST",+ body,+ });+export const getSession = (sessionId: string) =>apiFetch<SessionResponse>(`/api/sessions/${encodeURIComponent(sessionId)}`);diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 6bdc672b..2650bd86 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -699,6 +699,11 @@ export function Sidebar({const target = deletingSession;try {await api.deleteSession(target.sessionId);+ // remove() also tombstones the id (see the store's isDeleted), which is what keeps the+ // chat page from re-fetching the Session it is still routed at during the frames before+ // the navigate() below lands. Ordering the two is deliberately NOT the mechanism: the+ // list lives in a zustand store whose updates are not subject to React's transition+ // lanes, so scheduling tricks here cannot be relied on to sequence them.remove(target.sessionId);// The session is gone, so clear its input draft too (no orphaned keys left in localStorage; keys are scoped per user, #68).if (user) clearDraft(sessionDraftKey(user.userId, target.sessionId));diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex fabbb111..5e7da319 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -42,7 +42,13 @@ import {humanizeTokens,} from "../../lib/format";import { latestConversation } from "../../lib/session-grouping";-import { approvalKey, isModelAuthDead } from "../../lib/omni/stream-model";+import {+ approvalKey,+ createStreamModel,+ finalizeHistory,+ isModelAuthDead,+ pushMessage,+} from "../../lib/omni/stream-model";import type { StreamModel } from "../../lib/omni/stream-model";import { bucketCostUsd, liveSessionElapsedMs } from "../../lib/omni/task-stats";import type { TaskStatsTracker } from "../../lib/omni/task-stats";@@ -61,6 +67,7 @@ import { EmptyState } from "../../components/ui/empty-state";import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";import { MessageStream } from "./message-stream";import type { StreamRenderContext } from "./message-stream";+import type { ForkTarget } from "./task-stats-line";import { latestTaskHasSubagent, taskStartCount } from "./agent-topology";import { ChatInput } from "./chat-input";import {@@ -269,6 +276,7 @@ export function ChatPage() {loading: sessionsLoading,reload: reloadSessions,add: addSession,+ isDeleted: isSessionDeleted,replace,setStatus,setTitle,@@ -570,6 +578,15 @@ export function ChatPage() {useEffect(() => {if (draft || !routeSessionId || sessionsLoading) return;if (sessions.some((s) => s.sessionId === routeSessionId)) return;+ // We deleted this Session ourselves: the row is gone from the list on purpose, so the+ // lookup below could only 404 (and the server would record that as an error). Deleting+ // the conversation you are looking at is the normal way to discard a Session fork, so+ // this path runs on every such delete. Treat it as an already-failed probe, which+ // releases the redirect effect below to move on to another conversation.+ if (isSessionDeleted(routeSessionId)) {+ setProbeFailedId(routeSessionId);+ return;+ }let cancelled = false;api.getSession(routeSessionId).then((res) => {@@ -582,7 +599,7 @@ export function ChatPage() {return () => {cancelled = true;};- }, [draft, routeSessionId, sessionsLoading, sessions, addSession]);+ }, [draft, routeSessionId, sessionsLoading, sessions, addSession, isSessionDeleted]);// Auto-select the most recent conversation when the route doesn't select one (newest loaded// active/schedule Session — archived rows are hidden by choice and subagent Sessions belong@@ -1297,6 +1314,44 @@ export function ChatPage() {navigate("/models");}, [navigate]);+ const onFork = useCallback(+ async (target: ForkTarget): Promise<void> => {+ if (!selected) return;+ try {+ let position = target.position;+ // Live SSE messages do not carry disk coordinates. Once the Task is idle, one history+ // read resolves the just-finished footer onto the immutable Trace position; the fork+ // request itself always sends that position, never display text or a timestamp.+ if (position === undefined) {+ const history = await api.getMessages(selected.sessionId);+ const model = createStreamModel();+ for (const message of history.messages) pushMessage(model, message);+ finalizeHistory(model);+ const match = [...model.items]+ .reverse()+ .find(+ (item) =>+ item.kind === "task_stats" &&+ item.assistantText === target.assistantText &&+ item.atMs === target.atMs &&+ item.forkPosition !== undefined,+ );+ position = match?.kind === "task_stats" ? match.forkPosition : undefined;+ }+ if (position === undefined) {+ toastError(S.chat.forkSessionFailed);+ return;+ }+ const created = await api.forkSession(selected.sessionId, { position });+ addSession(created.session);+ navigate(`/chat/${created.session.sessionId}`);+ } catch (e) {+ toastError(apiErrorText(e, { modelId: selected.modelId }));+ }+ },+ [selected, addSession, navigate],+ );+// Real-time cost for this turn: converts the Task's bucketed usage using the session Model's// (paired reference) current pricing; null if no pricing is configured.const modelPricing = models?.models.find((m) => sameModelRef(m, activeModelRef))?.pricing;@@ -1335,6 +1390,7 @@ export function ChatPage() {},workspace: selected?.workspace ?? null,statFiles,+ onFork,};// Any pending approval sitting inside a subagent (approvalKey = "originChain toolCallId";diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsxindex ddd48911..9125e2a2 100644--- a/packages/web/src/features/chat/message-item.tsx+++ b/packages/web/src/features/chat/message-item.tsx@@ -387,6 +387,10 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCoassistantText={item.assistantText}cost={item.stats ? (ctx.taskCost?.(item.stats) ?? null) : null}{...(item.atMs !== undefined ? { atMs: item.atMs } : {})}+ {...(ctx.origin.length === 0 && item.forkable && ctx.onFork+ ? { onFork: ctx.onFork }+ : {})}+ {...(item.forkPosition !== undefined ? { forkPosition: item.forkPosition } : {})}/></>);diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsxindex bbd4ab50..7e3e4d8a 100644--- a/packages/web/src/features/chat/message-stream.tsx+++ b/packages/web/src/features/chat/message-stream.tsx@@ -16,6 +16,7 @@ import { MessageItem } from "./message-item";import { WorkGroup, isWorkItem } from "./work-group";import { createStreamFollow, stickToBottom } from "./stream-follow";import type { StreamFollow } from "./stream-follow";+import type { ForkTarget } from "./task-stats-line";/** Context passed down to nested rendering (pending approvals + approval submit callback + current origin chain). */export interface StreamRenderContext {@@ -49,6 +50,8 @@ export interface StreamRenderContext {workspace?: string | null;/** Batch file-existence check (with session-level caching); the card doesn't render if this isn't wired up. */statFiles?: (paths: string[]) => Promise<ReadonlySet<string>>;+ /** Creates a new root Session through the selected completed assistant turn. */+ onFork?: (target: ForkTarget) => Promise<void>;}/** Pure list rendering (reused recursively inside subagent cards): consecutive thinking + tool-call items are aggregated into one "Reasoning & Tools" group. */diff --git a/packages/web/src/features/chat/task-stats-line.tsx b/packages/web/src/features/chat/task-stats-line.tsxindex 767b9da0..25c9f2db 100644--- a/packages/web/src/features/chat/task-stats-line.tsx+++ b/packages/web/src/features/chat/task-stats-line.tsx@@ -4,7 +4,9 @@* in real time from the current Model's pricing, hidden if no pricing is configured); all five* share the same basis (this turn's usage), each expressed uniformly as icon + value (no text* labels); the reply timestamp and a copy button sit at the end (copies this turn's assistant- * text, falling back to the stats themselves when there's no text). Below sm the row is slimmed+ * text, falling back to the stats themselves when there's no text), with the fork action to the+ * right of copy — forking asks for confirmation first (it duplicates the conversation into a new+ * Session up to this reply), while copy stays a plain immediate click. Below sm the row is slimmed* to fit the width: the TPS chip is dropped and cost/elapsed lose excess decimals (compact* formatter variants); desktop shows all five, formatted as always.* At ≥sm the whole line is invisible but takes up space by default, surfacing only on hovering@@ -24,6 +26,8 @@* footer**: it provides the reply timestamp and copy button at the end, so the assistant message* itself doesn't render a separate one (otherwise two copy buttons would pop up in the same spot).*/+import { useState } from "react";+import type { TracePosition } from "@prismshadow/penguin-server/api";import { formatTaskStats } from "../../lib/omni/task-stats";import type { TaskStats } from "../../lib/omni/task-stats";import {@@ -36,10 +40,17 @@ import {import { STAT_ICONS } from "../../lib/stat-icons";import { S } from "../../lib/strings";import { GlyphIcon } from "../../components/ui/glyph-icon";+import { ConfirmModal } from "../../components/ui/confirm-modal";import { CopyButton } from "../../components/ui/copy-button";import { useTheme } from "../../state/theme";import { useLocale } from "../../state/locale";+export interface ForkTarget {+ assistantText: string;+ atMs?: number;+ position?: TracePosition;+}+/*** Icon + value; hover explains what this item is (the icon alone doesn't convey the exact* meaning). `display` swaps the default `flex` for a responsive variant (the TPS chip is@@ -79,6 +90,8 @@ export function TaskStatsLine({assistantText,cost,atMs,+ forkPosition,+ onFork,}: {/** This turn's stats; `null` = no token_usage for this turn (reply was aborted) -> only the timestamp and copy are shown, no stat numbers drawn. */stats: TaskStats | null;@@ -88,9 +101,16 @@ export function TaskStatsLine({cost?: number | null;/** Timestamp of this turn's AI reply (this line is that reply's footer). */atMs?: number;+ forkPosition?: TracePosition;+ onFork?: (target: ForkTarget) => Promise<void>;}) {const { currency } = useTheme();const { locale } = useLocale();+ const [forking, setForking] = useState(false);+ // Fork is gated behind an explicit confirmation (review request): duplicating a whole+ // conversation is a heavier action than the neighboring copy button suggests, so a stray+ // click must not silently create a Session. Plain copy stays unconfirmed.+ const [confirmingFork, setConfirmingFork] = useState(false);// This turn's usage (not a context snapshot): input = this Task's cached + uncached input.const b = stats?.tokensByBucket;@@ -171,6 +191,60 @@ export function TaskStatsLine({label={S.chat.copyReply}className="flex h-5 w-5 shrink-0 items-center justify-center rounded transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300"/>+ {/* Fork sits to the RIGHT of copy (review request): copy is the frequent action and+ keeps its accustomed spot; the click only opens the confirmation below — the fork+ request fires on Confirm, never directly. */}+ {onFork && assistantText?.trim() && (+ <>+ <button+ type="button"+ disabled={forking}+ title={S.chat.forkSession}+ aria-label={S.chat.forkSession}+ onClick={() => setConfirmingFork(true)}+ className="flex h-5 w-5 shrink-0 items-center justify-center rounded transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 disabled:cursor-wait disabled:opacity-50 dark:hover:bg-gray-800 dark:hover:text-gray-300"+ >+ <svg+ width="13"+ height="13"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.8"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ className={forking ? "animate-pulse" : ""}+ >+ <circle cx="6" cy="5" r="2" />+ <circle cx="18" cy="7" r="2" />+ <circle cx="6" cy="19" r="2" />+ <path d="M6 7v8M8 11h4a6 6 0 0 0 6-2" />+ </svg>+ </button>+ <ConfirmModal+ open={confirmingFork}+ title={S.chat.forkSession}+ tone="primary"+ confirmLabel={S.chat.forkSessionConfirmAction}+ busy={forking}+ onClose={() => setConfirmingFork(false)}+ onConfirm={() => {+ setConfirmingFork(false);+ setForking(true);+ void onFork({+ assistantText,+ ...(atMs !== undefined ? { atMs } : {}),+ ...(forkPosition !== undefined ? { position: forkPosition } : {}),+ }).finally(() => setForking(false));+ }}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {S.chat.forkSessionConfirmBody}+ </p>+ </ConfirmModal>+ </>+ )}</div>);}diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.tsindex 5ffb715e..0259c9fa 100644--- a/packages/web/src/lib/omni/stream-model.ts+++ b/packages/web/src/lib/omni/stream-model.ts@@ -67,6 +67,7 @@ import type {StopReason,TokenUsagePayload,} from "@prismshadow/penguin-core/omnimessage";+import type { TracePosition } from "@prismshadow/penguin-server/api";import {addLlmDuration,beginCompaction,@@ -138,6 +139,8 @@ export interface AssistantTextItem {* timestamp — the same convention as Trace (which records the **completion** time).*/atMs?: number;+ /** Stable history coordinate, present after a history read (live replies resolve it on demand). */+ tracePosition?: TracePosition;}export interface ThinkingItem {@@ -329,6 +332,10 @@ export interface TaskStatsItem {* message is never rendered with its own separate footer (otherwise two copy buttons would appear in the same spot).*/atMs?: number;+ /** Final assistant record of this completed Task; used by Session fork. */+ forkPosition?: TracePosition;+ /** True only when the final assistant segment and its Request completed normally. */+ forkable?: boolean;}export type ChatItem =@@ -623,7 +630,13 @@ export function pushMessage(// message's time" up to just before a complete thinking message, or the approximated historical duration would collapse to ~0ms.return;}- handleComplete(model, msg.payload as CompleteModelPayload, msg.timestamp, nowMs);+ handleComplete(+ model,+ msg.payload as CompleteModelPayload,+ msg.timestamp,+ nowMs,+ (msg as OmniMessage & { tracePosition?: TracePosition }).tracePosition,+ );advanceLastTs(model, msg.timestamp);return;}@@ -868,7 +881,9 @@ function finalizeOpenTask(model: StreamModel): void {id: nextId(model),stats,assistantText: reply.text,+ forkable: reply.completed,...(reply.atMs !== undefined ? { atMs: reply.atMs } : {}),+ ...(reply.tracePosition !== undefined ? { forkPosition: reply.tracePosition } : {}),};// The stats row is inserted **before any trailing run of compaction banners**: compaction// is its own round, housekeeping outside this one, so it belongs after this round's ledger@@ -889,18 +904,34 @@ function finalizeOpenTask(model: StreamModel): void {* timestamp of the **last** assistant text item — the stats row is this* round's reply's footer, and this is the timestamp it shows.*/-function collectTaskAssistant(model: StreamModel): { text: string; atMs?: number } {+function collectTaskAssistant(model: StreamModel): {+ text: string;+ atMs?: number;+ tracePosition?: TracePosition;+ completed: boolean;+} {const parts: string[] = [];let atMs: number | undefined;+ let tracePosition: TracePosition | undefined;+ let completed = false;for (let i = model.items.length - 1; i >= 0; i--) {const it = model.items[i]!;if (it.kind === "task_stats") break;if (it.kind === "assistant_text" && it.text.trim()) {parts.push(it.text);- if (atMs === undefined) atMs = it.atMs; // walking backward: the first hit is the last one+ if (atMs === undefined) {+ atMs = it.atMs; // walking backward: the first hit is the last one+ tracePosition = it.tracePosition;+ completed = it.stopReason === "completed";+ }}}- return { text: parts.reverse().join("\n\n"), ...(atMs !== undefined ? { atMs } : {}) };+ return {+ text: parts.reverse().join("\n\n"),+ ...(atMs !== undefined ? { atMs } : {}),+ ...(tracePosition !== undefined ? { tracePosition } : {}),+ completed,+ };}// ---------------------------------------------------------------------------@@ -1029,6 +1060,7 @@ function handleComplete(p: CompleteModelPayload,timestamp: string,nowMs: number,+ tracePosition?: TracePosition,): void {switch (p.type) {case "text": {@@ -1096,6 +1128,7 @@ function handleComplete(target.streaming = false;const doneMs = tsOf(timestamp);if (doneMs !== undefined) target.atMs = doneMs; // the completion timestamp overrides the start placeholder+ if (tracePosition !== undefined) target.tracePosition = tracePosition;if (p.stop_reason !== undefined) target.stopReason = p.stop_reason;if (target === model.openText) model.openText = null;model.pendingText = null;@@ -1120,6 +1153,7 @@ function handleComplete(text: p.text,streaming: false,...(doneMs !== undefined ? { atMs: doneMs } : {}),+ ...(tracePosition !== undefined ? { tracePosition } : {}),};if (p.stop_reason !== undefined) item.stopReason = p.stop_reason;model.items.push(item);@@ -1720,18 +1754,26 @@ 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. */+function dedupKey(msg: OmniMessage): string {+ const { tracePosition: _tracePosition, ...envelope } = msg as OmniMessage & {+ tracePosition?: TracePosition;+ };+ return JSON.stringify(envelope);+}+/** Build a dedup index from the envelope JSON of history's **last `limit` messages**. */export function buildDedupIndex(messages: OmniMessage[], limit = 100): Set<string> {const index = new Set<string>();for (let i = Math.max(0, messages.length - limit); i < messages.length; i++) {- index.add(JSON.stringify(messages[i]));+ index.add(dedupKey(messages[i]!));}return index;}/** Determine whether a complete message/event is exactly identical to history's envelope JSON (overlap dedup). */export function isDuplicate(index: Set<string>, msg: OmniMessage): boolean {- return index.has(JSON.stringify(msg));+ return index.has(dedupKey(msg));}/**diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex fd49ae9f..fe6ab151 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1292,6 +1292,11 @@ Scenarios:approvalWaiting: "awaiting approval",copyCode: "Copy code",copyReply: "Copy reply",+ forkSession: "Fork chat from here",+ forkSessionConfirmBody:+ "This copies the conversation up to this reply into a new chat. The original chat stays unchanged.",+ forkSessionConfirmAction: "Fork",+ forkSessionFailed: "This reply could not be located. Refresh and try again.",copyMessage: "Copy message",deleteSession: "Delete chat",renameSession: "Rename chat",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 7beb76dc..8e7a41c3 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1254,6 +1254,10 @@ Benchmark:approvalWaiting: "待审批",copyCode: "复制代码",copyReply: "复制回复",+ forkSession: "从这里分叉对话",+ forkSessionConfirmBody: "将把这段对话(截至这条回复)复制为一个新对话,原对话保持不变。",+ forkSessionConfirmAction: "分叉",+ forkSessionFailed: "无法定位这条回复,请刷新后重试。",copyMessage: "复制消息",deleteSession: "删除对话",renameSession: "重命名对话",diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex d2ad949b..c7a7b19a 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -62,8 +62,15 @@ interface SessionsContextValue {loadMoreFor: (agentIds: string[], category: SessionCategory) => Promise<void>;/** Prepend to the list on success (draft materialized by the first message, or explicit creation via dialog). */add: (session: SessionInfo) => void;- /** Remove from the list in place after deletion. */+ /** Remove from the list in place after deletion (also tombstones the id — see isDeleted). */remove: (sessionId: string) => void;+ /**+ * Whether this client deleted the Session during this page's lifetime. A row missing from+ * the paged list normally means "not fetched yet", which the chat page resolves with a+ * direct lookup; for an id we deleted ourselves that lookup is guaranteed to 404, so+ * callers consult this first and skip the request entirely.+ */+ isDeleted: (sessionId: string) => boolean;/** Replace the whole entry with the PATCH result. */replace: (session: SessionInfo) => void;/** Live stream task_state → list badge. */@@ -101,6 +108,12 @@ interface SessionsStoreState {agentIds: string[];sessions: SessionInfo[];+ /**+ * Ids this client deleted during the page's lifetime (see isDeleted). Deliberately kept+ * OUTSIDE the rendered state: it must not be read as "the list changed", and nothing+ * renders from it — consumers only ask whether a specific id is in it.+ */+ deletedSessionIds: ReadonlySet<string>;/** pageKey → that pair's paging cursor; a key is present iff its first page has been fetched. */pageState: ReadonlyMap<string, PagePosition>;countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;@@ -121,6 +134,14 @@ interface SessionsStoreState {setShowCliSessions: (value: boolean) => void;}+/**+ * Cap on remembered deleted ids. Session ids are never reused, so a tombstone never expires+ * on correctness grounds — this only keeps a very long-lived tab from growing the set without+ * bound. Evicts oldest-first (Sets iterate in insertion order); the only cost of dropping a+ * tombstone is that a re-visit of that dead id would fall back to the (404-ing) lookup again.+ */+const DELETED_IDS_MAX = 500;+function createSessionsStore() {// Generation counter: invalidates any in-flight response once the Project/Agent set// changes or a reload happens.@@ -155,6 +176,7 @@ function createSessionsStore() {agentIds: [],sessions: [],+ deletedSessionIds: new Set(),pageState: new Map(),countsByAgent: new Map(),workspaceCountsByAgent: new Map(),@@ -321,7 +343,21 @@ function createSessionsStore() {gen += 1;const row = get().sessions.find((s) => s.sessionId === sessionId);if (row) adjustCount(row, sessionCategory(row), -1);- set({ sessions: get().sessions.filter((s) => s.sessionId !== sessionId) });+ // Tombstone BEFORE pruning the list, in the same update: consumers re-render on the+ // pruned list, and any of them that reacts to the row's disappearance (the chat+ // page's deep-link lookup) must already be able to see that the id is dead rather+ // than merely unfetched — otherwise it fires a request that can only 404.+ const deleted = new Set(get().deletedSessionIds);+ deleted.add(sessionId);+ while (deleted.size > DELETED_IDS_MAX) {+ const oldest = deleted.values().next();+ if (oldest.done) break;+ deleted.delete(oldest.value);+ }+ set({+ deletedSessionIds: deleted,+ sessions: get().sessions.filter((s) => s.sessionId !== sessionId),+ });},replace: (session) => {@@ -392,6 +428,9 @@ export function SessionsProvider({ children }: { children: ReactNode }) {// carry folder page state across via shared Agent ids (default_agent exists in every// Project). Also reruns on a showCliSessions flip: refetch the whole list under the// new filter.+ // deletedSessionIds is deliberately NOT reset: session ids are globally unique and never+ // reused, so a Session deleted before a Project switch is still deleted after it — and+ // re-arming its lookup would just re-create the 404 this set exists to prevent.store.setState({projectId,agentIds: agentIdsKey === "" ? [] : agentIdsKey.split(","),@@ -442,6 +481,14 @@ export function SessionsProvider({ children }: { children: ReactNode }) {[pageState, countsByAgent],);+ // Reads the store directly rather than the subscribed snapshot: this answers "is this id+ // already dead", and a caller asking that inside an effect must get the newest answer even+ // when it runs before its own re-render. Stable identity, so it never re-triggers effects.+ const isDeleted = useCallback(+ (sessionId: string) => store.getState().deletedSessionIds.has(sessionId),+ [store],+ );+const value = useMemo<SessionsContextValue>(() => {const byAgent = new Map<string, SessionInfo[]>();for (const s of state.sessions) {@@ -469,13 +516,14 @@ export function SessionsProvider({ children }: { children: ReactNode }) {loadMoreFor: state.loadMoreFor,add: state.add,remove: state.remove,+ isDeleted,replace: state.replace,setStatus: state.setStatus,setTitle: state.setTitle,showCliSessions: state.showCliSessions,setShowCliSessions: state.setShowCliSessions,};- }, [state, isLoadedFor, hasMoreFor]);+ }, [state, isLoadedFor, hasMoreFor, isDeleted]);return <SessionsContext.Provider value={value}>{children}</SessionsContext.Provider>;}diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.tsindex d30e87a8..35360fd5 100644--- a/packages/web/test/stream-model.test.ts+++ b/packages/web/test/stream-model.test.ts@@ -1042,6 +1042,19 @@ describe("Task segmentation and stats triggering", () => {expect(stats.assistantText).toBe("Creating `package.json`.\n\nInstallation finished.");});+ it("carries the final assistant Trace position into the forkable Task footer", () => {+ const m = createStreamModel();+ const reply = {+ ...at(assistantText("fork here"), "2026-07-05T00:00:03.000Z"),+ tracePosition: { fileIndex: 2, ordinal: 17 },+ };+ pushMessages(m, [at(userText("Q"), "2026-07-05T00:00:00.000Z"), reply]);+ finalizeHistory(m);+ const stats = items(m).find((item) => item.kind === "task_stats") as TaskStatsItem;+ expect(stats.forkable).toBe(true);+ expect(stats.forkPosition).toEqual({ fileIndex: 2, ordinal: 17 });+ });+it("stream end (finalizeHistory) closes the last Task; rounds without usage get no stats figures but still get a footer", () => {const m = createStreamModel();pushMessages(m, [@@ -1842,6 +1855,12 @@ describe("overlap dedup (contract §7.2)", () => {expect(isDuplicate(index, { ...m3 })).toBe(true); // matches on identical structure});+ it("history-only Trace positions do not defeat overlap dedup against the live envelope", () => {+ const live = at(assistantText("same"), "2026-07-05T00:00:01.000Z");+ const history = { ...live, tracePosition: { fileIndex: 1, ordinal: 9 } };+ expect(isDuplicate(buildDedupIndex([history]), live)).toBe(true);+ });+it("a full message hitting dedup discards the matching in-flight fragment (discardFragmentFor)", () => {const m = createStreamModel();// History already contains the full message.