perf(client): optimize PTC definition complexity for Chat and Trajectory (#9387)

* perf(client): 让 PTC 嵌套分发折叠保持线性

客户端折叠会话历史时,updateDispatch 对每个 tool/ptc-dispatch-start 与
tool/ptc-dispatch 事件都用 findIndex 查找子调用、复制父调用的整个子节点
数组,并把全部父子关系复制进新的 Map。单个父调用下 n 个子调用因此是
O(n²):一个约 5 万事件、最大扇出约 2 万的 PTC 会话折叠要 8.9 秒,打开
会话时主线程被同步阻塞。

ToolState 改为按 parent/child id 索引的 DispatchTree,updateDispatch 就地
写入内层 Map(替换幂等、首次挂载定序),发布时 projectBlock 再物化数组,
发布出的工具调用树仍是不共享数组的不可变值。

conversation-fold 基准新增 ptc-dispatch-fan-out 用例:2 个根调用各结算
10,000 个嵌套子调用,参考机预期 100 ms(CI 预算 250 ms)。旧实现同一形状
在编译 worker 中耗时 9,295 ms,新实现 51–81 ms。

Refs #9385

* perf(client): 让 Trajectory 的 PTC 分发折叠保持线性

默认启用的 Trajectory Tool Definition 与修复前的 Chat 实现同构:每个
tool/ptc-dispatch[-start] 事件都 indexOf 查找子调用并复制调用 Map,首次挂载
时还复制子节点 Map、父节点 Map 和兄弟列表;根 tool/result 再复制调用 Map,
每次发布重建整棵投影树。Assembler 无论目标是否激活都会更新已注册的
Definition,所以即使只打开 Chat,2 个根调用各 10,000 个子调用的窗口也要
12,228 ms。

ToolState 改为持有就地更新的 DispatchTree(调用 Map、首次挂载顺序的子调用
id 列表、父节点 Map),每个事件 O(1);projectCall 增加按存储块、中断点和
子调用引用缓存的投影,未变化子树复用已发布对象,发布值不与树共享引用。

conversation-fold 的 ptc-dispatch-fan-out 用例在 worker 中注册 Trajectory
Tool Definition 与视图,并分别断言 Chat 与 Trajectory 目标的子调用数和
250 ms 预算。回退 Trajectory 实现时该用例超过 60 秒 worker 时限;修复后
Chat 63–72 ms,Trajectory 60–64 ms。

Refs #9385

* perf(client): 收紧 PTC 分发折叠的状态更新

按评审意见收紧 Chat 与 Trajectory 的 Tool Definition:

- updateDispatch 与 Trajectory 根 result 分支原地修改后返回同一 State,
  不再浅拷贝;start() 仍新建 State。ToolState 与 DispatchTree 去掉
  readonly,JSDoc 引用 Assembler 的 update() 规则,原因链接 Agent Note。
- 删除 Trajectory 的投影缓存及其身份用例,projectCall 与 master 一致,
  每次发布新建投影树。
- 基准两个目标共用一个预算常量,去掉 trajectoryViewDefinition 的类型断言。
- Agent Note 合并修复前后表格并更新为本次实测;统一负向对照数据,
  说明两种树布局的取舍,注明返回同一 State 参考了 #9400。

编译 worker 2×10,000:master 29,176 / 22,483 ms,修复后 58–63 / 53–59 ms
(激活 Chat / Trajectory);只回退 Chat 时门禁测得 9,073 ms 并失败。

Refs #9385
This commit is contained in:
Dudu-0223 authored and GitHub committed 2026-11-27 16:12:10 +08:00
1 parent 3a0d5f0d0b
commit 6a4ee478d7
11 files changed
+476 -69

No files matched your search

@@ -0,0 +1,22 @@
# Bilingual-pair consistency record for 2026-11-27-ptc-dispatch-fold-quadratic.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 .agents/notes/implemented/bug-fix/2026-11-27-ptc-dispatch-fold-quadratic.md
/agent-note-linear-ptc-dispatch-folding:
en: 3038bbb7bc9dc317
zh: 559beea74e493e53
/agent-note-linear-ptc-dispatch-folding/problem:
en: 2ddfdb7a0c49638d
zh: 59c1811f07c461ff
/agent-note-linear-ptc-dispatch-folding/decision:
en: 6e7e06f7cfa1c918
zh: cc2626c4297980b5
/agent-note-linear-ptc-dispatch-folding/calibration:
en: a881888b78b69fd5
zh: ceb075334437ec0e
/agent-note-linear-ptc-dispatch-folding/alternatives-considered:
en: 06aa789e224bea8d
zh: 6c39704c81cfc71a
/agent-note-linear-ptc-dispatch-folding/consequences:
en: 39f0379d7ea633d8
zh: 458f240ffa587f17
@@ -0,0 +1,55 @@
# Agent Note: Linear PTC dispatch folding
Status: implemented
English | [中文](2026-11-27-ptc-dispatch-fold-quadratic.zh.md)
## Problem
Opening a real computer-use Session in the Web GUI took seconds before the conversation appeared. The Session JSONL expands to 50,294 events, and 49,258 of them are nested PTC dispatch events: 24,629 `tool/ptc-dispatch-start` and 24,629 `tool/ptc-dispatch`, with up to 20,480 subcalls under one parent call. The Client requests `maxMessages: 500` with `turnWindow { minMessages: 50, minTurns: 2 }`, so it intends to read a bounded tail; the resulting window held 50,260 events, almost the whole log. The [Chat Tool Definition](../../../../packages/client/ui-chat/src/client/conversation-nodes/tool.ts) folded that window in 8,950 ms. Its `updateDispatch` found the child with `findIndex`, copied the parent's whole child array, and copied every parent edge into a new `Map` for each dispatch event, so one parent with n children cost O(n²).
The [Trajectory Tool Definition](../../../../packages/client/ui-trajectory/src/client/trajectory-tool-definition.ts) had the same structure. For each dispatch event its `updateDispatch` searched the parent's child-id list with `indexOf` and copied the call map; on first attachment it also copied the child map, the parent map, and the parent's child-id list. Each root `tool/result` copied the call map again. The [Web composition](../../../../packages/bundle/web-app/cordis.patch.yml) enables ui-trajectory by default, and the Assembler updates every registered Definition whether or not its target is active, so this cost applied to every Chat open, not only to the Trajectory tab.
## Decision
Both Definitions keep a `DispatchTree` in their State and mutate it in place. Dispatch updates, and the Trajectory root-result update, return the same State object; `start()` still creates a new State, so a replay starts from a fresh tree. The [Assembler update rule](../architecture/2026-08-09-client-conversation-node-assembly.md) permits returning the mutated State, because the Assembler does not decide publication by State reference. Returning the same State follows the approach of #9400 by imccyu.
The Chat tree is `Map<parentCallId, Map<subCallId, ToolCallBlock>>` for children in first-attachment order, plus `Map<subCallId, parentCallId>` for cycle and depth checks. `updateDispatch` inserts or replaces the child in its parent's inner map, so replacement is idempotent, first attachment fixes the order, and one dispatch costs O(1) map work. `projectBlock` materializes each parent's inner-map values into a fresh array when it publishes.
The Trajectory tree keeps that Definition's existing indexes: one call map keyed by call id for the root and every accepted child, child-id lists in first-attachment order, and the parent map. Chat uses inner maps because its State has no call map keyed by id, and a repeated settle must find the child under its parent in constant time. Trajectory keeps its single call map because that map already provides the lookup, and keeping it preserves the existing acceptance and replacement behavior for every id, including a subcall id equal to the root id. Because `acceptsEdge` gives each child at most one parent, an edge exists exactly when the parent map names that parent, which replaces the `indexOf` scan without changing which events are accepted. A dispatch writes the call map and, on first attachment, appends one id and one parent entry; the root result writes the root entry in place. `projectCall` still builds a new projected tree on every publication.
Published Tool call blocks in both targets carry their own arrays and never alias the dispatch trees, so downstream code keeps its immutable value semantics. Every event is folded once in logical `seq` order.
The [conversation-fold benchmark](../../../../benchmarks/conversation-fold/conversation-fold.bench.client.ts) case `conversation-fold/ptc-dispatch-fan-out` runs the `ptc` entry point of its [worker](../../../../benchmarks/conversation-fold/conversation-fold.worker.client.ts). The worker registers the Trajectory Tool Definition and Trajectory view beside the Chat Definitions, matching the default Web composition. The case synthesizes two root calls with 10,000 settled nested dispatches each: one start and one settle event per subcall, 40,004 events in total. It folds the window three times with Chat active and three times with Trajectory active, keeping the fastest sample of each. It asserts that each target's snapshot contains 20,000 children and that every child is a settled tool result. Both targets share one 100 ms reference-machine expectation, which `ciTimeBudget(100)` turns into 250 ms at the shared 2× CI time scale and 1.25× headroom. The [frontend performance budgets](../testing/2026-09-06-frontend-performance-budgets.md) note lists the case among the conversation-fold benchmarks.
## Calibration
All measurements use the compiled benchmark worker under plain Node on macOS arm64 with Node 26.0.0. Before values come from the same worker with both copy-per-dispatch implementations restored from master; they are negative controls, not a historical checkout. Before rows are one sample; after rows are the fastest of three.
| Nested dispatches under one parent | Before, Chat active | Before, Trajectory active | After, Chat active | After, Trajectory active |
|---|---:|---:|---:|---:|
| 1,000 | 97 ms | 89 ms | 4 ms | 3 ms |
| 2,000 | 372 ms | 352 ms | 8 ms | 7 ms |
| 4,000 | 1,511 ms | 1,516 ms | 17 ms | 12 ms |
| 8,000 | 6,680 ms | 6,327 ms | 32 ms | 22 ms |
| 2 × 10,000 (benchmark shape) | 29,176 ms | 22,483 ms | 58–63 ms | 53–59 ms |
Before the change each doubling roughly quadruples the time; after it the time doubles. Restoring only one Definition still makes both targets quadratic, because the Assembler updates both. On the benchmark shape, restoring only the Chat implementation measured 9,073 ms with Chat active and 8,035 ms with Trajectory active in the required case, which failed its 250 ms budget. Restoring only the Trajectory implementation measured 12,078 ms and 11,496 ms in one worker sample, and the required case exceeded its 60-second worker deadline.
On the real 50,260-event window, the complete Chat fold fell from 8,950 ms to 112 ms. Separate phase measurements on the same window recorded match/update at 9,365 ms → 102 ms and publication at 17 ms → 10 ms. Those numbers were measured with the Vitest source harness before the Trajectory change.
## Alternatives considered
- **Keep the array and index it by child id.** A per-parent `Map<subCallId, index>` would remove `findIndex`, but every dispatch would still copy the growing array and all parent edges, so the quadratic copying remains.
- **Append to arrays in place and copy once at publication in Chat.** This also removes the per-event copy, but Chat's `updateDispatch` must still reject cycles and depth overflow during the fold; arrays plus a parent map would duplicate the index that the inner map provides, and a repeated settle would need a scan or a second index.
- **Give Trajectory the Chat inner-map layout or a shared module.** Rejected because the two Definitions are intentionally independent, and Trajectory's single call map preserves its existing acceptance and replacement behavior for every id.
- **Cache Trajectory projections as Chat does.** Not part of this change: the cold fold publishes each root once, and per-publication rebuilding is the existing Trajectory behavior.
- **Fold or render only a bounded prefix of a PTC run.** Rejected because one turn can legitimately hold the whole run, a parent's nested calls have no message boundary to page at, and hiding children changes the user-visible tool tree rather than removing the fold cost.
## Consequences
One dispatch now costs constant map work in both Definitions, so a Session with a wide PTC fan-out opens in proportion to its event count. Each tree retains one entry per call and child edge, the same order of memory the copied maps and arrays used. Publication still materializes arrays per parent, so each published tree is an immutable value. The Chat projection cache reuses unchanged blocks; Trajectory rebuilds its projected tree on each publication.
The case fails CI within one benchmark run when either per-event copy returns. It covers settled nested dispatches under two roots in a cold fold; it does not cover live appends that republish after each dispatch, dispatch events still streaming, error results, or a tree near the 256-call depth ceiling. A wall-clock budget still needs recalibration on a new reference machine, and the 250 ms CI budget follows the shared scale rather than a hosted measurement of this case.
The existing 1,066 ui-chat tests, including [turns and tool-call-tree](../../../../packages/client/ui-chat/tests/tool-call-tree.client.spec.ts), and the existing ui-trajectory tests pass unchanged. [Trajectory conversation Definition tests](../../../../packages/client/ui-trajectory/tests/conversation-definitions.client.spec.ts) add cases for attachment order, repeated starts, cycles, reparenting, adopted detached subtrees, and roots rebuilt from their result; these cases also pass against the copy-per-dispatch implementation. Both Definition files are outside the per-file coverage gate through the `vitest.config.ts` exclusions for ui-chat conversation nodes and ui-trajectory sources; measured with their package tests, `tool.ts` reaches 98.56% of lines and `trajectory-tool-definition.ts` 97.84%, and the remaining gaps are defensive and non-dispatch paths. The real Session log was used only for local diagnosis; no log content entered the repository or a fixture.
@@ -0,0 +1,55 @@
# Agent Note:PTC 分发折叠的线性化
Status: implemented
[English](2026-11-27-ptc-dispatch-fold-quadratic.md) | 中文
## 问题
在 Web GUI 中打开一个真实的 computer-use Session 时,对话要等数秒才出现。会话 JSONL 解压后有 50,294 个事件,其中 49,258 个是嵌套 PTC 分发事件:24,629 个 `tool/ptc-dispatch-start` 和 24,629 个 `tool/ptc-dispatch`,单个父调用下最多有 20,480 个子调用。客户端以 `maxMessages: 500` 和 `turnWindow { minMessages: 50, minTurns: 2 }` 请求有界尾部,实际窗口却有 50,260 个事件,几乎是整个日志。[Chat Tool Definition](../../../../packages/client/ui-chat/src/client/conversation-nodes/tool.ts) 折叠该窗口用时 8,950 ms。它的 `updateDispatch` 对每个分发事件都用 `findIndex` 查找子调用、复制父调用的整个子节点数组,并把全部父子关系复制进新的 `Map`,因此单个父调用下 n 个子调用的成本为 O(n²)。
[Trajectory Tool Definition](../../../../packages/client/ui-trajectory/src/client/trajectory-tool-definition.ts) 有同样的结构。它的 `updateDispatch` 对每个分发事件都用 `indexOf` 搜索父调用的子调用 id 列表并复制调用 Map;首次挂载时还复制子节点 Map、父节点 Map 和父调用的子调用 id 列表。每个根 `tool/result` 再复制一次调用 Map。[Web 组合](../../../../packages/bundle/web-app/cordis.patch.yml)默认启用 ui-trajectory,而 Assembler 无论目标是否激活都会更新所有已注册的 Definition,因此这项成本作用于每次打开 Chat,而不仅是 Trajectory 标签页。
## 决策
两个 Definition 都在 State 中持有 `DispatchTree` 并原地修改。分发更新以及 Trajectory 的根结果更新返回同一个 State 对象;`start()` 仍新建 State,因此重放从新树开始。[Assembler 更新规则](../architecture/2026-08-09-client-conversation-node-assembly.zh.md)允许返回原地修改后的 State,因为 Assembler 不按 State 引用判定发布。返回同一 State 的做法参考了 imccyu 的 #9400。
Chat 的树用 `Map<parentCallId, Map<subCallId, ToolCallBlock>>` 按首次挂载顺序保存子节点,另用 `Map<subCallId, parentCallId>` 支持环检测和深度检查。`updateDispatch` 把子节点写入或替换到父调用的内层 Map,因此替换是幂等的,首次挂载决定顺序,一次分发只做 O(1) 的 Map 操作。`projectBlock` 在发布时把每个父调用的内层 Map 值物化成新数组。
Trajectory 的树保留该 Definition 原有的索引:一个按调用 id 保存根调用和每个已接受子调用的调用 Map、按首次挂载顺序排列的子调用 id 列表,以及父节点 Map。Chat 采用内层 Map,是因为它的 State 没有按 id 索引的调用 Map,而重复结算必须在常数时间内找到父调用下的子调用。Trajectory 保留单一调用 Map,是因为该 Map 已经提供这种查找,保留它也就对每个 id 保持了原有的接受与替换行为,包括与根调用 id 相同的子调用 id。由于 `acceptsEdge` 保证每个子调用至多有一个父调用,一条边存在当且仅当父节点 Map 记录的正是该父调用;这取代了 `indexOf` 扫描,且不改变哪些事件被接受。一次分发写入调用 Map,首次挂载时再追加一个 id 和一条父节点记录;根结果就地写入根条目。`projectCall` 仍在每次发布时新建投影树。
两个目标发布出的 Tool 调用块都持有自己的数组,绝不与分发树共享引用,下游代码保留不可变值语义。每个事件按逻辑 `seq` 顺序只折叠一次。
[conversation-fold 基准](../../../../benchmarks/conversation-fold/conversation-fold.bench.client.ts)的用例 `conversation-fold/ptc-dispatch-fan-out` 运行其 [worker](../../../../benchmarks/conversation-fold/conversation-fold.worker.client.ts) 的 `ptc` 入口。worker 在 Chat Definitions 之外注册 Trajectory Tool Definition 和 Trajectory 视图,与默认 Web 组合一致。用例合成两个根调用,每个根调用有 10,000 个已结算的嵌套分发:每个子调用包含一个 start 事件和一个 settle 事件,共 40,004 个事件。它分别在激活 Chat 和激活 Trajectory 时各折叠窗口三次,各取最快样本。它断言每个目标的快照都包含 20,000 个子调用且全部为已结算 tool-result。两个目标共用一个 100 ms 的参考机预期,经 `ciTimeBudget(100)` 得到 250 ms 预算,即共享的 2× CI 时间倍率与 1.25× 余量。[前端性能预算](../testing/2026-09-06-frontend-performance-budgets.zh.md)记录将此用例列入 conversation-fold 基准。
## 校准
所有测量都在 macOS arm64、Node 26.0.0 上于纯 Node 下运行编译后的基准 worker。改动前数值来自同一 worker,两个逐事件复制实现都从 master 恢复;它们是负向对照,并非历史 checkout。改动前各行为一个样本,改动后各行为三次中的最快值。
| 单个父调用下的嵌套分发数 | 改动前,激活 Chat | 改动前,激活 Trajectory | 改动后,激活 Chat | 改动后,激活 Trajectory |
|---|---:|---:|---:|---:|
| 1,000 | 97 ms | 89 ms | 4 ms | 3 ms |
| 2,000 | 372 ms | 352 ms | 8 ms | 7 ms |
| 4,000 | 1,511 ms | 1,516 ms | 17 ms | 12 ms |
| 8,000 | 6,680 ms | 6,327 ms | 32 ms | 22 ms |
| 2 × 10,000(基准形状) | 29,176 ms | 22,483 ms | 58–63 ms | 53–59 ms |
改动前每翻一倍耗时约增至四倍;改动后耗时翻倍。只恢复其中一个 Definition 仍会让两个目标都呈二次增长,因为 Assembler 会更新两者。在基准形状上,只恢复 Chat 实现时,必跑用例测得激活 Chat 9,073 ms、激活 Trajectory 8,035 ms,超出 250 ms 预算而失败。只恢复 Trajectory 实现时,一次 worker 样本测得 12,078 ms 和 11,496 ms,必跑用例超过 60 秒的 worker 时限。
在真实的 50,260 事件窗口上,完整 Chat 折叠从 8,950 ms 降至 112 ms。同一窗口的分阶段测量记录 match/update 从 9,365 ms 降至 102 ms,发布阶段从 17 ms 降至 10 ms。这些数字是在 Trajectory 改动之前用 Vitest 源码 harness 测得的。
## 备选方案
- **保留数组并用子调用 id 建索引。** 每个父调用加一个 `Map<subCallId, index>` 可以省掉 `findIndex`,但每次分发仍要复制不断增长的数组和全部父子关系,二次复制依然存在。
- **在 Chat 中就地追加数组,只在发布时复制一次。** 这同样能去掉逐事件复制,但 Chat 的 `updateDispatch` 仍须在折叠期间拒绝环和深度溢出;数组加父子映射会重复内层 Map 已提供的索引,重复结算还需要扫描或第二个索引。
- **让 Trajectory 采用 Chat 的内层 Map 布局或共享模块。** 不采用:两个 Definition 刻意保持独立,而 Trajectory 的单一调用 Map 对每个 id 都保留了原有的接受与替换行为。
- **像 Chat 一样缓存 Trajectory 投影。** 不属于本次改动:冷折叠中每个根调用只发布一次,而每次发布都重建是 Trajectory 的既有行为。
- **只折叠或渲染 PTC run 的有界前缀。** 不采用:一个轮次可以合法包含整个 run,父调用的嵌套调用没有可按消息分页的边界,隐藏子调用改变的是用户可见的工具树,而不是消除折叠成本。
## 影响
两个 Definition 中一次分发现在都只做常数级 Map 操作,因此包含宽 PTC 扇出的 Session 按其事件数线性打开。每棵树为每个调用和每条子调用边保留一个条目,与原先复制的 Map 和数组内存数量级相同。发布时仍按父调用物化数组,所以每棵发布树都是不可变值。Chat 的投影缓存复用未变化的块;Trajectory 在每次发布时重建投影树。
任一逐事件复制回归时,该用例都会在一次基准运行内让 CI 失败。它覆盖冷折叠中两个根调用下的已结算嵌套分发;不覆盖每次分发后都重新发布的实时追加、仍在流式到达的分发事件、错误结果或接近 256 层深度上限的调用树。墙钟预算仍需在新参考机上重新校准;250 ms 的 CI 预算来自共享倍率,而不是本用例的托管实测。
现有 1,066 项 ui-chat 测试(包括 [turns 与 tool-call-tree](../../../../packages/client/ui-chat/tests/tool-call-tree.client.spec.ts))和现有 ui-trajectory 测试全部通过。[Trajectory 对话 Definition 测试](../../../../packages/client/ui-trajectory/tests/conversation-definitions.client.spec.ts)新增挂载顺序、重复 start、环、改挂父调用、收养游离子树以及由结果重建根调用的用例;这些用例在逐事件复制实现上同样通过。两个 Definition 文件都因 `vitest.config.ts` 对 ui-chat 对话节点和 ui-trajectory 源码的排除项而不在逐文件覆盖率门禁内;用各自包的测试测量,`tool.ts` 行覆盖率为 98.56%,`trajectory-tool-definition.ts` 为 97.84%,其余缺口是防御性路径和非分发路径。真实会话日志仅用于本地诊断,没有任何日志内容进入仓库或 fixture。
@@ -9,8 +9,8 @@
en: 9bf1200b5f980008
zh: d2dc07922817c581
/agent-note-frontend-large-session-performance-budgets/decision:
en: db46b4d42d64aa1b
zh: a21caffa675e8b42
en: 5d377756cc0a3104
zh: d6def2a657e05558
/agent-note-frontend-large-session-performance-budgets/calibration:
en: 2bbee3ec0bc9e618
zh: b4f937d7f4f09ae5
@@ -10,7 +10,7 @@ A fast Node conversation fold does not prove that a browser paints a long conver
## Decision
The existing serial benchmark inventory includes two frontend owners: [active reconnect](../../../../benchmarks/active-stream-reconnect/README.md) and a [browser workflow](../../../../benchmarks/long-session-browser/README.md). The browser workflow combines cold open, older-page navigation, first Trajectory activation, return to Chat, and a paced response with trusted keyboard input into one sequential scenario. These are endpoints of one workflow, not independent cold scenarios. The settled conversation-fold benchmark remains unchanged.
The existing serial benchmark inventory includes two frontend owners: [active reconnect](../../../../benchmarks/active-stream-reconnect/README.md) and a [browser workflow](../../../../benchmarks/long-session-browser/README.md). The browser workflow combines cold open, older-page navigation, first Trajectory activation, return to Chat, and a paced response with trusted keyboard input into one sequential scenario. These are endpoints of one workflow, not independent cold scenarios. The settled conversation-fold benchmark remains a Node-only fold owner, and its existing cases are unchanged; it also gains the [PTC dispatch fan-out case](../bug-fix/2026-11-27-ptc-dispatch-fold-quadratic.md), which settles 20,000 nested subcalls under two root calls and reads them through the Chat and Trajectory targets.
`build:bench` keeps the Node-only library and worker build. `test:bench` additionally builds the Web shell before running all cases; the required benchmark CI job follows the [standard hosted runner reference](../../../../.github/workflows/ci.yml), unconditionally provisions Chromium and its Linux dependencies on that hosted runner, and enables the existing verbose gate output so successful raw samples remain available for calibration. Browser cases reuse the shipped-composition Web scaffold with private temporary roots and an atomically assigned loopback port. Only the nondeterministic model is replaced by synthetic replay. The scaffold Host runs under the existing Vitest source resolver; measured Client rendering runs built bundles in fresh Chromium processes. Browser wall times therefore include this test Host, transport, Playwright actionability, and rendering, and are not claims about a published Host process.
@@ -10,7 +10,7 @@ Node 对话折叠很快,并不能证明浏览器能绘制长对话或在流式
## 决策
现有串行基准清单包含两个前端所有者:[活跃重连](../../../../benchmarks/active-stream-reconnect/README.zh.md)和[浏览器工作流](../../../../benchmarks/long-session-browser/README.zh.md)。浏览器工作流在一个顺序场景中组合冷打开、更早分页导航、首次激活 Trajectory、返回 Chat,以及伴随真实键盘输入的有节奏回复。这些是同一工作流的测量终点,而不是相互独立的冷场景。已结算对话折叠基准保持不变。
现有串行基准清单包含两个前端所有者:[活跃重连](../../../../benchmarks/active-stream-reconnect/README.zh.md)和[浏览器工作流](../../../../benchmarks/long-session-browser/README.zh.md)。浏览器工作流在一个顺序场景中组合冷打开、更早分页导航、首次激活 Trajectory、返回 Chat,以及伴随真实键盘输入的有节奏回复。这些是同一工作流的测量终点,而不是相互独立的冷场景。已结算对话折叠基准仍是仅 Node 的折叠所有者,其现有用例保持不变;它另外新增了 [PTC 分发扇出用例](../bug-fix/2026-11-27-ptc-dispatch-fold-quadratic.zh.md),在两个根调用下结算 20,000 个嵌套子调用,并分别经 Chat 和 Trajectory 目标读取。
`build:bench` 保留仅 Node 的 library 与 worker 构建。`test:bench` 额外构建 Web shell 后再运行所有用例;必需的基准 CI job 遵循[标准托管运行器说明](../../../../.github/workflows/ci.yml),在该托管运行器上无条件安装 Chromium 及其 Linux 依赖,并启用现有门禁详细输出,使成功用例的原始样本可用于校准。浏览器用例复用产品组合的 Web scaffold,使用私有临时目录和原子分配的回环端口。只有不确定的模型被合成重放替代。scaffold Host 通过现有 Vitest 源码解析器运行;被测 Client 渲染在全新 Chromium 进程中执行构建后的 bundle。因此浏览器壁钟时间包含测试 Host、传输、Playwright 可交互性等待及渲染,不代表发布版 Host 进程。
@@ -11,7 +11,9 @@ import {
PERFORMANCE_BUDGET_HEADROOM,
} from '../support/calibration.ts'
import { recordPeakMemory, recordTimings, type BenchmarkCase } from '../support/scaling-report.ts'
import type { ConversationFoldWorkerReport, PreparingToolWorkerReport, StreamingAssistantWorkerReport } from './conversation-fold.worker.client.ts'
import type {
ConversationFoldWorkerReport, PreparingToolWorkerReport, PtcDispatchWorkerReport, StreamingAssistantWorkerReport,
} from './conversation-fold.worker.client.ts'
/** Replies in the folded window; each carries one reasoning block and one text block. */
const TURNS = 200
@@ -32,6 +34,27 @@ const PREPARING_AFFECTS = { write: 'Watching the model stream a large file write
/** A stuck fold worker is reaped before the outer benchmark deadline. */
const WORKER_TIMEOUT_MS = 60_000
/** PTC root calls in the folded window; each fans out into the same number of settled subcalls. */
const PTC_PARENTS = 2
const PTC_CHILDREN_PER_PARENT = 10_000
const PTC_ATTEMPTS = 3
/** A PTC run keeps every nested dispatch under one root call, so a parent's child list grows without bound. */
const PTC_CASE: BenchmarkCase = {
id: 'conversation-fold/ptc-dispatch-fan-out',
measures: 'Client fold of one PTC run that settles 20,000 nested subcalls under two root calls, read through the Chat and Trajectory targets.',
affects: 'Opening or resuming a long computer-use or PTC conversation in the Web GUI.',
}
/**
* The fold pairs and settles every dispatch under its parent in both the Chat
* and the default-enabled Trajectory Tool Definitions, which the Assembler
* updates whichever target is active. Copying a growing child list or call map
* per event made this window take seconds; the linear folds that only insert
* each dispatch measure tens of milliseconds per target.
*/
const EXPECTED_PTC_FOLD_MS = 100
/** Each target folds the same window, so both endpoints share one budget. */
const PTC_FOLD_BUDGET_MS = ciTimeBudget(EXPECTED_PTC_FOLD_MS)
/**
* The large window contains 500,000 streamed deltas compacted into 1,600
* stream records. The budget separates the record-proportional fold from the
@@ -107,6 +130,27 @@ describe('cold Chat fold of a large v2 history window', () => {
})
})
describe('cold fold of a PTC dispatch fan-out', () => {
it(`settles ${String(PTC_PARENTS * PTC_CHILDREN_PER_PARENT)} nested subcalls within ${String(PTC_FOLD_BUDGET_MS)} ms for Chat and for Trajectory`, async () => {
const report = requireReport(await runBuiltBenchmarkWorker<PtcDispatchWorkerReport>({
worker: WORKER,
args: ['ptc', String(PTC_PARENTS), String(PTC_CHILDREN_PER_PARENT), String(PTC_ATTEMPTS)],
timeoutMs: WORKER_TIMEOUT_MS,
}))
console.log(JSON.stringify({
benchmark: PTC_CASE.id, ...report, budgetMs: PTC_FOLD_BUDGET_MS,
}))
recordTimings(PTC_CASE, {
ptcFoldMs: { ms: report.foldMs, ioShare: IO_SHARE },
ptcTrajectoryFoldMs: { ms: report.trajectoryFoldMs, ioShare: IO_SHARE },
}, { ptcFoldMs: PTC_FOLD_BUDGET_MS, ptcTrajectoryFoldMs: PTC_FOLD_BUDGET_MS })
expect(report.children).toBe(PTC_PARENTS * PTC_CHILDREN_PER_PARENT)
expect(report.trajectoryChildren).toBe(PTC_PARENTS * PTC_CHILDREN_PER_PARENT)
expect(report.foldMs).toBeLessThanOrEqual(PTC_FOLD_BUDGET_MS)
expect(report.trajectoryFoldMs).toBeLessThanOrEqual(PTC_FOLD_BUDGET_MS)
})
})
describe('preparing tool arguments', () => {
it.each(PREPARING_CASES)('publishes streamed $tool arguments within bounded CPU and heap costs', async (workload) => {
const samples: PreparingToolWorkerReport[] = []
@@ -8,6 +8,7 @@ import type { LlmAttemptId, ToolCallId } from '@deepseek-ai/dsh-llm/types'
import type { StreamChunk } from '@deepseek-ai/dsh-llm'
import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
import type { ChatNode, ChatSnapshot } from '@deepseek-ai/dsh-client-ui-chat/client'
import type { ConversationNode, ToolCallBlock } from '@deepseek-ai/dsh-client-ui-conversation/client'
import type { SessionEventLikeEntry } from '@deepseek-ai/dsh-api-session-controller/client'
// These Client-only fold modules have no plain-Node package export and are compiled into this worker.
import { ConversationNodeAssembler } from '../../packages/client/ui-conversation/src/client/conversation/assembler.ts'
@@ -29,6 +30,9 @@ import { turnErrorDefinition } from '../../packages/client/ui-chat/src/client/co
import { turnMaxTokensDefinition } from '../../packages/client/ui-chat/src/client/conversation-nodes/turn-max-tokens.ts'
import { registerTurnProcess } from '../../packages/client/ui-chat/src/client/conversation-nodes/turn-process.ts'
import { registerTurnTailConversationNode } from '../../packages/client/ui-chat/src/client/conversation-nodes/turn-tail.ts'
import type { TrajectorySnapshot } from '../../packages/client/ui-trajectory/src/client/trajectory-contract.ts'
import { trajectoryViewDefinition } from '../../packages/client/ui-trajectory/src/client/trajectory-snapshot-builder.ts'
import { registerTrajectoryToolDefinition } from '../../packages/client/ui-trajectory/src/client/trajectory-tool-definition.ts'
import { assertBuiltBenchmarkRuntime } from '../support/built-worker.ts'
const TIME_ZERO = 1_700_000_000_000
@@ -44,6 +48,21 @@ export interface ConversationFoldWorkerReport {
readonly scaling: number
}
/** Client fold of one PTC run whose root calls fan out into settled subcalls, read through each target. */
export interface PtcDispatchWorkerReport {
readonly parents: number
readonly perParent: number
readonly events: number
/** Settled subcalls published by the Chat target. */
readonly children: number
/** Replace and Chat activation, fastest sample. */
readonly foldMs: number
/** Settled subcalls published by the Trajectory target. */
readonly trajectoryChildren: number
/** Replace and Trajectory activation of the same window, fastest sample. */
readonly trajectoryFoldMs: number
}
/** Incremental argument folding through the Tool Definition and Chat group publication. */
export interface PreparingToolWorkerReport {
readonly tool: 'write' | 'bash'
@@ -88,13 +107,15 @@ function registerEventDefinitions(ctx: Context): ConversationEventRegistry {
events.register(turnErrorDefinition)
events.register(turnMaxTokensDefinition)
registerTurnTailConversationNode(ctx)
// The Web composition enables Trajectory by default, and the Assembler folds its Definitions whether or not that target is active.
registerTrajectoryToolDefinition(ctx)
events.registerFallback(unknownFallbackDefinition)
return events
}
class BenchViewDefinitions {
entries(): readonly ConversationViewDefinition[] {
return [chatViewDefinition]
return [chatViewDefinition, trajectoryViewDefinition]
}
}
@@ -193,6 +214,97 @@ function bestOf(
return best
}
/** One PTC run that dispatches `perParent` settled subcalls under each root call. */
function synthesizePtcWindow(parents: number, perParent: number): readonly SessionEventLikeEntry[] {
const entries: SessionEventLikeEntry[] = []
let seq = 0
const push = (type: string, data: unknown): void => {
entries.push(entry(seq, type, data))
seq += 1
}
push('turn/start', { turn: 1 })
for (let parent = 0; parent < parents; parent += 1) {
const rootCallId = `call-root-${String(parent)}`
push('tool/call', { callId: rootCallId, name: 'run_code', arguments: '{}' })
for (let child = 0; child < perParent; child += 1) {
const subCallId = `${rootCallId}:ptc:${String(child)}`
push('tool/ptc-dispatch-start', {
rootCallId, parentCallId: rootCallId, subCallId, name: 'read', arguments: { file_path: 'src/a.ts' },
})
push('tool/ptc-dispatch', {
rootCallId, parentCallId: rootCallId, subCallId, name: 'read', arguments: { file_path: 'src/a.ts' },
isError: false, content: [{ type: 'text', text: 'ok' }],
})
}
}
push('turn/end', { turn: 1, reason: { kind: 'completed' } })
return entries
}
type PtcTarget = 'chat' | 'trajectory'
/** Root Tool call blocks published by one activated target. */
function publishedPtcRoots(assembler: ConversationNodeAssembler, target: PtcTarget): readonly ToolCallBlock[] {
if (target === 'chat') {
const snapshot = assembler.snapshot('chat') as ChatSnapshot | undefined
return snapshot === undefined
? []
: [...snapshot.nodes.values()]
.filter((candidate): candidate is ChatNode<'tool-call'> => candidate.kind === 'tool-call')
.map(node => node.data.root)
}
const snapshot = assembler.snapshot('trajectory') as TrajectorySnapshot | undefined
return (snapshot?.eventNodes ?? []).filter((node: ConversationNode): node is Extract<ConversationNode, { kind: 'tool-result' }> =>
node.kind === 'tool-result')
}
/** Fold a PTC run into one target and read every published nested subcall back out of its snapshot. */
function foldPtcTarget(
entries: readonly SessionEventLikeEntry[],
target: PtcTarget,
expected: { readonly parents: number; readonly children: number },
definitions: ConversationEventRegistry,
): { readonly ms: number; readonly children: number } {
const started = performance.now()
const assembler = new ConversationNodeAssembler(definitions, new BenchViewDefinitions())
assembler.replaceWindow(entries, false)
assembler.activateTarget(target)
const roots = publishedPtcRoots(assembler, target)
const children = roots.reduce((total, root) => total + root.subCalls.length, 0)
const settled = roots.every(root => root.subCalls.every(child => 'kind' in child && child.kind === 'tool-result'))
const ms = performance.now() - started
if (roots.length !== expected.parents || children !== expected.children || !settled) {
throw new Error(`PTC benchmark published ${String(roots.length)} ${target} roots with ${String(children)} children`)
}
return { ms, children }
}
/** Fold a PTC run through the Chat and Trajectory targets and keep each target's fastest sample. */
function foldPtc(
parents: number,
perParent: number,
attempts: number,
definitions: ConversationEventRegistry,
): PtcDispatchWorkerReport {
const entries = synthesizePtcWindow(parents, perParent)
const expected = { parents, children: parents * perParent }
const best = (target: PtcTarget): { readonly ms: number; readonly children: number } => {
let fastest = foldPtcTarget(entries, target, expected, definitions)
for (let attempt = 1; attempt < attempts; attempt += 1) {
const next = foldPtcTarget(entries, target, expected, definitions)
if (next.ms < fastest.ms) fastest = next
}
return fastest
}
const chat = best('chat')
const trajectory = best('trajectory')
return {
parents, perParent, events: entries.length,
children: chat.children, foldMs: Math.round(chat.ms * 10) / 10,
trajectoryChildren: trajectory.children, trajectoryFoldMs: Math.round(trajectory.ms * 10) / 10,
}
}
function positiveInteger(value: string | undefined, label: string): number {
const parsed = Number(value)
if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`${label} must be a positive integer`)
@@ -366,6 +478,14 @@ try {
positiveInteger(process.argv[6], 'fragments'), definitions,
)
process.stdout.write(`${JSON.stringify(report)}\n`)
} else if (process.argv[2] === 'ptc') {
const report = foldPtc(
positiveInteger(process.argv[3], 'parents'),
positiveInteger(process.argv[4], 'per parent'),
positiveInteger(process.argv[5], 'attempts'),
definitions,
)
process.stdout.write(`${JSON.stringify(report)}\n`)
} else {
const [turnsValue, smallDeltasValue, largeDeltasValue, attemptsValue] = process.argv.slice(2)
const turns = positiveInteger(turnsValue, 'turns')
@@ -18,11 +18,31 @@ declare module '../contract/chat-nodes.ts' {
const MAX_DEPTH = 256
/**
* Fold State of one root Tool call. Dispatch updates mutate it in place and return the same object, as the
* [Assembler update rule](../../../../../../.agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md)
* permits.
*/
interface ToolState {
/** Absent until a named delta or `tool/call` identifies the call. */
readonly root: ToolCallBlock | undefined
readonly children: ReadonlyMap<string, readonly ToolCallBlock[]>
readonly parents: ReadonlyMap<string, string>
root: ToolCallBlock | undefined
/** Dispatch edges accumulated by incremental updates. */
calls: DispatchTree
}
/**
* Nested dispatch edges, keyed by parent then child call id and mutated in place
* ([rationale](../../../../../../.agents/notes/implemented/bug-fix/2026-11-27-ptc-dispatch-fold-quadratic.md)).
* Published Tool call blocks carry their own arrays and never alias this tree.
*/
interface DispatchTree {
/** Children of each parent, in dispatch order. */
children: Map<string, Map<string, ToolCallBlock>>
parents: Map<string, string>
}
function emptyDispatchTree(): DispatchTree {
return { children: new Map(), parents: new Map() }
}
interface ProjectedBlockCache {
@@ -171,7 +191,7 @@ function locationStep(match: ConversationMatch): number {
}
function acceptsEdge(state: ToolState, parent: string, child: string): boolean {
if (parent === child || state.parents.has(child)) return false
if (parent === child || state.calls.parents.has(child)) return false
let cursor: string | undefined = parent
let parentDepth = 0
const ancestors = new Set<string>()
@@ -179,7 +199,7 @@ function acceptsEdge(state: ToolState, parent: string, child: string): boolean {
if (cursor === child || ancestors.has(cursor)) return false
ancestors.add(cursor)
parentDepth++
cursor = state.parents.get(cursor)
cursor = state.calls.parents.get(cursor)
}
const pending = [{ callId: child, depth: 1 }]
const descendants = new Set<string>()
@@ -188,7 +208,7 @@ function acceptsEdge(state: ToolState, parent: string, child: string): boolean {
if (descendants.has(candidate.callId)) return false
descendants.add(candidate.callId)
subtreeDepth = Math.max(subtreeDepth, candidate.depth)
for (const nested of state.children.get(candidate.callId) ?? []) {
for (const nested of state.calls.children.get(candidate.callId)?.values() ?? []) {
pending.push({ callId: nested.callId, depth: candidate.depth + 1 })
}
}
@@ -201,26 +221,26 @@ function updateDispatch(state: ToolState, match: ConversationMatch): ToolState {
const data = event.data
const parentCallId = String(data.parentCallId)
const subCallId = String(data.subCallId)
const siblings = state.children.get(parentCallId) ?? []
const index = siblings.findIndex(candidate => candidate.callId === subCallId)
const previous = state.calls.children.get(parentCallId)?.get(subCallId)
if (event.type === 'tool/ptc-dispatch-start') {
if (index >= 0 || !acceptsEdge(state, parentCallId, subCallId)) return state
const children = new Map(state.children)
children.set(parentCallId, [...siblings, childCall(match, data)])
const parents = new Map(state.parents)
parents.set(subCallId, parentCallId)
return { ...state, children, parents }
if (previous !== undefined || !acceptsEdge(state, parentCallId, subCallId)) return state
attachChild(state.calls, parentCallId, childCall(match, data))
return state
}
if (index < 0 && !acceptsEdge(state, parentCallId, subCallId)) return state
const previous = index < 0 ? undefined : siblings[index]
const settled = childResult(match, data, previous)
const children = new Map(state.children)
children.set(parentCallId, index < 0
? [...siblings, settled]
: siblings.map((child, at) => at === index ? settled : child))
const parents = new Map(state.parents)
if (index < 0) parents.set(subCallId, parentCallId)
return { ...state, children, parents }
if (previous === undefined && !acceptsEdge(state, parentCallId, subCallId)) return state
attachChild(state.calls, parentCallId, childResult(match, data, previous))
return state
}
/** Record one child under its parent, keeping first-attachment order on replacement. */
function attachChild(calls: DispatchTree, parentCallId: string, child: ToolCallBlock): void {
let siblings = calls.children.get(parentCallId)
if (siblings === undefined) {
siblings = new Map()
calls.children.set(parentCallId, siblings)
}
siblings.set(child.callId, child)
calls.parents.set(child.callId, parentCallId)
}
function projectBlock(
@@ -234,7 +254,8 @@ function projectBlock(
if (visited.has(block.callId) || depth > MAX_DEPTH) return { ...block, subCalls: [] }
const nextVisited = new Set(visited)
nextVisited.add(block.callId)
const children = (state.children.get(block.callId) ?? block.subCalls)
const attached = state.calls.children.get(block.callId)
const children = (attached === undefined ? block.subCalls : [...attached.values()])
.map(child => projectBlock(child, state, interruptedAt, nextVisited, depth + 1))
const interruptionSeq = 'kind' in block ? undefined : interruptedAt?.seq
const interruptionTime = 'kind' in block ? undefined : interruptedAt?.time
@@ -283,7 +304,7 @@ function fallbackState(context: ConversationNodeContext<ToolState>): ToolState |
const match = context.matches.find(candidate => candidate.event.type === 'tool/result')
const root = match === undefined ? undefined : rootResult(match)
if (root === undefined) return undefined
let state: ToolState = { root, children: new Map(), parents: new Map() }
let state: ToolState = { root, calls: emptyDispatchTree() }
for (const candidate of context.matches) state = updateDispatch(state, candidate)
return state
}
@@ -314,7 +335,7 @@ export const toolDefinition: ConversationNodeDefinition<ToolState> = {
return null
},
start: (_context, match) => {
const state: ToolState = { root: undefined, children: new Map(), parents: new Map() }
const state: ToolState = { root: undefined, calls: emptyDispatchTree() }
return match.event.type === 'tool/call' ? { ...state, root: rootCall(match) } : applyDelta(state, match)
},
update: (context, match) => {
@@ -14,11 +14,31 @@ const MAX_DEPTH = 256
type ToolCallBlock = StartedToolCall | ToolResultNode
/**
* Fold State of one root Tool call. Dispatch and root-result updates mutate it in place and return the same
* object, as the Assembler update rule in the Note above permits.
*/
interface ToolState {
readonly rootId: string
readonly calls: ReadonlyMap<string, ToolCallBlock>
readonly children: ReadonlyMap<string, readonly string[]>
readonly parents: ReadonlyMap<string, string>
rootId: string
/** Root and dispatch calls accumulated by incremental updates. */
tree: DispatchTree
}
/**
* Root and nested dispatch calls, mutated in place
* ([rationale](../../../../../.agents/notes/implemented/bug-fix/2026-11-27-ptc-dispatch-fold-quadratic.md)).
* Published Tool call blocks carry their own arrays and never alias this tree.
*/
interface DispatchTree {
/** Latest block of the root and of each accepted child, keyed by call id. */
calls: Map<string, ToolCallBlock>
/** Child call ids of each parent, in first-attachment order. */
children: Map<string, string[]>
parents: Map<string, string>
}
function dispatchTree(root: ToolCallBlock): DispatchTree {
return { calls: new Map([[root.callId, root]]), children: new Map(), parents: new Map() }
}
interface DispatchData {
@@ -121,7 +141,8 @@ function childResult(
}
function acceptsEdge(state: ToolState, parent: string, child: string): boolean {
if (parent === child || state.parents.has(child)) return false
const tree = state.tree
if (parent === child || tree.parents.has(child)) return false
let cursor: string | undefined = parent
let parentDepth = 0
const ancestors = new Set<string>()
@@ -129,7 +150,7 @@ function acceptsEdge(state: ToolState, parent: string, child: string): boolean {
if (cursor === child || ancestors.has(cursor)) return false
ancestors.add(cursor)
parentDepth++
cursor = state.parents.get(cursor)
cursor = tree.parents.get(cursor)
}
const pending = [{ callId: child, depth: 1 }]
const descendants = new Set<string>()
@@ -138,7 +159,7 @@ function acceptsEdge(state: ToolState, parent: string, child: string): boolean {
if (descendants.has(candidate.callId)) return false
descendants.add(candidate.callId)
subtreeDepth = Math.max(subtreeDepth, candidate.depth)
for (const nested of state.children.get(candidate.callId) ?? []) {
for (const nested of tree.children.get(candidate.callId) ?? []) {
pending.push({ callId: nested, depth: candidate.depth + 1 })
}
}
@@ -151,21 +172,21 @@ function updateDispatch(state: ToolState, match: ConversationMatch): ToolState {
const data = event.data
const parentId = String(data.parentCallId)
const childId = String(data.subCallId)
const siblings = state.children.get(parentId) ?? []
const index = siblings.indexOf(childId)
if (index < 0 && !acceptsEdge(state, parentId, childId)) return state
if (event.type === 'tool/ptc-dispatch-start' && index >= 0) return state
const calls = new Map(state.calls)
calls.set(childId, event.type === 'tool/ptc-dispatch-start'
const tree = state.tree
// A child has at most one parent, so this edge exists exactly when the parent map names it.
const attached = tree.parents.get(childId) === parentId
if (!attached && !acceptsEdge(state, parentId, childId)) return state
if (event.type === 'tool/ptc-dispatch-start' && attached) return state
tree.calls.set(childId, event.type === 'tool/ptc-dispatch-start'
? childCall(match, data)
: childResult(match, data, calls.get(childId)))
if (index >= 0) return { ...state, calls }
const children = new Map(state.children)
children.set(parentId, [...siblings, childId])
const parents = new Map(state.parents)
parents.set(childId, parentId)
return { ...state, calls, children, parents }
: childResult(match, data, tree.calls.get(childId)))
if (!attached) {
const siblings = tree.children.get(parentId)
if (siblings === undefined) tree.children.set(parentId, [childId])
else siblings.push(childId)
tree.parents.set(childId, parentId)
}
return state
}
function interruption(
@@ -185,12 +206,12 @@ function projectCall(
visited = new Set<string>(),
depth = 1,
): ToolCallBlock | undefined {
const block = state.calls.get(callId)
const block = state.tree.calls.get(callId)
if (block === undefined) return undefined
if (visited.has(callId) || depth > MAX_DEPTH) return { ...block, subCalls: [] }
const nextVisited = new Set(visited)
nextVisited.add(callId)
const subCalls = (state.children.get(callId) ?? [])
const subCalls = (state.tree.children.get(callId) ?? [])
.flatMap((childId) => {
const child = projectCall(state, childId, interruptedAt, nextVisited, depth + 1)
return child === undefined ? [] : [child]
@@ -219,9 +240,7 @@ function fallbackState(context: ConversationNodeContext<ToolState>): ToolState |
if (root === undefined) return undefined
let state: ToolState = {
rootId: root.callId,
calls: new Map([[root.callId, root]]),
children: new Map(),
parents: new Map(),
tree: dispatchTree(root),
}
for (const match of context.matches) state = updateDispatch(state, match)
return state
@@ -246,22 +265,16 @@ const trajectoryToolDefinition: ConversationNodeDefinition<ToolState> = {
},
start: (_context, match) => {
const root = rootCall(match)
return {
rootId: root.callId,
calls: new Map([[root.callId, root]]),
children: new Map(),
parents: new Map(),
}
return { rootId: root.callId, tree: dispatchTree(root) }
},
update: (context, match) => {
if (match.event.type !== 'tool/result') return updateDispatch(context.state, match)
const previous = context.state.calls.get(context.state.rootId)
const previous = context.state.tree.calls.get(context.state.rootId)
const running = previous !== undefined && !('kind' in previous) ? previous : undefined
const result = rootResult(match, running)
if (result === undefined) return context.state
const calls = new Map(context.state.calls)
calls.set(context.state.rootId, result)
return { ...context.state, calls }
context.state.tree.calls.set(context.state.rootId, result)
return context.state
},
buildViewNode: (context) => {
const state = context.state ?? fallbackState(context)
@@ -742,6 +742,83 @@ describe('Trajectory conversation Definitions', () => {
})
})
it('keeps first-attachment order, rejects repeated starts, cycles, and reparenting, and adopts detached subtrees', () => {
const dispatch = (seq: number, type: string, parentCallId: string, subCallId: string, text?: string) => at(seq, type, {
rootCallId: 'root', parentCallId, subCallId, name: 'read', arguments: { path: subCallId },
...text === undefined ? {} : { content: [{ type: 'text', text }] },
})
const current = snapshot(assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'tool/call', { turn: 1, step: 1, callId: 'root', name: 'code', arguments: '{}' }),
dispatch(4, 'tool/ptc-dispatch-start', 'root', 'a'),
dispatch(5, 'tool/ptc-dispatch-start', 'root', 'b'),
dispatch(6, 'tool/ptc-dispatch-start', 'root', 'a'),
dispatch(7, 'tool/ptc-dispatch', 'root', 'b', 'b settled'),
dispatch(8, 'tool/ptc-dispatch', 'root', 'a', 'a first'),
dispatch(9, 'tool/ptc-dispatch', 'root', 'a', 'a second'),
dispatch(10, 'tool/ptc-dispatch-start', 'a', 'c'),
dispatch(11, 'tool/ptc-dispatch-start', 'c', 'a'),
dispatch(12, 'tool/ptc-dispatch-start', 'b', 'c'),
dispatch(13, 'tool/ptc-dispatch', 'c', 'c', 'self'),
dispatch(14, 'tool/ptc-dispatch', 'detached', 'd', 'adopted'),
dispatch(15, 'tool/ptc-dispatch-start', 'root', 'a'),
dispatch(16, 'tool/ptc-dispatch-start', 'c', 'root'),
dispatch(17, 'tool/ptc-dispatch-start', 'b', 'detached'),
at(18, 'step/end', { turn: 1, step: 1 }),
]))
const roots = current.eventNodes.filter(node => node.kind === 'tool-result')
expect(roots).toHaveLength(1)
expect(roots[0]).toMatchObject({
callId: 'root',
error: { name: 'Interrupted', code: 'interrupted' },
subCalls: [
{
kind: 'tool-result', callId: 'a', content: [{ type: 'text', text: 'a second' }],
subCalls: [{
kind: 'tool-result', callId: 'c', parentCallId: 'a', seq: 17.2, callTime: 1_700_000_000_010,
error: { name: 'Interrupted', code: 'interrupted' }, subCalls: [],
}],
},
{
kind: 'tool-result', callId: 'b', content: [{ type: 'text', text: 'b settled' }],
subCalls: [{
kind: 'tool-result', callId: 'detached', parentCallId: 'b',
error: { name: 'Interrupted', code: 'interrupted' },
subCalls: [{ kind: 'tool-result', callId: 'd', parentCallId: 'detached', content: [{ type: 'text', text: 'adopted' }] }],
}],
},
],
})
})
it('rebuilds a root whose call precedes the window from its result and dispatches', () => {
const current = snapshot(assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'step/start', { turn: 1, step: 1 }),
at(3, 'tool/ptc-dispatch-start', {
rootCallId: 'root', parentCallId: 'root', subCallId: 'a', name: 'read', arguments: { path: 'a' },
}),
at(4, 'tool/ptc-dispatch', {
rootCallId: 'root', parentCallId: 'root', subCallId: 'a', name: 'read', arguments: { path: 'a' },
content: [{ type: 'text', text: 'done' }],
}),
at(5, 'tool/result', {
turn: 1, step: 1,
message: {
id: 'result-root', role: 'tool', toolCallId: 'root', source: { kind: 'tool', callId: 'root' },
content: [{ type: 'text', text: 'root done' }],
},
}, { surfaceOp: 'append' }),
at(6, 'step/end', { turn: 1, step: 1 }),
], true))
expect(current.eventNodes.filter(node => node.kind === 'tool-result')).toMatchObject([{
seq: 5, callId: 'root', name: '', call: null, content: [{ type: 'text', text: 'root done' }],
subCalls: [{ kind: 'tool-result', callId: 'a', callTime: 1_700_000_000_003, content: [{ type: 'text', text: 'done' }] }],
}])
})
it('assembles compaction lifecycle, checkpoint replacement, and orphan interruption', () => {
const current = snapshot(assembler([
at(1, 'compaction/start', { compactionId: 'complete', turn: null }),