diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml
index ddd6d80912..5a918c8cc1 100644
--- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml
@@ -9,8 +9,8 @@
en: ab63c8127d68d294
zh: d3f99489c96ff1d4
/agent-note-open-the-session-when-migration-is-required/decision:
- en: 32627d744a6e7410
- zh: 2836a95ee5390111
+ en: 310ff84cece51901
+ zh: a9a29e3ba30e03a8
/agent-note-open-the-session-when-migration-is-required/alternatives-considered:
en: baea781018a49252
zh: bcc452029bf229fd
diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md
index 84b30b6cb4..c452ae85ae 100644
--- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md
+++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md
@@ -18,7 +18,7 @@ Other fork callers omit that option and allow automatic migration.
The `formatStatus` returned by `stat` carries the migration library's existing classification; `header` remains the current logical format. It describes the stored format, not migration-task progress or prepared in-memory history.
-When migration is required and `subagentCatalog` is absent, Web marks the Session's row “Migration required” and keeps its history-opening actions without descendant expansion or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
+When migration is required and `subagentCatalog` is absent, Web keeps the Session row's history-opening actions without a format notice, descendant expansion, or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch.
Create/adopt, full-text search, and ordinary history opening allow automatic migration.
diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md
index 31925f7a9f..e68747a9b6 100644
--- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md
+++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md
@@ -18,7 +18,7 @@ WorkspaceBrowser 行菜单的 fork 请求携带 `allowMigration: false`,由 Ho
`stat` 返回的 `formatStatus` 携带迁移库已有的分类;`header` 仍是当前逻辑格式。它描述存储格式,不描述迁移任务进度或内存准备缓存。
-在需要迁移且缺少 `subagentCatalog` 时,Web 将该会话行标为“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
+在需要迁移且缺少 `subagentCatalog` 时,Web 保留该会话行打开历史的操作,不显示格式提示,不展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。
create/adopt、全文搜索和普通历史打开允许自动迁移。
diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml
index dba92660c8..04a78f70d3 100644
--- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml
@@ -9,8 +9,8 @@
en: cdc04139c8d69415
zh: a3fe3e78ada08d95
/agent-note-continuous-cua-hover-without-cross-call-ownership/decision:
- en: d1ea8fdc05927896
- zh: d3039bbb82bc949c
+ en: 125c860c1c568960
+ zh: 8a2ece1101358200
/agent-note-continuous-cua-hover-without-cross-call-ownership/alternatives-considered:
en: 18d917ee2e909b93
zh: 5b5ad0530f138cda
diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md
index 1cc8db5f81..2cce428cff 100644
--- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md
+++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md
@@ -10,7 +10,7 @@ Hover interactions span movement, delayed content, observation and input inside
## Decision
-An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button; disabled controls can use system-pointer movement. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before falling back to system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check.
+An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button; disabled controls can use system-pointer movement with `systemPointerHover` enabled. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before allowing opt-in system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check.
The [shared helper](2026-10-09-cua-shared-native-helper.md) serializes complete individual operations. It grants no application ownership across calls. Earlier arrival, a retained app object and Session lifetime do not establish task priority. Waiting for the model does not reserve the application. Explicit task coordination determines any required execution order.
diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md
index 2f5ef0ce36..cc2457a70a 100644
--- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md
+++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md
@@ -10,7 +10,7 @@ Status: implemented
## 决策
-显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,禁用控件可使用系统鼠标移动路径。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,再回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。
+显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,启用 `systemPointerHover` 后可通过系统鼠标悬停禁用控件。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,只有启用该配置时才回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。
[共享 helper](2026-10-09-cua-shared-native-helper.zh.md)串行执行完整的单次操作,不分配跨调用的应用所有权。先发起请求、持有 app 对象和 Session 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。
diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml
index 8259c024fb..9775baf3a4 100644
--- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml
@@ -9,8 +9,8 @@
en: f96bf1ebc0719fb0
zh: e9a1144f0e76572d
/agent-note-background-hover-and-screenshot-coordinates/decision:
- en: 6ac0b77bea25fcf7
- zh: e50fec9049926fdc
+ en: bdf4d3386521ce00
+ zh: 96db93177ad96a76
/agent-note-background-hover-and-screenshot-coordinates/alternatives-considered:
en: 5fc4beaf79761c50
zh: 4948333b0020be28
diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md
index 1091fcaf5e..c385525731 100644
--- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md
+++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md
@@ -10,7 +10,7 @@ Hover-only controls can sometimes be revealed without moving the user's pointer.
## Decision
-Native hover first uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Entering its revealed descendants preserves the parent UI; leaving restores it. An unavailable route falls back to the real system pointer. An AX action failure propagates because received effects may be uncertain. The result records the route and whether the system pointer moved. System movement requires the selected foreground app and AppKit's mouse hit test, which excludes input-transparent overlays. No route grants [cross-call ownership](2026-10-13-cua-continuous-hover.md).
+Native hover first uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Entering its revealed descendants preserves the parent UI; leaving restores it. An unavailable route returns `HOVER_UNAVAILABLE` by default. Enabling `systemPointerHover` permits the real system pointer fallback. An AX action failure propagates because received effects may be uncertain. The result records the route and whether the system pointer moved. System movement requires the selected foreground app and AppKit's mouse hit test, which excludes input-transparent overlays. No route grants [cross-call ownership](2026-10-13-cua-continuous-hover.md).
Model-facing coordinate input defaults to pixels in the returned screenshot. `relative: true` accepts integer thousandths from 0 to 999 for `click`, `mouseMove`, `scroll` and `drag`; it does not apply to opaque element IDs. The Host owns the mapping to native window points. An application-wide observation refreshes its inventory; a scoped observation preserves other windows' image mappings. Window resizing invalidates the old image, while movement preserves local coordinates. Relative endpoints remain inside the window and do not depend on screenshot resolution.
diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md
index 2344d61c95..0d3db32400 100644
--- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md
+++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md
@@ -10,7 +10,7 @@ Status: implemented
## 决策
-原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时回退到真实系统鼠标。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。
+原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时默认返回 `HOVER_UNAVAILABLE`。启用 `systemPointerHover` 后才允许移动系统光标。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。
面向模型的坐标默认使用返回截图中的像素。`click`、`mouseMove`、`scroll` 和 `drag` 传入 `relative: true` 时接受 0~999 的千分比整数,仅用于坐标目标。Host 负责换算原生窗口 point。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。
diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml
index f3a0d8f1d3..3e32b6eb92 100644
--- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml
+++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml
@@ -15,5 +15,5 @@
en: 32c970ae153e0f6c
zh: 8431be0a10ffed15
/agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences:
- en: 5c6ec60b77f1bff0
- zh: e1ae568ef3501b7b
+ en: c4b12ca80865e670
+ zh: 396426fad0105eaa
diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md
index 609e5bf901..cce266e52b 100644
--- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md
+++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md
@@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps
Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first.
-Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, because the API never sends the opposite event. Keyboard modifier names are provider-defined, so the same string may have different support across providers.
+Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, during execution. macOS releases that run’s remaining keys when the program ends or the user pauses it. Keyboard modifier names are provider-defined, so the same string may have different support across providers.
Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock.
diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md
index 081f02986e..5135dc9be8 100644
--- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md
+++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md
@@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅
元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。
-键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,因为 API 从不发送相反事件。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
+键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。
Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。
diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml
index ca48f70356..5736f23e73 100644
--- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml
+++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml
@@ -18,11 +18,11 @@
en: 16c4ee08b65ead23
zh: df80d6e49982615b
/agent-note-parallel-tool-call-execution-by-per-call-safety/configuration-and-declarations:
- en: e112957ed8a48039
- zh: 37d63f9ea4968fb2
+ en: 082e5a02b092b656
+ zh: ca674a08323d8cc1
/agent-note-parallel-tool-call-execution-by-per-call-safety/verification:
- en: 224b6838130c113f
- zh: f3d7eb68ab5932fb
+ en: 20d0e1724ebc1247
+ zh: baa89694cea135c8
/agent-note-parallel-tool-call-execution-by-per-call-safety/alternatives-considered:
en: 17becc038bb7df7c
zh: 673d9a9bdfa39edf
diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md
index 4eb497b1ff..03e35dba6b 100644
--- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md
+++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md
@@ -60,13 +60,13 @@ Any shared state touched during execution must be concurrency-safe. This include
`maxParallelToolCalls` is a positive AgentLoop deployment cap shared by every agent the factory creates. It defaults to `10`; `1` preserves serial execution. Exact fields and defaults live in the generated [configuration catalog](../../../../docs/config-catalog.md).
-The shipped declarations are conservative. Web search, web fetch, filesystem read, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Filesystem writes and edits, bash tools, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive.
+The shipped declarations are conservative. Web search, web fetch, filesystem read, glob, grep, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Read-only queries also opt in: the background job list, the subagent tree and model listings, scheduled task and Team task reads, Cordis Inspect queries, and MCP resource reads. Filesystem writes and edits, bash tools, `job_output` because it consumes a read cursor, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive. Read-only `lsp` stays exclusive because its language-server pool already serializes queries per workspace, so overlap would gain nothing, and the goal tools stay exclusive under the [goal tools Agent Note](2026-07-19-model-facing-goal-tools.md).
-Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`.
+Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `working-directory/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session.
## Verification
-Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration.
+Unit coverage pins fail-closed classification, typed argument validation, grouping, barriers, rejection of unstarted calls after registry replacement, the rolling cap, distinct execution objects, middleware order, ordered results and context, abort draining, and scheduler-failure quiescence. First-party tests pin each parallel declaration, and the working-directory service tests pin per-Session serialization of concurrent directory changes.
Snapshot coverage pins the visible multi-call transcript: pending calls may overlap while completed results remain model-ordered. PTC mode coverage pins its serial boundary. No provider-backed e2e is required because scheduling is deterministic loop behavior.
diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md
index dbfa7cd684..38db00b5ff 100644
--- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md
+++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md
@@ -60,13 +60,13 @@ Status: implemented
`maxParallelToolCalls` 是 AgentLoop 的正整数部署上限,由工厂创建的所有 agent(智能体)共享。默认值为 `10`;`1` 保持串行执行。字段和默认值的精确定义见生成的[配置目录](../../../../docs/config-catalog.zh.md)。
-当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。文件系统写入与编辑、bash 工具、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。
+当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、glob、grep、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。只读查询也选择并行:后台任务列表、subagent 树与模型列表、定时任务与 Team 任务读取、Cordis Inspect 查询以及 MCP 资源读取。文件系统写入与编辑、bash 工具、`job_output`(因为它会消费读取游标)、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。只读的 `lsp` 仍按独占方式执行,因为其语言服务器池已按工作区串行化查询,重叠执行不会带来收益;goal 工具依照 [goal 工具 Agent Note](2026-07-19-model-facing-goal-tools.zh.md) 仍按独占方式执行。
-文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。
+文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `working-directory/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。
## 验证
-单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明。
+单元测试固定了按安全侧原则进行的分类、类型化参数验证、分组、屏障、注册表替换后拒绝尚未开始的调用、滚动上限、独立执行对象、中间件顺序、有序结果与上下文、中止排空,以及调度器故障后的完全停稳。第一方测试固定了每项并行声明,工作目录服务测试固定了按会话串行化并发目录变更。
快照测试固定了可见的多调用 transcript(文本记录):待处理调用可以重叠执行,已完成结果仍按模型顺序排列。PTC mode 测试固定了其串行边界。此调度属于确定性循环行为,因此无需依赖提供方的 e2e 测试。
diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml
index b5373db47c..201593ebbe 100644
--- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml
+++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.i18n.yaml
@@ -9,8 +9,8 @@
en: 12ab239ab0c58e31
zh: c32874442ce66041
/agent-note-explicit-worktree-creation/decision:
- en: 92782d5964d1a021
- zh: 37b385836e9ae2b9
+ en: 571a2d4c5352170b
+ zh: aeb12b849c5f8d31
/agent-note-explicit-worktree-creation/alternatives-considered:
en: 72d42e892a37b94c
zh: 92a14a51c6a89c53
diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md
index 33cabb9b8e..9facc68061 100644
--- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md
+++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.md
@@ -18,7 +18,7 @@ Git and directory creation use the mounted subprocess and sandbox providers with
Leaving uses the shared working-directory operation and retains the checkout and branch. Failed setup can retain partial artifacts and reports their location. The service does not own a branch merge policy or a task association database.
-The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees.
+The service records each creation as a `plugin:worktree/created` record and owns archive-triggered cleanup of those checkouts, as the job and Agent registries own their archive-admission families. A Session's inherited prefix decides whether it created a checkout or merely refers to one; cwd alone never grants cleanup ownership. Admission registers the attempt inside the Workspace write queue and returns; inspection reads cold Sessions through the projection cache or their log, without starting an Agent, and runs afterwards. Only a clean, unreferenced checkout is removed, without force and without deleting its branch; tracked changes and untracked files retain it, ignored files do not, matching Git's own non-force refusal. Inspection trusts `git status` alone, as peer agent products do: edits to skip-worktree or assume-unchanged files are discarded with the checkout, because sparse checkout sets skip-worktree on every file outside its cone and inspecting those bits would retain every sparse checkout. A checkout whose administrative directory holds submodule repositories is retained; a committed embedded repository is not inspected, and Git's refusal of that removal settles the attempt as failed. Processes and terminals are not consulted. A volatile `retainOnArchive` setting, read at admission, turns the cleanup off without unmounting the service; the Forge client edits it on the bundle's worktree row of the Plugins page because the service package has no Client half. Unarchiving cancels an unadmitted removal and waits for an admitted one, and directory entry into a checkout being removed waits for that removal. No startup sweep deletes previously archived worktrees.
## Alternatives considered
diff --git a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md
index a3c7313ddd..bc9fc0670c 100644
--- a/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md
+++ b/.agents/notes/implemented/feature/2026-09-13-explicit-worktree-creation.zh.md
@@ -18,7 +18,7 @@ Git 与目录创建使用挂载的子进程及沙箱提供方,不扩大调用
离开使用共享工作目录操作,保留检出目录与分支。初始化失败可能留下部分产物,并报告其位置。该服务不拥有分支合并策略或任务关联数据库。
-服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。
+服务把每次创建记录为 `plugin:worktree/created` Session 事件,并像 job 与 Agent 注册表各自拥有归档准入家族那样,拥有这些检出目录的归档触发清理。Session 的继承前缀决定它创建了某个检出目录还是仅引用它;当前工作目录本身不授予清理所有权。准入在 Workspace 写队列内登记尝试并返回;检查通过投影缓存或日志读取冷 Session,不启动 Agent,并在之后执行。只删除干净且无人引用的检出目录,不带 force 也不删除分支;跟踪文件改动与未跟踪文件保留目录,被忽略的文件不保留,与 Git 自身不带 force 时的拒绝条件一致。检查与同类 Agent 产品一样只依据 `git status`:skip-worktree 或 assume-unchanged 文件的改动随检出目录一起丢弃,因为 sparse checkout 会给稀疏范围之外的每个文件设置 skip-worktree,检查这些标记会保留每个稀疏检出目录。管理目录中含子模块仓库的检出目录会保留;已提交的内嵌仓库不在检查范围内,Git 拒绝这类删除,本次尝试以失败结束。不咨询进程与终端。volatile 的 `retainOnArchive` 设置在准入时读取,无需卸载服务即可关闭清理;由于服务包没有 Client 半部,Forge 客户端在插件页该套件的 worktree 行上编辑它。取消归档会取消尚未获准的删除并等待已获准的删除,进入正在删除的检出目录会等待该删除结束。不在启动时扫描删除此前已归档的工作树。
## Alternatives considered
diff --git a/.gitattributes b/.gitattributes
index 2bead994d2..f6b77ce2c7 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -16,3 +16,12 @@ docs/persistence-changes/historical-formats/*.schema.json linguist-generated=tru
# Unified patch blank context lines require their leading space.
patches/*.patch whitespace=-blank-at-eol
+
+# Review layers of the forge changes view (dsh-review-layer), for this repository's own conventions:
+# plugin locale dictionaries and the session snapshot tree hide with test files, generated bilingual
+# pairing records join them, and a package's types-only module is part of its interface.
+packages/*/*/locale/*.json dsh-review-layer=test
+locales.ts dsh-review-layer=test
+snapshots/** dsh-review-layer=test
+*.i18n.yaml dsh-review-layer=test
+packages/*/*/src/types.ts dsh-review-layer=interface
diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl
index 311240e645..a7352b5dd7 100644
--- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl
+++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl
@@ -17,8 +17,8 @@
{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
-{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}}
-{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"}
+{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}}
+{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
{"type":"session/title","data":{"title":"Tighten this session to read-only.","messageSeqs":[3],"source":{"kind":"fallback"}}}
{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"delegate-write","name":"subagent","args":["{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts
index 14be185017..ac293e8017 100644
--- a/apps/cli/tests/web-agent-presets.e2e.ts
+++ b/apps/cli/tests/web-agent-presets.e2e.ts
@@ -289,6 +289,55 @@ describe('the shipped Web composition', () => {
expect(ctx.agentPresets.defaultId).toBe('standard')
})
+ it.each(['standard', 'cordis', 'ptc'] as const)('keeps interruption disabled in %s with Team mode off or on', async (preset) => {
+ const handle = await ctx.agents.create({
+ sessionId: SessionId(`preset-interrupt-${preset}`),
+ setup: agentCtx => ctx.agentPresets.mount(agentCtx, preset).then(() => undefined),
+ })
+ try {
+ for (const enabled of [false, true]) {
+ await ctx.agentTeams.setEnabled(handle.agent, enabled)
+ const names = toolNames(ctx, handle.agent)
+ expect(names).not.toContain('interrupt_agent')
+ expect(names).toEqual(expect.arrayContaining(['send_message', 'list_agents', 'wait_agent']))
+ }
+ } finally {
+ await handle.dispose()
+ }
+ })
+
+ it.each(['standard', 'cordis', 'ptc'] as const)('restores interruption through a complete %s declaration override', async (preset) => {
+ const root = await mkdtemp(join(tmpdir(), 'dsh-preset-interrupt-'))
+ onTestFinished(() => rm(root, { recursive: true, force: true }))
+ const declaration = composeEntries([webPatches('interrupt migration')])
+ .find(row => row.id === `preset-${preset}`)!.config as {
+ id: string
+ order: number
+ plugins: import('@deepseek-ai/cordis-plugin-loader').EntryOptions[]
+ }
+ const configured = await bootWeb(root, [{
+ id: `preset-${preset}`,
+ config: {
+ ...declaration,
+ plugins: composeEntries([[{ insert: declaration.plugins }, {
+ id: 'tool-subagent-control', config: { interrupt: true },
+ }]]),
+ },
+ }])
+ try {
+ const handle = await configured.agents.create({
+ sessionId: SessionId(`preset-interrupt-enabled-${preset}`),
+ setup: agentCtx => configured.agentPresets.mount(agentCtx, preset).then(() => undefined),
+ })
+ try {
+ expect(toolNames(configured)).not.toContain('interrupt_agent')
+ expect(toolNames(configured, handle.agent)).toEqual(expect.arrayContaining([
+ 'interrupt_agent', 'send_message', 'list_agents', 'wait_agent',
+ ]))
+ } finally { await handle.dispose() }
+ } finally { await configured.fiber.dispose() }
+ })
+
it('composes the full agent from `standard`', async () => {
const handle = await ctx.agents.create({
sessionId: SessionId('preset-standard'),
@@ -302,7 +351,7 @@ describe('the shipped Web composition', () => {
// depend on ripgrep being present on the machine.
expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
- 'get_goal', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image',
+ 'get_goal', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image',
'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view',
'send_message', 'skill',
'subagent', 'subagent_fork', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'todo_write', 'update_goal', 'wait_agent', 'web_fetch', 'web_search',
diff --git a/apps/web/tests/expected/forge-panel/changes-view.expected.md b/apps/web/tests/expected/forge-panel/changes-view.expected.md
index b4f0445c07..1e3111ba0c 100644
--- a/apps/web/tests/expected/forge-panel/changes-view.expected.md
+++ b/apps/web/tests/expected/forge-panel/changes-view.expected.md
@@ -1,8 +1,12 @@
- img "变更请求状态:需要处理"
- text: "Add the pull request panel #7"
+- button "查看的提交:全部提交": 全部提交
- button "提交评审"
- button "在浏览器中打开"
- button "全部 2 个文件"
+- button "分层透镜:全部": 全部
+- switch "隐藏测试文件"
+- progressbar "已审阅的文件": 已审阅 0 / 2
- text: +4 −2
- button "刷新变更"
- button "全部折叠"
@@ -11,6 +15,7 @@
- region "全部 2 个文件":
- button "收起 panel.md" [expanded]
- text: docs/panel.md 新文件 +2 −0
+ - checkbox "将 panel.md 标记为已审阅"
- button "panel.md 的更多操作"
- button "选择第 R1 行": "1"
- text: "+ # Panel"
@@ -18,6 +23,7 @@
- text: + Shows the change requests of a Session.
- button "收起 panel.ts" [expanded]
- text: src/panel.ts +2 −2
+ - checkbox "将 panel.ts 标记为已审阅"
- button "panel.ts 的更多操作"
- button "选择第 L1 行": "1"
- text: export const n1 = 1
diff --git a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md
index 72d7382c18..e7f09431a2 100644
--- a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md
+++ b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md
@@ -1,8 +1,16 @@
- img "变更请求状态:需要处理"
- text: "Add the pull request panel #7"
+- button "查看的提交:全部提交": 全部提交
- button "提交评审"
- button "在浏览器中打开"
+- radiogroup "分层透镜":
+ - radio "全部 2" [checked]
+ - radio "接口 0"
+ - radio "实现 2"
+ - radio "测试 0"
- button "全部 2 个文件"
+- switch "隐藏测试文件"
+- progressbar "已审阅的文件": 已审阅 0 / 2
- text: +4 −2
- button "刷新变更"
- button "全部折叠"
@@ -12,6 +20,7 @@
- region "全部 2 个文件":
- button "收起 panel.md" [expanded]
- text: docs/panel.md 新文件 +2 −0
+ - checkbox "将 panel.md 标记为已审阅"
- button "panel.md 的更多操作"
- button "选择第 R1 行": "1"
- text: "+ # Panel"
@@ -19,6 +28,7 @@
- text: + Shows the change requests of a Session.
- button "收起 panel.ts" [expanded]
- text: src/panel.ts +2 −2
+ - checkbox "将 panel.ts 标记为已审阅"
- button "panel.ts 的更多操作"
- button "选择第 L1 行": "1"
- text: export const n1 = 1
diff --git a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md
index 114cf607bf..d5e6cce057 100644
--- a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md
+++ b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md
@@ -1,6 +1,7 @@
- text: main
- button "基准分支:origin/main": origin/main
- text: 包含未提交的修改
+- button "查看的提交:全部提交": 全部提交
- button "创建变更请求"
- button "分支"
- button "全部 0 个文件" [disabled]
diff --git a/apps/web/tests/expected/forge-panel/review-layers.expected.md b/apps/web/tests/expected/forge-panel/review-layers.expected.md
new file mode 100644
index 0000000000..e160dbbd40
--- /dev/null
+++ b/apps/web/tests/expected/forge-panel/review-layers.expected.md
@@ -0,0 +1,42 @@
+- img "变更请求状态:需要处理"
+- text: "Add the pull request panel #7"
+- button "查看的提交:全部提交": 全部提交
+- button "提交评审"
+- button "在浏览器中打开"
+- radiogroup "分层透镜":
+ - radio "全部 3" [checked]
+ - radio "接口 1"
+ - radio "实现 2"
+ - radio "测试" [disabled]
+- button "全部 3 个文件"
+- switch "隐藏测试文件" [checked]
+- progressbar "已审阅的文件": 已审阅 2 / 3
+- text: +5 −2
+- button "刷新变更"
+- button "全部折叠"
+- button "左右对比" [pressed]
+- button "自动换行" [pressed]
+- button "将文件树移到右侧" [expanded]
+- region "全部 3 个文件":
+ - button "展开 panel.md"
+ - text: docs/panel.md 新文件 +2 −0
+ - checkbox "将 panel.md 标记为已审阅" [checked]
+ - button "panel.md 的更多操作"
+ - button "展开 panel.ts"
+ - text: src/panel.ts +2 −2
+ - checkbox "将 panel.ts 标记为已审阅" [checked]
+ - button "panel.ts 的更多操作"
+ - button "收起 package.json" [expanded]
+ - text: package.json 新文件 +1 −0
+ - checkbox "将 package.json 标记为已审阅"
+ - button "package.json 的更多操作"
+ - button "选择第 R1 行": "1"
+ - text: "+ { \"name\": \"demo\" }"
+- separator "调整文件树宽度"
+- navigation "全部 3 个文件":
+ - textbox "筛选文件…"
+ - button "docs" [expanded]
+ - button "docs/panel.md": panel.md +2 −0
+ - button "src" [expanded]
+ - button "src/panel.ts": panel.ts +2 −2
+ - button "package.json": package.json +1 −0
diff --git a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md
index b60114ef0f..b86fcda5f5 100644
--- a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md
+++ b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md
@@ -1,13 +1,13 @@
# Before opening the child
- tree "Subagent sessions":
- - treeitem "historical researcher migration-catalog-child · Migration required · not running" [level=1]:
- - text: historical researcher migration-catalog-child Migration required
+ - treeitem "historical researcher migration-catalog-child · continuable · not running" [level=1]:
+ - text: historical researcher migration-catalog-child
- button "Open historical researcher in sidebar"
# After opening the child
- tree "Subagent sessions":
- - treeitem "historical editor migration-catalog-grandchild · Migration required · not running" [level=1]:
- - text: historical editor migration-catalog-grandchild Migration required
+ - treeitem "historical editor migration-catalog-grandchild · continuable · not running" [level=1]:
+ - text: historical editor migration-catalog-grandchild
- button "Open historical editor in sidebar"
diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts
index bb1ea51c5a..f05b31e50d 100644
--- a/apps/web/tests/forge-panel.e2e.ts
+++ b/apps/web/tests/forge-panel.e2e.ts
@@ -44,11 +44,13 @@ const run = promisify(execFile)
* required review, and pull request 9, an approved draft whose checks passed.
* `gh pr ready 9` and the REST merge of pull request 9 change what later
* queries report, through `state.json`, which can also move the head of pull
- * request 9. The compare API between a pull request's recorded base and its
- * head prints `pr-N.diff`, or, when `pr-N.refused` exists, fails with that JSON
- * error body and the matching diagnostic as GitHub's HTTP 406 refusal. The raw
- * contents API serves `contents.json`, keyed by `path@commit`. Every invocation
- * is appended to `calls.jsonl`.
+ * request 9. The compare API serves `compare.json`, keyed by `base...head`, and
+ * otherwise, between a pull request's recorded base and its head, prints
+ * `pr-N.diff`, or, when `pr-N.refused` exists, fails with that JSON error body
+ * and the matching diagnostic as GitHub's HTTP 406 refusal. The raw contents API
+ * serves `contents.json`, keyed by `path@commit`, and the commit listing of pull
+ * request 7 serves `commits.json`, oldest first. Every invocation is appended to
+ * `calls.jsonl`.
*/
const GH = `#!/usr/bin/env node
import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
@@ -93,6 +95,11 @@ const BASE = 'e'.repeat(40)
const heads = () => ({ 7: 'a'.repeat(40), 9: state.head ?? 'b'.repeat(40) })
if (args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')) {
const [, range] = args.at(-1).split('/compare/')
+ const chosen = existsSync(join(here, 'compare.json')) ? JSON.parse(readFileSync(join(here, 'compare.json'), 'utf8'))[range] : undefined
+ if (chosen !== undefined) {
+ process.stdout.write(chosen)
+ process.exit(0)
+ }
const [base, head] = range.split('...')
const number = Object.entries(heads()).find(([, oid]) => oid === head)?.[0]
if (base !== BASE || number === undefined) {
@@ -153,6 +160,17 @@ if (args[0] === 'api' && args[1] === 'graphql') {
} } } }] },
},
}
+ if (query.includes('commits(first: $first')) {
+ const commits = existsSync(join(here, 'commits.json')) ? JSON.parse(readFileSync(join(here, 'commits.json'), 'utf8')) : []
+ process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: 'a'.repeat(40), commits: {
+ totalCount: commits.length, pageInfo: { hasNextPage: false, endCursor: null },
+ nodes: commits.map(commit => ({ commit: {
+ oid: commit.sha, messageHeadline: commit.title, authoredDate: '2026-10-08T00:00:00Z',
+ author: { name: 'Octo', user: { login: 'octo' } }, parents: { nodes: [{ oid: commit.parent }] },
+ } })),
+ } } } } }))
+ process.exit(0)
+ }
if (query.includes('pullRequest(number: $number)')) {
const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length))
process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid, baseRefOid: BASE } } } }))
@@ -224,6 +242,53 @@ const PR7_DIFF = [
'',
].join('\n')
+/** A patch section that adds `lines` as the new file `path`. */
+function addedSection(path: string, lines: readonly string[]): string[] {
+ return [`diff --git a/${path} b/${path}`, 'new file mode 100644', 'index 0000000..4444444', '--- /dev/null', `+++ b/${path}`,
+ `@@ -0,0 +1,${lines.length} @@`, ...lines.map(line => `+${line}`)]
+}
+
+/** Commits of pull request 7 in the review fixture, oldest first; the last is its head. */
+const REVIEW_COMMITS = [
+ { sha: '1'.repeat(40), parent: 'f'.repeat(40), title: 'Add the pull request panel' },
+ { sha: '2'.repeat(40), parent: '1'.repeat(40), title: 'Test the panel and translate it' },
+ { sha: HEAD7, parent: '2'.repeat(40), title: 'Publish the panel schema' },
+] as const
+
+/** New files of each review fixture commit after the first, which changes `src/panel.ts` and adds `docs/panel.md`. */
+const REVIEW_SECTIONS = {
+ test: [
+ ...addedSection('src/panel.spec.ts', ['it(\'shows the panel\', () => {})']),
+ ...addedSection('locale/zh.json', ['{ "title": "面板" }']),
+ ],
+ schema: [
+ ...addedSection('package.json', ['{ "name": "demo" }']),
+ ...addedSection('docs/schema.json', ['{ "type": "object" }']),
+ ],
+}
+
+/**
+ * Pull request 7 with review layers: `src/panel.ts` and `docs/panel.md` are implementation, `package.json` is
+ * interface, and the spec, the locale dictionary, which `.gitattributes` places in the test layer, and
+ * `docs/schema.json`, which it marks generated, are tests.
+ */
+const REVIEW_DIFF = [PR7_DIFF.trimEnd(), ...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n')
+
+/** Write the review fixture of pull request 7: its patch, commits, commit ranges, and root `.gitattributes`. */
+async function writeReviewFixture(root: string): Promise {
+ await writeFile(join(root, 'pr-7.diff'), REVIEW_DIFF)
+ await writeFile(join(root, 'commits.json'), JSON.stringify(REVIEW_COMMITS))
+ await writeFile(join(root, 'compare.json'), JSON.stringify({
+ [`${'1'.repeat(40)}...${'2'.repeat(40)}`]: [...REVIEW_SECTIONS.test, ''].join('\n'),
+ [`${'1'.repeat(40)}...${HEAD7}`]: [...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n'),
+ }))
+ const contents = JSON.parse(await readFile(join(root, 'contents.json'), 'utf8')) as Record
+ for (const commit of ['2'.repeat(40), HEAD7]) {
+ contents[`.gitattributes@${commit}`] = 'docs/schema.json linguist-generated\nlocale/*.json dsh-review-layer=test\n'
+ }
+ await writeFile(join(root, 'contents.json'), JSON.stringify(contents))
+}
+
async function git(cwd: string, ...args: string[]): Promise {
const { stdout } = await run('git', args, { cwd, env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } })
return stdout.trim()
@@ -482,10 +547,14 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi
await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'),
await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE)
- expect(events.flatMap((event) => {
- const record = pluginRecordOf(event)
- return record?.type === 'plugin:forge-session/binding' ? [record.data] : []
- })).toEqual([{ action: 'reference', url: PULL }])
+ await expect.poll(async () => {
+ await scaffold.ctx.sessionPersistence.flush()
+ const boundEvents = await readPersistedEvents(scaffold, sessionId)
+ return boundEvents.flatMap((event) => {
+ const record = pluginRecordOf(event)
+ return record?.type === 'plugin:forge-session/binding' ? [record.data] : []
+ })
+ }).toEqual([{ action: 'reference', url: PULL }])
const calls = (await readFile(join(project, '.fixture-bin', 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url'])
expect(tripwire.pageErrors).toEqual([])
@@ -1646,3 +1715,184 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i
await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor()
expect(tripwire.pageErrors).toEqual([])
})
+
+/** Open the change request view of pull request 7 in full screen, its tree on the left. */
+async function openReview(page: Page, scaffold: WebScaffold): Promise<{ readonly view: ReturnType; readonly sessionId: SessionId }> {
+ const { settled } = await sendPrompt(page, scaffold)
+ const sessionId = await settled
+ const session = scaffold.ctx.sessions.get(sessionId)
+ if (session === undefined) throw new Error('Session must stay loaded')
+ scaffold.ctx.forgeSession.track(session, PULL)
+ await page.locator('[data-forge-header]').click()
+ await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click()
+ await page.getByRole('button', { name: '全屏', exact: true }).click()
+ const view = page.locator('[data-forge-changes="change"]')
+ await view.locator('[data-forge-diff-file="src/panel.ts"]').waitFor({ timeout: 20_000 })
+ return { view, sessionId }
+}
+
+/** Paths of the diff sections a changes view shows, in order. */
+async function shownPaths(view: ReturnType): Promise<(string | null)[]> {
+ return await view.locator('[data-forge-diff-file]').evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file')))
+}
+
+it.skipIf(MODE === 'record')('reviews a change request by layer, hides test files, marks files viewed, and views chosen commits', async () => {
+ const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-layers')
+ await writeReviewFixture(root)
+ const { view } = await openReview(page, scaffold)
+ const lens = view.getByRole('radiogroup', { name: '分层透镜', exact: true })
+ const tree = view.getByRole('navigation')
+ await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部6', '接口1', '实现2', '测试3'])
+ // The lens spans the file tree with the filter field's insets, and its divider continues the tree's border.
+ const [lensBox, fieldBox, cellBox, treeBox] = await Promise.all([
+ lens.boundingBox(), tree.locator('input').locator('xpath=..').boundingBox(), lens.locator('xpath=..').boundingBox(), tree.locator('xpath=..').boundingBox(),
+ ])
+ if (lensBox === null || fieldBox === null || cellBox === null || treeBox === null) throw new Error('Lens and tree must be visible')
+ expect([lensBox.x, lensBox.x + lensBox.width]).toEqual([fieldBox.x, fieldBox.x + fieldBox.width])
+ expect(cellBox.x + cellBox.width).toBe(treeBox.x + treeBox.width)
+
+ await lens.getByRole('radio', { name: /^接口/ }).click()
+ await expect.poll(() => shownPaths(view)).toEqual(['package.json'])
+ await lens.getByRole('radio', { name: /^测试/ }).click()
+ await expect.poll(() => shownPaths(view)).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts'])
+ await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click()
+ await expect.poll(() => shownPaths(view)).toEqual(['docs/panel.md', 'src/panel.ts', 'package.json'])
+ expect(await tree.getByRole('button', { name: 'src/panel.spec.ts', exact: true }).count()).toBe(0)
+ expect(await lens.getByRole('radio', { name: /^测试/ }).isDisabled()).toBe(true)
+
+ const progress = view.getByRole('progressbar', { name: '已审阅的文件', exact: true })
+ await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 0 / 3')
+ const docs = view.locator('[data-forge-diff-file="docs/panel.md"]')
+ await docs.getByRole('checkbox', { name: '将 panel.md 标记为已审阅', exact: true }).check()
+ await expect.poll(() => docs.getAttribute('data-expanded')).toBe(null)
+ await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 1 / 3')
+ const panel = view.locator('[data-forge-diff-file="src/panel.ts"]')
+ await panel.getByText('export const n2 = \'two\'', { exact: true }).first().click()
+ await page.keyboard.press('v')
+ await expect.poll(() => panel.getAttribute('data-viewed')).toBe('viewed')
+ await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 2 / 3')
+ await compareOrRefreshGolden(join(EXPECTED, 'review-layers.expected.md'),
+ await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE)
+
+ await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click()
+ const commits = view.getByRole('button', { name: '查看的提交:全部提交', exact: true })
+ await commits.click()
+ const menu = page.locator('[data-forge-commit-menu]')
+ await expect.poll(() => menu.getByRole('menuitem').evaluateAll(rows => rows.map(row => row.querySelector('[data-forge-commit]')?.getAttribute('data-forge-commit') ?? 'all')))
+ .toEqual(['all', '1'.repeat(40), '2'.repeat(40), HEAD7])
+ await menu.locator(`[data-forge-commit="${'2'.repeat(40)}"]`).click()
+ await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['locale/zh.json', 'src/panel.spec.ts'])
+ expect(await view.getByRole('button', { name: '提交评审', exact: true }).isDisabled()).toBe(true)
+ await view.getByRole('button', { name: '查看的提交:2222222', exact: true }).click()
+ await page.locator(`[data-forge-commit="${HEAD7}"]`).click({ modifiers: ['Shift'] })
+ await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).waitFor()
+ await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts', 'package.json'])
+ await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部4', '接口1', '实现0', '测试3'])
+ const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[])
+ // The whole pull request is read from its recorded base; chosen commits are read from the first one's parent.
+ expect(calls.filter(args => args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')).map(args => args.at(-1))
+ .filter(path => path?.includes(`/compare/${'e'.repeat(40)}...`) === false)).toEqual([
+ `repos/octo/demo/compare/${'1'.repeat(40)}...${'2'.repeat(40)}`, `repos/octo/demo/compare/${'1'.repeat(40)}...${HEAD7}`,
+ ])
+ await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).click()
+ await page.locator('[data-forge-commit-menu]').getByRole('menuitem', { name: /^全部提交/ }).click()
+ await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toHaveLength(6)
+ await expect.poll(() => docs.getAttribute('data-viewed')).toBe('viewed')
+ expect(tripwire.pageErrors).toEqual([])
+})
+
+it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a mark when the file changes again, and views branch commits', async () => {
+ const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-review-local', 'normal', { branch: 'feat' })
+ await git(project, 'update-ref', 'refs/remotes/origin/main', 'main')
+ await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main')
+ await mkdir(join(project, 'src'))
+ for (const [path, text, message] of [
+ ['src/app.ts', 'export const app = 1\n', 'Add the app'],
+ ['src/app.spec.ts', 'it(\'runs\', () => {})\n', 'Test the app'],
+ ] as const) {
+ await writeFile(join(project, path), text)
+ await git(project, 'add', path)
+ await git(project, 'commit', '--quiet', '-m', message)
+ }
+ await writeFile(join(project, 'notes.md'), 'note\n')
+ const { settled } = await sendPrompt(page, scaffold)
+ await settled
+ await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click()
+ await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click()
+ await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
+ const card = page.locator('[data-forge-local]')
+ await card.getByRole('button', { name: /^查看本会话的变更:3 个文件/ }).click({ timeout: 20_000 })
+ const local = page.locator('[data-forge-changes="local"]')
+ const app = local.locator('[data-forge-diff-file="src/app.ts"]')
+ await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).check({ timeout: 20_000 })
+ await expect.poll(() => app.getAttribute('data-expanded')).toBe(null)
+
+ await page.reload()
+ await page.locator('[data-forge-changes="local"] [data-forge-diff-file="src/app.ts"]').waitFor({ timeout: 20_000 })
+ await expect.poll(() => app.getAttribute('data-viewed')).toBe('viewed')
+ expect(await app.getAttribute('data-expanded')).toBe(null)
+ await writeFile(join(project, 'src', 'app.ts'), 'export const app = 2\n')
+ await local.getByRole('button', { name: '刷新变更', exact: true }).click()
+ await expect.poll(() => app.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('changed')
+ await app.getByText('有新改动', { exact: true }).waitFor()
+ await expect.poll(() => app.getAttribute('data-expanded')).toBe('')
+ expect(await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).isChecked()).toBe(false)
+
+ await local.getByRole('button', { name: '查看的提交:全部提交', exact: true }).click()
+ const menu = page.locator('[data-forge-commit-menu]')
+ await menu.getByRole('menuitem', { name: /Test the app/ }).click()
+ await expect.poll(() => shownPaths(local), { timeout: 20_000 }).toEqual(['src/app.spec.ts'])
+ // Without the file tree beside the diff, the toolbar offers the lens as a menu.
+ await local.getByRole('button', { name: '分层透镜:全部', exact: true }).click()
+ await expect.poll(() => page.getByRole('menu').getByRole('menuitem').allTextContents()).toEqual(['全部1', '接口0', '实现0', '测试1'])
+ await page.keyboard.press('Escape')
+ expect(tripwire.pageErrors).toEqual([])
+})
+
+it.skipIf(MODE === 'record')('keeps a narrow file header\'s viewed mark and menu inside its card and its name under the pointer', async () => {
+ const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-narrow-header', 'normal', { branch: 'feat' })
+ const from = 'src/original-review-module-with-a-long-name.ts'
+ const to = 'src/renamed-review-module-with-an-even-longer-name.ts'
+ const body = Array.from({ length: 20 }, (_, index) => `export const value${index} = ${index}\n`).join('')
+ await mkdir(join(project, 'src'))
+ await writeFile(join(project, from), body)
+ await git(project, 'add', from)
+ await git(project, 'commit', '--quiet', '-m', 'Add the module')
+ // The base holds the old path, so the branch shows a rename.
+ await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD')
+ await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main')
+ await git(project, 'mv', from, to)
+ await writeFile(join(project, to), `${body}export const extra = 1\n`)
+ await git(project, 'commit', '--quiet', '-am', 'Rename the module')
+ const { settled } = await sendPrompt(page, scaffold)
+ await settled
+ await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click()
+ await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click()
+ await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click()
+ await page.locator('[data-forge-local]').getByRole('button', { name: /^查看本会话的变更/ }).click({ timeout: 20_000 })
+ const local = page.locator('[data-forge-changes="local"]')
+ const name = 'renamed-review-module-with-an-even-longer-name.ts'
+ const file = local.locator(`[data-forge-diff-file="${to}"]`)
+ const viewed = file.getByRole('checkbox', { name: `将 ${name} 标记为已审阅`, exact: true })
+ await viewed.check({ timeout: 20_000 })
+ await writeFile(join(project, to), `${body}export const extra = 2\n`)
+ await local.getByRole('button', { name: '刷新变更', exact: true }).click()
+ await expect.poll(() => file.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('changed')
+ await file.getByText('由 original-review-module-with-a-long-name.ts 重命名', { exact: true }).waitFor()
+
+ // The changed tag, the rename badge, and the long path compete for one narrow header with the counts and actions.
+ await page.setViewportSize({ width: 390, height: 780 })
+ const label = file.locator('[data-forge-file-label]')
+ const [card, mark, menu, labelBox] = await Promise.all([
+ file.boundingBox(), viewed.boundingBox(), file.getByRole('button', { name: `${name} 的更多操作`, exact: true }).boundingBox(), label.boundingBox(),
+ ])
+ if (card === null || mark === null || menu === null || labelBox === null) throw new Error('The header controls must be rendered')
+ expect(mark.x + mark.width).toBeLessThanOrEqual(card.x + card.width)
+ expect(menu.x + menu.width).toBeLessThanOrEqual(card.x + card.width)
+ expect(labelBox.width).toBeGreaterThan(40)
+ await label.hover()
+ await page.getByRole('tooltip').filter({ hasText: `${from} → ${to}` }).waitFor()
+ await viewed.check()
+ await expect.poll(() => file.getAttribute('data-viewed')).toBe('viewed')
+ expect(tripwire.pageErrors).toEqual([])
+})
diff --git a/apps/web/tests/reasoning-spacing.e2e.ts b/apps/web/tests/reasoning-spacing.e2e.ts
new file mode 100644
index 0000000000..aa3b3935a4
--- /dev/null
+++ b/apps/web/tests/reasoning-spacing.e2e.ts
@@ -0,0 +1,119 @@
+/** Reasoning rows of one Assistant message keep the 4px process-row gap, and display-empty reasoning adds none. */
+import { chromium } from 'playwright'
+import { expect, it, onTestFinished } from 'vitest'
+import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session'
+import { launchWebScaffold, seedSession, watchConsole } from './scaffold.ts'
+import { newEnglishPage } from './support.ts'
+
+type Block = readonly ['reasoning' | 'signature' | 'text' | 'bash', string]
+
+/** Turn 1: reasoning around a signature-only block. Turn 2: signature-only blocks before and after reasoning. */
+const TURNS: readonly (readonly (readonly Block[])[])[] = [
+ [[['reasoning', 'a'], ['signature', 's1'], ['reasoning', 'b'], ['bash', 'k1']], [['text', 'Answer one']]],
+ [
+ [['reasoning', 'c'], ['bash', 'k2']],
+ [['signature', 's2'], ['signature', 's3'], ['reasoning', 'd'], ['bash', 'k3']],
+ [['reasoning', 'e'], ['signature', 's4'], ['signature', 's5'], ['bash', 'k4']],
+ [['text', 'Answer two']],
+ ],
+]
+
+function bashArguments(label: string): string {
+ return JSON.stringify({ command: `echo ${label}`, description: `Run ${label}` })
+}
+
+function content([kind, label]: Block): Record {
+ switch (kind) {
+ case 'reasoning': return { type: 'reasoning', text: `Thinking ${label}\n\nDetails for ${label}.` }
+ case 'signature': return { type: 'reasoning', text: `${label}` }
+ case 'text': return { type: 'text', text: label }
+ case 'bash': return {
+ type: 'tool-call', id: `call_${label}`, name: 'bash', arguments: bashArguments(label),
+ }
+ }
+}
+
+/** One closed Session whose Assistant messages carry the block layouts above. */
+function sessionLog(): string {
+ const header = {
+ type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 0, cwd: '{{cwd}}',
+ isSeeded: false, delegationDepth: 0,
+ }
+ const events: Record[] = []
+ let message = 0
+ const id = (): string => `{{message:${String(++message)}}}`
+ TURNS.forEach((steps, index) => {
+ const turn = index + 1
+ events.push({ type: 'turn/start', data: { turn } })
+ steps.forEach((blocks, stepIndex) => {
+ const step = stepIndex + 1
+ events.push({ type: 'step/start', data: { turn, step } })
+ if (step === 1) {
+ events.push({
+ type: 'user/message', surfaceOp: 'append',
+ data: { content: [{ type: 'text', text: `Turn ${String(turn)}` }], source: { kind: 'user' }, role: 'user', id: id() },
+ })
+ }
+ events.push({
+ type: 'assistant/message', surfaceOp: 'append',
+ data: {
+ turn, step, stream: [],
+ message: {
+ role: 'assistant', content: blocks.map(content), id: id(),
+ source: { kind: 'model', provider: 'deepseek-official', model: 'deepseek-v4-flash' },
+ },
+ },
+ })
+ for (const [kind, label] of blocks) {
+ if (kind !== 'bash') continue
+ const callId = `call_${label}`
+ events.push({ type: 'tool/call', data: { turn, step, callId, name: 'bash', arguments: bashArguments(label) } })
+ events.push({
+ type: 'tool/result', surfaceOp: 'append', sourceEventSeqs: [events.length - 1],
+ data: {
+ turn, step, meta: { cwd: '{{cwd}}' },
+ message: {
+ role: 'tool', source: { kind: 'tool', callId }, toolCallId: callId,
+ content: [{ type: 'text', text: `${label}\n` }], isError: false, id: id(),
+ },
+ },
+ })
+ }
+ events.push({ type: 'step/end', data: { turn, step } })
+ })
+ events.push({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } })
+ })
+ return [header, ...events].map(line => JSON.stringify(line)).join('\n')
+}
+
+it('keeps 4px between reasoning and tool rows around display-empty reasoning blocks', async () => {
+ const scaffold = await launchWebScaffold({})
+ onTestFinished(() => scaffold.close())
+ await scaffold.ctx.settings.update('ui-chat', { transcriptView: 'verbose' })
+ await seedSession(scaffold, sessionLog(), 'reasoning-spacing')
+ const browser = await chromium.launch()
+ onTestFinished(() => browser.close())
+ const page = await newEnglishPage(browser)
+ const console = watchConsole(page)
+ await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
+ await page.locator('[role="treeitem"]').first().click()
+ await page.locator('[role="treeitem"]').nth(1).click()
+ await page.getByText('Answer two', { exact: true }).waitFor()
+
+ // Rows in reading order; signature-only reasoning renders no row of its own.
+ const rows = await page.evaluate(() => [...document.querySelectorAll('[data-variant="think"], [data-chat-call-id]')]
+ .filter(row => row.getBoundingClientRect().height > 0)
+ .map((row) => {
+ const { top, bottom } = row.getBoundingClientRect()
+ const name = row.matches('[data-variant="think"]')
+ ? /Thinking (\w+)/.exec(row.textContent ?? '')?.[1]
+ : row.getAttribute('data-chat-call-id')?.replace('call_', '')
+ return { name: name ?? '?', top, bottom }
+ })
+ .sort((left, right) => left.top - right.top))
+ expect(rows.map(row => row.name)).toEqual(['a', 'b', 'k1', 'c', 'k2', 'd', 'k3', 'e', 'k4'])
+ const gaps = Object.fromEntries(rows.slice(1).map((row, index) =>
+ [`${rows[index]!.name}→${row.name}`, Math.round(row.top - rows[index]!.bottom)]))
+ expect(gaps).toMatchObject({ 'a→b': 4, 'b→k1': 4, 'c→k2': 4, 'k2→d': 4, 'd→k3': 4, 'k3→e': 4, 'e→k4': 4 })
+ expect(console.pageErrors).toEqual([])
+})
diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts
index 82f436c837..adfea25d10 100644
--- a/apps/web/tests/replay-round-trip.e2e.ts
+++ b/apps/web/tests/replay-round-trip.e2e.ts
@@ -124,14 +124,24 @@ describe('web e2e: fresh round trip through the real assembly', () => {
let accepted = false
try {
await input.fill(PROMPT)
+ // Hold the prompt POST at the browser boundary so the Host cannot accept
+ // the message before the pre-accept snapshot is read.
+ const promptSent = Promise.withResolvers()
+ const releasePrompt = Promise.withResolvers()
+ const holdPrompt = async (route: Route): Promise => {
+ promptSent.resolve(undefined)
+ await releasePrompt.promise
+ await route.continue()
+ }
+ await page.route('**/api/session/prompt', holdPrompt, { times: 1 })
const admitted = page.waitForResponse('**/api/session/prompt')
- const [echoSnapshot, response] = await Promise.all([
- input.evaluate(async (element, prompt) => {
+ try {
+ const echoCapture = input.evaluate(async (element, prompt) => {
element.dispatchEvent(new KeyboardEvent('keydown', {
key: 'Enter', code: 'Enter', bubbles: true, cancelable: true,
}))
- // sendSession registered its paint yield first. This frame observes the
- // composer holding the message while the Host has not accepted it yet.
+ // sendSession registered its paint yield first; this frame observes the
+ // composer holding the message while the POST is still held.
await new Promise((resolve) => { requestAnimationFrame(() => { resolve() }) })
const echo = document.querySelector('[data-submission-echo]')
return [
@@ -139,12 +149,15 @@ describe('web e2e: fresh round trip through the real assembly', () => {
`composer: ${JSON.stringify(element.textContent ?? '')}`,
`contenteditable: ${element.getAttribute('contenteditable')}`,
].join('\n')
- }, PROMPT),
- admitted,
- ])
+ }, PROMPT)
+ await promptSent.promise
+ await compareOrRefreshGolden(ECHO_EXPECTED, await echoCapture, MODE)
+ } finally {
+ releasePrompt.resolve(undefined)
+ }
+ const response = await admitted
expect(await response.json()).toMatchObject({ result: { ok: true, value: { accepted: true } } })
accepted = true
- await compareOrRefreshGolden(ECHO_EXPECTED, echoSnapshot, MODE)
// Acceptance publishes the echo and clears the composer; maintenance keeps the Turn from starting.
await page.locator('[data-submission-echo]', { hasText: PROMPT }).waitFor()
await expect.poll(() => input.textContent()).toBe('')
diff --git a/apps/web/tests/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts
index 36b74d0e88..35a08e5fb2 100644
--- a/apps/web/tests/shipped-composition.e2e.ts
+++ b/apps/web/tests/shipped-composition.e2e.ts
@@ -479,7 +479,6 @@ const EXPECTED_TOOLS = [
'edit',
'exit_plan_mode',
'get_goal',
- 'interrupt_agent',
'job_kill',
'job_list',
'job_output',
diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts
index 9690154afe..a3345c93bf 100644
--- a/apps/web/tests/subagent-conversation.e2e.ts
+++ b/apps/web/tests/subagent-conversation.e2e.ts
@@ -365,6 +365,61 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed')
})
+ it('retries a failed cold catalog and discovers descendants without reopening the menu', async () => {
+ onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-unread-catalog'))
+ const reads = apiCalls.filter(path => path === '/api/session/projections').length
+ const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession')
+ const projections = vi.spyOn(scaffold.ctx.sessionController, 'projections')
+ try {
+ const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
+ await page.locator('[data-composer-input]').first().hover()
+ await trigger.hover()
+ const tree = page.getByRole('tree', { name: 'Subagent sessions' })
+ const child = tree.getByRole('treeitem', { name: new RegExp(LABEL) })
+ await child.waitFor()
+ expect(await child.getAttribute('aria-expanded')).toBeNull()
+ expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
+ expect(await tree.getByText(/Loading subagents|unknown/u).count()).toBe(0)
+ expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads)
+ expect(observe).not.toHaveBeenCalled()
+ const parentUrl = page.url()
+ await page.route('**/api/session/projections', route => route.abort('failed'), { times: 1 })
+ await trigger.click()
+ const retry = tree.getByRole('button', { name: 'Retry', exact: true })
+ await retry.waitFor()
+ expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0)
+ expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads + 1)
+ expect(projections).not.toHaveBeenCalled()
+ await retry.click()
+ await retry.waitFor({ state: 'detached' })
+ const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
+ await expand.waitFor()
+ await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId)).toEqual([parentId, childId, oneShotId])
+ expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false)
+ const lastRead = page.waitForResponse('**/api/session/projections')
+ await expand.click()
+ await (await lastRead).finished()
+ await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId))
+ .toEqual([parentId, childId, oneShotId, grandchildId])
+ const grandchild = tree.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) })
+ await grandchild.waitFor()
+ expect(await grandchild.getAttribute('aria-expanded')).toBeNull()
+ await compareOrRefreshGolden(
+ TREE_EXPECTED,
+ await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE,
+ )
+ expect(page.url()).toBe(parentUrl)
+ expect(scaffold.ctx.agents.get(childId)).toBeUndefined()
+ expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined()
+ await page.keyboard.press('Escape')
+ await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
+ } finally {
+ await page.unroute('**/api/session/projections')
+ observe.mockRestore()
+ projections.mockRestore()
+ }
+ })
+
it('lists direct subagents by label in the reference menu', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-reference-title'))
expect(liveReferenceOptions.some(text => text.includes(LABEL))).toBe(true)
@@ -424,7 +479,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
}
expect(await row.getAttribute('aria-label')).toContain(`${LABEL} ${CHILD_NAME} `)
expect(await row.getByRole('button', { name: /description/u }).count()).toBe(0)
- expect(await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).count()).toBe(1)
+ await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).waitFor()
expect(await row.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(1)
expect(page.url()).toBe(originalUrl)
expect(await page.getByRole('tooltip').count()).toBe(0)
@@ -438,9 +493,34 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
}
})
- it('recovers a current-format cold child catalog cache miss without activating either level', async () => {
+ it('expands locally available cold catalogs without requesting or activating either level', async () => {
onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree'))
- await page.getByRole('button', { name: '2 subagents' }).hover()
+ const warningStart = tripwire.warnings.length
+ await page.reload({ waitUntil: 'load' })
+ const trigger = page.getByRole('button', { name: '2 subagents', exact: true })
+ await trigger.waitFor()
+ acknowledgeReloadConnectionLoss(tripwire, warningStart)
+ const siblingsRead = page.waitForResponse((response) => {
+ if (!response.url().endsWith('/api/session/projections')) return false
+ const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
+ return body.payload.args.request.sessionId === oneShotId
+ })
+ await trigger.click()
+ await (await siblingsRead).finished()
+ const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true })
+ await expand.waitFor()
+ const descendantsRead = page.waitForResponse((response) => {
+ if (!response.url().endsWith('/api/session/projections')) return false
+ const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } }
+ return body.payload.args.request.sessionId === grandchildId
+ })
+ await expand.click()
+ await (await descendantsRead).finished()
+ await page.keyboard.press('Escape')
+ await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' })
+ const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length
+ await page.locator('[data-composer-input]').first().hover()
+ await trigger.hover()
const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' })
expect(await catalogTree.evaluate((element) => {
const rect = element.getBoundingClientRect()
@@ -453,6 +533,10 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
name: `Expand ${ONE_SHOT_LABEL} descendants`,
})
expect(await oneShotDisclosure.count()).toBe(0)
+ await compareOrRefreshGolden(
+ fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/disclosures.expected.md', import.meta.url)),
+ await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE,
+ )
const oneShotRow = page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) })
expect(await oneShotRow.locator('[data-state="done"]').count()).toBe(1)
expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1)
@@ -501,18 +585,13 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
expect(await page.getByText(PARENT_PROMPT, { exact: true }).isVisible()).toBe(true)
expect(await page.locator('[data-sidebar-chat]').count()).toBe(0)
}
- const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession')
- try {
- const projections = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session/projections')
- await clickDisclosureGutter(3)
- await projections
- await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 })
- expect(await sectionHeader.count()).toBe(0)
- expect(observe.mock.calls.some(([id]) => id === childId)).toBe(true)
- expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false)
- } finally {
- observe.mockRestore()
- }
+ await clickDisclosureGutter(3)
+ const grandchildRow = page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) })
+ await grandchildRow.waitFor({ timeout: 15_000 })
+ expect(await catalogTree.getByText('Loading subagents…', { exact: true }).count()).toBe(0)
+ expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull()
+ expect(await grandchildRow.getByRole('button', { name: `Expand ${NESTED_LABEL} descendants` }).count()).toBe(0)
+ expect(await sectionHeader.count()).toBe(0)
await clickDisclosureGutter(26)
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ state: 'detached' })
expect(await childRow.getAttribute('aria-expanded')).toBe('false')
@@ -571,6 +650,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () =
scaffold.workspaceCwd,
)
await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE)
+ expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(catalogReads)
await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getByText(grandchildId, { exact: true }).click()
await page.getByText(NESTED_PROMPT).waitFor()
const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' })
@@ -994,10 +1074,9 @@ describe('web e2e: migration-required subagent catalog', () => {
const tree = page.getByRole('tree', { name: 'Subagent sessions' })
const childRow = tree.getByRole('treeitem', { name: new RegExp(childLabel) })
await childRow.waitFor()
- await expect.poll(() => childRow.textContent()).toContain('Migration required')
await expect.poll(() => childRow.getByRole('button', { name: `Expand ${childLabel} descendants`, exact: true }).count()).toBe(0)
expect(await childRow.getAttribute('aria-expanded')).toBeNull()
- expect(await childRow.textContent()).toContain('Migration required')
+ expect(await childRow.textContent()).not.toContain('Migration required')
expect(await childRow.textContent()).not.toContain('unknown mode')
expect(await childRow.getByRole('button', { name: `Open ${childLabel} in sidebar`, exact: true }).isEnabled()).toBe(true)
expect(await tree.getByRole('treeitem').count()).toBe(1)
@@ -1015,7 +1094,7 @@ describe('web e2e: migration-required subagent catalog', () => {
await page.getByRole('button', { name: '1 subagent', exact: true }).hover()
const grandchildRow = tree.getByRole('treeitem', { name: new RegExp(grandchildLabel) })
await grandchildRow.waitFor()
- expect(await grandchildRow.textContent()).toContain('Migration required')
+ expect(await grandchildRow.textContent()).not.toContain('Migration required')
expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull()
expect(await grandchildRow.getByRole('button', { name: `Expand ${grandchildLabel} descendants`, exact: true }).count()).toBe(0)
expect(projections).not.toHaveBeenCalled()
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index 9e6e59f142..a70870d5ec 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -89,6 +89,7 @@
"tests/trajectory-virtualization.e2e.ts",
"tests/lifecycle-chrome.e2e.ts",
"tests/reasoning-preview.e2e.ts",
+ "tests/reasoning-spacing.e2e.ts",
"tests/details-session-lifecycle.e2e.ts",
"tests/sessionless-header.e2e.ts",
"tests/document-preview.e2e.ts",
diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml
index 573a7492dc..d897229806 100644
--- a/docs/architecture.i18n.yaml
+++ b/docs/architecture.i18n.yaml
@@ -21,8 +21,8 @@
en: 20ef882e44b06a10
zh: c10c3934ed5570e9
/deepseek-harness-architecture/events:
- en: ddebac7cfd41ec73
- zh: 51e6d0866a9e7839
+ en: 0d4481070a0ba352
+ zh: 026be77a9f3db68e
/deepseek-harness-architecture/turn-flow:
en: 1d496f1893bdbb8d
zh: f16d162a803fc791
diff --git a/docs/architecture.md b/docs/architecture.md
index 05ecbdcf3b..c7c036016b 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -74,7 +74,7 @@ Events provide extension points in three domains.
Subagent Activations own runtime tree membership.
-AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; unload retains resources through teardown ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)).
+AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; shutdown cancels and awaits active work despite queue-cleanup failures before releasing resources ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)).
[Event producers and consumers](event-producer-consumer.md).
diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md
index e7e5ebf8d0..2eae113769 100644
--- a/docs/architecture.zh.md
+++ b/docs/architecture.zh.md
@@ -76,7 +76,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共
Subagent Activation 拥有运行时树成员关系。
-AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;卸载在 teardown 期间保留所需资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。
+AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;关闭时即使队列清理失败,也会取消并等待当前工作,再释放资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。
[事件生产者与消费者](event-producer-consumer.zh.md)。
diff --git a/docs/config-catalog.md b/docs/config-catalog.md
index 216036a336..bdf09bf8b8 100644
--- a/docs/config-catalog.md
+++ b/docs/config-catalog.md
@@ -1081,7 +1081,7 @@ export interface CotTranslationPreferences {
## `@deepseek-ai/dsh-experimental-client-ui-forge`
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
-- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts)
+- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1109,6 +1109,18 @@ export interface Config {
maxUntrackedFiles?: number
/** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */
maxCachedDiffBytes?: number
+ /** Most commits of the `branch` scope listed; a longer branch lists its newest ones. */
+ maxCommits?: number
+ /**
+ * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before
+ * them; matched against repository-relative paths with dot files included. A repository's `.gitattributes` overrides both.
+ */
+ testPaths?: string[]
+ /**
+ * Globs of files in the `interface` layer beside the built-in rules, matched like `testPaths`; checked after
+ * `testPaths` and before the built-in rules.
+ */
+ interfacePaths?: string[]
}
```
@@ -1144,13 +1156,15 @@ export interface Config {
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
-- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts)
+- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
+ /** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */
+ systemPointerHover: boolean
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
@@ -1174,7 +1188,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
-- `source`: [`packages/experimental/forge/src/types.ts:239`](../packages/experimental/forge/src/types.ts)
+- `source`: [`packages/experimental/forge/src/types.ts:273`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1212,6 +1226,8 @@ export interface Config {
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
maxReviewThreads?: number
+ /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
+ maxCommits?: number
}
```
@@ -1545,7 +1561,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official'
- `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
-- `source`: [`packages/experimental/worktree/src/index.ts:35`](../packages/experimental/worktree/src/index.ts)
+- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts)
```ts config-catalog
/** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */
@@ -1564,7 +1580,11 @@ export interface Config {
timeoutMs?: number
/** Subprocess termination grace in milliseconds. */
graceMs?: number
- /** Maximum captured bytes per subprocess output stream. */
+ /**
+ * Maximum captured bytes per subprocess output stream; archive inspection
+ * streams `git status`, and inspection and restoration stream the worktree
+ * listing, so it bounds only their stderr.
+ */
maxOutputBytes?: number
}
```
diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md
index a3e3fd153a..a511ffe7a2 100644
--- a/docs/config-catalog.zh.md
+++ b/docs/config-catalog.zh.md
@@ -1083,7 +1083,7 @@ export interface CotTranslationPreferences {
## `@deepseek-ai/dsh-experimental-client-ui-forge`
- `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents`
-- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts)
+- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1111,6 +1111,18 @@ export interface Config {
maxUntrackedFiles?: number
/** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */
maxCachedDiffBytes?: number
+ /** Most commits of the `branch` scope listed; a longer branch lists its newest ones. */
+ maxCommits?: number
+ /**
+ * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before
+ * them; matched against repository-relative paths with dot files included. A repository's `.gitattributes` overrides both.
+ */
+ testPaths?: string[]
+ /**
+ * Globs of files in the `interface` layer beside the built-in rules, matched like `testPaths`; checked after
+ * `testPaths` and before the built-in rules.
+ */
+ interfacePaths?: string[]
}
```
@@ -1146,13 +1158,15 @@ export interface Config {
- `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents`
- `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts)
-- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts)
+- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts)
```ts config-catalog
/** Native preparation, source-build signing, operation bounds, and profile-local application grants. */
export interface Config extends CuaConfig {
/** Interval in milliseconds between permission and position checks while the native guide is open. */
permissionPollIntervalMs: number
+ /** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */
+ systemPointerHover: boolean
/**
* Source-build signing: `ad-hoc` (default) binds grants to the code hash;
* an object selects an existing certificate in an explicitly configured keychain.
@@ -1176,7 +1190,7 @@ export type SourceSigning = 'ad-hoc' | {
## `@deepseek-ai/dsh-experimental-forge`
-- `source`: [`packages/experimental/forge/src/types.ts:239`](../packages/experimental/forge/src/types.ts)
+- `source`: [`packages/experimental/forge/src/types.ts:273`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1214,6 +1228,8 @@ export interface Config {
maxOutputBytes?: number
/** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */
maxReviewThreads?: number
+ /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */
+ maxCommits?: number
}
```
@@ -1547,7 +1563,7 @@ export type PaidTranslationProvider = 'deepseek-account' | 'deepseek-official'
- `inject`: `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `sessionProjections`
- `refs`: `Volatile` (`@deepseek-ai/cordis`)
-- `source`: [`packages/experimental/worktree/src/index.ts:35`](../packages/experimental/worktree/src/index.ts)
+- `source`: [`packages/experimental/worktree/src/index.ts:36`](../packages/experimental/worktree/src/index.ts)
```ts config-catalog
/** Worktree location, generated names, executables, subprocess resource limits, and the archive cleanup switch. */
@@ -1566,7 +1582,11 @@ export interface Config {
timeoutMs?: number
/** Subprocess termination grace in milliseconds. */
graceMs?: number
- /** Maximum captured bytes per subprocess output stream. */
+ /**
+ * Maximum captured bytes per subprocess output stream; archive inspection
+ * streams `git status`, and inspection and restoration stream the worktree
+ * listing, so it bounds only their stderr.
+ */
maxOutputBytes?: number
}
```
diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md
index f350e48496..6cfcb20f7e 100644
--- a/docs/event-producer-consumer.md
+++ b/docs/event-producer-consumer.md
@@ -12,17 +12,17 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| --- | --- | --- | --- | --- |
| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` |
-| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
-| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
-| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
-| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
-| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
-| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
-| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
-| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
-| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
-| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
+| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
+| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
+| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
+| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
+| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
+| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
+| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
+| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
+| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
+| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
@@ -73,8 +73,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
-| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
-| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
+| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
+| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
@@ -84,7 +84,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) |
| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - |
| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` |
-| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
+| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, `cua-macos`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) |
| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) |
diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md
index 88ff269bf8..0510683b33 100644
--- a/docs/event-producer-consumer.zh.md
+++ b/docs/event-producer-consumer.zh.md
@@ -14,17 +14,17 @@
| --- | --- | --- | --- | --- |
| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - |
| `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` |
-| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
-| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
-| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
-| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
-| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
-| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
-| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
-| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
-| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
-| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
-| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
+| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` |
+| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) |
+| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
+| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) |
+| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) |
+| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) |
+| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) |
+| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) |
+| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) |
+| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` |
+| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` |
@@ -75,8 +75,8 @@
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
-| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
-| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
+| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
+| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
@@ -86,7 +86,7 @@
| `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) |
| `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - |
| `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` |
-| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
+| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, `cua-macos`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` |
| `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) |
| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) |
diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml
index d58a9835d5..fe01ca6bf3 100644
--- a/docs/persistence-catalog.i18n.yaml
+++ b/docs/persistence-catalog.i18n.yaml
@@ -12,8 +12,8 @@
en: 35ffb6107a5fbae2
zh: 06ce2128075e157b
/session-persistence-event-catalog/event-envelope:
- en: 56414ffd00cdc32a
- zh: 6dc11eb013e95e41
+ en: 189352d7a3bba620
+ zh: 5361f42035034672
/session-persistence-event-catalog/events:
en: f4776ba3d0fd53ce
zh: e86769f50a69055a
diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md
index 20b3c20fa2..b499a7875f 100644
--- a/docs/persistence-catalog.md
+++ b/docs/persistence-catalog.md
@@ -161,7 +161,7 @@ export type SessionEvent = {
}[T]
```
-Sources: [`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:501`](../packages/core/session/src/types.ts)
+Sources: [`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:506`](../packages/core/session/src/types.ts)
## Events
diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md
index 00b7347de0..dc50e8fff0 100644
--- a/docs/persistence-catalog.zh.md
+++ b/docs/persistence-catalog.zh.md
@@ -163,7 +163,7 @@ export type SessionEvent = {
}[T]
```
-来源:[`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:501`](../packages/core/session/src/types.ts)
+来源:[`packages/core/session/src/types.ts:439`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:447`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:470`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:506`](../packages/core/session/src/types.ts)
## 事件
diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md
index 40264ec898..a00dc512ef 100644
--- a/docs/subsystems/core.md
+++ b/docs/subsystems/core.md
@@ -78,6 +78,7 @@ interface Agent {
* Clear queued and steering work — unless `keepInbox` — and abort the active
* turn or between-turn task. The first cause wins for that activity. With no
* active activity, cancellation is a no-op and does not arm later work.
+ * Queue-write failures still abort the activity and propagate to the caller.
* @param cause - the stable caller intent carried by the active operation signal.
* @param options - cancellation options; `keepInbox` preserves pending work.
*/
diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md
index ff1d3b579e..5cb66a1692 100644
--- a/docs/subsystems/core.zh.md
+++ b/docs/subsystems/core.zh.md
@@ -82,6 +82,7 @@ interface Agent {
* Clear queued and steering work — unless `keepInbox` — and abort the active
* turn or between-turn task. The first cause wins for that activity. With no
* active activity, cancellation is a no-op and does not arm later work.
+ * Queue-write failures still abort the activity and propagate to the caller.
* @param cause - the stable caller intent carried by the active operation signal.
* @param options - cancellation options; `keepInbox` preserves pending work.
*/
diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml
index d8c9c3ada9..97ebf7bece 100644
--- a/docs/subsystems/forge.i18n.yaml
+++ b/docs/subsystems/forge.i18n.yaml
@@ -6,8 +6,8 @@
en: 3990a17e12c66a23
zh: 4170c33e49248f8f
/forges/providers-and-change-requests:
- en: 4ec7d1892b4067db
- zh: 6bb70d21ae3d7a89
+ en: e5d807b29f553751
+ zh: e0b25d9e964f988e
/forges/status-polling:
en: 26ccfa2e342e3e67
zh: fe6cc2a622757c48
@@ -18,5 +18,5 @@
en: 13dfd36f2166bba0
zh: a369434f52f04d57
/forges/panel:
- en: 1d3400c14260e62c
- zh: 191e9bae2d753244
+ en: e52a5c57abc4d30e
+ zh: 509a40f421cc3d33
diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md
index 94de4749bf..b5156c101f 100644
--- a/docs/subsystems/forge.md
+++ b/docs/subsystems/forge.md
@@ -78,9 +78,49 @@ interface ForgeProvider {
fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise
/** Build the web page of `path` at `commit` in the change request's repository. */
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string
+ /**
+ * List the commits of a change request at its current head. A provider implements `commits` and `compare`
+ * together; omitting either declares that the change request can be read only as a whole.
+ */
+ commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise
+ /**
+ * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch
+ * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`.
+ */
+ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise
}
```
+```ts type-equiv
+/** One commit of a change request. */
+interface ForgeCommit {
+ /** Full commit object name. */
+ readonly sha: string
+ /** Full object name of the first parent, or null for a root commit. */
+ readonly parent: string | null
+ /** First line of the commit message. */
+ readonly title: string
+ /** Author name or login as the host reports it, or null when it reports none. */
+ readonly author: string | null
+ /** ISO 8601 time the commit was authored. */
+ readonly authoredAt: string
+}
+```
+
+```ts type-equiv
+/** The commits of a change request at one head commit. */
+interface ForgeCommitList {
+ /** Head commit the list was read at. */
+ readonly headSha: string
+ /** Commits oldest first, ending with the head commit unless `truncated`. */
+ readonly commits: readonly ForgeCommit[]
+ /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */
+ readonly truncated: boolean
+}
+```
+
+`ctx.forge.commits` and `ctx.forge.compare` delegate to a provider that implements both; otherwise `commits` resolves to undefined and `compare` to an `unavailable` failure, so the forge panel offers its commit picker only where the provider reads commits.
+
```ts type-equiv
/** Whether a provider can reach one host with the current credentials. */
interface ForgeReadiness {
@@ -575,7 +615,20 @@ type ForgeChangeRequestStatesFrame =
| { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] }
```
-The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows.
+The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once, once per head commit; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows.
+
+```ts type-equiv
+/**
+ * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order
+ * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last.
+ */
+interface ForgeCommitRange {
+ /** First, oldest commit shown. */
+ readonly from: string
+ /** Last, newest commit shown; equal to `from` for one commit. */
+ readonly to: string
+}
+```
```ts type-equiv
/** Which local changes a diff covers; each reads the Session's checkout through Git. */
@@ -583,9 +636,10 @@ type ForgeLocalScope =
/**
* The working tree and untracked files against a fork point: the merge base of HEAD with the
* `base` ref, or while `base` is null, the base commit of the worktree the Session created,
- * else the merge base of HEAD with the default branch of the code host remote.
+ * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes
+ * of those commits between the fork point and HEAD, without uncommitted or untracked files.
*/
- | { readonly kind: 'branch'; readonly base: string | null }
+ | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null }
/** The working tree and untracked files against HEAD. */
| { readonly kind: 'uncommitted' }
/** The working tree and untracked files against the index. */
@@ -647,6 +701,15 @@ interface ForgeDiffHunk {
type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed'
```
+```ts type-equiv
+/**
+ * Review layer of a changed file: the layer the repository's root `.gitattributes` names with `dsh-review-layer`, else
+ * `test` for a file it marks `linguist-generated`, else the first of `testPaths`, `interfacePaths`, and the built-in
+ * test and interface rules that the path matches, else `implementation`.
+ */
+type ForgeFileLayer = 'interface' | 'implementation' | 'test'
+```
+
```ts type-equiv
/** One changed file of a diff. */
interface ForgeDiffFile {
@@ -668,6 +731,13 @@ interface ForgeDiffFile {
readonly deletions: number
/** Hunks in file order; none for a binary file or a change of mode or name only. */
readonly hunks: readonly ForgeDiffHunk[]
+ /** Review layer the path falls in. */
+ readonly layer: ForgeFileLayer
+ /**
+ * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content
+ * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it.
+ */
+ readonly digest: string
}
```
@@ -684,22 +754,34 @@ interface ForgeLocalDiff {
```
```ts type-equiv
-/** Changes of a change request as its code host computes them. */
+/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */
interface ForgeChangeRequestDiff {
- /** Head commit the diff describes. */
+ /** Commit whose new side the diff describes: the head, or the last chosen commit. */
readonly headSha: string
/** Changed files in the host's order. */
readonly files: readonly ForgeDiffFile[]
/**
* Commits the checkout's branch has beyond the head when that branch is the change request's head
- * branch and the head commit is present locally; null otherwise.
+ * branch and the head commit is present locally; null otherwise and for chosen commits.
*/
readonly localAhead: number | null
- /** Web page of each changed file at the head commit, by path. */
+ /** Web page of each changed file at `headSha`, by path. */
readonly fileUrls: Readonly>
}
```
+```ts type-equiv
+/** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */
+interface ForgeLocalCommits {
+ /** HEAD commit the list was read at. */
+ readonly headSha: string
+ /** Commits oldest first, ending with HEAD's commit. */
+ readonly commits: readonly ForgeCommit[]
+ /** Whether the branch has more commits than `maxCommits`; the listed ones are the newest. */
+ readonly truncated: boolean
+}
+```
+
```ts type-equiv
/** One file the `branch` scope changes, without its hunks. */
interface ForgeChangedFile {
@@ -834,6 +916,27 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise
+/**
+ * List the commits of a change request at its current head.
+ * @param ref - change request served by a registered provider.
+ * @param signal - cancellation of the read.
+ * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits.
+ * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
+ */
+async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise
+
+/**
+ * Read the changes between two commits of a change request's repository.
+ * @param ref - change request served by a registered provider.
+ * @param base - full object name of the commit compared from.
+ * @param head - full object name of a commit that descends from `base`.
+ * @param signal - cancellation of the read.
+ * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that
+ * does not read commits returns `unavailable`.
+ * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
+ */
+async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise
+
/**
* Publish one comment or a completed review, then refresh the watched status.
* @param ref - change request served by a registered provider.
@@ -987,21 +1090,37 @@ Serves the forge panel. Following a Session inspects the checkout of its current
* @returns the files, the base of the `branch` scope, and the untracked files left out.
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch
* chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without
- * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before
+ * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order;
+ * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
+ * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before
* any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.
*/
@Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise
+/**
+ * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or
+ * several of instead of the whole scope.
+ * @param session - Session whose checkout is read.
+ * @param base - the base ref of the `branch` scope, or null for its automatic fork point.
+ * @param signal - request cancellation.
+ * @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit.
+ * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not
+ * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.
+ */
+@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise
+
/**
* Read the new side of one changed file in a scope, which supplies the
- * unchanged lines between its hunks: the index for `staged`, else the working tree.
+ * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of
+ * the `branch` scope, else the working tree.
* @param session - Session whose checkout is read.
* @param scope - the scope the diff was read in.
* @param path - path relative to the checkout's top-level directory, as the diff names it.
* @param signal - request cancellation.
* @returns the text.
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`;
- * an error for a path outside the checkout, binary content, or a failed read.
+ * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside
+ * the checkout, binary content, or a failed read.
*/
@Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise
@@ -1018,20 +1137,39 @@ Serves the forge panel. Following a Session inspects the checkout of its current
@Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise
/**
- * Read the changes of a change request of a Session as its code host
- * computes them, at the head commit of its latest status. A patch already
- * read at the same head commit and base branch is reused from memory, for
- * any Session, until `maxCachedDiffBytes` evicts it.
+ * List the commits of a change request of a Session at its current head, which the changes view can show one or
+ * several of instead of the whole change request.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param signal - request cancellation.
- * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head.
+ * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
- * `forgePanel/stale-head` when the head moved past the latest status, which is then polled again;
- * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit;
- * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise.
+ * `forgePanel/diff-failed` when the host does not list them.
*/
-@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise
+@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise
+
+/**
+ * Read the changes of a change request of a Session as its code host
+ * computes them, with each file's layer following the root `.gitattributes`
+ * of the commit the diff ends at. Without `commits` the diff covers the change
+ * request at the head commit of its latest status; a patch already read at the
+ * same head commit and base branch is reused from memory with its attributes, for
+ * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those
+ * commits, from the first one's first parent to the last, and is read every time.
+ * @param session - Session the change request is bound to.
+ * @param url - binding URL of the change request.
+ * @param commits - consecutive commits of the change request, or null for all of it.
+ * @param signal - request cancellation.
+ * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head.
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
+ * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order;
+ * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
+ * `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again;
+ * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit;
+ * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host
+ * does not provide the commits, the diff, or an existing `.gitattributes` otherwise.
+ */
+@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise
/**
* Read one file of a change request's repository at a commit, which
diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md
index 6d0a6db1cc..2ca42cde71 100644
--- a/docs/subsystems/forge.zh.md
+++ b/docs/subsystems/forge.zh.md
@@ -78,9 +78,49 @@ interface ForgeProvider {
fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise
/** Build the web page of `path` at `commit` in the change request's repository. */
fileUrl(ref: ChangeRequestRef, commit: string, path: string): string
+ /**
+ * List the commits of a change request at its current head. A provider implements `commits` and `compare`
+ * together; omitting either declares that the change request can be read only as a whole.
+ */
+ commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise
+ /**
+ * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch
+ * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`.
+ */
+ compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise
}
```
+```ts type-equiv
+/** One commit of a change request. */
+interface ForgeCommit {
+ /** Full commit object name. */
+ readonly sha: string
+ /** Full object name of the first parent, or null for a root commit. */
+ readonly parent: string | null
+ /** First line of the commit message. */
+ readonly title: string
+ /** Author name or login as the host reports it, or null when it reports none. */
+ readonly author: string | null
+ /** ISO 8601 time the commit was authored. */
+ readonly authoredAt: string
+}
+```
+
+```ts type-equiv
+/** The commits of a change request at one head commit. */
+interface ForgeCommitList {
+ /** Head commit the list was read at. */
+ readonly headSha: string
+ /** Commits oldest first, ending with the head commit unless `truncated`. */
+ readonly commits: readonly ForgeCommit[]
+ /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */
+ readonly truncated: boolean
+}
+```
+
+`ctx.forge.commits` 与 `ctx.forge.compare` 委托给同时实现两者的提供方;否则 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此 forge 面板只在提供方能读取提交时提供提交选择器。
+
```ts type-equiv
/** Whether a provider can reach one host with the current credentials. */
interface ForgeReadiness {
@@ -575,7 +615,20 @@ type ForgeChangeRequestStatesFrame =
| { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] }
```
-变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更,提供方只返回描述该 head 提交的补丁;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。
+变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更(提供方只返回描述该 head 提交的补丁),或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求(每个 head 提交一次);`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。
+
+```ts type-equiv
+/**
+ * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order
+ * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last.
+ */
+interface ForgeCommitRange {
+ /** First, oldest commit shown. */
+ readonly from: string
+ /** Last, newest commit shown; equal to `from` for one commit. */
+ readonly to: string
+}
+```
```ts type-equiv
/** Which local changes a diff covers; each reads the Session's checkout through Git. */
@@ -583,9 +636,10 @@ type ForgeLocalScope =
/**
* The working tree and untracked files against a fork point: the merge base of HEAD with the
* `base` ref, or while `base` is null, the base commit of the worktree the Session created,
- * else the merge base of HEAD with the default branch of the code host remote.
+ * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes
+ * of those commits between the fork point and HEAD, without uncommitted or untracked files.
*/
- | { readonly kind: 'branch'; readonly base: string | null }
+ | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null }
/** The working tree and untracked files against HEAD. */
| { readonly kind: 'uncommitted' }
/** The working tree and untracked files against the index. */
@@ -647,6 +701,15 @@ interface ForgeDiffHunk {
type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed'
```
+```ts type-equiv
+/**
+ * Review layer of a changed file: the layer the repository's root `.gitattributes` names with `dsh-review-layer`, else
+ * `test` for a file it marks `linguist-generated`, else the first of `testPaths`, `interfacePaths`, and the built-in
+ * test and interface rules that the path matches, else `implementation`.
+ */
+type ForgeFileLayer = 'interface' | 'implementation' | 'test'
+```
+
```ts type-equiv
/** One changed file of a diff. */
interface ForgeDiffFile {
@@ -668,6 +731,13 @@ interface ForgeDiffFile {
readonly deletions: number
/** Hunks in file order; none for a binary file or a change of mode or name only. */
readonly hunks: readonly ForgeDiffHunk[]
+ /** Review layer the path falls in. */
+ readonly layer: ForgeFileLayer
+ /**
+ * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content
+ * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it.
+ */
+ readonly digest: string
}
```
@@ -684,22 +754,34 @@ interface ForgeLocalDiff {
```
```ts type-equiv
-/** Changes of a change request as its code host computes them. */
+/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */
interface ForgeChangeRequestDiff {
- /** Head commit the diff describes. */
+ /** Commit whose new side the diff describes: the head, or the last chosen commit. */
readonly headSha: string
/** Changed files in the host's order. */
readonly files: readonly ForgeDiffFile[]
/**
* Commits the checkout's branch has beyond the head when that branch is the change request's head
- * branch and the head commit is present locally; null otherwise.
+ * branch and the head commit is present locally; null otherwise and for chosen commits.
*/
readonly localAhead: number | null
- /** Web page of each changed file at the head commit, by path. */
+ /** Web page of each changed file at `headSha`, by path. */
readonly fileUrls: Readonly>
}
```
+```ts type-equiv
+/** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */
+interface ForgeLocalCommits {
+ /** HEAD commit the list was read at. */
+ readonly headSha: string
+ /** Commits oldest first, ending with HEAD's commit. */
+ readonly commits: readonly ForgeCommit[]
+ /** Whether the branch has more commits than `maxCommits`; the listed ones are the newest. */
+ readonly truncated: boolean
+}
+```
+
```ts type-equiv
/** One file the `branch` scope changes, without its hunks. */
interface ForgeChangedFile {
@@ -834,6 +916,27 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise
+/**
+ * List the commits of a change request at its current head.
+ * @param ref - change request served by a registered provider.
+ * @param signal - cancellation of the read.
+ * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits.
+ * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
+ */
+async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise
+
+/**
+ * Read the changes between two commits of a change request's repository.
+ * @param ref - change request served by a registered provider.
+ * @param base - full object name of the commit compared from.
+ * @param head - full object name of a commit that descends from `base`.
+ * @param signal - cancellation of the read.
+ * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that
+ * does not read commits returns `unavailable`.
+ * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts.
+ */
+async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise
+
/**
* Publish one comment or a completed review, then refresh the watched status.
* @param ref - change request served by a registered provider.
@@ -987,21 +1090,37 @@ Serves the forge panel. Following a Session inspects the checkout of its current
* @returns the files, the base of the `branch` scope, and the untracked files left out.
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch
* chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without
- * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before
+ * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order;
+ * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
+ * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before
* any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.
*/
@Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise
+/**
+ * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or
+ * several of instead of the whole scope.
+ * @param session - Session whose checkout is read.
+ * @param base - the base ref of the `branch` scope, or null for its automatic fork point.
+ * @param signal - request cancellation.
+ * @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit.
+ * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not
+ * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.
+ */
+@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise
+
/**
* Read the new side of one changed file in a scope, which supplies the
- * unchanged lines between its hunks: the index for `staged`, else the working tree.
+ * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of
+ * the `branch` scope, else the working tree.
* @param session - Session whose checkout is read.
* @param scope - the scope the diff was read in.
* @param path - path relative to the checkout's top-level directory, as the diff names it.
* @param signal - request cancellation.
* @returns the text.
* @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`;
- * an error for a path outside the checkout, binary content, or a failed read.
+ * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside
+ * the checkout, binary content, or a failed read.
*/
@Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise
@@ -1018,20 +1137,39 @@ Serves the forge panel. Following a Session inspects the checkout of its current
@Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise
/**
- * Read the changes of a change request of a Session as its code host
- * computes them, at the head commit of its latest status. A patch already
- * read at the same head commit and base branch is reused from memory, for
- * any Session, until `maxCachedDiffBytes` evicts it.
+ * List the commits of a change request of a Session at its current head, which the changes view can show one or
+ * several of instead of the whole change request.
* @param session - Session the change request is bound to.
* @param url - binding URL of the change request.
* @param signal - request cancellation.
- * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head.
+ * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits.
* @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
- * `forgePanel/stale-head` when the head moved past the latest status, which is then polled again;
- * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit;
- * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise.
+ * `forgePanel/diff-failed` when the host does not list them.
*/
-@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise
+@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise
+
+/**
+ * Read the changes of a change request of a Session as its code host
+ * computes them, with each file's layer following the root `.gitattributes`
+ * of the commit the diff ends at. Without `commits` the diff covers the change
+ * request at the head commit of its latest status; a patch already read at the
+ * same head commit and base branch is reused from memory with its attributes, for
+ * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those
+ * commits, from the first one's first parent to the last, and is read every time.
+ * @param session - Session the change request is bound to.
+ * @param url - binding URL of the change request.
+ * @param commits - consecutive commits of the change request, or null for all of it.
+ * @param signal - request cancellation.
+ * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head.
+ * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves;
+ * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order;
+ * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it;
+ * `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again;
+ * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit;
+ * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host
+ * does not provide the commits, the diff, or an existing `.gitattributes` otherwise.
+ */
+@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise
/**
* Read one file of a change request's repository at a commit, which
diff --git a/docs/subsystems/mcp.md b/docs/subsystems/mcp.md
index a07100c4e7..da3c4539a3 100644
--- a/docs/subsystems/mcp.md
+++ b/docs/subsystems/mcp.md
@@ -86,7 +86,9 @@ type McpResourceRequest =
/** One configured server's resource access, owned by its MCP connection plugin. */
interface McpResourceProvider {
/**
- * Run an operation against one live connection generation.
+ * Run an operation against one live connection generation. The resource tools
+ * dispatch in parallel, so one provider may receive several concurrent requests;
+ * each must settle independently.
* @param request - MCP resource method and parameters.
* @param exec - caller identity and cancellation for this invocation.
* @returns the protocol result as lossless JSON.
diff --git a/docs/subsystems/mcp.zh.md b/docs/subsystems/mcp.zh.md
index 216db4413a..a2eecf3f11 100644
--- a/docs/subsystems/mcp.zh.md
+++ b/docs/subsystems/mcp.zh.md
@@ -86,7 +86,9 @@ type McpResourceRequest =
/** One configured server's resource access, owned by its MCP connection plugin. */
interface McpResourceProvider {
/**
- * Run an operation against one live connection generation.
+ * Run an operation against one live connection generation. The resource tools
+ * dispatch in parallel, so one provider may receive several concurrent requests;
+ * each must settle independently.
* @param request - MCP resource method and parameters.
* @param exec - caller identity and cancellation for this invocation.
* @returns the protocol result as lossless JSON.
diff --git a/docs/subsystems/session.i18n.yaml b/docs/subsystems/session.i18n.yaml
index b4cd4bba34..2c56dc6e76 100644
--- a/docs/subsystems/session.i18n.yaml
+++ b/docs/subsystems/session.i18n.yaml
@@ -39,8 +39,11 @@
en: 13820e0611b2e141
zh: 2aafb1e5e3dc42f6
/sessions/session-public-api:
- en: 04e9982948d9560d
- zh: 221961cadebc6fb1
+ en: 2dbf1890d8c38701
+ zh: 9948971a092b3243
+/sessions/session-public-api/sessioneventinput-one-proposed-event:
+ en: 90c3989856a301dc
+ zh: 839a494d5b2b1fa4
/sessions/derived-history-derivemessages-and-deriveeventmessage:
en: 45d1a9ee6d610ac5
zh: 79c061252fde4ceb
diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md
index 7a0ad908d9..c1651bf32e 100644
--- a/docs/subsystems/session.md
+++ b/docs/subsystems/session.md
@@ -447,6 +447,17 @@ interface SurfaceFoldResult {
## `Session` public API
+### `SessionEventInput` — one proposed event
+
+```ts type-equiv
+/** One positional event call proposed for append, without assigned sequence or time. */
+type SessionEventInput = {
+ [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent] : []]
+}[SessionEventType]
+```
+
+Each array member keeps its event type paired with its payload and requires surface intent only for message-producing events.
+
The body-stripped declaration keeps the plain class's detached factory, state accessors, append method, and history projections synchronized with source. Store operations remain in the generated [`ctx.sessions` section](#ctxsessions--sessionstore).
```ts public-api
@@ -573,6 +584,18 @@ declare class Session {
isOwnSeq(seq: SessionSeq): boolean;
/** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
get seq(): SessionLogOffset;
+ /** Current event while synchronously notifying a batch's observers. */
+ get currentBatchPublication(): SessionEvent | undefined;
+ /**
+ * Append consecutive events together after validating every candidate and dispatch.
+ * Observers read the complete committed log and final message surface.
+ * Listener registration changes during publication take effect on the next append.
+ * Persistence listeners retain their own durability rules.
+ * @param inputs - event payloads and surface intents in commit order. An empty array records no events.
+ * @returns immutable committed events in the same order.
+ * @throws if the Session cannot accept writes, including an empty append, or any candidate or synchronous dispatch validation fails.
+ */
+ append(inputs: readonly SessionEventInput[]): readonly SessionEvent[];
/**
* Append one typed event to the log and synchronously notify observers via
* the store-owned, module-private publication hooks. The hot path never blocks
@@ -1384,13 +1407,16 @@ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/i
#### `session/event` — emit
-Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context.
+Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Array append commits every member before publishing them in order; `session.seq` and `session.surface` already include the complete batch. `session.currentBatchPublication` identifies the member being delivered. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context.
```ts cordis-catalog
/**
* Post-commit, fire-and-forget append feed. The listener snapshot resolves
* before the log push, but callbacks run after it; observer failures are
* logged and contained without making the committed append fail.
+ * Array append commits every member before publishing them in order;
+ * `session.seq` and `session.surface` already include the complete batch.
+ * `session.currentBatchPublication` identifies the member being delivered.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
* receive only events from sessions entered through that agent's context.
* @param session - the session whose log grew.
diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md
index ec9fab642f..e359382e86 100644
--- a/docs/subsystems/session.zh.md
+++ b/docs/subsystems/session.zh.md
@@ -449,6 +449,17 @@ interface SurfaceFoldResult {
## `Session` 公共 API
+### `SessionEventInput`:一个候选事件
+
+```ts type-equiv
+/** One positional event call proposed for append, without assigned sequence or time. */
+type SessionEventInput = {
+ [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent] : []]
+}[SessionEventType]
+```
+
+数组中的每个成员将事件类型与对应载荷配对,且仅对产生消息的事件要求surface意图。
+
去除方法体的声明与源码中的普通类保持同步,覆盖其脱离态工厂、状态访问器、append 方法和历史投影。存储操作仍由生成的 [`ctx.sessions` 小节](#ctxsessions--sessionstore)记录。
```ts public-api
@@ -575,6 +586,18 @@ declare class Session {
isOwnSeq(seq: SessionSeq): boolean;
/** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
get seq(): SessionLogOffset;
+ /** Current event while synchronously notifying a batch's observers. */
+ get currentBatchPublication(): SessionEvent | undefined;
+ /**
+ * Append consecutive events together after validating every candidate and dispatch.
+ * Observers read the complete committed log and final message surface.
+ * Listener registration changes during publication take effect on the next append.
+ * Persistence listeners retain their own durability rules.
+ * @param inputs - event payloads and surface intents in commit order. An empty array records no events.
+ * @returns immutable committed events in the same order.
+ * @throws if the Session cannot accept writes, including an empty append, or any candidate or synchronous dispatch validation fails.
+ */
+ append(inputs: readonly SessionEventInput[]): readonly SessionEvent[];
/**
* Append one typed event to the log and synchronously notify observers via
* the store-owned, module-private publication hooks. The hot path never blocks
@@ -1388,13 +1411,16 @@ Source: [`packages/core/session/src/index.ts`](../../packages/core/session/src/i
#### `session/event` — emit
-Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context.
+Post-commit, fire-and-forget append feed. The listener snapshot resolves before the log push, but callbacks run after it; observer failures are logged and contained without making the committed append fail. Array append commits every member before publishing them in order; `session.seq` and `session.surface` already include the complete batch. `session.currentBatchPublication` identifies the member being delivered. Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners receive only events from sessions entered through that agent's context.
```ts cordis-catalog
/**
* Post-commit, fire-and-forget append feed. The listener snapshot resolves
* before the log push, but callbacks run after it; observer failures are
* logged and contained without making the committed append fail.
+ * Array append commits every member before publishing them in order;
+ * `session.seq` and `session.surface` already include the complete batch.
+ * `session.currentBatchPublication` identifies the member being delivered.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
* receive only events from sessions entered through that agent's context.
* @param session - the session whose log grew.
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml
index b563eb7323..b748855bae 100644
--- a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml
+++ b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.i18n.yaml
@@ -9,8 +9,8 @@
en: bc309764ab7b8b98
zh: 20fdfbce76706025
/worktree-cleanup-on-archive/change:
- en: 05f27e166f2dbb40
- zh: a320ac6252fd2e38
+ en: 990690039f918e72
+ zh: 8e23fbabf88a777f
/worktree-cleanup-on-archive/migration:
- en: c9b2fca77d02e07f
- zh: a4228d7f22fb7e35
+ en: 05f29b760cb99ae9
+ zh: 33f181ac2a582bdf
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md
index 77912a2e71..74f3986277 100644
--- a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md
+++ b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.md
@@ -9,13 +9,13 @@ English | [中文](guide.zh.md)
## Change
-Archiving a Session previously retained its checkout. The worktree service now records each checkout it creates as a `plugin:worktree/created` record and, when the Session that created one is archived, removes it with a non-force `git worktree remove` when no unarchived Session refers to it, its creator's policy is not read-only, and Git finds no tracked changes, untracked files, hidden index flags, submodules, locks, or detached HEAD. Ignored files such as `node_modules` do not retain it. Branches and commits remain. The service's `retainOnArchive` setting, off by default, keeps every checkout instead. Checkouts created before this release have no such event and are never swept, nor are Sessions archived earlier. See the [worktree service](../../../../packages/experimental/worktree/README.md).
+Archiving a Session previously retained its checkout. The worktree service now records each checkout it creates as a `plugin:worktree/created` record and, when the Session that created one is archived, removes it with a non-force `git worktree remove` when no unarchived Session refers to it, its creator's policy is not read-only, and Git finds no tracked changes, untracked files, initialized submodules, locks, or detached HEAD. Ignored files such as `node_modules` and edits to skip-worktree or assume-unchanged files, which `git status` hides, do not retain it; Git discards them. Git refuses to remove a checkout holding a committed embedded repository, so that checkout stays and the archive notice reports a failed cleanup. Branches and commits remain. The service's `retainOnArchive` setting, off by default, keeps every checkout instead. Checkouts created before this release have no such event and are never swept, nor are Sessions archived earlier. See the [worktree service](../../../../packages/experimental/worktree/README.md).
The Forge bundle mounts one `worktree` service for both the panel and the `create_worktree` tool. The `forge-worktree` row and the `optional-forge-panel` group that isolated a second service are gone; the panel is the top-level `forge-panel` row.
## Migration
-1. If a checkout must remain available outside DSH, keep its Session unarchived, lock it with `git worktree lock ` before archiving, or turn on **Keep worktrees when archiving** on the Forge bundle's worktree row of the Plugins page (`retainOnArchive`), which keeps every checkout. Ignored files are not kept.
+1. If a checkout must remain available outside DSH, keep its Session unarchived, lock it with `git worktree lock ` before archiving, or turn on **Keep worktrees when archiving** on the Forge bundle's worktree row of the Plugins page (`retainOnArchive`), which keeps every checkout. Ignored files are not kept, nor are edits to skip-worktree or assume-unchanged files: commit those edits, or clear the flags with `git update-index --no-skip-worktree` or `--no-assume-unchanged`, before archiving.
2. To resume an archived Session whose checkout was removed, unarchive it and use **Restore worktree**. The retained branch is checked out at the recorded path.
3. In a profile's `cordis.patch.yml`, move any `forge-worktree` override to the `worktree` row and any `optional-forge-panel` override to the `forge-panel` row; a `disabled: true` on `forge-panel` turns off the panel alone.
4. Confirm the branch and commits are present with `git branch --list` and that **Restore worktree** makes the recorded checkout available. Session logs require no migration.
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md
index 5edf966298..d5295cfb18 100644
--- a/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md
+++ b/docs/upgrade-guide/v0.2.2-rc.1/archive-worktrees/guide.zh.md
@@ -9,13 +9,13 @@ description: "归档 Session 可以删除其干净的工作树并保留分支,
## 变更
-归档 Session 以前会保留检出目录。工作树服务现在把它创建的每个检出目录记录为 `plugin:worktree/created` Session 事件;当创建它的 Session 被归档时,若没有未归档的 Session 引用该目录、创建者的策略不是只读,且 Git 未发现跟踪文件改动、未跟踪文件、隐藏的索引标记、子模块、锁或分离 HEAD,就用不带 force 的 `git worktree remove` 删除它。`node_modules` 之类被忽略的文件不会保留目录。分支和提交仍会保留。服务的 `retainOnArchive` 设置默认关闭,开启后改为保留所有检出目录。本版本之前创建的检出目录没有该事件,不会被扫描;更早归档的 Session 也不会。参见[工作树服务](../../../../packages/experimental/worktree/README.zh.md)。
+归档 Session 以前会保留检出目录。工作树服务现在把它创建的每个检出目录记录为 `plugin:worktree/created` Session 事件;当创建它的 Session 被归档时,若没有未归档的 Session 引用该目录、创建者的策略不是只读,且 Git 未发现跟踪文件改动、未跟踪文件、已初始化的子模块、锁或分离 HEAD,就用不带 force 的 `git worktree remove` 删除它。`node_modules` 之类被忽略的文件,以及 `git status` 不报告的 skip-worktree 或 assume-unchanged 文件改动,都不会保留目录,Git 会丢弃它们。含已提交内嵌仓库的检出目录会被 Git 拒绝删除,因此保留,归档提示显示清理失败。分支和提交仍会保留。服务的 `retainOnArchive` 设置默认关闭,开启后改为保留所有检出目录。本版本之前创建的检出目录没有该事件,不会被扫描;更早归档的 Session 也不会。参见[工作树服务](../../../../packages/experimental/worktree/README.zh.md)。
Forge bundle 为面板和 `create_worktree` 工具挂载同一个 `worktree` 服务。隔离第二个服务的 `forge-worktree` 行与 `optional-forge-panel` 组已移除;面板是顶层的 `forge-panel` 行。
## 迁移
-1. 如果检出目录必须供 DSH 之外继续使用,请保持其 Session 未归档,在归档前用 `git worktree lock ` 锁定它,或在插件页 Forge 套件的 worktree 行上开启**归档时不删除工作树**(`retainOnArchive`),它会保留所有检出目录。被忽略的文件不会保留。
+1. 如果检出目录必须供 DSH 之外继续使用,请保持其 Session 未归档,在归档前用 `git worktree lock ` 锁定它,或在插件页 Forge 套件的 worktree 行上开启**归档时不删除工作树**(`retainOnArchive`),它会保留所有检出目录。被忽略的文件不会保留,skip-worktree 或 assume-unchanged 文件的改动也不会:归档前请提交这些改动,或用 `git update-index --no-skip-worktree` 或 `--no-assume-unchanged` 清除标记。
2. 要继续使用已归档且检出目录已删除的 Session,请取消归档并使用**恢复工作树**。保留的分支会在记录的路径重新检出。
3. 在 profile 的 `cordis.patch.yml` 中,把针对 `forge-worktree` 的覆盖迁到 `worktree` 行,把针对 `optional-forge-panel` 的覆盖迁到 `forge-panel` 行;对 `forge-panel` 设置 `disabled: true` 可以只关闭面板。
4. 用 `git branch --list` 确认分支与提交仍然存在,并确认**恢复工作树**使记录的检出目录重新可用。Session 日志无需迁移。
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml
new file mode 100644
index 0000000000..9a48f7428c
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml
@@ -0,0 +1,16 @@
+# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
+# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
+# After editing either side, bring the other along and re-record with:
+# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md
+/:
+ en: 5ebb4c8a6b20b644
+ zh: 22a8983d06fa5789
+/macos-hover-keeps-the-system-pointer-in-place-by-default:
+ en: 6833a7851486f10d
+ zh: 22983f326fb725ce
+/macos-hover-keeps-the-system-pointer-in-place-by-default/change:
+ en: 55c3070b24b4ad39
+ zh: 2555d127b0f4e4a0
+/macos-hover-keeps-the-system-pointer-in-place-by-default/migration:
+ en: 1f0ab7e8741e821f
+ zh: f59adc3a23ebcb43
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md
new file mode 100644
index 0000000000..f7191cc254
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md
@@ -0,0 +1,18 @@
+---
+kind: upgrade-guide
+description: "macOS mouseMove requires AX alternate UI by default and returns HOVER_UNAVAILABLE instead of moving the user's cursor."
+---
+
+# macOS hover keeps the system pointer in place by default
+
+English | [中文](guide.zh.md)
+
+## Change
+
+On macOS, `win.mouseMove(target)` uses an enabled element or ancestor that advertises both `AXShowAlternateUI` and `AXShowDefaultUI`. Without that route, previous versions moved the visible system cursor. The default now returns `HOVER_UNAVAILABLE` before sending input.
+
+## Migration
+
+1. For an available control, use its advertised action or click it directly. Use browser tools for web content that requires page hover.
+2. To restore visible pointer movement, set `systemPointerHover: true` in the `config` of the macOS provider entry (`id: cua`) in your profile's `cordis.patch.yml`. Preserve the entry's other settings. If you set `helperPath`, rebuild the custom helper so it accepts `systemPointerHover` in the connection handshake. Restart the profile.
+3. Call `win.mouseMove` on a foreground, unobscured control without AX alternate UI. The opt-in result reports `hoverRoute: "system-pointer"` and `systemPointerMoved: true`. Keep the default to avoid disturbing the user's cursor.
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md
new file mode 100644
index 0000000000..713ae43fb3
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md
@@ -0,0 +1,18 @@
+---
+kind: upgrade-guide
+description: "macOS 的 mouseMove 默认要求控件支持 AX 备用界面,否则返回 HOVER_UNAVAILABLE,保留用户的光标位置。"
+---
+
+# macOS 悬停默认保留系统光标位置
+
+[English](guide.md) | 中文
+
+## 变更
+
+在 macOS 上,`win.mouseMove(target)` 会查找已启用且同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的控件或祖先。找不到时,旧版会移动系统光标,新版默认在发送输入前返回 `HOVER_UNAVAILABLE`。
+
+## 迁移
+
+1. 对已经可用的控件,可执行它声明的动作或直接点击。需要网页悬停时可用浏览器工具。
+2. 要恢复可见光标移动,在 profile 的 `cordis.patch.yml` 中,给 macOS 提供方条目(`id: cua`)的 `config` 添加 `systemPointerHover: true`。保留该条目的其他设置。如果指定了 `helperPath`,先重新构建自定义 helper,使其在建立连接时能读取 `systemPointerHover`,然后重启 profile。
+3. 对前台未受遮挡且不提供 AX 备用界面的控件调用 `win.mouseMove`。启用配置时,结果为 `hoverRoute: "system-pointer"` 和 `systemPointerMoved: true`。要保留用户的光标位置,使用默认配置。
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml
index 8d9654901c..a017e7f82b 100644
--- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml
+++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml
@@ -12,5 +12,5 @@
en: e5d1027faa55adba
zh: 4b88ad6a70977fb3
/native-cua-application-and-window-api/migration:
- en: 6cabae699a340845
- zh: f2256751518c5e36
+ en: a63e88dce467d6ee
+ zh: fc25bb283ca0eaff
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md
index 5023ac9ff0..2675699a71 100644
--- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md
+++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md
@@ -15,9 +15,9 @@ Providers supply startup capabilities alongside their platform guidance. The nat
## Migration
-1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`.
+1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action.
2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it.
3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active.
-4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`.
+4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` to hold a key across tool calls. To request one repeat, send another down for a non-modifier key held by that execution. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying.
5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID.
6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls.
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md
index 880034fbd8..b4551f624b 100644
--- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md
+++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md
@@ -15,9 +15,9 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享
## 迁移
-1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。
+1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。
2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。
3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。
-4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。
+4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。
5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。
6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.i18n.yaml
new file mode 100644
index 0000000000..cc9434e9c3
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.i18n.yaml
@@ -0,0 +1,16 @@
+# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
+# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
+# After editing either side, bring the other along and re-record with:
+# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md
+/:
+ en: 0c7dd958bce09e16
+ zh: 3b3c85a2152294ec
+/update-replacements-for-session-append:
+ en: 5cc8a72cf2203e52
+ zh: 22976024cf5453eb
+/update-replacements-for-session-append/change:
+ en: 51fbd9ed1cd50cdf
+ zh: 103d3ac9b631414e
+/update-replacements-for-session-append/migration:
+ en: 19c39d4582b09f41
+ zh: 4345d25a52dec57e
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md
new file mode 100644
index 0000000000..db74ea4789
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.md
@@ -0,0 +1,17 @@
+---
+kind: upgrade-guide
+description: "Code that replaces Session.append must implement both the single-event and array overloads."
+---
+
+# Update replacements for `Session.append`
+
+English | [中文](guide.zh.md)
+
+## Change
+
+In v0.2.2-rc.1, `Session.append` had a single call signature. It now accepts either one typed event call or an array of event tuples. Ordinary single-event calls still compile. Test doubles and wrappers assigned to `Session['append']` must support both overloads.
+
+## Migration
+
+1. For a wrapper around `Session.append`, preserve both overloads by wrapping the original function with a `Proxy` and forwarding from its `apply` trap with `Reflect.apply`. For a test double that only accepts one event, type the single-event helper separately and call it from the relevant test.
+2. Typecheck assignments to `Session['append']`. Call replacements with both `append('turn/start', { turn: 1 })` and `append([['turn/start', { turn: 1 }]])` and verify the first returns one event and the second an array.
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md
new file mode 100644
index 0000000000..c71289c7f7
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/session-append-overloads/guide.zh.md
@@ -0,0 +1,17 @@
+---
+kind: upgrade-guide
+description: "替换 Session.append 的代码必须实现单事件和数组两种重载。"
+---
+
+# 更新 `Session.append` 的替代实现
+
+[English](guide.md) | 中文
+
+## 变更
+
+在 v0.2.2-rc.1 中,`Session.append` 只有一个调用签名。现在它可接收一个带类型的事件调用,也可接收事件元组数组。普通单事件调用仍可编译。赋值给 `Session['append']` 的测试替身和包装函数必须支持两种重载。
+
+## 迁移
+
+1. 包装 `Session.append` 时,用 `Proxy` 包装原函数,在 `apply` 拦截器内用 `Reflect.apply` 转发,以保留两种重载。若测试替身只接收单个事件,给该辅助函数单独声明类型并在相应测试中调用。
+2. 检查赋值给 `Session['append']` 的代码能通过类型检查。分别以 `append('turn/start', { turn: 1 })` 和 `append([['turn/start', { turn: 1 }]])` 调用替代实现,验证前者返回一个事件,后者返回数组。
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml
new file mode 100644
index 0000000000..fb72a12add
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml
@@ -0,0 +1,16 @@
+# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
+# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
+# After editing either side, bring the other along and re-record with:
+# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md
+/:
+ en: fda192f58c50cd90
+ zh: 2ebe5d7389eb9689
+/built-in-configurations-disable-agent-interruption:
+ en: c253388db5ba6f5a
+ zh: af138bbc7bfd31b4
+/built-in-configurations-disable-agent-interruption/change:
+ en: 76b23fa746332e06
+ zh: d30315eab3aa53bd
+/built-in-configurations-disable-agent-interruption/migration:
+ en: 0f5bd67305b455dc
+ zh: a98770b64686d612
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md
new file mode 100644
index 0000000000..ddcd5a2149
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md
@@ -0,0 +1,27 @@
+---
+kind: upgrade-guide
+description: "Built-in configurations disable interrupt_agent for subagents and Team mode."
+---
+
+# Built-in configurations disable agent interruption
+
+English | [中文](guide.zh.md)
+
+## Change
+
+The base bundle and the Web `standard`, `cordis`, and `ptc` presets now set `config.interrupt: false` on their `tool-subagent-control` rows. Models using these configurations no longer receive `interrupt_agent`, including in Team mode. Messaging, discovery, inbox waiting, and the subagent service interruption API remain available. The plugin's own default remains `true`; independent compositions that omit the setting retain interruption.
+
+## Migration
+
+Keep `interrupt: false` to retain the built-in behavior. To restore interruption:
+
+1. Edit `$DSH_HOME/profiles//cordis.patch.yml`. For base-backed profiles such as `headless`, `sdk`, and `acp`, append:
+
+ ```yaml
+ - id: tool-subagent-control
+ config:
+ interrupt: true
+ ```
+
+2. For `web` or `desktop`, instead override each required declaration: `preset-standard`, `preset-cordis`, or `preset-ptc`. Copy that declaration's complete `config` from the installed `@deepseek-ai/dsh-web-app` bundle's `presets/.patch.yml` (source: [standard](../../../../packages/bundle/web-app/presets/standard.patch.yml), [cordis](../../../../packages/bundle/web-app/presets/cordis.patch.yml), [ptc](../../../../packages/bundle/web-app/presets/ptc.patch.yml)). If your profile already overrides the declaration, edit that override to preserve your customizations. A patch replaces the whole `config`: retain `id`, `order`, and the entire `plugins` list, including the `delegation` group. Within that group's `config`, change the `tool-subagent-control` row's `config.interrupt` to `true`. Use the declaration's outer ID as the patch target, following [Change a shipped preset](../../../../packages/preset/agent-preset/skills/dsh-doc/references/compositions.md#change-a-shipped-preset). A top-level patch targeting `tool-subagent-control` does not reach the preset's child row; it only changes the disabled Host row. Leave that Host row disabled.
+3. Restart the profile and create a new Session using the changed preset; existing Sessions retain their preset revision. Confirm that the model's tool definitions include `interrupt_agent`, `send_message`, `list_agents`, and `wait_agent`.
diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md
new file mode 100644
index 0000000000..7f9455936a
--- /dev/null
+++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md
@@ -0,0 +1,27 @@
+---
+kind: upgrade-guide
+description: "内置配置关闭普通 subagent 和 Team 模式的 interrupt_agent。"
+---
+
+# 内置配置关闭 agent 中断
+
+[English](guide.md) | 中文
+
+## 变更
+
+base 组合包及 Web 的 `standard`、`cordis`、`ptc` preset 现在为各自的 `tool-subagent-control` 行设置 `config.interrupt: false`。使用这些配置的模型不再获得 `interrupt_agent`,也包括 Team 模式。消息、发现、收件箱等待和 subagent 服务的中断 API 仍然可用。插件自身的默认值仍为 `true`;省略该设置的独立组合仍提供中断工具。
+
+## 迁移
+
+保留 `interrupt: false` 可维持内置行为。如需恢复中断工具:
+
+1. 编辑 `$DSH_HOME/profiles//cordis.patch.yml`。对于 `headless`、`sdk`、`acp` 等基于 base 的 profile,追加:
+
+ ```yaml
+ - id: tool-subagent-control
+ config:
+ interrupt: true
+ ```
+
+2. 对于 `web` 或 `desktop`,改为覆盖需要启用的声明行:`preset-standard`、`preset-cordis` 或 `preset-ptc`。从已安装的 `@deepseek-ai/dsh-web-app` 组合包的 `presets/.patch.yml` 中复制该声明的完整 `config`(源码:[standard](../../../../packages/bundle/web-app/presets/standard.patch.yml)、[cordis](../../../../packages/bundle/web-app/presets/cordis.patch.yml)、[ptc](../../../../packages/bundle/web-app/presets/ptc.patch.yml))。如果 profile 已经覆盖该声明,编辑已有覆盖以保留自定义配置。patch 会替换整个 `config`:保留 `id`、`order` 和完整的 `plugins` 列表,包括 `delegation` 组。在该组的 `config` 内,将 `tool-subagent-control` 行的 `config.interrupt` 改为 `true`。以声明的外层 ID 为 patch 目标,写法参见[修改内置 preset](../../../../packages/preset/agent-preset/skills/dsh-doc/references/compositions.md#change-a-shipped-preset)。顶层以 `tool-subagent-control` 为目标的 patch 无法修改 preset 内的子行,只会修改已禁用的 Host 行。保持该 Host 行禁用。
+3. 重启 profile,并使用修改后的 preset 创建新 Session;已有 Session 保留原 preset 修订。确认模型的工具定义包含 `interrupt_agent`、`send_message`、`list_agents` 和 `wait_agent`。
diff --git a/packages/bundle/base/README.i18n.yaml b/packages/bundle/base/README.i18n.yaml
index b475ce9b82..bd859ea112 100644
--- a/packages/bundle/base/README.i18n.yaml
+++ b/packages/bundle/base/README.i18n.yaml
@@ -21,8 +21,8 @@
en: 0f971f7ac7c09139
zh: ceb866da681c709c
/deepseek-ai-dsh-base/use-this-package/what-you-get:
- en: ab2fb279cdd726c5
- zh: ae84c61bddc00ddf
+ en: dd7e69c32d06cb6a
+ zh: 9301140a8e023b41
/deepseek-ai-dsh-base/use-this-package/shell-tools-per-platform:
en: 2dce12f82d6ee955
zh: d4599eb899a3cd88
diff --git a/packages/bundle/base/README.md b/packages/bundle/base/README.md
index 5b5f163694..b2ab5dcf1e 100644
--- a/packages/bundle/base/README.md
+++ b/packages/bundle/base/README.md
@@ -53,6 +53,8 @@ Both `subagent` and `subagent_fork` create managed children and return the child
The bundle also mounts [Agent Teams](../../team/agent-team/README.md) and its task tools. Team mode defaults off per root Session; the root conversation’s **Use Agent Teams** menu switch enables collaboration for that tree without changing the profile.
+The `tool-subagent-control` row sets `interrupt: false`, so ordinary subagents and Team mode omit `interrupt_agent`. Set `config.interrupt: true` on that row in a later patch to enable it. The plugin itself still defaults to `true`.
+
The built-in `working_directory` tool changes the directory for subsequent operations while existing processes and write permissions remain independent. Current directory information appears in user context. Default file editing uses `read`, `write`, and `edit`. The `str_replace_editor` tool remains available as an explicit opt-in. To add it to a base-backed profile, put this entry in the profile, home, or invocation patch:
```yaml
diff --git a/packages/bundle/base/README.zh.md b/packages/bundle/base/README.zh.md
index 62d6ad03b9..223b88bb0a 100644
--- a/packages/bundle/base/README.zh.md
+++ b/packages/bundle/base/README.zh.md
@@ -53,6 +53,8 @@ kind: "package-bundle"
此 bundle 还挂载 [Agent Teams](../../team/agent-team/README.zh.md) 及其任务工具。每个根 Session 的 Team 模式默认关闭;根会话菜单中的**使用智能体团队**开关为当前树开启协作,无需修改 profile。
+`tool-subagent-control` 行显式设置 `interrupt: false`,因此普通 subagent 和 Team 模式均不提供 `interrupt_agent`。在后续 patch 中为该行设置 `config.interrupt: true` 可启用它。插件自身的默认值仍为 `true`。
+
内置 `working_directory` 工具改变后续操作使用的目录,已有进程与写权限保持独立。当前目录信息出现在用户上下文中。默认文件编辑使用 `read`、`write` 和 `edit`。`str_replace_editor` 工具仍可显式启用。要将它加入基于 base 的 profile,请在 profile、home 或逐次调用 patch 中添加以下条目:
```yaml
diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml
index 26082074f3..18286618f9 100644
--- a/packages/bundle/base/cordis.patch.yml
+++ b/packages/bundle/base/cordis.patch.yml
@@ -385,6 +385,8 @@
# separately loaded follow-up tool registers the one global `send_message`.
- id: tool-subagent-control
name: '@deepseek-ai/dsh-tool-subagent-control'
+ config:
+ interrupt: false
- id: tool-subagent
name: '@deepseek-ai/dsh-tool-subagent'
diff --git a/packages/bundle/headless/tests/terminal-failures.spec.ts b/packages/bundle/headless/tests/terminal-failures.spec.ts
index c92f095334..959eebb401 100644
--- a/packages/bundle/headless/tests/terminal-failures.spec.ts
+++ b/packages/bundle/headless/tests/terminal-failures.spec.ts
@@ -7,7 +7,7 @@ import AgentDefaultModelConfig from '@deepseek-ai/dsh-agent-default-model'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
import { createUserMessage } from '@deepseek-ai/dsh-llm'
-import { SessionId } from '@deepseek-ai/dsh-session'
+import { SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
import { apply } from '../src/index.ts'
import { internals } from '../src/runner-internals.ts'
@@ -62,11 +62,10 @@ describe('headless terminal failures', () => {
test.ctx.on('agent/error', ({ error }) => { failures.push(error) })
const waitForTreeWork = vi.fn().mockImplementationOnce((parent: Agent) => {
const append = parent.session.append.bind(parent.session)
- const failAppend: typeof parent.session.append = (type, data, ...intent) => {
+ vi.spyOn(parent.session, 'append').mockImplementation((type, data, ...intent) => {
if (type === failedEvent) throw new Error(`summary ${failedEvent} unavailable`)
- return append(type, data, ...intent)
- }
- vi.spyOn(parent.session, 'append').mockImplementation(failAppend)
+ return Reflect.apply(append, undefined, [type, data, ...intent]) as SessionEvent
+ })
followup(parent)
return Promise.resolve(true)
}).mockResolvedValue(false)
@@ -110,14 +109,13 @@ describe('headless terminal failures', () => {
const waitForTreeWork = vi.fn().mockImplementationOnce((parent: Agent) => {
const append = parent.session.append.bind(parent.session)
let failed = false
- const failAppend: typeof parent.session.append = (type, data, ...intent) => {
+ vi.spyOn(parent.session, 'append').mockImplementation((type, data, ...intent) => {
if (!failed && type === failedEvent) {
failed = true
throw new Error(`summary ${failedEvent} unavailable`)
}
- return append(type, data, ...intent)
- }
- vi.spyOn(parent.session, 'append').mockImplementation(failAppend)
+ return Reflect.apply(append, undefined, [type, data, ...intent]) as SessionEvent
+ })
followup(parent)
return Promise.resolve(true)
}).mockImplementationOnce((parent: Agent) => {
diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml
index cef33b6aac..1a650beec8 100644
--- a/packages/bundle/web-app/README.i18n.yaml
+++ b/packages/bundle/web-app/README.i18n.yaml
@@ -21,8 +21,8 @@
en: e3cac911f080d8ef
zh: 60749e9f5c39c1bc
/deepseek-ai-dsh-web-app/use-this-package/configuration:
- en: b1787804544f2587
- zh: ce09d2c248ffd999
+ en: f876c60a37e3cb0e
+ zh: 42a535554fe4bc40
/deepseek-ai-dsh-web-app/use-this-package/listening-trust-and-public-deployments:
en: e6ddea1d2fc40501
zh: ff08b6fa3fc24136
diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md
index d80b45463d..aed6c22d91 100644
--- a/packages/bundle/web-app/README.md
+++ b/packages/bundle/web-app/README.md
@@ -61,6 +61,8 @@ The `minimal` agent preset uses a persistent shell, the `read_image` tool, and a
The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-web-app) lists this runtime plugin's accepted fields and their JSDoc. The shipped composition inserts the `schedule` service row and the `ui-schedule` task page row, while the clock reading and the four reminder tools belong to the `standard`, `cordis`, and `ptc` presets. The `tool-subagent` and `tool-subagent-fork` rows in those presets deny the four tools, so a delegated child's scope never lists them.
+The `standard`, `cordis`, and `ptc` presets set `config.interrupt: false` on their `tool-subagent-control` rows. To expose `interrupt_agent`, including in Team mode, override the relevant preset declaration as described in the [migration steps](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md); changing the disabled Host row does not change preset tools.
+
### Listening, trust, and public deployments
diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md
index 8952c0d315..80b1fd2216 100644
--- a/packages/bundle/web-app/README.zh.md
+++ b/packages/bundle/web-app/README.zh.md
@@ -61,6 +61,8 @@ dsh --profile web --no-open --port 8080
生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-web-app)列出了本运行时插件接受的字段及其 JSDoc。随发行版交付的组合插入 `schedule` 服务行与 `ui-schedule` 任务页面行,时钟读数与四个提醒工具则属于 `standard`、`cordis` 与 `ptc` 三个 preset。这三个 preset 的 `tool-subagent` 与 `tool-subagent-fork` 两行都 deny 这四个工具,因此被委派子 agent 的作用域不会列出它们。
+`standard`、`cordis` 和 `ptc` 三个 preset 在各自的 `tool-subagent-control` 行中设置 `config.interrupt: false`。如需提供 `interrupt_agent`(也适用于 Team 模式),按[迁移步骤](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md)覆盖相应 preset 声明;修改已禁用的 Host 行不会改变 preset 的工具。
+
### 监听、信任与公开部署
diff --git a/packages/bundle/web-app/presets/cordis.patch.yml b/packages/bundle/web-app/presets/cordis.patch.yml
index d0c9f7f419..912fb7d3ac 100644
--- a/packages/bundle/web-app/presets/cordis.patch.yml
+++ b/packages/bundle/web-app/presets/cordis.patch.yml
@@ -90,6 +90,8 @@
config:
- id: tool-subagent-control
name: '@deepseek-ai/dsh-tool-subagent-control'
+ config:
+ interrupt: false
- id: tool-subagent
name: '@deepseek-ai/dsh-tool-subagent'
config:
diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml
index 86ccc4f0ad..7a9329e5db 100644
--- a/packages/bundle/web-app/presets/ptc.patch.yml
+++ b/packages/bundle/web-app/presets/ptc.patch.yml
@@ -91,6 +91,8 @@
config:
- id: tool-subagent-control
name: '@deepseek-ai/dsh-tool-subagent-control'
+ config:
+ interrupt: false
- id: tool-subagent
name: '@deepseek-ai/dsh-tool-subagent'
config:
diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml
index d0bca7e336..a3532d0f3a 100644
--- a/packages/bundle/web-app/presets/standard.patch.yml
+++ b/packages/bundle/web-app/presets/standard.patch.yml
@@ -94,6 +94,8 @@
config:
- id: tool-subagent-control
name: '@deepseek-ai/dsh-tool-subagent-control'
+ config:
+ interrupt: false
- id: tool-subagent
name: '@deepseek-ai/dsh-tool-subagent'
config:
diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml
index 964aa397f7..9703f06e32 100644
--- a/packages/client/ui-chat/README.i18n.yaml
+++ b/packages/client/ui-chat/README.i18n.yaml
@@ -33,8 +33,8 @@
en: 7cc6692b879aa500
zh: e924733c88b526c9
/deepseek-ai-dsh-client-ui-chat/grouped-rendering:
- en: e2b02942a55fb669
- zh: a38bbee0cc69ae4e
+ en: f6d8bbae13a1a8f8
+ zh: 96c8f400c215e33d
/deepseek-ai-dsh-client-ui-chat/scroll-ownership:
en: 983f27806146e9ea
zh: bb60333c7a6736ed
diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md
index 723c0a9ec7..5c736a587a 100644
--- a/packages/client/ui-chat/README.md
+++ b/packages/client/ui-chat/README.md
@@ -127,7 +127,7 @@ Live tool deltas share reasoning's frame-batched publication; durable calls and
The process group uses a stable `div` layout box, a scroll body, and an uncapped content box that reports growth inside the body. Business styles must adapt spacing within and across groups, including hidden or empty members and the answer-spacing exception. The `conversation.chat.flow` slot adds a `display: contents` DOM anchor; row selectors match that anchor directly, without repeating its column ancestry. The running status shares the rows' parent, so its divider uses the same visible-sibling rules. The anchor contributes no spacing of its own. The earlier-history control directly precedes the flow anchor; their sibling relationship supplies the leading gap. CSS variables do not belong in the Group Definition.
-Running group titles, reasoning previews, tool and command rows, the active retry line, and the bottom running status use the shared [TextShimmer](../ui-primitives/README.md#component-catalog). Each row’s text shares one left-to-right highlight, including collapsed group titles; icons and hover chevrons retain their base appearance. Ordinary flow rows sit 4px apart. An expanded group title has 8px before its content, Assistant responses have 12px from adjacent process rows, and completed-Turn duration/status controls have 16px from their input and from a directly following visible row. A reply that follows the control after folded rows keeps the 12px reply gap, so folding never changes its spacing. Hidden and empty rows, including retained empty slot anchors, add no gap. The running “Deep diving” text retains its blue base while its theme-specific highlight sweeps across it.
+Running group titles, reasoning previews, tool and command rows, the active retry line, and the bottom running status use the shared [TextShimmer](../ui-primitives/README.md#component-catalog). Each row’s text shares one left-to-right highlight, including collapsed group titles; icons and hover chevrons retain their base appearance. Ordinary flow rows sit 4px apart, including adjacent reasoning rows of one Assistant message. An expanded group title has 8px before its content, Assistant responses have 12px from adjacent process rows, and completed-Turn duration/status controls have 16px from their input and from a directly following visible row. A reply that follows the control after folded rows keeps the 12px reply gap, so folding never changes its spacing. Hidden and empty rows, including retained empty slot anchors, add no gap. The running “Deep diving” text retains its blue base while its theme-specific highlight sweeps across it.
The running status shows a whale whose APNG mask inherits the text color. CSS selects the static SVG when reduced motion or forced colors are active, or alpha masks are unsupported. The APNG is a [package asset](../AGENTS.md#dependency-declaration) referenced by the plugin stylesheet; React does not pass image data through DOM styles.
diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md
index 28af96a74b..9b0c13b8d0 100644
--- a/packages/client/ui-chat/README.zh.md
+++ b/packages/client/ui-chat/README.zh.md
@@ -127,7 +127,7 @@ Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载的
过程组使用稳定的 `div` 布局盒子、滚动正文及不限高的内容盒子,后者报告正文内部的内容增长。业务样式必须适配组内及组边界间距,处理隐藏或空成员以及回答前的间距特例。`conversation.chat.flow` 插槽添加一个 `display: contents` DOM 锚点;行选择器直接匹配该锚点,不重复匹配其正文容器祖先。运行状态与各行共享父级,使分隔线使用同一套可见兄弟节点规则。锚点自身不产生间距。更早历史控件紧邻流锚点之前,两者的兄弟关系决定首行间距。CSS 变量不属于 Group Definition。
-运行中的分组标题、思考预览、工具与命令行、当前重试行以及底部运行状态使用共享的 [TextShimmer](../ui-primitives/README.zh.md#component-catalog)。每行的文字共用一道从左到右的高光,包括折叠的分组标题;图标和悬停箭头保留底色。普通流程行之间相隔 4px;展开的分组标题与内容之间相隔 8px;Assistant 回复与相邻过程行之间相隔 12px;每轮完成/耗时控件与其输入、以及紧随其后的可见行之间保留 16px。控件与回复之间隔着已收起的行时,回复保持 12px 回复间距,因此折叠不会改变它的间距。隐藏行与空行(包括保留的空 slot 锚点)不产生间距。“深度求索”运行文字保留蓝色底色,并使用主题专用高光扫过文字。
+运行中的分组标题、思考预览、工具与命令行、当前重试行以及底部运行状态使用共享的 [TextShimmer](../ui-primitives/README.zh.md#component-catalog)。每行的文字共用一道从左到右的高光,包括折叠的分组标题;图标和悬停箭头保留底色。普通流程行之间相隔 4px,同一条 Assistant 消息里相邻的推理行也是如此;展开的分组标题与内容之间相隔 8px;Assistant 回复与相邻过程行之间相隔 12px;每轮完成/耗时控件与其输入、以及紧随其后的可见行之间保留 16px。控件与回复之间隔着已收起的行时,回复保持 12px 回复间距,因此折叠不会改变它的间距。隐藏行与空行(包括保留的空 slot 锚点)不产生间距。“深度求索”运行文字保留蓝色底色,并使用主题专用高光扫过文字。
运行状态显示一只鲸鱼,其 APNG 遮罩继承文字颜色。启用减少动态效果或强制颜色模式、或浏览器不支持 alpha 遮罩时,CSS 选择静态 SVG。APNG 是插件样式表引用的[包资源](../AGENTS.md#dependency-declaration);React 不通过 DOM 样式传递图片数据。
diff --git a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css
index 990aa985f6..6441ce20c6 100644
--- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css
+++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.module.css
@@ -15,9 +15,17 @@
}
.body {
+ --dsh-assistant-block-gap: 16px;
display: flex;
flex-direction: column;
- gap: 16px;
+ gap: var(--dsh-assistant-block-gap);
+}
+
+/* A step-group reasoning part (its Chat seat carries data-chat-group-part)
+ holds only reasoning rows, which are process rows: they sit 4px apart, like
+ rows of different steps. */
+:global([data-chat-group-part="reasoning"]) .body {
+ --dsh-assistant-block-gap: 4px;
}
/* Wide markdown tables (the renderer's ≥4-column md-table-wide hook) span
@@ -50,11 +58,13 @@
z-index: 1;
}
-/* hidden="until-found" keeps a zero-height reasoning box in flex layout.
- Cancel the one gap that box would otherwise leave before the visible reply;
- visible Assistant blocks retain the ordinary 16px rhythm. */
-.body > [data-turn-process-inline][hidden] {
- margin-bottom: -16px;
+/* hidden="until-found" keeps a zero-height reasoning box in flex layout, and
+ so does the class-less wrapper of a reasoning block whose row renders
+ nothing (signature-only reasoning has no display text). Cancel the one gap
+ each box would otherwise leave. */
+.body > [data-turn-process-inline][hidden],
+.body > :empty:not([class]) {
+ margin-bottom: calc(-1 * var(--dsh-assistant-block-gap));
}
/* Interrupted-turn terminal marker: quiet inline tag, no animation. Fixed
diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml
index 32d15ae638..7381b1f9d5 100644
--- a/packages/client/ui-subagent/README.i18n.yaml
+++ b/packages/client/ui-subagent/README.i18n.yaml
@@ -15,11 +15,11 @@
en: d152484eb41ac6b4
zh: 09388d293f9be9cb
/deepseek-ai-dsh-client-ui-subagent/use-this-package:
- en: bc1c5164849937a8
- zh: e03adf54d2d5a668
+ en: c7a9485c0cdcd9de
+ zh: 903ad54e44d79eae
/deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree:
- en: 5ea28139189887e9
- zh: f5a51f041c39b0fa
+ en: 35e983f0276188d0
+ zh: df588dc1523031da
/deepseek-ai-dsh-client-ui-subagent/use-this-package/continuing-a-conversation:
en: e4ec261d3b122eb5
zh: 320bb2efc93dccdc
@@ -30,8 +30,8 @@
en: c158f12dcaed87b7
zh: e5d315e7b1fb4fa9
/deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation:
- en: 45772c086f8a55f1
- zh: c80584bf49897b8f
+ en: 3c06acc93d7d4d59
+ zh: b967155aec39df0c
/deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens:
en: dcbc58d4cad47fa8
zh: e962a8cbdfd4a914
@@ -57,8 +57,8 @@
en: de2762a99572475f
zh: 9b41107ad14ebf8a
/deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work:
- en: ee310ff3cd487639
- zh: 23793aa1c28a23af
+ en: ea983111988e4b9b
+ zh: c0ed7a583d2cad52
/deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md
index 764025ddfa..555c6fd2d9 100644
--- a/packages/client/ui-subagent/README.md
+++ b/packages/client/ui-subagent/README.md
@@ -25,7 +25,7 @@ Browse local subagent conversations and external tasks from the parent header. L
## Use this package
-The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and loads nested catalogs only when their rows expand. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits.
+The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and discovers the next level on explicit activation. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits.
This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls.
@@ -39,7 +39,7 @@ The wide root count trigger shows a 14px Users icon in its 14px slot when no chi
Count, owner, and sidebar-action tooltips appear after 500ms of hover. Hovering a text-visible trigger opens its catalog after 150ms; leaving both trigger and catalog closes it after 120ms. Clicking the descendant-count trigger opens and pins its catalog, or closes an already pinned catalog. The icon-only count trigger does not open on hover, including when a pending hover crosses into the narrow layout. Clicking toggles its pinned menu; ArrowDown opens and pins the menu and focuses its first row. Outside click or Escape dismisses a pinned menu. Clicking moves focus into the panel, where ArrowDown/Home enters the first tree row and ArrowUp/End enters the last; Escape returns focus when it was inside. Breadcrumb-title clicks navigate to the corresponding conversation.
-Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. A row is a known leaf only after its own catalog loads empty.
+Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. Only rows with confirmed children show an expansion arrow. Clicking or keyboard-opening the menu reads its catalog and its direct children; expanding a branch does the same for that branch. Each activation reads direct children sequentially through the existing projection reader, which reuses completed reads and merges in-flight requests. It does not recursively discover deeper descendants. Hover and rendering do not initiate reads. Once started, a level read may finish after the menu closes. Missing catalogs show no expansion arrow or unknown marker; shared projection updates reveal confirmed branches while preserving the agent activity marker. Failed reads keep navigation available and offer Retry.
### Continuing a conversation
@@ -61,11 +61,11 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and
### Catalog derivation
-The header lineage renderer reads `projectionsBySession` through the standard `useSessions` hook. The renderer selects `subagentCatalog` from each Session’s shared values for membership, disclosure, and counts. Activity prefers the unified UI status and falls back to Session summaries; summaries supply titles and usage. Expanding a row reads its target's projections, including ordinary cold history. A list row with `formatStatus: migration-required` displays “Migration required” before expansion and keeps its history-opening actions without descendant expansion or changing its subagent mode; a projection read requiring migration without a catalog supplies the same notice. Opening the Session supplies its catalog through history and control projections. Otherwise, an available catalog remains usable, including an explicit empty catalog. Live projection frames update every loaded level without menu subscriptions or repeated membership queries. Other rows remain expandable while their catalogs are absent, loading, or failed, and become known leaves after ready empty catalogs. External rows are always leaves and do not load child Sessions.
+The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering and hovering use only local projections and never request missing catalogs. An unread empty menu says “Subagents not loaded”; the loading notice appears only during a request. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions.
Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent.
-Opening a catalog dropdown does not request its root catalog. Child-catalog expansion and failed-read retries call `refreshProjection`; shared projection-value changes update the display automatically.
+Explicit menu activation, branch expansion, and failed-read retries call `prepareCatalog` to read the current catalog and its direct children. Ancestor-title clicks navigate to that Session. The Session object layer deduplicates reads and refreshes previously requested projections after reconnect.
Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors.
@@ -123,6 +123,8 @@ Append-only. This package never edits earlier request tokens.
These limits define what the catalog can show and what `@` references mean; they are current package constraints.
- **Non-completed inactive outcomes remain grouped** — the catalog distinguishes a latest normal completion from other inactive states, but does not distinguish failure, cancellation, refusal, token exhaustion, or a child with no closed turn; the UI exposes no Activation identity, and stopping is limited to the composer's current-turn Stop for a running continuable child.
+- **Ancestor menus require keyboard activation for uncached branches** — hovering does not read, and clicking the ancestor title navigates. Focus the title and press ArrowDown to prepare that level without leaving the current Session.
+- **Level discovery stops on interruption** — an unexpected read rejection stops later siblings and is logged to the console. A reconnect can interrupt discovery before direct children are read; explicitly reopen the menu to prepare the level again.
- **`@` references remain display-title text** — duplicate or renamed labels are ambiguous, so they intentionally do not acquire continuation semantics.
diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md
index 52d9abc110..056fad6cde 100644
--- a/packages/client/ui-subagent/README.zh.md
+++ b/packages/client/ui-subagent/README.zh.md
@@ -25,7 +25,7 @@ kind: "package-reference"
## 使用本包
-会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并且只在行展开时加载嵌套目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。
+会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并在用户显式打开时发现下一层目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。
本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。
@@ -39,7 +39,7 @@ kind: "package-reference"
数量、负责人及侧边栏操作的工具提示在悬停 500ms 后显示。悬停文字可见的触发器 150ms 后打开目录;指针离开触发器和目录后,经过 120ms 关闭。点击后代数量触发器会打开并固定目录,或关闭已固定的目录。纯图标数量触发器不会因悬停而打开,包括等待悬停打开期间切换到窄布局的情况。点击可切换固定菜单的开关状态;ArrowDown 会打开并固定菜单,并将焦点移至首行。点击外部或按 Escape 可关闭已固定的菜单。点击会将焦点移入面板,此时 ArrowDown/Home 进入首个树行,ArrowUp/End 进入最后一个树行;Escape 在焦点原本位于面板内时将其送回。点击面包屑标题会导航至对应会话。
-目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有一行自身的目录加载为空后,它才是已知叶子。
+目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。点击或通过键盘打开菜单时,读取当前目录及其直属子节点的目录;展开分支时对该分支执行相同操作。每次打开操作通过现有投影读取器依次读取直接子节点,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。悬停与渲染不触发读取。已开始的单层读取可能在菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。
### 续接对话
@@ -61,11 +61,11 @@ kind: "package-reference"
### 目录派生
-页头谱系 renderer 通过标准 `useSessions` 钩子读取 `projectionsBySession`。renderer 从每个 Session 的共享值中选择 `subagentCatalog`,用于成员关系、展开控件与数量。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要提供标题与用量。展开行读取目标投影,包括普通冷历史。列表行的 `formatStatus` 为 `migration-required` 时,行在展开前即显示“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode;投影读取需要迁移且缺少目录时,也显示同一提示。打开会话后,历史与 control 投影提供其目录。其他情况下,已有目录仍可使用,包括显式空目录。实时 projection 帧更新所有已加载层级,无需菜单订阅或重复成员查询。其他行在目录缺席、加载中或失败时保持可展开,并在目录就绪且为空后成为已知叶子。外部行始终为叶子,不加载子 Session。
+页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。
每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。
-打开目录下拉菜单不会请求其根目录。展开子节点目录或重试失败读取时调用 `refreshProjection`;共享投影值的变化会自动更新显示。
+显式激活菜单、展开分支或重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。
面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。
@@ -123,6 +123,8 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由
这些限制定义目录能显示什么、`@` 引用意味着什么;它们是当前包约束。
- **非完成的 inactive 结果仍合并显示**:目录能区分最近一次正常完成与其他 inactive 状态,但不区分失败、取消、拒绝、token 耗尽或尚无已结束轮次的 child;UI 不公开 Activation 身份,停止能力仅限编辑器上针对运行中可继续 child 的当前轮次 Stop。
+- **祖先菜单的未缓存分支需要键盘激活**:悬停不读取,点击祖先标题会导航。聚焦标题后按 ArrowDown,可在不离开当前 Session 的情况下准备这一层。
+- **单层发现会在中断后停止**:意外的读取拒绝会停止后续兄弟节点,并记录到控制台。重连可能在直接子节点读取前中断发现;需再次显式打开菜单来准备这一层。
- **`@` 引用仍是显示标题文本**:重复或改名后的 label 会有歧义,因此它们刻意不获得继续执行语义。
diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css
index d3f58ad409..c450098395 100644
--- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css
+++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css
@@ -350,8 +350,7 @@
}
.label,
-.secondaryLabel,
-.summary {
+.secondaryLabel {
white-space: normal;
overflow-wrap: anywhere;
}
@@ -370,14 +369,10 @@
color: var(--dsw-alias-label-tertiary);
}
-.summary,
.metrics {
color: var(--dsw-alias-label-tertiary);
font-size: 10px;
line-height: 15px;
-}
-
-.metrics {
display: grid;
grid-template-rows: 17px 15px;
flex: none;
@@ -455,10 +450,6 @@
height: 23px;
}
-.children[aria-busy='true']::before {
- content: none;
-}
-
.children > .node::before {
top: 0;
bottom: 0;
diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx
index 92a802ac66..8cbb5be217 100644
--- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx
+++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx
@@ -19,7 +19,7 @@ import type {} from './slots.ts'
import css from './SubagentHeaderLineage.module.css'
type SubagentCatalogSnapshot = Omit & {
- state: 'loading' | 'ready' | 'migration-required' | 'error'
+ state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error'
entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[]
}
type Catalogs = Readonly>
@@ -29,6 +29,8 @@ export type SubagentCatalogInjected = {
openChild: (address: SubagentAddress) => void
openChildAside: (address: SubagentAddress) => void
refreshProjection: (parentSessionId: SessionId) => void
+ /** Read this catalog and its direct children after explicit activation or retry. */
+ prepareCatalog: (parentSessionId: SessionId) => Promise
}
/** Root catalog actions and availability of its optional footer. */
@@ -203,9 +205,11 @@ function CatalogLoadingRows({ t }: { t: TranslateNS }) {
return
{t('loading.label')}
}
-/** A child becomes a known leaf only after its own authoritative catalog loads empty. */
-function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean {
- return catalog?.state === 'ready' && catalog.entries.length === 0
+/** Only confirmed child membership exposes a branch disclosure. */
+function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean {
+ return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0
+ && summaries[entry.id]?.formatStatus !== 'migration-required'
+ && catalogs[entry.id]?.state !== 'migration-required'
}
/** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */
@@ -252,12 +256,12 @@ function CatalogRows({
return () => { clearInterval(timer) }
}, [running])
const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0
- const reserveDisclosure = catalog.entries.some(entry =>
- entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id])
- && summaries[entry.id]?.formatStatus !== 'migration-required'
- && catalogs[entry.id]?.state !== 'migration-required')
+ const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries))
return (
<>
+ {catalog.state === 'idle' && catalog.entries.length === 0 && (
+
)}
@@ -497,7 +501,7 @@ type CatalogDropdownProps = CatalogDropdownSharedProps & (
function CatalogDropdown(props: CatalogDropdownProps) {
const {
rootSessionId, currentSessionId, displayTitle, openTitle, variant,
- useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, hasSharedTasks = false,
+ useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, hasSharedTasks = false,
} = props
const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined
const projections = useSessions(state => state.projectionsBySession)
@@ -507,7 +511,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => {
const projected = snapshot.values.subagentCatalog
const state = snapshot.state === 'idle'
- ? projected === undefined ? 'loading' : 'ready'
+ ? projected === undefined ? 'idle' : 'ready'
: snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state
return [id, {
state,
@@ -521,6 +525,11 @@ function CatalogDropdown(props: CatalogDropdownProps) {
}))
}, [projections, summaries, statuses])
const catalog = catalogs[rootSessionId]
+ const prepareLevel = (sessionId: SessionId): void => {
+ void prepareCatalog(sessionId).catch((error: unknown) => {
+ console.error('[ui-subagent] catalog discovery failed:', error)
+ })
+ }
const [open, setOpen] = useState(false)
const [expanded, setExpanded] = useState>(() => new Set())
const rootRef = useRef(null)
@@ -546,7 +555,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other'
const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other'
const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent
- ? { entries: [], state: 'loading', error: null }
+ ? { entries: [], state: 'idle', error: null }
: undefined)
const cancelHoverClose = (): void => {
@@ -622,7 +631,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
return
}
setExpanded(current => new Set(current).add(childSessionId))
- refreshProjection(childSessionId)
+ prepareLevel(childSessionId)
}
useEffect(() => {
@@ -736,6 +745,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
}
pinnedRef.current = true
if (!open) changeOpen(true)
+ prepareLevel(rootSessionId)
queueMicrotask(() => { menuRef.current?.focus() })
}
: () => {
@@ -748,6 +758,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
event.preventDefault()
if (variant === 'count' && !allowsHoverOpen()) pinnedRef.current = true
if (!open) changeOpen(true)
+ prepareLevel(rootSessionId)
queueMicrotask(() => { focusAt(0) })
}}
>
@@ -804,7 +815,7 @@ function CatalogDropdown(props: CatalogDropdownProps) {
level={1}
openChild={openChild}
openChildAside={openChildAside}
- refreshProjection={refreshProjection}
+ refreshProjection={prepareLevel}
toggleBranch={toggleBranch}
closeCatalog={() => { changeOpen(false) }}
t={t}
@@ -841,7 +852,7 @@ export function SubagentCatalogAction(props: SubagentCatalogActionProps) {
/** Bind task-board visibility only in root conversations. */
function RootCatalogAction({
sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable,
- openChild, openChildAside, refreshProjection, t, renderSlot,
+ openChild, openChildAside, refreshProjection, prepareCatalog, t, renderSlot,
}: SubagentCatalogActionProps) {
const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true
&& team.tasks.some(task => task.status !== 'deleted'))
@@ -860,6 +871,7 @@ function RootCatalogAction({
openChild={openChild}
openChildAside={openChildAside}
refreshProjection={refreshProjection}
+ prepareCatalog={prepareCatalog}
t={t}
/>
)
@@ -872,7 +884,7 @@ function RootCatalogAction({
*/
export function SubagentHeaderLineage({
lineageSessionId, displayTitle, openTitle,
- useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, t,
+ useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t,
}: SubagentHeaderLineageProps) {
const address = useSession(session => session.subagent?.address)
const parentId = useSessions((state) => {
@@ -883,7 +895,7 @@ export function SubagentHeaderLineage({
const summary = state.byId[lineageSessionId]
return summary?.origin === 'subagent' ? summary.parentId : undefined
})
- const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t }
+ const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t }
// Root sessions carry no breadcrumb; their descendant count lives in the
// header actions band (SubagentCatalogAction).
if (parentId === undefined) return null
diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts
index a84992246d..b44d4f8e55 100644
--- a/packages/client/ui-subagent/src/client/index.ts
+++ b/packages/client/ui-subagent/src/client/index.ts
@@ -62,6 +62,19 @@ export function apply(ctx: ClientContext): void {
preferNewPane: true,
})
},
+ async prepareCatalog(parentSessionId: SessionId) {
+ await ctx.sessions.refreshProjections(parentSessionId)
+ const parent = ctx.sessions.list.getSnapshot().projectionsBySession[parentSessionId]
+ if (parent?.state !== 'ready') return
+ for (const entry of parent.values.subagentCatalog ?? []) {
+ if (entry.mode === 'external') continue
+ const state = ctx.sessions.list.getSnapshot()
+ if (state.byId[entry.id]?.formatStatus === 'migration-required'
+ || state.projectionsBySession[entry.id]?.state === 'migration-required'
+ || state.projectionsBySession[entry.id]?.state === 'error') continue
+ await ctx.sessions.refreshProjections(entry.id)
+ }
+ },
refreshProjection(parentSessionId: SessionId) {
void ctx.sessions.refreshProjections(parentSessionId)
},
diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts
index 27a5b61391..83754edd6c 100644
--- a/packages/client/ui-subagent/src/client/locales.ts
+++ b/packages/client/ui-subagent/src/client/locales.ts
@@ -26,8 +26,8 @@ export const zh = {
'tokens.million': '{value}M',
'tokens.total': '{value} tok',
'loading.label': '正在加载子智能体…',
+ 'load.idle': '尚未加载子智能体',
'load.error': '无法加载子智能体',
- 'catalog.migrationRequired': '需要迁移',
'retry': '重试',
'mode.external': '外部任务',
'mode.oneShot': '一次性',
@@ -77,8 +77,8 @@ export const en: Record = {
'tokens.million': '{value}M',
'tokens.total': '{value} tok',
'loading.label': 'Loading subagents…',
+ 'load.idle': 'Subagents not loaded',
'load.error': 'Unable to load subagents',
- 'catalog.migrationRequired': 'Migration required',
'retry': 'Retry',
'mode.external': 'External task',
'mode.oneShot': 'one-shot',
@@ -131,8 +131,8 @@ export const ja = {
'tokens.million': '{value}M',
'tokens.total': '{value} tok',
'loading.label': 'サブエージェントを読み込み中…',
+ 'load.idle': 'サブエージェントは未読み込みです',
'load.error': 'サブエージェントを読み込めません',
- 'catalog.migrationRequired': '移行が必要です',
'retry': '再試行',
'mode.external': '外部タスク',
'mode.oneShot': '単発',
@@ -182,8 +182,8 @@ export const es = {
'tokens.million': '{value}M',
'tokens.total': 'Tok {value}',
'loading.label': 'Cargando subagentes…',
+ 'load.idle': 'Subagentes sin cargar',
'load.error': 'No se pueden cargar subagentes',
- 'catalog.migrationRequired': 'Migración requerida',
'retry': 'Reintentar',
'mode.external': 'tarea externa',
'mode.oneShot': 'un solo disparo',
@@ -233,8 +233,8 @@ export const fr = {
'tokens.million': '{value}M',
'tokens.total': 'Jeton {value}',
'loading.label': 'Chargement des sous-agents…',
+ 'load.idle': 'Sous-agents non chargés',
'load.error': 'Impossible de charger les sous-agents',
- 'catalog.migrationRequired': 'Migration requise',
'retry': 'Réessayer',
'mode.external': 'Tâche externe',
'mode.oneShot': 'un coup',
@@ -284,8 +284,8 @@ export const de = {
'tokens.million': '{value}M',
'tokens.total': '{value}-Token',
'loading.label': 'Subagenten werden geladen…',
+ 'load.idle': 'Subagenten nicht geladen',
'load.error': 'Subagenten können nicht geladen werden',
- 'catalog.migrationRequired': 'Migration erforderlich',
'retry': 'Erneut versuchen',
'mode.external': 'Externe Aufgabe',
'mode.oneShot': 'One-Shot',
@@ -335,8 +335,8 @@ export const ru = {
'tokens.million': '{value}M',
'tokens.total': '{value} ток',
'loading.label': 'Загрузка субагентов…',
+ 'load.idle': 'Субагенты не загружены',
'load.error': 'Невозможно загрузить субагенты',
- 'catalog.migrationRequired': 'Требуется миграция',
'retry': 'Повторить',
'mode.external': 'Внешняя задача',
'mode.oneShot': 'одноразовый',
@@ -386,8 +386,8 @@ export const pt = {
'tokens.million': '{value}M',
'tokens.total': '{value} valor',
'loading.label': 'Carregando subagentes…',
+ 'load.idle': 'Subagentes não carregados',
'load.error': 'Não foi possível carregar subagentes',
- 'catalog.migrationRequired': 'Migração necessária',
'retry': 'Tentar novamente',
'mode.external': 'Tarefa externa',
'mode.oneShot': 'tiro único',
diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts
index b5006a277b..83c5839e8d 100644
--- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts
+++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts
@@ -4,7 +4,7 @@ import { Context } from '@deepseek-ai/cordis'
import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import type {
- SessionListState, SessionSnapshot, SessionSummary,
+ SessionListState, SessionSnapshot, SessionSummary, SessionProjectionSnapshot,
} from '@deepseek-ai/dsh-api-session-controller/client'
import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client'
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
@@ -35,7 +35,8 @@ const sid = (id: string) => id as SessionId
function sessionsWith(sessions: SessionSummary[]) {
const byId: Record = {}
for (const s of sessions) byId[s.id] = s
- const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: {} }
+ const projections: Record = {}
+ const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: projections }
const actionCalls: { method: string; args: unknown[] }[] = []
const address: SubagentAddress = {
parentSessionId: sid('parent'),
@@ -48,6 +49,7 @@ function sessionsWith(sessions: SessionSummary[]) {
subscribe: () => () => {},
},
actionCalls,
+ projections,
subagentAddress: (childSessionId: SessionId) => childSessionId === address.childSessionId
? address
: undefined,
@@ -121,6 +123,40 @@ describe('apply', () => {
expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1)
})
+ it('reads direct child catalogs sequentially after reading the parent', async () => {
+ const { ctx, face } = await fullBench([...FAMILY, summary({ id: sid('legacy'), formatStatus: 'migration-required' })])
+ onTestFinished(() => ctx.fiber.dispose())
+ const entry = ctx.slots.entries('conversation.session.header.lineage')
+ .find(entry => entry.component === SubagentHeaderLineage)!
+ const actions = (entry.inject as (id: SessionId) => SubagentCatalogInjected)(sid('parent'))
+ const projections = face.projections
+ const held = Promise.withResolvers()
+ const refresh = vi.spyOn(face, 'refreshProjections').mockImplementation(async (id) => {
+ if (id === sid('parent')) projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [
+ { id: sid('external'), mode: 'external', createdAt: 1 },
+ ...['c1', 'c2', 'legacy', 'blocked', 'failed'].map(id => ({ id: sid(id), mode: 'one-shot' as const, createdAt: 1 })),
+ ] } }
+ if (id === sid('c1')) {
+ await held.promise
+ projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [
+ { id: sid('grandchild'), mode: 'one-shot', createdAt: 1 },
+ ] } }
+ }
+ })
+ onTestFinished(() => { refresh.mockRestore() })
+ projections[sid('blocked')] = { state: 'migration-required', error: null, values: {} }
+ projections[sid('failed')] = { state: 'error', error: null, values: {} }
+ const reading = actions.prepareCatalog(sid('parent'))
+ await vi.waitFor(() => { expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')]]) })
+ held.resolve(undefined)
+ await reading
+ expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')], [sid('c2')]])
+ await actions.prepareCatalog(sid('c2'))
+ projections[sid('c2')] = { state: 'ready', error: null, values: {} }
+ await actions.prepareCatalog(sid('c2'))
+ expect(refresh.mock.calls.slice(3)).toEqual([[sid('c2')], [sid('c2')]])
+ })
+
it('registers catalog actions and selects read-only subagent composers from session facts', async () => {
const { ctx, face } = await fullBench(FAMILY)
const catalogEntry = ctx.slots.entries('conversation.session.header.lineage')
diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx
index 43d2255936..a70f41295e 100644
--- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx
+++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx
@@ -75,31 +75,44 @@ function props(
) {
const catalogs = value === undefined ? nested : { [PARENT]: value, ...nested }
const statuses: SessionStatusSnapshot = new Map()
+ const byId: Record = {
+ ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, {
+ id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, projectionValues: { subagentCatalog: [] },
+ }]))),
+ [CHILD]: {
+ id: CHILD,
+ title: '正在扫描项目文件',
+ displayTitle: 'worker',
+ running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')),
+ retainedBy: {},
+ blank: false,
+ updatedAt: Date.now(),
+ projectionValues: { subagentCatalog: [] },
+ },
+ ...summaries,
+ }
const state = {
ids: [CHILD],
- byId: summaries ?? {
- ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, {
- id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {},
- }]))),
- [CHILD]: {
- id: CHILD,
- title: '正在扫描项目文件',
- displayTitle: 'worker',
- running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')),
- retainedBy: {},
- blank: false,
- updatedAt: Date.now(),
- },
- },
+ byId,
phase: 'ready',
- projectionsBySession: Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, {
- state: catalog.state, error: catalog.error,
- values: {
- ...catalog.team === undefined ? {} : { agentTeam: catalog.team },
- subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })),
- },
- }])) ,
+ projectionsBySession: {
+ ...Object.fromEntries(Object.entries(byId).flatMap(([id, entry]) => entry.projectionValues === undefined ? [] : [[id, {
+ state: 'idle' as const, error: null, values: entry.projectionValues,
+ }]])),
+ ...Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, {
+ state: catalog.state, error: catalog.error,
+ values: {
+ ...byId[id as SessionId]?.projectionValues,
+ ...catalog.team === undefined ? {} : { agentTeam: catalog.team },
+ subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })),
+ },
+ }])),
+ },
} satisfies SessionListState
+ for (const [id, entry] of Object.entries(byId)) {
+ const projection = state.projectionsBySession[id]
+ if (projection !== undefined) byId[id as SessionId] = { ...entry, projectionValues: projection.values }
+ }
function useSessions(select: (snapshot: SessionListState) => T): T {
return select(state)
}
@@ -142,6 +155,7 @@ function props(
openChild: vi.fn(),
openChildAside: vi.fn(),
refreshProjection: vi.fn(),
+ prepareCatalog: vi.fn<(id: SessionId) => Promise>().mockResolvedValue(),
renderSlot: vi.fn(() => null),
lineageSessionId: PARENT,
displayTitle: 'Parent title',
@@ -528,8 +542,8 @@ describe('SubagentHeaderLineage', () => {
expect(screen.getByText('worker')).toBeTruthy()
expect(screen.queryByText('正在扫描项目文件')).toBeNull()
expect(screen.getByRole('treeitem', { name: /reviewer child-2 · 一次性 · 当前未运行/ })).toBeTruthy()
- expect(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })).toBeTruthy()
- expect(screen.getByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
+ expect(screen.queryByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeNull()
const sidebarButton = within(screen.getByRole('treeitem', { name: /worker/ }))
.getByRole('button', { name: '在侧边栏打开 worker' })
@@ -732,8 +746,11 @@ describe('SubagentHeaderLineage', () => {
expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(1)
})
- it('aligns a known leaf with siblings whose child catalog is still unknown', () => {
- render()
+ it('aligns a known leaf with siblings whose child catalog contains descendants', () => {
+ render()
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(2)
@@ -1043,6 +1060,7 @@ describe('SubagentHeaderLineage', () => {
origin: 'subagent' as const,
running: activity === 'running',
projectionValues: {
+ subagentCatalog: [],
subagentTiming: {
settledMs,
...(id === 'finished'
@@ -1111,6 +1129,7 @@ describe('SubagentHeaderLineage', () => {
origin: 'subagent',
running: true,
projectionValues: {
+ subagentCatalog: [],
subagentTiming: { settledMs: 0, active: { since: now - 5_000, through: now } },
},
},
@@ -1147,7 +1166,7 @@ describe('SubagentHeaderLineage', () => {
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
- expect(input.refreshProjection).toHaveBeenCalledWith(CHILD)
+ expect(input.refreshProjection).not.toHaveBeenCalled()
const nested = screen.getByRole('treeitem', { name: /indexer/ })
expect(nested.getAttribute('aria-level')).toBe('2')
@@ -1158,15 +1177,15 @@ describe('SubagentHeaderLineage', () => {
})
})
- it('keeps ordinary cold descendants loading until their real catalog arrives', () => {
+ it('reveals cold descendants only when shared catalog data arrives', () => {
const secondGrandchild = 'grandchild-2' as SessionId
const summaries = {
[CHILD]: { ...summary(CHILD, 1), running: true },
[GRANDCHILD]: {
- ...summary(GRANDCHILD, 1), parentId: CHILD, origin: 'subagent' as const,
+ ...summary(GRANDCHILD, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const,
},
[secondGrandchild]: {
- ...summary(secondGrandchild, 1), parentId: CHILD, origin: 'subagent' as const,
+ ...summary(secondGrandchild, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const,
running: true,
},
}
@@ -1176,11 +1195,11 @@ describe('SubagentHeaderLineage', () => {
const current = { ...deferred, useSessions: (select: (snapshot: SessionListState) => T): T => select(state) }
const view = render()
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
- fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
- expect(deferred.refreshProjection).toHaveBeenCalledWith(CHILD)
- expect(screen.getByRole('group').getAttribute('aria-busy')).toBe('true')
- expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
+ expect(deferred.refreshProjection).not.toHaveBeenCalled()
+ expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull()
+ expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryByRole('treeitem', { name: '正在加载子智能体' })).toBeNull()
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
expect(screen.queryByText(/模式未知/)).toBeNull()
@@ -1193,7 +1212,7 @@ describe('SubagentHeaderLineage', () => {
},
}
view.rerender()
- expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
+ expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
expect(screen.queryByText(/模式未知/)).toBeNull()
@@ -1213,16 +1232,162 @@ describe('SubagentHeaderLineage', () => {
}, summaries)
state = { ...state, projectionsBySession: ready.useSessions(value => value.projectionsBySession) }
view.rerender()
+ fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
expect(screen.getByRole('group').getAttribute('aria-busy')).toBeNull()
expect(screen.getByRole('treeitem', { name: /indexer/ }).querySelector('[data-state="idle"]')).not.toBeNull()
expect(screen.getByRole('treeitem', { name: /critic/ }).querySelector('[data-state="ongoing"]')).not.toBeNull()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryByText(/模式未知/)).toBeNull()
- expect(deferred.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD)
+ expect(deferred.refreshProjection).not.toHaveBeenCalled()
expect(deferred.openChild).not.toHaveBeenCalled()
})
- it.each([false, true])('shows list migration status before expanding, with cached descendants=%s', (cached) => {
+ it.each([
+ { running: true, completed: false, dot: 'ongoing' },
+ { running: false, completed: true, dot: 'done' },
+ { running: false, completed: false, dot: 'idle' },
+ ])('preserves the $dot activity marker while an unknown directory loads', ({ running, completed, dot }) => {
+ const input = props(catalog({ entries: [{
+ id: CHILD, mode: 'continuable', label: 'worker', activity: running ? 'running' : 'inactive',
+ }] }), {}, { [CHILD]: {
+ ...summary(CHILD, 1), running,
+ projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: completed } },
+ } })
+ let state = input.useSessions(value => value)
+ const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) }
+ const view = render()
+ fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' }))
+ const row = screen.getByRole('treeitem', { name: /worker/ })
+ const marker = row.querySelector(`[data-state="${dot}"]`)
+ expect(marker).not.toBeNull()
+ expect(row.children).toHaveLength(1)
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+
+ state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: {
+ ...state.projectionsBySession[CHILD]!, state: 'loading',
+ } } }
+ view.rerender()
+ expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(row)
+ expect(row.querySelector(`[data-state="${dot}"]`)).toBe(marker)
+ expect(screen.queryByText('正在加载子智能体…')).toBeNull()
+ expect(row.hasAttribute('aria-busy')).toBe(false)
+ expect(row.hasAttribute('aria-expanded')).toBe(false)
+ expect(within(row).getByRole('button', { name: '在侧边栏打开 worker' }).hasAttribute('disabled')).toBe(false)
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ })
+
+ it('leaves missing catalogs unread and retries only an explicitly selected failure', () => {
+ const input = props(catalog(), {}, { [CHILD]: summary(CHILD, 1) })
+ let state = input.useSessions(value => value)
+ const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) }
+ const view = render()
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
+ expect(screen.queryByText('正在加载子智能体…')).toBeNull()
+
+ state = { ...state, projectionsBySession: {
+ ...state.projectionsBySession,
+ [CHILD]: { state: 'error', values: {}, error: new RemoteError('gateway/internal', 'private diagnostic', {}) },
+ } }
+ view.rerender()
+ expect(screen.getByRole('alert').textContent).toContain('无法加载子智能体')
+ expect(screen.queryByText('private diagnostic')).toBeNull()
+ expect(screen.queryByRole('status')).toBeNull()
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: '重试' }))
+ expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]])
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ expect(input.openChild).not.toHaveBeenCalled()
+ state = { ...state, projectionsBySession: {
+ ...state.projectionsBySession, [CHILD]: { state: 'ready', values: { subagentCatalog: [] }, error: null },
+ } }
+ view.rerender()
+ expect(screen.queryByRole('alert')).toBeNull()
+ expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
+ expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull()
+ })
+
+ it('expands cached shared projections without reading the next level', () => {
+ const childSummary = { ...summary(CHILD, 1), projectionValues: { subagentCatalog: [
+ { id: GRANDCHILD, createdAt: 1, mode: 'continuable' as const, label: 'indexer' },
+ ] } }
+ const input = props(catalog(), {}, { [CHILD]: childSummary, [GRANDCHILD]: summary(GRANDCHILD, 1) })
+ let state = input.useSessions(value => value)
+ const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) }
+ const view = render()
+ fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy()
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull()
+
+ state = { ...state, projectionsBySession: {
+ ...state.projectionsBySession, [CHILD]: { state: 'ready', error: null, values: { subagentCatalog: [] } },
+ } }
+ view.rerender()
+ expect(screen.queryByRole('button', { name: '收起 worker 的下级子智能体' })).toBeNull()
+ expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
+ })
+
+ it('updates disclosure when a visible leaf gains children without fetching any level', () => {
+ const input = props(catalog())
+ let state = input.useSessions(value => value)
+ const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) }
+ const view = render()
+ fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
+ const worker = screen.getByRole('treeitem', { name: /worker/ })
+ expect(worker.hasAttribute('aria-expanded')).toBe(false)
+ state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: {
+ state: 'idle', error: null, values: {
+ subagentCatalog: [{ id: GRANDCHILD, createdAt: 1, mode: 'continuable', label: 'indexer' }],
+ },
+ } } }
+ view.rerender()
+ expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(worker)
+ expect(worker.getAttribute('aria-expanded')).toBe('false')
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy()
+ })
+
+ it('prepares only explicitly opened levels', () => {
+ const input = props(catalog(), {
+ [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }),
+ })
+ render()
+ const trigger = screen.getByRole('button', { name: /\d+ 个子智能体$/ })
+ hoverCatalog(trigger)
+ expect(input.prepareCatalog).not.toHaveBeenCalled()
+ fireEvent.click(trigger)
+ fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]])
+ fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' }))
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
+ expect(input.prepareCatalog).toHaveBeenCalledTimes(2)
+ fireEvent.keyDown(trigger, { key: 'ArrowDown' })
+ expect(input.prepareCatalog.mock.calls.at(-1)).toEqual([PARENT])
+ })
+
+ it('reports an unexpected explicit catalog failure', async () => {
+ const input = props(catalog())
+ const failure = new Error('projection reader failed')
+ input.prepareCatalog.mockRejectedValueOnce(failure)
+ const report = vi.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ render()
+ fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
+ await vi.waitFor(() => { expect(report).toHaveBeenCalledWith('[ui-subagent] catalog discovery failed:', failure) })
+ } finally {
+ report.mockRestore()
+ }
+ })
+
+ it.each([false, true])('keeps legacy rows navigable without a migration notice, with cached descendants=%s', (cached) => {
const input = props(catalog(), cached ? {
[CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }),
} : {}, {
@@ -1235,7 +1400,8 @@ describe('SubagentHeaderLineage', () => {
hoverCatalog(trigger)
const child = screen.getByRole('treeitem', { name: /worker/ })
- expect(within(child).getByText(/需要迁移/)).toBeTruthy()
+ expect(within(child).queryByText(/需要迁移/)).toBeNull()
+ expect(child.getAttribute('aria-label')).not.toContain('需要迁移')
expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull()
fireEvent.keyDown(child, { key: 'ArrowRight' })
expect(input.refreshProjection).not.toHaveBeenCalled()
@@ -1248,8 +1414,13 @@ describe('SubagentHeaderLineage', () => {
view.rerender()
hoverCatalog(trigger)
expect(screen.queryByText(/需要迁移/)).toBeNull()
- fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
- expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD)
+ if (cached) {
+ fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ } else {
+ expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
+ expect(input.refreshProjection).not.toHaveBeenCalled()
+ }
})
it.each(['ready', 'migration-required'] as const)('stops at a migration-required child until its real catalog arrives with %s read state', (readState) => {
@@ -1272,7 +1443,7 @@ describe('SubagentHeaderLineage', () => {
const current = { ...input, useSessions: (select: (snapshot: SessionListState) => T): T => select(state) }
const view = render()
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
- fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull()
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
state = {
@@ -1287,15 +1458,15 @@ describe('SubagentHeaderLineage', () => {
expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull()
expect(screen.queryByRole('treeitem', { name: /ordinary-fork/ })).toBeNull()
const child = screen.getByRole('treeitem', { name: /worker/ })
- expect(within(child).getByText(/需要迁移/)).toBeTruthy()
+ expect(within(child).queryByText(/需要迁移/)).toBeNull()
+ expect(child.getAttribute('aria-label')).not.toContain('需要迁移')
expect(within(child).queryByText(/模式未知/)).toBeNull()
- expect(en['catalog.migrationRequired']).toBe('Migration required')
expect(child.hasAttribute('aria-expanded')).toBe(false)
expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull()
expect(screen.queryByRole('group')).toBeNull()
expect(screen.queryByText('正在加载子智能体…')).toBeNull()
fireEvent.keyDown(child, { key: 'ArrowRight' })
- expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD)
+ expect(input.refreshProjection).not.toHaveBeenCalled()
expect(input.openChild).not.toHaveBeenCalled()
fireEvent.click(child)
expect(input.openChild).toHaveBeenCalledExactlyOnceWith({
@@ -1347,7 +1518,8 @@ describe('SubagentHeaderLineage', () => {
fireEvent.keyDown(child, { key: 'ArrowRight' })
fireEvent.keyDown(child, { key: 'ArrowRight' })
expect(input.refreshProjection).not.toHaveBeenCalled()
- expect(within(child).getByText(/需要迁移/)).toBeTruthy()
+ expect(within(child).queryByText(/需要迁移/)).toBeNull()
+ expect(child.getAttribute('aria-label')).not.toContain('需要迁移')
expect(within(child).queryByText(/模式未知/)).toBeNull()
expect(child.hasAttribute('aria-expanded')).toBe(false)
expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull()
@@ -1406,7 +1578,30 @@ describe('SubagentHeaderLineage', () => {
expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
})
- it('closes expanded descendants even when their own catalogs have not arrived', () => {
+ it('collapses expanded descendants whose catalog is removed before their parent closes', () => {
+ const input = props(catalog(), {
+ [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }),
+ [GRANDCHILD]: catalog({ entries: [{ id: 'great-grandchild' as SessionId, mode: 'continuable', label: 'deep', activity: 'inactive' }] }),
+ })
+ let state = input.useSessions(value => value)
+ const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) }
+ const view = render()
+ fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' }))
+ fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' }))
+ const { [GRANDCHILD]: _projection, ...projectionsBySession } = state.projectionsBySession
+ const { [GRANDCHILD]: _summary, ...byId } = state.byId
+ state = { ...state, projectionsBySession, byId }
+ view.rerender()
+ fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' }))
+ expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
+ state = input.useSessions(value => value)
+ view.rerender()
+ fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
+ expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-expanded')).toBe('false')
+ })
+
+ it('closes a branch while the visible descendants are loading', () => {
const input = props(catalog(), {
[CHILD]: catalog({
entries: [{
@@ -1414,11 +1609,12 @@ describe('SubagentHeaderLineage', () => {
label: 'indexer', activity: 'running',
}],
}),
- })
+ }, { [GRANDCHILD]: summary(GRANDCHILD, 1) })
render()
hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ }))
fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' }))
- fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' }))
+ expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull()
+ expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-busy')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' }))
expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull()
@@ -1443,7 +1639,8 @@ describe('SubagentHeaderLineage', () => {
hoverCatalog(screen.getByRole('button', { name: /0 个子智能体/ }))
expect(screen.getByText('index down')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /重试/ }))
- expect(failed.refreshProjection).toHaveBeenCalledWith(PARENT)
+ expect(failed.prepareCatalog).toHaveBeenCalledExactlyOnceWith(PARENT)
+ expect(failed.refreshProjection).not.toHaveBeenCalled()
})
it.each(['absent', 'idle', 'loading', 'ready'] as const)('does not expose header-only descendants when the projection read is %s', (state) => {
@@ -1584,7 +1781,9 @@ describe('SubagentHeaderLineage', () => {
const switcher = screen.getByRole('button', { name: '切换子智能体:worker' })
hoverCatalog(switcher)
- expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
+ expect(input.prepareCatalog).not.toHaveBeenCalled()
+ expect(screen.getByText('尚未加载子智能体')).toBeTruthy()
+ expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryAllByRole('treeitem')).toEqual([])
expect(input.refreshProjection).not.toHaveBeenCalled()
})
@@ -1690,11 +1889,30 @@ describe('SubagentHeaderLineage', () => {
const switcher = screen.getByRole('button', { name: '切换子智能体:正在扫描项目文件' })
expect(input.refreshProjection).not.toHaveBeenCalled()
hoverCatalog(switcher)
- expect(screen.getByText('正在加载子智能体…')).toBeTruthy()
+ expect(input.prepareCatalog).not.toHaveBeenCalled()
+ expect(screen.getByText('尚未加载子智能体')).toBeTruthy()
+ expect(screen.queryByText('正在加载子智能体…')).toBeNull()
expect(screen.queryAllByRole('treeitem')).toEqual([])
expect(input.refreshProjection).not.toHaveBeenCalled()
})
+ it.each(['idle', 'loading'] as const)('shows the actual %s state of an empty title menu', (state) => {
+ const input = {
+ ...props(undefined, {}, {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }),
+ lineageSessionId: CHILD,
+ displayTitle: 'worker',
+ }
+ const initial = input.useSessions(value => value)
+ render( select({
+ ...initial,
+ projectionsBySession: { [PARENT]: { state, error: null, values: {} } },
+ })} />)
+ hoverCatalog(screen.getByRole('button', { name: '切换子智能体:worker' }))
+ expect(screen.getByText(state === 'idle' ? zh['load.idle'] : zh['loading.label'])).toBeTruthy()
+ expect(screen.queryByText(state === 'idle' ? zh['loading.label'] : zh['load.idle'])).toBeNull()
+ expect(input.prepareCatalog).not.toHaveBeenCalled()
+ })
+
it('keeps a nested title switcher scoped to its direct-parent catalog', () => {
const input = {
...props(catalog(), {
diff --git a/packages/client/web/src/boot-page.module.css b/packages/client/web/src/boot-page.module.css
index f154c42761..c28097cf8c 100644
--- a/packages/client/web/src/boot-page.module.css
+++ b/packages/client/web/src/boot-page.module.css
@@ -56,7 +56,8 @@
content: '';
position: absolute;
inset: -2px;
- border-radius: inherit;
+ border-radius: 50%;
+ corner-shape: round;
background: conic-gradient(
var(--dsw-alias-brand-primary, var(--dsh-boot-brand)) var(--dsh-boot-arc, 72deg),
transparent 0
diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml
index 303831978e..253c4536e4 100644
--- a/packages/core/agent-loop/README.i18n.yaml
+++ b/packages/core/agent-loop/README.i18n.yaml
@@ -39,8 +39,8 @@
en: ec2bf804bd1a5439
zh: 316e767507e859ef
/deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown:
- en: e2cb7b6101f20425
- zh: a056c43886207083
+ en: 4a10108fb0d37732
+ zh: cc3be0eb8f00901c
/deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration:
en: 3b48a480036bd5df
zh: 28cea2036b0dccee
diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md
index bc38634345..30443d6ace 100644
--- a/packages/core/agent-loop/README.md
+++ b/packages/core/agent-loop/README.md
@@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu
Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete `session/created`; await optional setup and its commit; enter the AgentRegistry; await serial `agent/created` listeners; then release queued input. The caller Context owns the transaction and live handle; delegation services bind their runtime relationships during setup. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits `session/disposed`, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement.
-The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown.
+The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. Queue-clear errors do not skip cancellation or the wait for admitted work, and resources remain available until that work settles.
### Persistence integration
diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md
index 3717ca17d9..e20aa96f37 100644
--- a/packages/core/agent-loop/README.zh.md
+++ b/packages/core/agent-loop/README.zh.md
@@ -109,7 +109,7 @@ const handle = await ctx.agents.create({
新建和恢复共用一个受回滚保护的初始化流程:围绕已取得的 Session 构造具象 agent 与带作用域上下文;存储构造历史、进入 SessionStore 并完成 `session/created`;等待可选 setup 及其 commit;进入 AgentRegistry;等待串行 `agent/created` 监听器;随后释放已排队输入。调用方 Context 拥有事务和存活句柄;委派服务在 setup 期间绑定自己的运行时关系。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。setup 期间 Session 可写;每次移除都会发出 `session/disposed`,包括 Agent 创建宣告前的 setup 失败。初始化失败保留恢复出的收件箱输入及已存储事件,并在释放自身作用域及已取得的写句柄后才拒绝。持久化层仍在创建写句柄时发生取消,可以更早拒绝;该句柄在创建完成后关闭。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。
-loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。
+loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。清队列错误不会跳过取消或等待已接纳工作,资源会保留到该工作结束。
### 持久化集成
diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts
index 479b59096a..7ec43dd132 100644
--- a/packages/core/agent-loop/src/agent.ts
+++ b/packages/core/agent-loop/src/agent.ts
@@ -141,6 +141,7 @@ export class ReactLoopAgent implements Agent {
public readonly session: Session,
projections: LoopProjections,
lastTurn: number,
+ private readonly lifetimeSignal: AbortSignal,
) {
this.requestSurfaceGeneration = session.surface.contentGeneration
this.dispatch = agentEvents(loopCtx, this)
@@ -189,11 +190,15 @@ export class ReactLoopAgent implements Agent {
}
cancel(cause: AgentCancelCause, options: CancelOptions = {}): void {
- if (!options.keepInbox) {
- this.inbox.clear()
- if (this.phase.kind !== 'idle') this.phase.wakeRequested = false
+ try {
+ if (!options.keepInbox) this.inbox.clear()
+ } finally {
+ // Queue persistence must not prevent cancellation of admitted work.
+ if (this.phase.kind !== 'idle') {
+ if (!options.keepInbox) this.phase.wakeRequested = false
+ this.phase.abort.abort(cause)
+ }
}
- if (this.phase.kind !== 'idle') this.phase.abort.abort(cause)
}
runMaintenance(job: (signal: AbortSignal) => Promise): Promise {
@@ -228,6 +233,7 @@ export class ReactLoopAgent implements Agent {
* the inbox insertion so a reentrant cancel cannot reclassify it.
*/
private wakeDriver(wakeAfterAbort = false): void {
+ if (this.lifetimeSignal.aborted) return
if (this.phase.kind !== 'idle') {
// Maintenance and aborted drivers cannot deliver the wake: latch it for
// replay at convergence. Live drivers claim queued work themselves;
diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts
index 22b3192588..bda53c3b56 100644
--- a/packages/core/agent-loop/src/index.ts
+++ b/packages/core/agent-loop/src/index.ts
@@ -469,11 +469,8 @@ export class AgentLoop extends Service implements AgentFactory {
const id = session.id
const loopCtx = this.runtime.ctx
- // Deactivation fuses three owners, each with its own reason: the caller's
- // cancellation signal, the owner fiber's unload, and factory teardown.
- // It is registered BEFORE any resource exists, over mutable slots, so an
- // unload arriving while the scope is still minting finds a working
- // disposer instead of a leak.
+ // The caller's signal governs creation. Owner disposal and factory
+ // shutdown can end the Agent's lifetime both during and after creation.
const abort = new AbortController()
const onCallerAbort = (): void => {
abort.abort(callerSignal?.reason instanceof Error
@@ -514,7 +511,12 @@ export class AgentLoop extends Service implements AgentFactory {
if (machine === undefined) await machineReady.promise
/* v8 ignore next -- setup failure untracks this disposer before resolving without a machine. */
if (machine !== undefined) {
- machine.cancel({ kind: 'disposed' }, { keepInbox: !ready })
+ try {
+ machine.cancel({ kind: 'disposed' }, { keepInbox: !ready })
+ } catch (error: unknown) {
+ failures.push(error)
+ }
+ // A failed queue write must not release resources underneath work.
await machine.whenIdle()
}
} catch (error: unknown) {
@@ -572,7 +574,7 @@ export class AgentLoop extends Service implements AgentFactory {
const created = machine = new ReactLoopAgent(
loopCtx, id, agentOptions, session,
projections,
- lastTurn,
+ lastTurn, abort.signal,
)
machineReady.resolve()
// Adopt the scope on its original fiber so it cannot unload before teardown.
@@ -636,6 +638,7 @@ export class AgentLoop extends Service implements AgentFactory {
await loopCtx.agents.announce(agent, source, abort.signal)
assertLive()
ready = true
+ callerSignal?.removeEventListener('abort', onCallerAbort)
return { agent, dispose }
} catch (error: unknown) {
// Failed initialization must not release queued input into a new turn.
diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts
index c702b64e89..e5e9be01fc 100644
--- a/packages/core/agent-loop/tests/cancel.spec.ts
+++ b/packages/core/agent-loop/tests/cancel.spec.ts
@@ -319,20 +319,51 @@ describe('Agent.cancel()', () => {
})
const agent = handle.agent
+ const streaming = Promise.withResolvers()
+ ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streaming.resolve(undefined) })
send(agent, 'active')
- await new Promise(resolve => setTimeout(resolve, 30))
-
- // Dispose cancels with `{ kind: 'disposed' }`; a wake landing in the
- // abort-to-idle window must not latch, so `whenIdle()` does not wait on
- // a model turn over the session being torn down.
+ await streaming.promise
const disposal = handle.dispose()
- setTimeout(() => { send(agent, 'late wake') }, 10)
+ send(agent, 'late wake')
await disposal
expect(adapter.requests).toHaveLength(1)
expect(userTexts(agent)).toEqual(['active'])
})
+ it.each(['before scope cleanup', 'during scope cleanup'])('does not start an idle Agent after disposal begins %s', async (window) => {
+ const adapter = new MockAdapter([textResponse('late reply')])
+ const ctx = await harness(adapter)
+ const cleanupStarted = Promise.withResolvers()
+ const releaseCleanup = Promise.withResolvers()
+ let disposal: Promise | undefined
+ try {
+ const handle = await ctx.agents.create({
+ sessionId: SessionId('idle-disposal-wake'),
+ agentOptions: { provider: 'mock', model: 'mock' },
+ })
+ const agent = handle.agent
+ agent.ctx.effect(() => async () => {
+ cleanupStarted.resolve(undefined)
+ await releaseCleanup.promise
+ })
+ disposal = handle.dispose()
+ if (window === 'during scope cleanup') await cleanupStarted.promise
+ send(agent, 'late wake')
+ await agent.whenIdle()
+
+ expect(agent.session.snapshotEvents().filter(event => event.type === 'turn/start')).toHaveLength(0)
+ expect(adapter.requests).toHaveLength(0)
+ } finally {
+ releaseCleanup.resolve(undefined)
+ try {
+ await disposal
+ } finally {
+ await ctx.fiber.dispose()
+ }
+ }
+ })
+
it('cancel after waking send closes its synchronously opened turn without a step', async () => {
const adapter = new MockAdapter([textResponse('should not run')])
const ctx = await harness(adapter)
diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs
index 8cc624caae..e3e659f15c 100644
--- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs
+++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs
@@ -6,7 +6,44 @@ export const name = 'serial-created-fixture'
export const inject = ['agents', 'sessions']
/** Install ordered creation listeners whose context must precede the first turn. */
-export function apply(ctx) {
+export function apply(ctx, config = {}) {
+ const checkedCancellation = new WeakSet()
+ ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => {
+ if (checkedCancellation.has(agent)
+ || (!config.checkRootCancellation && agent.session.header.origin !== 'subagent')) return next()
+ checkedCancellation.add(agent)
+ const pending = {
+ id: randomUUID(), role: 'user',
+ content: [{ type: 'text', text: 'Cancellation checkpoint probe.' }],
+ source: { kind: `plugin:${name}` },
+ }
+ agent.inject(pending)
+ const failure = new Error('fixture queue-clear refusal')
+ const stopRejecting = ctx.on('internal/dispatch', (_mode, eventName, args) => {
+ if (eventName !== 'session/event') return
+ const [session, event] = args
+ if (session === agent.session && event.type === 'agent/inbox/spliced'
+ && event.data.outcome === 'canceled' && (event.data.removedCount ?? 0) > 0) throw failure
+ })
+ let rejected = false
+ try {
+ try {
+ agent.cancel({ kind: 'user' })
+ } catch (error) {
+ if (error !== failure) throw error
+ rejected = true
+ }
+ } finally {
+ stopRejecting()
+ }
+ if (!rejected || !signal.aborted) throw new Error('expected queue-clear rejection and activity cancellation')
+ agent.inbox.remove(pending.id)
+ for (const message of messages) {
+ const ordinary = message.source.kind === 'user'
+ agent.send(message, ordinary ? 'next-turn' : 'next-step', ordinary)
+ }
+ return next()
+ })
const ready = new WeakSet()
ctx.on('agent/created', async ({ agent }) => {
await setImmediate()
diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts
new file mode 100644
index 0000000000..0ce7898bb2
--- /dev/null
+++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts
@@ -0,0 +1,163 @@
+import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'
+import { afterEach, expect, it, vi } from 'vitest'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { Context } from '@deepseek-ai/cordis'
+import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
+import AgentLoop from '@deepseek-ai/dsh-agent-loop'
+import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm'
+import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
+import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
+import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
+import * as CheckpointPolicy from '@deepseek-ai/dsh-session-checkpoint-policy'
+import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
+import ToolRuntime from '@deepseek-ai/dsh-tools'
+import { MockAdapter, textResponse } from './mock-adapter.ts'
+
+const fixtures: { ctx: Context; agent?: Agent; root: string }[] = []
+afterEach(async () => {
+ for (const fixture of fixtures.splice(0)) {
+ try {
+ fixture.agent?.cancel({ kind: 'disposed' }, { keepInbox: true })
+ await fixture.agent?.whenIdle()
+ await fixture.ctx.fiber.dispose()
+ } finally {
+ await rm(fixture.root, { recursive: true, force: true })
+ }
+ }
+})
+
+const input = (text: string) => createUserMessage({ content: [{ type: 'text' as const, text }], source: { kind: 'user' as const } })
+
+async function harness() {
+ const ctx = new Context()
+ const root = await mkdtemp(join(tmpdir(), 'dsh-input-atomicity-'))
+ const fixture: { ctx: Context; agent?: Agent; root: string } = { ctx, root }
+ fixtures.push(fixture)
+ await ctx.plugin(LlmRuntime)
+ await ctx.plugin(SessionStore)
+ await ctx.plugin(SessionProjectionRegistry)
+ await ctx.plugin(SystemPrompt)
+ await ctx.plugin(ToolRuntime)
+ await ctx.plugin(NativeToolExecutor)
+ await ctx.plugin(AgentRegistry)
+ await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
+ await ctx.plugin(CheckpointPolicy)
+ await ctx.plugin(AgentLoop, { agents: [] })
+ const adapter = new MockAdapter(Array.from({ length: 5 }, () => textResponse('ok')))
+ ctx.llm.registerAdapter(['mock'], adapter)
+ const handle = await ctx.agents.create({ sessionId: SessionId('diagnostic'), agentOptions: { provider: 'mock', model: 'mock' } })
+ fixture.agent = handle.agent
+ return { ctx, root, adapter, handle, agent: handle.agent }
+}
+
+it('cancellation still aborts the running request when queue clearing fails', async () => {
+ const { ctx, agent } = await harness()
+ const entered = Promise.withResolvers()
+ const release = Promise.withResolvers()
+ const hold = ctx.on('agent/pre-step', async ({ signal }, next) => { entered.resolve(signal); await release.promise; return next() })
+ let stopRejecting = () => {}
+ try {
+ agent.followup(input('running'))
+ const signal = await entered.promise
+ agent.inject(input('steering'))
+ const queued = input('queued')
+ agent.followup(queued)
+ stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => {
+ if (name !== 'session/event') return
+ const [session, event] = args as [Session, SessionEvent]
+ if (session === agent.session && event.type === 'agent/inbox/spliced' && event.data.target === 'next-turn'
+ && (event.data.removedCount ?? 0) > 0) throw new Error('injected queue clear failure')
+ })
+ expect(() => { agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure')
+ expect(signal.aborted).toBe(true)
+ expect(agent.inbox.nextTurn).toEqual([queued])
+ } finally {
+ stopRejecting()
+ hold()
+ agent.cancel({ kind: 'disposed' }, { keepInbox: true })
+ release.resolve(undefined)
+ await agent.whenIdle()
+ }
+})
+
+it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => {
+ const { ctx, agent, handle } = await harness()
+ const release = Promise.withResolvers()
+ const waiting = Promise.withResolvers<'waiting'>()
+ const disposed = Promise.withResolvers<'disposed'>()
+ let scopeDisposed = false
+ agent.ctx.effect(() => () => { scopeDisposed = true; disposed.resolve('disposed') })
+ const work = agent.runMaintenance(async () => {
+ await release.promise
+ agent.session.append('request/context', { provider: 'mock', model: 'mock' })
+ })
+ agent.inject(input('pending'))
+ const stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => {
+ if (name !== 'session/event') return
+ const [session, event] = args as [Session, SessionEvent]
+ if (session === agent.session && event.type === 'agent/inbox/spliced' && (event.data.removedCount ?? 0) > 0) {
+ throw new Error('queue clear failed')
+ }
+ })
+ const whenIdle = agent.whenIdle.bind(agent)
+ const spy = vi.spyOn(agent, 'whenIdle').mockImplementation(() => { waiting.resolve('waiting'); return whenIdle() })
+ const closing = handle.dispose().then(() => undefined, (error: unknown) => error)
+ try {
+ expect(await Promise.race([waiting.promise, disposed.promise])).toBe('waiting')
+ expect(scopeDisposed).toBe(false)
+ expect(ctx.sessions.get(agent.id)).toBe(agent.session)
+ release.resolve(undefined)
+ await work
+ expect(await closing).toEqual(new Error('queue clear failed'))
+ expect(scopeDisposed).toBe(true)
+ expect(agent.session.snapshotEvents().at(-1)?.type).toBe('request/context')
+ } finally {
+ stopRejecting()
+ spy.mockRestore()
+ release.resolve(undefined)
+ await work
+ await closing
+ }
+})
+
+it('reports a quiescence failure while releasing the Agent and Session', async () => {
+ const { ctx, agent, handle } = await harness()
+ const failure = new Error('injected quiescence failure')
+ const idle = vi.spyOn(agent, 'whenIdle').mockRejectedValueOnce(failure)
+ try {
+ await expect(handle.dispose()).rejects.toThrow('injected quiescence failure')
+ expect(ctx.agents.get(agent.id)).toBeUndefined()
+ expect(ctx.sessions.get(agent.id)).toBeUndefined()
+ } finally {
+ idle.mockRestore()
+ }
+})
+
+it('keeps creation resources alive until an interrupted creation listener finishes', async () => {
+ const { ctx } = await harness()
+ const entered = Promise.withResolvers()
+ const release = Promise.withResolvers()
+ const signal = new AbortController()
+ const id = SessionId('interrupted-announcement')
+ const stop = ctx.on('agent/created', async ({ agent }) => {
+ if (agent.id !== id) return
+ entered.resolve(agent)
+ await release.promise
+ })
+ const creation = ctx.agents.create({ sessionId: id, agentOptions: { provider: 'mock', model: 'mock' }, signal: signal.signal })
+ .then(handle => handle.dispose(), (error: unknown) => error)
+ try {
+ const agent = await entered.promise
+ signal.abort(new Error('creation interrupted'))
+ expect(ctx.sessions.get(id)).toBe(agent.session)
+ release.resolve(undefined)
+ expect(await creation).toEqual(new Error('creation interrupted'))
+ expect(ctx.sessions.get(id)).toBeUndefined()
+ } finally {
+ release.resolve(undefined)
+ await creation
+ stop()
+ }
+})
diff --git a/packages/core/agent-loop/tests/request-freeze.spec.ts b/packages/core/agent-loop/tests/request-freeze.spec.ts
index 8ed1c4d138..f4ef29eea3 100644
--- a/packages/core/agent-loop/tests/request-freeze.spec.ts
+++ b/packages/core/agent-loop/tests/request-freeze.spec.ts
@@ -79,7 +79,8 @@ describe('loop-owned request freezing', () => {
const inbox = await loopCtx.sessionProjections.register(inboxProjectionDefinition)
const model = await loopCtx.sessionProjections.register(modelSelectionProjectionDefinition)
const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session,
- { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn)
+ { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn,
+ new AbortController().signal)
cleanups.push(async () => {
agent.cancel({ kind: 'disposed' })
await agent.whenIdle()
@@ -129,7 +130,8 @@ describe('loop-owned request freezing', () => {
expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1)
expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1)
const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session,
- { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn)
+ { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn,
+ new AbortController().signal)
cleanups.push(async () => {
resumed.cancel({ kind: 'disposed' })
await resumed.whenIdle()
diff --git a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts
index d6a6f50730..4b01c61f80 100644
--- a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts
+++ b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts
@@ -446,7 +446,9 @@ describe('agent scope lifecycle', () => {
})
it('uses signal only for creation: aborts pending setup but not a returned live handle', async () => {
- const ctx = await harness()
+ const adapter = new MockAdapter([textResponse('ok')])
+ const ctx = await harness(adapter)
+ onTestFinished(() => ctx.fiber.dispose())
const pendingController = new AbortController()
const setupStarted = Promise.withResolvers()
const pending = ctx.agents.create({
@@ -474,6 +476,9 @@ describe('agent scope lifecycle', () => {
await Promise.resolve()
expect(ctx.agents.get(live.agent.id)).toBe(live.agent)
expect(live.agent.status).toBe('idle')
+ live.agent.followup(createUserMessage({ content: text('continue'), source: { kind: 'user' } }))
+ await live.agent.whenIdle()
+ expect(adapter.requests).toHaveLength(1)
await live.dispose()
})
diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml
index 358d56ae02..46e9eb2a5a 100644
--- a/packages/core/agent/README.i18n.yaml
+++ b/packages/core/agent/README.i18n.yaml
@@ -24,8 +24,8 @@
en: 85b0ff72a187110f
zh: 3f61c1568d27b8bc
/deepseek-ai-dsh-agent/use-this-package/drive-an-agent-s-conversation:
- en: 71e258897e2e7d73
- zh: abf0991012faa17e
+ en: 8dcb90a344e7ef2c
+ zh: d48f07379f4674d6
/deepseek-ai-dsh-agent/use-this-package/scope-registrations-to-one-agent:
en: 2594a1e02adea801
zh: cae8860369728efb
diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md
index c84ac3d237..c7ff87b6d0 100644
--- a/packages/core/agent/README.md
+++ b/packages/core/agent/README.md
@@ -55,7 +55,7 @@ For scoped switch notices, call `installModelSelection(agentCtx)` from `dsh-agen
### Drive an agent's conversation
-The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence.
+The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. A queue-write failure during cancellation still aborts active work and propagates to the caller.
```text
handle.agent.followup({
diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md
index a2fae55b56..98cda69819 100644
--- a/packages/core/agent/README.zh.md
+++ b/packages/core/agent/README.zh.md
@@ -55,7 +55,7 @@ await handle.dispose() // stops the loop, unregisters, removes the session, un
### 驱动 agent 的对话
-句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。
+句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。取消期间的队列写入失败仍会中止当前工作,并把错误传给调用方。
```text
handle.agent.followup({
diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts
index 2b1698e39c..7012dfdf50 100644
--- a/packages/core/agent/src/runtime-types.ts
+++ b/packages/core/agent/src/runtime-types.ts
@@ -206,6 +206,7 @@ declare module './types.ts' {
* Clear queued and steering work — unless `keepInbox` — and abort the active
* turn or between-turn task. The first cause wins for that activity. With no
* active activity, cancellation is a no-op and does not arm later work.
+ * Queue-write failures still abort the activity and propagate to the caller.
* @param cause - the stable caller intent carried by the active operation signal.
* @param options - cancellation options; `keepInbox` preserves pending work.
*/
diff --git a/packages/core/session/README.i18n.yaml b/packages/core/session/README.i18n.yaml
index 376a117359..0d793887f4 100644
--- a/packages/core/session/README.i18n.yaml
+++ b/packages/core/session/README.i18n.yaml
@@ -30,8 +30,8 @@
en: 002b8240caa0c57c
zh: e0954dd62913a944
/deepseek-ai-dsh-session/use-this-package/fork-a-session:
- en: 1c40d17a786059d3
- zh: 81320ce118977c65
+ en: 4fcc9eb5c0278b51
+ zh: 2a26e81ebffbd9a6
/deepseek-ai-dsh-session/use-this-package/flush-durable-state:
en: 70a7673145c851ad
zh: 0dd1667d9518993d
diff --git a/packages/core/session/README.md b/packages/core/session/README.md
index 0f368e9ead..3b55b1fcce 100644
--- a/packages/core/session/README.md
+++ b/packages/core/session/README.md
@@ -83,6 +83,8 @@ The [experimental persistence catalog](../../../docs/experimental-persistence-ca
The logical `SessionHeader.isSeeded` field reports whether fork history exists without exposing a positional integer. `Session.inheritedEventCount` retains the exact checked `SessionLogOffset`; `ownEvents()` returns events at and after that cut, and `isOwnSeq(seq)` accepts only an existing child-owned position. A low-level seeded constructor must supply an explicit `seed` and `inheritedEventCount` because the constructor seed can contain child-owned setup events after the inherited prefix.
+`session.append(type, data, ...opts)` appends one event and returns that event. `session.append(inputs)` accepts a readonly array of positional `[type, data, ...opts]` tuples (`SessionEventInput`) and returns the committed events in input order; an empty array appends nothing. Array admission validates every candidate and synchronous dispatch before changing the log or message surface, so observers read the complete committed group. Persistence listeners retain their own durability rules; array admission alone does not guarantee crash-atomic storage.
+
### Flush durable state
`ctx.sessions.flush(session)` dispatches the awaited durability checkpoint: every persistence listener flushes and the call settles after all of them. A producer that needs an immediate durability barrier awaits it instead of assuming the write-behind drained.
diff --git a/packages/core/session/README.zh.md b/packages/core/session/README.zh.md
index 9b4a192d81..9ca25d8a11 100644
--- a/packages/core/session/README.zh.md
+++ b/packages/core/session/README.zh.md
@@ -83,6 +83,8 @@ session.deriveMessages() // the derived model history
逻辑 `SessionHeader.isSeeded` 字段报告是否存在 fork 历史,而不公开位置整数。`Session.inheritedEventCount` 保留经过校验的精确 `SessionLogOffset`;`ownEvents()` 返回从该切点开始的事件,`isOwnSeq(seq)` 只接受已存在且由子会话拥有的位置。底层带 seed 构造必须显式提供 `seed` 与 `inheritedEventCount`,因为构造 seed 可以在继承前缀之后包含子会话自有的设置事件。
+`session.append(type, data, ...opts)` 追加一个事件并返回该事件。`session.append(inputs)` 接受位置参数元组 `[type, data, ...opts]`(`SessionEventInput`)的只读数组,并按输入顺序返回已提交事件;空数组不追加任何内容。数组准入会在改变日志或surface前验证所有候选和同步分发,因此观察者读取完整的已提交组。持久化监听器保留各自的持久性规则;仅数组准入不保证进程崩溃时整组存储的原子性。
+
### 刷新持久状态
`ctx.sessions.flush(session)` 分发需等待完成的持久性检查点:每个持久化监听器都会刷新,调用在所有监听器结算后完成。需要立即持久性屏障的生产方应等待它,而不是假定延后写入已经排空。
diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts
index e9baee1b82..ea6c337f55 100644
--- a/packages/core/session/src/index.ts
+++ b/packages/core/session/src/index.ts
@@ -15,7 +15,7 @@ import type { Scoped } from '@deepseek-ai/dsh-scope'
import type { Message } from '@deepseek-ai/dsh-llm'
import { SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from './types.ts'
import type { TypertLookup } from '@deepseek-ai/dsh-typert-protocol'
-import type { CreateSessionOptions, EpochHeader, PluginRecord, PluginRecordMap, PluginRecordType, PrepareSessionOptions, RequestContext, SessionEvent, SessionEventMap, SessionEventType, SessionHeader, SessionId, SessionSeedEventState, SurfaceIntent, SurfaceEventType } from './types.ts'
+import type { CreateSessionOptions, EpochHeader, PluginRecord, PluginRecordMap, PluginRecordType, PrepareSessionOptions, RequestContext, SessionEvent, SessionEventInput, SessionEventMap, SessionEventType, SessionHeader, SessionId, SessionSeedEventState, SurfaceIntent, SurfaceEventType } from './types.ts'
import { SurfaceManager, validateSessionEventData, validateSurfaceMetadata } from './surface.ts'
import type { SessionSurface, SessionMessageProjection } from './surface.ts'
import { foldRequestHeader } from './request-header.ts'
@@ -67,6 +67,9 @@ declare module '@deepseek-ai/cordis' {
* Post-commit, fire-and-forget append feed. The listener snapshot resolves
* before the log push, but callbacks run after it; observer failures are
* logged and contained without making the committed append fail.
+ * Array append commits every member before publishing them in order;
+ * `session.seq` and `session.surface` already include the complete batch.
+ * `session.currentBatchPublication` identifies the member being delivered.
* Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
* receive only events from sessions entered through that agent's context.
* @param session - the session whose log grew.
@@ -514,6 +517,33 @@ export function pluginRecordOf(event: SessionEvent): PluginRecord | undefined {
return { type, seq: event.seq, time: event.time, data: event.data }
}
+/** Copy live append inputs before sequence assignment. */
+function snapshotAppend(
+ type: SessionEventType,
+ data: SessionEventMap[SessionEventType] | undefined,
+ opts: SurfaceIntent | undefined,
+ subject: string,
+) {
+ const surfaceOp = opts?.surfaceOp
+ const sourceEventSeqs = opts?.sourceEventSeqs
+ const dataSnapshot = snapshotJsonValue(data)
+ if (dataSnapshot === undefined) throw new Error(`${subject} carries non-JSON-serializable data`)
+ const surface = snapshotJsonValue({
+ ...sourceEventSeqs === undefined ? {} : { sourceEventSeqs },
+ ...surfaceOp === undefined ? {} : { surfaceOp },
+ })
+ if (surface === undefined) throw new Error(`${subject} carries non-JSON-serializable surface metadata`)
+ return { type, data: dataSnapshot, surface }
+}
+
+/** Construct and validate one live event from detached inputs. */
+function createAppendEvent(snapshot: ReturnType, seq: SessionSeq): SessionEvent {
+ const { type, data, surface } = snapshot
+ const event = deepFreeze({ type, seq, time: Date.now(), data, ...surface } as SessionEvent)
+ validateSessionEventData(event, `session event "${type}" at seq ${seq}`)
+ return event
+}
+
/**
* An event-sourced session: an append-only log of {@link SessionEvent}s.
*
@@ -524,6 +554,7 @@ export function pluginRecordOf(event: SessionEvent): PluginRecord | undefined {
*/
export class Session {
private log: SessionEvent[] = []
+ private batchPublication: SessionEvent | undefined
/** Single incremental owner of surface acceptance and projection state. */
private readonly surfaceManager: SurfaceManager
@@ -761,6 +792,22 @@ export class Session {
return SessionLogOffset(this.log.length)
}
+ /** Current event while synchronously notifying a batch's observers. */
+ get currentBatchPublication(): SessionEvent | undefined {
+ return this.batchPublication
+ }
+
+ /**
+ * Append consecutive events together after validating every candidate and dispatch.
+ * Observers read the complete committed log and final message surface.
+ * Listener registration changes during publication take effect on the next append.
+ * Persistence listeners retain their own durability rules.
+ * @param inputs - event payloads and surface intents in commit order. An empty array records no events.
+ * @returns immutable committed events in the same order.
+ * @throws if the Session cannot accept writes, including an empty append, or any candidate or synchronous dispatch validation fails.
+ */
+ append(inputs: readonly SessionEventInput[]): readonly SessionEvent[]
+
/**
* Append one typed event to the log and synchronously notify observers via
* the store-owned, module-private publication hooks. The hot path never blocks
@@ -807,35 +854,68 @@ export class Session {
type: T,
data: SessionEventMap[T],
...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : []
- ): SessionEvent {
+ ): SessionEvent
+ append(
+ type: SessionEventType | readonly SessionEventInput[],
+ data?: SessionEventMap[SessionEventType],
+ ...opts: [opts?: SurfaceIntent]
+ ): SessionEvent | readonly SessionEvent[] {
+ if (typeof type !== 'string') return this.#appendEvents(type)
this.publicationEntry()
- const surfaceOpts: SurfaceIntent | undefined = opts[0]
- const surfaceMetadata = {
- ...surfaceOpts?.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: surfaceOpts.sourceEventSeqs },
- ...surfaceOpts?.surfaceOp === undefined ? {} : { surfaceOp: surfaceOpts.surfaceOp },
- }
- const dataSnapshot = snapshotJsonValue(data)
- if (dataSnapshot === undefined) {
- throw new Error(`session event "${type}" carries non-JSON-serializable data`)
- }
- const surfaceMetadataSnapshot = snapshotJsonValue(surfaceMetadata)
- if (surfaceMetadataSnapshot === undefined) {
- throw new Error(`session event "${type}" carries non-JSON-serializable surface metadata`)
- }
+ const snapshot = snapshotAppend(type, data, opts[0], `session event "${type}"`)
// Payload getters can detach the Session while the snapshots are read.
const entry = this.publicationEntry()
- const event = deepFreeze({
- type,
- seq: SessionSeq(this.log.length),
- time: Date.now(),
- data: dataSnapshot,
- ...(surfaceMetadataSnapshot as { surfaceOp?: unknown; sourceEventSeqs?: unknown }),
- } as unknown as SessionEvent)
- validateSessionEventData(event, `session event "${type}" at seq ${event.seq}`)
- this.commit(event as SessionEvent, entry)
+ const event = createAppendEvent(snapshot, SessionSeq(this.log.length))
+ this.commit(event, entry)
return event
}
+ /**
+ * Validate and publish consecutive events together. Observers see the complete log.
+ * @param inputs - event payloads and surface intents in commit order.
+ * @returns immutable committed events in the same order.
+ * @throws before changing the log if any candidate or synchronous dispatch validation fails.
+ */
+ #appendEvents(inputs: readonly SessionEventInput[]): readonly SessionEvent[] {
+ this.publicationEntry()
+ if (inputs.length === 0) return []
+ const snapshots = Array.from({ length: inputs.length }, (_, index) => {
+ const input = inputs.at(index)
+ if (input === undefined) throw new Error(`session batch has an empty member at index ${index}`)
+ const [type, data, surfaceOpts] = input
+ return snapshotAppend(type, data, surfaceOpts, `session batch member ${index} ("${type}")`)
+ })
+ // Payload getters may append to or detach the Session.
+ const entry = this.publicationEntry()
+ const startSeq = this.log.length
+ const events = snapshots.map((snapshot, index) => createAppendEvent(snapshot, SessionSeq(startSeq + index)))
+ const acceptSurface = this.surfaceManager.prepareBatch(events)
+ if (entry !== undefined) entry.appending = true
+ try {
+ const publications = entry === undefined ? [] : events.map((event) => {
+ const args: unknown[] = [this, event]
+ const callbacks = collectSessionCallbacks(entry.emitCtx, [entry.carrier, 'session/event', ...args])
+ return { event, args, callbacks }
+ })
+ for (const event of events) this.log.push(event)
+ this.eventsSnapshot = undefined
+ acceptSurface()
+ if (entry !== undefined) {
+ for (const { event, args, callbacks } of publications) {
+ this.batchPublication = event
+ invokeContainedSessionObservers(entry.emitCtx, 'session/event', entry.id, args, callbacks)
+ }
+ }
+ } finally {
+ this.batchPublication = undefined
+ if (entry !== undefined) {
+ entry.appending = false
+ if (entry.detachRequested) entry.detach()
+ }
+ }
+ return events
+ }
+
static {
commitPluginRecord = (session, type, data) => session.#appendRecord(type, data)
}
diff --git a/packages/core/session/src/surface.ts b/packages/core/session/src/surface.ts
index 0bb84c030e..7a13bc1d7c 100644
--- a/packages/core/session/src/surface.ts
+++ b/packages/core/session/src/surface.ts
@@ -367,14 +367,13 @@ function assertSourceEventReferences(
/** Resolve tool additions against their immutable historical request header. */
function assertDeveloperHeader(
event: SessionEvent,
- events: readonly SessionEvent[],
- baseSeq: SessionLogOffset,
+ read: (seq: number) => SessionEvent | undefined,
): void {
if (event.type !== 'developer/message') return
validateSessionEventData(event, `developer/message at seq ${event.seq}`)
if (event.data.headerSeq === undefined) return
const headerSeq = event.data.headerSeq
- const headerEvent = events[headerSeq - baseSeq]
+ const headerEvent = read(headerSeq)
if (headerSeq >= event.seq || headerEvent?.type !== 'request/header') {
throw new Error('developer/message headerSeq must reference an earlier request/header')
}
@@ -456,15 +455,14 @@ function isDeepEqualJson(a: unknown, b: unknown): boolean {
function assertToolResultRewrite(
event: SessionEvent,
shadowedSeqs: readonly SessionSeq[],
- events: readonly SessionEvent[],
- baseSeq: SessionLogOffset,
+ read: (seq: number) => SessionEvent | undefined,
): void {
if (event.type !== 'tool/result') return
if (shadowedSeqs.length !== 1) {
throw new Error('tool/result surface replacement must rewrite exactly one current node')
}
for (const originalSeq of shadowedSeqs) {
- const original = events[originalSeq - baseSeq]
+ const original = read(originalSeq)
if (original?.type !== 'tool/result') {
throw new Error('tool/result surface replacement must target a current tool/result')
}
@@ -495,11 +493,10 @@ function assertSystemHeadRewrite(
state: SurfaceFoldState,
startIdx: number,
shadowedSeqs: readonly SessionSeq[],
- events: readonly SessionEvent[],
- baseSeq: SessionLogOffset,
+ read: (seq: number) => SessionEvent | undefined,
): void {
if (startIdx !== 0) return
- const head = events[state.nodes[0] as number - baseSeq]
+ const head = read(state.nodes[0] as number)
if (head?.type !== 'system/message') return
if (event.type !== 'system/message' || shadowedSeqs.length !== 1) {
throw new Error('surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node')
@@ -514,16 +511,25 @@ function planSurfaceEvent(
events: readonly SessionEvent[],
baseSeq: SessionLogOffset,
projections: readonly SessionMessageProjection[],
+ candidates?: readonly SessionEvent[],
): SurfacePlan | undefined {
if (event.seq !== expectedSeq) {
throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`)
}
const surfaceOp = validateSurfaceMetadata(event)
- assertDeveloperHeader(event, events, baseSeq)
+ const read = (seq: number): SessionEvent | undefined => {
+ const index = seq - baseSeq
+ return index < events.length ? events[index] : candidates?.[index - events.length]
+ }
+ assertDeveloperHeader(event, read)
const projection = projections.find(item => item.type === event.type)
if (projection !== undefined) {
+ let projectionEvents: readonly SessionEvent[] | undefined
return { kind: 'project', projection, messages: projection.project(event, {
- nodes: state.nodes, events, baseSeq, messages: state.projectedMessages,
+ nodes: state.nodes,
+ get events() { return candidates === undefined ? events : (projectionEvents ??= [...events, ...candidates]) },
+ baseSeq,
+ messages: state.projectedMessages,
}) }
}
if (MESSAGE_PROJECTION_EVENT_TYPES.has(event.type)) {
@@ -535,8 +541,8 @@ function planSurfaceEvent(
}
const range = replacementRange(state, surfaceOp)
assertSourceEventReferences(event, range.shadowedSeqs)
- assertToolResultRewrite(event, range.shadowedSeqs, events, baseSeq)
- assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, events, baseSeq)
+ assertToolResultRewrite(event, range.shadowedSeqs, read)
+ assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, read)
return {
kind: 'replace',
seq: event.seq,
@@ -645,6 +651,46 @@ export class SurfaceManager implements SessionSurface {
}
}
+ /**
+ * Validate consecutive candidates against an isolated surface fold.
+ * @param events - candidates immediately following the committed log.
+ * @returns a callback adopting the validated fold after all candidates enter the log.
+ */
+ prepareBatch(events: readonly SessionEvent[]): () => void {
+ this._assertProjections()
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta()
+ const lastProcessedSeq = SessionSeq(this.baseSeq + this.log.length + events.length - 1)
+ if (events.every(event => (event.surfaceOp === undefined || event.surfaceOp === 'append')
+ && !this.projections.some(projection => projection.type === event.type))) {
+ const plans = events.map((event, index) => planSurfaceEvent(
+ this._state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events,
+ ))
+ return () => {
+ for (const plan of plans) applySurfacePlan(this._state, plan)
+ this._lastProcessedSeq = lastProcessedSeq
+ this._pendingPlan = undefined
+ }
+ }
+ const state: SurfaceFoldState = {
+ ...this._state,
+ nodes: [...this._state.nodes],
+ projectedMessages: new Map(this._state.projectedMessages),
+ projections: new Set(this._state.projections),
+ }
+ const plans = events.map((event, index) => {
+ const plan = planSurfaceEvent(
+ state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events,
+ )
+ applySurfacePlan(state, plan)
+ return plan
+ })
+ return () => {
+ for (const plan of plans) applySurfacePlan(this._state, plan)
+ this._lastProcessedSeq = lastProcessedSeq
+ this._pendingPlan = undefined
+ }
+ }
+
/** Monotonic count of folded positional replacements. */
get replaceGeneration(): number {
this._assertProjections()
diff --git a/packages/core/session/src/types.ts b/packages/core/session/src/types.ts
index 7787dd9bd0..0cf13c86a0 100644
--- a/packages/core/session/src/types.ts
+++ b/packages/core/session/src/types.ts
@@ -485,6 +485,11 @@ export type SurfaceIntent = {
sourceEventSeqs?: SessionSeq[]
})
+/** One positional event call proposed for append, without assigned sequence or time. */
+export type SessionEventInput = {
+ [K in SessionEventType]: readonly [type: K, data: SessionEventMap[K], ...opts: K extends SurfaceEventType ? [opts: SurfaceIntent] : []]
+}[SessionEventType]
+
/**
* One immutable entry in the session log.
*
diff --git a/packages/core/session/tests/append.spec.ts b/packages/core/session/tests/append.spec.ts
new file mode 100644
index 0000000000..ecc5a514c4
--- /dev/null
+++ b/packages/core/session/tests/append.spec.ts
@@ -0,0 +1,213 @@
+import { describe, expect, it, onTestFinished } from 'vitest'
+import { Context } from '@deepseek-ai/cordis'
+import { createUserMessage } from '@deepseek-ai/dsh-llm'
+import SessionStore, { Session, SessionId, SessionSeq, type SessionEventInput } from '@deepseek-ai/dsh-session'
+
+function message(text: string) {
+ return createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })
+}
+
+describe('multiple Session appends', () => {
+ it('rejects sparse arrays before changing the log or surface', () => {
+ const session = Session.create(SessionId('sparse-append'))
+ const inputs = new Array(3)
+ inputs[0] = ['turn/start', { turn: 1 }]
+ inputs[2] = ['user/message', message('last'), { surfaceOp: 'append' }]
+ expect(() => session.append(inputs)).toThrow(/empty member at index 1/)
+ expect(session.seq).toBe(0)
+ expect(session.surface.nodes).toEqual([])
+ })
+
+ it('reads only surface metadata from event options', () => {
+ const session = Session.create(SessionId('options-append'))
+ const old = session.append('user/message', message('old'), { surfaceOp: 'append' })
+ const next = message('new')
+ const events = session.append([['user/message', next, old]])
+ expect(events[0]?.data).toEqual(next)
+ expect(session.deriveMessages()).toEqual([old.data, next])
+ })
+
+ it('leaves the log unchanged for empty input and accepts a single array member', () => {
+ const session = Session.create(SessionId('empty-append'))
+ expect(session.append([])).toEqual([])
+ expect(session.seq).toBe(0)
+ const events = session.append([['turn/start', { turn: 1 }]])
+ expect(events).toHaveLength(1)
+ expect(events[0]).toMatchObject({ type: 'turn/start', seq: 0, data: { turn: 1 } })
+ })
+
+ it('accepts both call forms through an append wrapper', () => {
+ const session = Session.create(SessionId('wrapped-append'))
+ const append = new Proxy(session.append.bind(session), {
+ apply: (target, receiver, args): unknown => Reflect.apply(target, receiver, args),
+ })
+ session.append = append
+ expect(session.append('turn/start', { turn: 1 }).seq).toBe(0)
+ expect(session.append([['step/start', { turn: 1, step: 1 }]])).toHaveLength(1)
+ })
+
+ it('publishes each member after the complete log and surface are committed', async () => {
+ const ctx = new Context()
+ onTestFinished(async () => { await ctx.fiber.dispose() })
+ await ctx.plugin(SessionStore)
+ const session = ctx.sessions.create(SessionId('observed-append'))
+ const observed: number[] = []
+ ctx.on('session/event', (current, event) => {
+ if (current !== session) return
+ expect(current.currentBatchPublication).toBe(event)
+ expect(current.seq).toBe(2)
+ expect(current.surface.nodes).toEqual([1])
+ expect(current.deriveMessages()).toEqual([messageValue])
+ observed.push(event.seq)
+ })
+ const messageValue = message('visible')
+ session.append([
+ ['turn/start', { turn: 1 }],
+ ['user/message', messageValue, { surfaceOp: 'append' }],
+ ])
+ expect(observed).toEqual([0, 1])
+ expect(session.currentBatchPublication).toBeUndefined()
+ })
+
+ it('replaces an earlier member in the same append', () => {
+ const session = Session.create(SessionId('replace-append'))
+ const nodes = session.surface.nodes
+ const replacement = message('replacement')
+ session.append([
+ ['user/message', message('original'), { surfaceOp: 'append' }],
+ ['user/message', replacement, { surfaceOp: { op: 'replace', startSeq: SessionSeq(0), endSeq: SessionSeq(0) }, sourceEventSeqs: [SessionSeq(0)] }],
+ ])
+ expect(nodes).toEqual([1])
+ expect(session.deriveMessages()).toEqual([replacement])
+ })
+
+ it('rejects non-JSON data before publishing any member', () => {
+ const session = Session.create(SessionId('non-json-append'))
+ expect(() => session.append([
+ ['turn/start', { turn: 1 }],
+ ['turn/start', { turn: Number.NaN }],
+ ])).toThrow('session batch member 1 ("turn/start") carries non-JSON-serializable data')
+ expect(session.seq).toBe(0)
+ })
+
+ it('assigns consecutive sequences after a candidate getter appends an event', () => {
+ const session = Session.create(SessionId('getter-append'))
+ const events = session.append([
+ ['turn/start', {
+ get turn() {
+ session.append('request/context', { provider: 'mock', model: 'mock' })
+ return 1
+ },
+ }],
+ ['step/start', { turn: 1, step: 1 }],
+ ])
+ expect(events.map(event => event.seq)).toEqual([1, 2])
+ expect(session.snapshotEvents().map(event => event.type)).toEqual(['request/context', 'turn/start', 'step/start'])
+ })
+
+ it('contains a reentrant append while publishing the remaining members', async () => {
+ const ctx = new Context()
+ onTestFinished(async () => { await ctx.fiber.dispose() })
+ await ctx.plugin(SessionStore)
+ const session = ctx.sessions.create(SessionId('reentrant-batch'))
+ const observed: number[] = []
+ const warnings: string[] = []
+ ctx.logger.warn = (warning: unknown) => { warnings.push(String(warning)) }
+ ctx.on('session/event', (current, event) => {
+ if (current === session && event.seq === 0) {
+ session.append('request/context', { provider: 'mock', model: 'mock' })
+ }
+ })
+ ctx.on('session/event', (current, event) => {
+ if (current === session) observed.push(event.seq)
+ })
+ session.append([
+ ['turn/start', { turn: 1 }],
+ ['step/start', { turn: 1, step: 1 }],
+ ])
+ expect(session.seq).toBe(2)
+ expect(observed).toEqual([0, 1])
+ expect(warnings).toEqual([expect.stringContaining('session append cannot reenter')])
+ })
+
+ it('detaches only after every member has been observed', async () => {
+ const ctx = new Context()
+ onTestFinished(async () => { await ctx.fiber.dispose() })
+ await ctx.plugin(SessionStore)
+ const session = ctx.sessions.prepare(SessionId('detached-append'))
+ const detach = ctx.sessions.enter(session)
+ ctx.sessions.announce(session)
+ const observed: number[] = []
+ ctx.on('session/event', (current, event) => {
+ expect(ctx.sessions.get(current.id)).toBe(current)
+ detach()
+ observed.push(event.seq)
+ })
+ session.append([
+ ['turn/start', { turn: 1 }],
+ ['step/start', { turn: 1, step: 1 }],
+ ])
+ expect(observed).toEqual([0, 1])
+ expect(ctx.sessions.get(session.id)).toBeUndefined()
+ })
+
+ it('folds preceding single appends before admitting an array', () => {
+ const session = Session.create(SessionId('mixed-append'))
+ session.append('user/message', message('before'), { surfaceOp: 'append' })
+ expect(session.surface.contentGeneration).toBe(0)
+ session.append([['user/message', message('after'), { surfaceOp: 'append' }]])
+ expect(session.surface.nodes).toEqual([0, 1])
+ expect(session.surface.replaceGeneration).toBe(0)
+ })
+
+ it('publishes a complete group with its final surface', () => {
+ const session = Session.create(SessionId('batch'))
+ const events = session.append([
+ ['turn/start', { turn: 1 }],
+ ['user/message', message('hello'), { surfaceOp: 'append' }],
+ ])
+ expect(events.map(event => event.seq)).toEqual([0, 1])
+ expect(session.surface.nodes).toEqual([1])
+ expect(session.deriveMessages()).toEqual([events[1]?.data])
+ })
+
+ it('retains the committed log and surface when a later candidate is invalid', () => {
+ const session = Session.create(SessionId('rejected-batch'))
+ session.append('user/message', message('before'), { surfaceOp: 'append' })
+ const before = session.deriveMessages()
+ expect(() => session.append([
+ ['user/message', message('candidate'), { surfaceOp: 'append' }],
+ ['user/message', message('invalid'), { surfaceOp: { op: 'replace', startSeq: SessionSeq(40), endSeq: SessionSeq(41) } }],
+ ])).toThrow()
+ expect(session.seq).toBe(1)
+ expect(session.deriveMessages()).toEqual(before)
+ expect(session.surface.nodes).toEqual([0])
+ })
+
+ it('rejects the entire group when dispatch validation vetoes its last event', async () => {
+ const ctx = new Context()
+ onTestFinished(async () => { await ctx.fiber.dispose() })
+ await ctx.plugin(SessionStore)
+ const session = ctx.sessions.create(SessionId('veto-batch'))
+ const observed: number[] = []
+ ctx.on('session/event', (current, event) => {
+ if (current === session) observed.push(event.seq)
+ })
+ const stop = ctx.on('internal/dispatch', (_mode, name, args) => {
+ if (name !== 'session/event') return
+ const [current, event] = args as [Session, { seq: number }]
+ if (current === session && event.seq === 1) throw new Error('veto final event')
+ })
+ expect(() => session.append([
+ ['turn/start', { turn: 1 }],
+ ['user/message', message('candidate'), { surfaceOp: 'append' }],
+ ])).toThrow('veto final event')
+ expect(session.seq).toBe(0)
+ expect(session.surface.nodes).toEqual([])
+ expect(observed).toEqual([])
+ stop()
+ session.append('turn/start', { turn: 1 })
+ expect(observed).toEqual([0])
+ })
+
+})
diff --git a/packages/core/session/tests/append.type-test.ts b/packages/core/session/tests/append.type-test.ts
new file mode 100644
index 0000000000..297725a048
--- /dev/null
+++ b/packages/core/session/tests/append.type-test.ts
@@ -0,0 +1,24 @@
+/** Compile-time checks for single and multiple event admission. */
+import { expectTypeOf } from 'vitest'
+import type { Session, SessionEvent, SessionEventInput } from '@deepseek-ai/dsh-session'
+import type { UserMessage } from '@deepseek-ai/dsh-llm'
+
+/**
+ * Check result cardinality and event-specific payload and surface requirements.
+ * @param session - target Session; this function is typechecked without execution.
+ * @param message - user input with durable identity.
+ */
+export function checkAppendTypes(session: Session, message: UserMessage): void {
+ expectTypeOf(session.append('turn/start', { turn: 1 })).toEqualTypeOf>()
+ const inputs: readonly SessionEventInput[] = [
+ ['turn/start', { turn: 1 }],
+ ['user/message', message, { surfaceOp: 'append' }],
+ ]
+ expectTypeOf(session.append(inputs)).toEqualTypeOf()
+ // @ts-expect-error -- message-producing members require a surface operation.
+ session.append([['user/message', message]])
+ // @ts-expect-error -- log-only members cannot carry a surface operation.
+ session.append([['turn/start', { turn: 1 }, { surfaceOp: 'append' }]])
+ // @ts-expect-error -- each payload must match its event type.
+ session.append([['turn/start', message]])
+}
diff --git a/packages/core/session/tests/canonical-envelopes.spec.ts b/packages/core/session/tests/canonical-envelopes.spec.ts
index 1c52750edb..9f66190dcd 100644
--- a/packages/core/session/tests/canonical-envelopes.spec.ts
+++ b/packages/core/session/tests/canonical-envelopes.spec.ts
@@ -37,17 +37,21 @@ function toolData(isError: boolean) {
}
function appendEvent(session: Session, event: SessionEvent) {
- const append = session.append.bind(session) as (
- type: SessionEvent['type'], data: unknown, metadata?: unknown,
- ) => SessionEvent
- return append(event.type, event.data, {
+ return Reflect.apply(session.append.bind(session), session, [event.type, event.data, {
...event.surfaceOp === undefined ? {} : { surfaceOp: event.surfaceOp },
...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs },
- })
+ }]) as SessionEvent
}
const entryPaths: Record unknown> = {
append: (event: SessionEvent) => appendEvent(Session.create(id), event),
+ batch: (event: SessionEvent) => {
+ const session = Session.create(id)
+ return Reflect.apply(session.append.bind(session), session, [[[event.type, event.data, {
+ ...event.surfaceOp === undefined ? {} : { surfaceOp: event.surfaceOp },
+ ...event.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: event.sourceEventSeqs },
+ }]]]) as readonly SessionEvent[]
+ },
seed: (event: SessionEvent) => Session.create(id, [event]),
restore: (event: SessionEvent) => Session.fromRestore(id, [event], { ...header }, SessionLogOffset(0), 'detached'),
adopt: adoptSessionEvent,
@@ -290,7 +294,7 @@ describe('canonical event-local surface metadata', () => {
surfaceOp: { opaque: ['not', 'placement'] }, sourceEventSeqs: { opaque: [null, true] },
} as unknown as SessionEvent
for (const [path, accept] of Object.entries(entryPaths)) {
- if (path === 'append') continue
+ if (path === 'append' || path === 'batch') continue
expect(() => accept(structuredClone(event))).not.toThrow()
}
const session = Session.create(id, [event])
diff --git a/packages/core/session/tests/developer-header.spec.ts b/packages/core/session/tests/developer-header.spec.ts
index de38469c8e..b1d094a6cf 100644
--- a/packages/core/session/tests/developer-header.spec.ts
+++ b/packages/core/session/tests/developer-header.spec.ts
@@ -20,6 +20,28 @@ function opened(tools: ToolSchema[] = [first]) {
}
describe('developer request-header references', () => {
+ it('resolves a tool addition against an earlier header in the same batch', () => {
+ const session = Session.create(SessionId('batch-developer-header'))
+ const message = addition()
+ session.append([
+ ['request/header', { reason: 'initial', header: { config: { provider: 'test', model: 'test' }, tools: [first] } }],
+ ['developer/message', { turn: 1, step: 1, headerSeq: SessionSeq(0), message }, { surfaceOp: 'append' }],
+ ])
+ expect(session.seq).toBe(2)
+ expect(session.deriveMessages()).toEqual([message])
+ expect(foldSurface(session.snapshotEvents()).nodes).toEqual([1])
+ })
+
+ it.each([1, 2])('rejects a non-earlier batch header reference %s without committing a prefix', (reference) => {
+ const session = Session.create(SessionId('invalid-batch-developer-header'))
+ expect(() => session.append([
+ ['request/header', { reason: 'initial', header: { config: { provider: 'test', model: 'test' }, tools: [first] } }],
+ ['developer/message', { turn: 1, step: 1, headerSeq: SessionSeq(reference), message: addition() }, { surfaceOp: 'append' }],
+ ])).toThrow('earlier request/header')
+ expect(session.seq).toBe(0)
+ expect(session.surface.nodes).toEqual([])
+ })
+
it('keeps an older header binding through compound changes, replacement, restore, and fork', () => {
const { session, headerSeq } = opened([first, { name: 'other', description: 'Other', parameters: {} }])
session.append('request/header', { reason: 'change', header: { config: { provider: 'test', model: 'test' }, tools: [second] } })
diff --git a/packages/core/session/tests/message-projections.spec.ts b/packages/core/session/tests/message-projections.spec.ts
index 6eccae4f3e..45c346e364 100644
--- a/packages/core/session/tests/message-projections.spec.ts
+++ b/packages/core/session/tests/message-projections.spec.ts
@@ -59,6 +59,24 @@ describe('plugin-owned message projections', () => {
expect(source.data.content).toEqual([{ type: 'text', text: 'original' }])
})
+ it.each(['projected', 'reject'])('admits message projections through array append (%s)', (text) => {
+ const session = Session.create(SessionId('array-projection'), undefined, undefined, undefined, [projection])
+ const original = createUserMessage({ content: [{ type: 'text', text: 'original' }], source: { kind: 'user' } })
+ const append = () => session.append([
+ ['user/message', original, { surfaceOp: 'append' }],
+ ['test/project', { seq: SessionSeq(0), text }],
+ ])
+ if (text === 'reject') {
+ expect(append).toThrow('rejected decision')
+ expect(session.seq).toBe(0)
+ expect(session.deriveMessages()).toEqual([])
+ } else {
+ append()
+ expect(session.deriveMessages()[0]?.content).toEqual([{ type: 'text', text }])
+ expect(session.surface.contentGeneration).toBe(1)
+ }
+ })
+
it('registers by fiber and refuses cached or pending decisions after disposal', async () => {
const ctx = new Context()
contexts.push(ctx)
diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml
index 6af7713408..c85baa23fe 100644
--- a/packages/experimental/client-ui-forge/README.i18n.yaml
+++ b/packages/experimental/client-ui-forge/README.i18n.yaml
@@ -15,23 +15,23 @@
en: d152484eb41ac6b4
zh: 2f8a621b991260a1
/deepseek-ai-dsh-experimental-client-ui-forge/use-this-package:
- en: 515de40b1b454d35
- zh: 567546768e9c080e
+ en: c7e1b7d87ccccd2e
+ zh: 42d864b918a6175c
/deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation:
- en: a9e32b45508aac41
- zh: 868c05f35a16d797
+ en: 7495fe1e0d0ee643
+ zh: f820a5790ae6e2a7
/deepseek-ai-dsh-experimental-client-ui-forge/further-exploration:
en: fa4d8c579ffc49ff
zh: 5856ed7469e4585b
/deepseek-ai-dsh-experimental-client-ui-forge/model-experience:
- en: d62a9841cc34dfdd
- zh: 5aa4ffb331c5bb93
+ en: 10101427d1e0589b
+ zh: c981cec12f64eb75
/deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect:
en: 2bc25a99e17789c4
zh: 4bec723fbf249d28
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work:
- en: 0f795ca1c607af01
- zh: a05ac28fb2313d6e
+ en: 5e29ac36aad15d02
+ zh: e46339bb637a69ef
/deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md
index 78ca51c3ef..3986c9bffc 100644
--- a/packages/experimental/client-ui-forge/README.md
+++ b/packages/experimental/client-ui-forge/README.md
@@ -38,13 +38,15 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish
- **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll.
- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, whose count ends in `+` when the provider counted only some threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing.
- **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent.
-- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host.
+- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host.
+
+- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits.
The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit.
The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior.
-`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, and `maxCachedDiffBytes` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge).
+`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge).
All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. The GitHub split button starts or adds to a pending review; its menu publishes a single comment immediately. Comments remain beside their code after quoting, queueing, or publishing. Pending comments are edited or removed there. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. Added and deleted files show only their populated line-number column. Pending reviews and comment records are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears its comments, summary, and decision, and reopening starts an empty review. Published GitHub comments and references already added to the main composer are unaffected. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission.
@@ -67,11 +69,11 @@ Restoration records `restoring` before mutation and `restored` only after succes
Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists.
-`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails.
+`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails.
`changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service.
-The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, and layout choices of each tab in a slot store, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon.
+The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon.
| Source | Responsibility |
|---|---|
@@ -82,13 +84,17 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
| [`src/git.ts`](src/git.ts) | Git queries under Session permissions |
| [`src/parse.ts`](src/parse.ts) | Git output parsing and remote order |
| [`src/diff.ts`](src/diff.ts) | Patch parsing, untracked files as additions, and numstat records |
-| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, new-side text, and the `branch` scope summary |
+| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, branch commits, new-side text, and the `branch` scope summary |
+| [`src/layers.ts`](src/layers.ts) | Review layers from path globs and `linguist-generated` attributes |
| [`src/client/mount.ts`](src/client/mount.ts) | Remote mount, slot entries, and action outcome mapping |
| [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card |
| [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | Local changes card |
| [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view |
| [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope |
| [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | One file of the changes view |
+| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | Lens, test file switch, and viewed progress |
+| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | Commit picker |
+| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | Viewed marks kept in the browser |
| [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory |
| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option |
| [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card |
@@ -111,7 +117,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t
## Model Experience
-Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, and local Branch quotes the base the view compared with. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context.
+Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context.
#### KV Cache effect
@@ -130,9 +136,12 @@ None for a new worktree, as its notice belongs to the first request of the Sessi
- **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well.
- **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project.
- **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree: under workspace-write its Git directory lies outside the writable root, so neither the new branch nor later commits could be written.
-- **Changes scopes** — deferred: scopes for one commit and for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen.
+- **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen.
- **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working.
- **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge.
+- **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them.
+- **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros.
+- **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head.
- **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches.
diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md
index 97b35eec90..d5bdf45e9d 100644
--- a/packages/experimental/client-ui-forge/README.zh.md
+++ b/packages/experimental/client-ui-forge/README.zh.md
@@ -38,13 +38,15 @@ kind: "package-reference"
- **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。
- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`)、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。
- **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。
-- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。
+- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。
+
+- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。
检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。
diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。
-`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles` 与 `maxCachedDiffBytes` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。
+`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。
“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。GitHub 分段按钮用于开始或加入待提交评审,下拉菜单可以立即发布单条评论。评论在引用、暂存或发布后保留在对应代码旁,暂存评论可在那里编辑或删除。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。新建和删除文件只显示有内容的一侧行号。待提交评审与评论记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空该页签的评论、总结与评审决定,重新打开从空评审开始。已发布到 GitHub 的评论与已加入主输入框的引用不受影响。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。
@@ -67,11 +69,11 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo
每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。
-Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。
+Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。
`changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。
-浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支与布局选择,经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。
+浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。
| 源码 | 职责 |
|---|---|
@@ -82,13 +84,17 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
| [`src/git.ts`](src/git.ts) | 按 Session 权限执行 Git 查询 |
| [`src/parse.ts`](src/parse.ts) | Git 输出解析与远端顺序 |
| [`src/diff.ts`](src/diff.ts) | 补丁解析、把未跟踪文件表示为新增,以及 numstat 记录 |
-| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、新版本文本与 `branch` 范围摘要 |
+| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、分支提交、新版本文本与 `branch` 范围摘要 |
+| [`src/layers.ts`](src/layers.ts) | 按路径 glob 与 `linguist-generated` 属性分层 |
| [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、slot 条目与操作结果映射 |
| [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 |
| [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 |
| [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 |
| [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 |
| [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 |
+| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | 分层透镜、测试文件开关与已审阅进度 |
+| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | 提交选择器 |
+| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | 保存在浏览器中的已审阅标记 |
| [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 |
| [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 |
| [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 |
@@ -111,7 +117,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
## 模型体验
-间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。
+间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。
#### KV Cache 影响
@@ -130,9 +136,12 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi
- **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。
- **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。
- **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用:在 workspace-write 下它的 Git 目录位于可写根之外,新分支与之后的提交都无法写入。
-- **变更范围**——待办:单个提交与上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。
+- **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。
- **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。
- **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。
+- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。
+- **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。
+- **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。
- **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。
diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json
index 7ab090b292..8dd840d825 100644
--- a/packages/experimental/client-ui-forge/package.json
+++ b/packages/experimental/client-ui-forge/package.json
@@ -71,7 +71,8 @@
"diff": "^9.0.0",
"zod": "4.6.6",
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
- "@deepseek-ai/dsh-storage-domain": "workspace:*"
+ "@deepseek-ai/dsh-storage-domain": "workspace:*",
+ "picomatch": "^4.0.7"
},
"devDependencies": {
"@deepseek-ai/cordis": "workspace:~",
@@ -115,7 +116,8 @@
"@deepseek-ai/dsh-timeout": "workspace:*",
"@deepseek-ai/dsh-session-projection-cache": "workspace:*",
"@deepseek-ai/dsh-session-query": "workspace:*",
- "@deepseek-ai/dsh-api-remote-access": "workspace:*"
+ "@deepseek-ai/dsh-api-remote-access": "workspace:*",
+ "@types/picomatch": "^4.0.3"
},
"files": [
"locale/*.json",
diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css
index 47193f0887..f1603a01d4 100644
--- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css
+++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css
@@ -91,21 +91,96 @@
}
.headerEnd {
- flex: none;
+ display: inline-flex;
+ flex: 0 1 auto;
+ align-items: center;
+ gap: 4px;
+ min-width: 0;
margin-left: auto;
}
+
.toolbar {
display: flex;
flex: none;
- align-items: center;
- gap: 4px;
+ align-items: stretch;
box-sizing: border-box;
- min-height: 38px;
- padding: 0 8px;
border-bottom: 0.5px solid var(--dsw-alias-border-l3);
}
+/* Spans the file tree's width with the tree's search inset, and its divider continues the tree's border. */
+.lensCell {
+ display: none;
+ flex: none;
+ align-items: center;
+ box-sizing: border-box;
+ width: var(--forge-tree-width);
+ padding: 0 8px;
+ border-inline-end: 0.5px solid var(--dsw-alias-border-l3);
+}
+
+.toolbar[data-tree='right'] .lensCell {
+ order: 1;
+ border-inline-start: 0.5px solid var(--dsw-alias-border-l3);
+ border-inline-end: 0;
+}
+
+.toolbarMain {
+ display: flex;
+ flex: 1;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0 4px;
+ box-sizing: border-box;
+ min-width: 0;
+ min-height: 38px;
+ padding: 5px 8px;
+}
+
+.lensMenu {
+ display: inline-flex;
+}
+
+@container forge-changes (min-width: 760px) {
+ .toolbar:not([data-tree='hidden']) .lensCell {
+ display: flex;
+ }
+
+ .toolbar:not([data-tree='hidden']) .lensMenu {
+ display: none;
+ }
+}
+
+.spacer {
+ flex: 1;
+}
+
+.progressSlot {
+ display: inline-flex;
+}
+
+/* Breaks the toolbar's review controls onto a second row where one row is too narrow for them. */
+.rowBreak {
+ display: none;
+}
+
+@container forge-changes (max-width: 640px) {
+ .reviewRow {
+ order: 2;
+ }
+
+ .rowBreak {
+ display: block;
+ flex-basis: 100%;
+ order: 1;
+ height: 4px;
+ }
+
+ .progressSlot {
+ margin-left: auto;
+ }
+}
+
.select {
display: inline-flex;
flex: 0 1 auto;
@@ -173,7 +248,6 @@
flex: none;
align-items: center;
gap: 2px;
- margin-left: auto;
}
.tool {
@@ -272,9 +346,12 @@
}
.files {
+ --forge-files-inset: 10px;
flex: 1;
+ box-sizing: border-box;
min-width: 0;
min-height: 0;
+ padding: var(--forge-files-inset);
overflow: auto;
}
@@ -303,14 +380,34 @@
text-align: center;
}
+/* Each file is one card, so a file's last collapsed-context strip and the next file's header no longer read as adjacent
+ rows. Diffs share R16; clip, unlike hidden, keeps the card from becoming the sticky header's scroll container. */
.file {
- border-bottom: 0.5px solid var(--dsw-alias-border-l3);
+ overflow: clip;
+ border: 0.5px solid var(--dsw-alias-border-l4);
+ border-radius: var(--dsw-radius-lg);
+ background: var(--forge-changes-bg);
}
-/* Above the comment plus (z-index 1) of rows scrolled beneath it. */
+.file + .file {
+ margin-top: 12px;
+}
+
+@container forge-changes (max-width: 380px) {
+ .files {
+ --forge-files-inset: 6px;
+ }
+
+ .file + .file {
+ margin-top: 8px;
+ }
+}
+
+/* Above the comment plus (z-index 1) of rows scrolled beneath it. Sticky offsets start inside the list's padding,
+ so the negative inset keeps a stuck header flush with the scroll area's top edge. */
.fileHeader {
position: sticky;
- top: 0;
+ top: calc(-1 * var(--forge-files-inset, 0px));
z-index: 2;
display: flex;
align-items: center;
@@ -319,7 +416,8 @@
min-height: 36px;
padding: 0 4px 0 8px;
border-bottom: 0.5px solid var(--dsw-alias-border-l3);
- background: var(--forge-changes-bg);
+ /* The hover tint over the view background stays opaque while code scrolls beneath the sticky header. */
+ background: linear-gradient(var(--dsw-alias-interactive-bg-hover), var(--dsw-alias-interactive-bg-hover)), var(--forge-changes-bg);
}
/* A bare chevron: its rotation shows whether the file is expanded, so it takes no fill in any state. */
@@ -348,10 +446,23 @@
border-bottom: 0;
}
+/* The file's own information gives way inside this box, so the counts, the viewed mark, and the menu after it stay
+ whole at any width. */
+.fileTitle {
+ display: flex;
+ flex: 1 1 0;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ overflow: hidden;
+}
+
.fileIcon {
flex: none;
}
+/* The path shares the shortage with the badge in proportion to their widths, so the longer path keeps the larger part
+ and stays under the pointer for its full-path tooltip. */
.filePath {
display: flex;
flex: 0 1 auto;
@@ -371,8 +482,73 @@
transform: rotate(-90deg);
}
-.badge {
+/* Capped rather than shrunk, so a long path never truncates the tag; a longer translation ends in an ellipsis. */
+.changedTag {
flex: none;
+ max-width: 30%;
+}
+
+.changedText {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+/* The viewed mark: a native checkbox with its label as one bordered chip, peer to the file menu button. */
+.viewed {
+ display: inline-flex;
+ flex: none;
+ align-items: center;
+ gap: 6px;
+ box-sizing: border-box;
+ height: 24px;
+ padding: 0 8px 0 6px;
+ border: 0.5px solid var(--dsw-alias-border-l2);
+ border-radius: var(--dsw-radius-sm);
+ color: var(--dsw-alias-label-secondary);
+ white-space: nowrap;
+ cursor: pointer;
+ user-select: none;
+}
+
+.viewed input {
+ margin: 0;
+ accent-color: var(--dsw-alias-state-business-primary);
+ cursor: pointer;
+}
+
+.viewed:has(input:checked) {
+ background: var(--dsw-alias-interactive-bg-hover);
+}
+
+@media (hover: hover) {
+ .viewed:hover {
+ color: var(--dsw-alias-label-primary);
+ }
+}
+
+.viewed:has(input:focus-visible) {
+ outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary));
+ outline-offset: -1px;
+}
+
+.viewed input:focus-visible {
+ outline: none;
+}
+
+@container forge-changes (max-width: 520px) {
+ .viewed {
+ padding: 0 6px;
+ }
+
+ .viewedLabel {
+ display: none;
+ }
+}
+
+.badge {
+ flex: 0 1 auto;
+ min-width: 0;
max-width: 50%;
overflow: hidden;
padding: 0 6px;
diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx
index 7a66da2466..6c73c8b96f 100644
--- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx
+++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx
@@ -7,7 +7,10 @@
* scope summary changes; a read keeps the previous changes on screen until it settles.
*/
-import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react'
+import {
+ useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent,
+ type ReactNode,
+} from 'react'
import clsx from 'clsx'
import {
Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular,
@@ -21,10 +24,10 @@ import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-rig
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path'
import type {
- ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest,
- ForgePanelState,
+ ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff,
+ ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState,
} from '../types.ts'
-import type { ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types'
+import type { ForgeCommitList, ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types'
import { sameReviewSource, type ReviewQueue } from './review-queue.ts'
import { ReviewThread, useFileReview } from './ReviewThread.tsx'
import type { ReviewActions } from './ReviewComposer.tsx'
@@ -32,7 +35,10 @@ import { SubmitReview } from './SubmitReview.tsx'
import type { ReviewSelection, ReviewSource } from './review.ts'
import { BaseMenu } from './BaseMenu.tsx'
import { parseChangesAddress, type ChangesSource } from './changes-address.ts'
-import type { createChangesStore } from './changes-store.ts'
+import type { ChangesLens, createChangesStore } from './changes-store.ts'
+import { CommitMenu } from './CommitMenu.tsx'
+import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx'
+import { viewedStateOf, type ViewedFiles, type ViewedMarks } from './viewed-files.ts'
import { Counts, DiffFile, type DiffFileAction } from './DiffFile.tsx'
import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx'
import { changedFileTree, filesInTreeOrder } from './file-tree.ts'
@@ -68,8 +74,16 @@ export interface ChangesTabInjected {
readonly diffBases: (query: string, signal: AbortSignal) => Promise>
/** Read the new side of one file in a local scope. */
readonly localText: (scope: ForgeLocalScope, path: string) => Promise>
- /** Read the changes of a change request by its binding URL; `signal` aborts the read. */
- readonly changeRequestDiff: (url: string, signal: AbortSignal) => Promise>
+ /** List the commits of the `branch` scope compared with `base`, or with the automatic fork point for null; `signal` aborts the read. */
+ readonly localCommits: (base: string | null, signal: AbortSignal) => Promise>
+ /** Read the changes of a change request, or of consecutive commits of it, by its binding URL; `signal` aborts the read. */
+ readonly changeRequestDiff: (
+ url: string, commits: ForgeCommitRange | null, signal: AbortSignal,
+ ) => Promise>
+ /** List the commits of a change request, or null when its provider does not read commits; `signal` aborts the read. */
+ readonly changeRequestCommits: (url: string, signal: AbortSignal) => Promise>
+ /** The Session's viewed marks, kept in the browser. */
+ readonly viewedFiles: ViewedFiles
/** Read one file of a change request at a commit. */
readonly changeRequestText: (url: string, commit: string, path: string) => Promise>
/** Open a URL outside the app. */
@@ -106,8 +120,10 @@ type ChangesData =
readonly files: readonly ForgeDiffFile[]
/** Binding URL of the change request. */
readonly url: string
- /** Head commit the files describe, which supplies unchanged lines. */
+ /** Commit the files end at, the head or the last chosen commit, which supplies unchanged lines. */
readonly headSha: string
+ /** Commits the files cover, or null for the whole change request. */
+ readonly commits: ForgeCommitRange | null
/** Commits the checkout's branch has beyond the head, or null. */
readonly localAhead: number | null
/** Web page of each file at the head. */
@@ -148,6 +164,8 @@ const FAILURE: Partial> = {
'forgePanel/no-fork-point': 'diff.noForkPoint',
'forgePanel/diff-too-large': 'diff.tooLarge',
'forgePanel/filter-config-failed': 'diff.filterConfigFailed',
+ 'forgePanel/commits-missing': 'commits.missing',
+ 'forgePanel/commits-not-linear': 'commits.notLinear',
}
/** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */
@@ -171,6 +189,7 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T
async function readChanges(
source: ChangesSource,
scope: ForgeLocalScope,
+ commits: ForgeCommitRange | null,
reads: Pick,
signal: AbortSignal,
): Promise> {
@@ -180,10 +199,10 @@ async function readChanges(
const { files, base, omitted } = result.value
return { ok: true, value: { kind: 'local', files, scope, base, omitted } }
}
- const result = await reads.changeRequestDiff(source.url, signal)
+ const result = await reads.changeRequestDiff(source.url, commits, signal)
if (!result.ok) return result
const { files, headSha, localAhead, fileUrls } = result.value
- return { ok: true, value: { kind: 'change', files, url: source.url, headSha, localAhead, fileUrls } }
+ return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls } }
}
/** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */
@@ -191,25 +210,51 @@ function baseRefOf(scope: ForgeLocalScope): string | null {
return scope.kind === 'branch' ? scope.base : null
}
+/** The commits a local scope shows, or null for all of them and for scopes other than `branch`. */
+function commitsOf(scope: ForgeLocalScope): ForgeCommitRange | null {
+ return scope.kind === 'branch' ? scope.commits : null
+}
+
/** The source review comments on loaded changes record: the change request head, or the local scope with its base. */
function reviewSourceOf(data: ChangesData): ReviewSource {
return data.kind === 'local'
- ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope) }
- : { kind: 'change', url: data.url, headSha: data.headSha }
+ ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope), commits: commitsOf(data.scope) }
+ : { kind: 'change', url: data.url, headSha: data.headSha, commits: data.commits }
}
-/** The files that start expanded: every file until those above it change more than {@link OPEN_LINES} lines. */
-function initiallyOpen(files: readonly ForgeDiffFile[]): ReadonlySet {
+/**
+ * Identity of a diff source for viewed marks: the change request or local scope with its base ref and chosen commits.
+ * A change request's marks stay across head commits, so a file whose change a new push altered reads as changed.
+ */
+function viewedSourceOf(source: ReviewSource): string {
+ return JSON.stringify(source.kind === 'local'
+ ? ['local', source.scope, source.baseRef, source.commits]
+ : ['change', source.url, source.commits])
+}
+
+/**
+ * The files that start expanded: every file not marked viewed until those above it change more than {@link OPEN_LINES} lines.
+ * @param files - every file in display order.
+ * @param marks - the viewed marks when the files loaded.
+ * @returns the paths of the expanded files.
+ */
+function initiallyOpen(files: readonly ForgeDiffFile[], marks: ViewedMarks): ReadonlySet {
const open = new Set()
let above = 0
for (const file of files) {
if (above > OPEN_LINES) break
+ if (viewedStateOf(marks, file.path, file.digest) === 'viewed') continue
open.add(file.path)
above += drawnLines(file)
}
return open
}
+/** Whether a file shows under a lens while test files hide or not. */
+function shownBy(file: ForgeDiffFile, lens: ChangesLens, hideTests: boolean): boolean {
+ return !(hideTests && file.layer === 'test') && (lens === 'all' || file.layer === lens)
+}
+
/** What a rename badge names: the old file name, or the old path when only the directory changed. */
function renamedFrom(previous: string, path: string): string {
const name = pathPartsOf(previous).name
@@ -231,9 +276,11 @@ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string {
return parts.join(' · ')
}
-function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onReview, t }: {
+function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDisabled, onReview, t }: {
readonly url: string
readonly entry: ForgePanelChangeRequest | undefined
+ /** Commit picker left of the review button. */
+ readonly commitMenu: ReactNode
readonly reviewCount: number
readonly reviewDisabled: boolean
readonly onReview: () => void
@@ -249,9 +296,12 @@ function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onRev
{snapshot === null ? url : snapshot.title}
{number !== null && {t('change.number', { number })}}
-
+
+ {commitMenu}
+
+