Merge pull request #3331 from deepseek-harness/worktree-chatctxmemory
perf(web): reduce retained conversation state
This commit is contained in:
commit
60a46b9f5d
64 files changed
+1090
-273
No files matched your search
+2
-2
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-08-client-tool-presentation-ownership.md
|
||||
2026-08-08-client-tool-presentation-ownership.md: 1daad1559a6c8ef15fadb8e7c8dfeb2874ae3f9a
|
||||
2026-08-08-client-tool-presentation-ownership.zh.md: f980db28e1174aa95b29defb8b0a36fc0ba4cf2e
|
||||
2026-08-08-client-tool-presentation-ownership.md: bf8568150cc173f0dc46ba0a125ca9c784d18f2e
|
||||
2026-08-08-client-tool-presentation-ownership.zh.md: 015a48a0499b84bf034dc905780eca0dcef99c10
|
||||
+10
-2
@@ -22,6 +22,8 @@ A business Tool plugin receives one standard `ToolCallBlock`, identity, workspac
|
||||
|
||||
The details panel is a second Tool presentation point, not the call-tree owner. `ui-conversation` locates the selected call and delegates its output body through `'conversation.details.tool'`; `ui-tool` reuses the card model, while the conversation fallback retains raw result text when the plugin is absent.
|
||||
|
||||
Generic row models retain the original argument string as `bodyRaw` and expose no preformatted body. `ToolRow` and the Bash fallback format it only while an expanded generic input section is visible; closing the row removes the formatted text, and rows rendering a structured card skip generic-body formatting.
|
||||
|
||||
## Runtime and render path
|
||||
|
||||
```text
|
||||
@@ -33,6 +35,8 @@ Session Event window
|
||||
-> tool.call.toolview(entryKey = toolName)
|
||||
|- registered atomic view
|
||||
`- GenericToolCard fallback
|
||||
|- collapsed or structured card: retain argsRaw only
|
||||
`- expanded generic input: format argsRaw
|
||||
```
|
||||
|
||||
## Ownership boundary
|
||||
@@ -42,12 +46,12 @@ Session Event window
|
||||
| Client Runtime Conversation engine | Context identity, Location, history replay, view Node publication | Tool event meaning, call tree, Tool renderer |
|
||||
| `ui-conversation` Tool Definition | call/result pairing, Code Dispatch topology, running/settled/interrupted `ToolCallBlock`, Chat ordering anchor | Tool-name dispatch, card models, recursive React structure |
|
||||
| `ui-conversation` Chat view | keyed Node order, scroll anchors, selection, and host actions | Tool lifecycle, subcall composition, atomic Tool renderers |
|
||||
| `ui-tool` | root/subcall recursive rendering, atomic keyed dispatch, fallback, card models, and details output | Session Event fold, Chat ordering |
|
||||
| `ui-tool` | root/subcall recursive rendering, atomic keyed dispatch, fallback, card models, expansion-time argument formatting, and details output | Session Event fold, Chat ordering |
|
||||
| Business Tool plugin | atomic renderers for one or more wire Tool names | root/subcall placement, lifecycle pairing, Session projectors |
|
||||
|
||||
## Verification
|
||||
|
||||
`ui-conversation` tests pin the Tool Definition's call/result pairing, Code Dispatch, interruption, and running-to-settled keyed identity without importing production `ui-tool` renderers. `ui-tool` tests mount the real conversation host and pin root/subcall recursion, keyed dispatch, Generic fallback, selection, details, and concrete Tool cards. Assembled Web tests cover the path with both plugins loaded.
|
||||
`ui-conversation` tests pin the Tool Definition's call/result pairing, Code Dispatch, interruption, and running-to-settled keyed identity without importing production `ui-tool` renderers. `ui-tool` tests mount the real conversation host and pin root/subcall recursion, keyed dispatch, Generic fallback, selection, details, concrete Tool cards, and expansion-only generic-body formatting. Assembled Web tests cover the path with both plugins loaded.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
@@ -61,8 +65,12 @@ Session Event window
|
||||
|
||||
**Let `ui-conversation` import `ui-tool` components directly.** Rejected: this would reverse the feature dependency and make Tool presentation mandatory. Slots preserve independent loading, lifecycle, and fallback behavior.
|
||||
|
||||
**Keep a preformatted body on the row model for compatibility.** Rejected: every collapsed row would retain a second full argument string, and the compatibility field would let future consumers restore eager formatting. The model exposes only `bodyRaw`, making expansion-time formatting the only generic path.
|
||||
|
||||
## Consequences
|
||||
|
||||
`ui-conversation` no longer depends on presentation for concrete Tool names, and root and subcalls cannot drift onto different dispatch paths. Business packages can independently own atomic Tool renderers; if `ui-tool` is absent, Conversation data assembly remains valid, Chat Nodes use the generic fallback, and details retain raw results.
|
||||
|
||||
Collapsed Tool rows retain the existing `argsRaw` reference without a pretty-printed copy or its formatting call. Expanding a generic input performs that work for the visible row, and closing it permits the derived text to be collected; repeated expansion trades bounded recomputation for lower retained memory.
|
||||
|
||||
The cost is an explicit dependency from `ui-tool` on the business Node slot and locale namespace declared by conversation, plus one Tool-specific child slot. Tool Definition remains in `ui-conversation` because this change does not split packages; it can later move through the Conversation registry seam without changing the presentation ownership recorded here.
|
||||
+10
-2
@@ -22,6 +22,8 @@ Conversation 数据组装遵循后续的 [Conversation 业务节点决策](2026-
|
||||
|
||||
details panel 是第二个工具展示点,但不是调用树所有者。`ui-conversation` 定位 selected call,并通过 `'conversation.details.tool'` 委托 output body;`ui-tool` 复用 card model,插件缺席时 conversation fallback 保留 raw result text。
|
||||
|
||||
Generic row model 保留原始参数字符串 `bodyRaw`,不暴露预格式化 body。`ToolRow` 与 Bash fallback 只在展开后的 generic input section 可见时格式化该字符串;收起行会移除格式化文本,渲染结构化卡片的行则跳过 generic body 格式化。
|
||||
|
||||
## 运行时与渲染路径
|
||||
|
||||
```text
|
||||
@@ -33,6 +35,8 @@ Session Event window
|
||||
-> tool.call.toolview(entryKey = toolName)
|
||||
|- registered atomic view
|
||||
`- GenericToolCard fallback
|
||||
|- collapsed or structured card: retain argsRaw only
|
||||
`- expanded generic input: format argsRaw
|
||||
```
|
||||
|
||||
## 所有权边界
|
||||
@@ -42,12 +46,12 @@ Session Event window
|
||||
| Client 运行时 Conversation engine | 上下文 identity、Location、历史回放、view Node 发布 | 工具事件含义、调用树、工具 renderer |
|
||||
| `ui-conversation` 工具 Definition | call/result 配对、Code Dispatch 拓扑、running/settled/interrupted `ToolCallBlock`、Chat 排序 anchor | 工具名称分发、card model、递归 React 结构 |
|
||||
| `ui-conversation` Chat view | keyed Node 顺序、scroll anchor、selection 与宿主动作 | 工具 lifecycle、subcall 组合、原子工具 renderer |
|
||||
| `ui-tool` | root/subcall 递归渲染、原子 keyed dispatch、fallback、card model 与 details output | 会话事件 fold、Chat 排序 |
|
||||
| `ui-tool` | root/subcall 递归渲染、原子 keyed dispatch、fallback、card model、展开时参数格式化与 details output | 会话事件 fold、Chat 排序 |
|
||||
| 业务工具插件 | 一个或多个 wire 工具名称的原子 renderer | root/subcall 位置、生命周期配对、会话 projector |
|
||||
|
||||
## 验证
|
||||
|
||||
`ui-conversation` 测试固定工具 Definition 的 call/result 配对、Code Dispatch、interruption 和 running-to-settled keyed identity,不导入 `ui-tool` 的生产 renderer。`ui-tool` 测试挂载真实 conversation 宿主,固定 root/subcall 递归、keyed dispatch、Generic fallback、selection、details 和具体工具 card。组装后的 Web 测试覆盖两个插件共同装载的路径。
|
||||
`ui-conversation` 测试固定工具 Definition 的 call/result 配对、Code Dispatch、interruption 和 running-to-settled keyed identity,不导入 `ui-tool` 的生产 renderer。`ui-tool` 测试挂载真实 conversation 宿主,固定 root/subcall 递归、keyed dispatch、Generic fallback、selection、details、具体工具 card 与只在展开时执行的 generic body 格式化。组装后的 Web 测试覆盖两个插件共同装载的路径。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
@@ -61,8 +65,12 @@ Session Event window
|
||||
|
||||
**让 `ui-conversation` 直接导入 `ui-tool` 组件。** 拒绝:这会反转功能依赖并把工具展示变成必选能力。slot 保留独立装载、生命周期和 fallback。
|
||||
|
||||
**为兼容性在 row model 上保留预格式化 body。** 拒绝:每个折叠行都会保留第二份完整参数字符串,而且兼容字段会让后续消费方恢复 eager 格式化。model 只暴露 `bodyRaw`,使展开时格式化成为唯一 generic 路径。
|
||||
|
||||
## 后果
|
||||
|
||||
`ui-conversation` 不再依赖工具名称对应的业务展示,root 与 subcall 也不会漂移到不同分发路径。业务包可以独立拥有原子工具 renderer;`ui-tool` 缺席时,Conversation 数据组装仍然成立,Chat Node 使用通用 fallback,details 保留 raw result。
|
||||
|
||||
折叠的工具行只保留既有 `argsRaw` 引用,不创建 pretty-print 副本,也不执行对应的格式化调用。展开 generic input 时才为当前可见行完成这项工作,收起后派生文本可以被回收;重复展开以有界重算换取更低的常驻内存。
|
||||
|
||||
代价是 `ui-tool` 明确依赖 conversation 声明的业务 Node slot 和 locale namespace,并拥有一个工具专属子 slot。工具 Definition 暂时位于 `ui-conversation`,因为本次没有拆包;它以后可以沿 Conversation 注册表 seam 移动,而不会改变本记录规定的展示所有权。
|
||||
+2
-2
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-09-client-conversation-node-assembly.md
|
||||
2026-08-09-client-conversation-node-assembly.md: e37f2ab3bdf9f3943cb1bcd193d5ea578a0b2c19
|
||||
2026-08-09-client-conversation-node-assembly.zh.md: be23b321b710f2f56e3e7af870ba554adb355cef
|
||||
2026-08-09-client-conversation-node-assembly.md: 4831c2261791749804b6d0bd555423b7d4894520
|
||||
2026-08-09-client-conversation-node-assembly.zh.md: 37463d0543bbabc5d236f662827b932b55bbb11d
|
||||
+20
-9
@@ -18,6 +18,8 @@ Client Runtime provides a target-neutral Conversation Node assembly engine. Busi
|
||||
|
||||
This Note retains the derivation, business-by-business validation, responsibilities, algorithms, and trade-offs that remain relevant after implementation.
|
||||
|
||||
Chat registers an Inbox Definition only for `next-step`, because message classification is its sole consumer; `next-turn` splices remain durable Session inputs but create no Chat Context. Chat and Trajectory each keep target-owned next-step state. Every insertion stores only message IDs in an immutable splice node. A successful claim materializes the pending chain once, replaces the previous claimed set with that batch, and lets later Contexts share the set until another claim. The AgentLoop appends every message admitted from that claim before it can claim another batch; a rejected claim appends no `user/message`, so later classification needs only the current batch. Historical Contexts therefore retain linear ID state instead of cumulative array and Set snapshots.
|
||||
|
||||
### Responsibility layers
|
||||
|
||||
| Layer | Durable responsibility | Explicitly does not own |
|
||||
@@ -257,8 +259,7 @@ Page size, record packing, the number of history loads, and RAF coalescing affec
|
||||
|
||||
| Business / `kind` | Stable ID | Start Match | Update Matches | State and cross-Context reads |
|
||||
|---|---|---|---|---|
|
||||
| Next-turn Inbox / `inbox-next-turn` | Splice Event seq | Each `agent/inbox/spliced` targeting next-turn | None | Apply the current splice to the pending/claimed instantaneous state from `reader.previous(ownKind)` |
|
||||
| Next-step Inbox / `inbox-next-step` | Splice Event seq | Each `agent/inbox/spliced` targeting next-step | None | Build the same per-instruction instantaneous state; Message reads its claimed set |
|
||||
| Next-step Inbox / `inbox-next-step` | Splice Event seq | Each `agent/inbox/spliced` targeting next-step | None | Append message IDs to persistent splice state; materialize once per claim and expose the shared current claimed batch to Message |
|
||||
| Message / `input-message` | Message ID | Append-surface `user/message` | None | Use source for a context message, or read the nearest next-step Inbox to distinguish user from steering |
|
||||
| Request Prompt / `request-prompt` | Header Event seq | Each `request/header` | None | Read the preceding Request Prompt through Reader, retain the full prompt state, and classify system/tool changes |
|
||||
| Assistant / `assistant-step` | `turn:step` | `step/start` | Scalar or packed `assistant/chunk`, final `assistant/message`, and same-step Retry | Aggregate blocks, usage, first-token time, final evidence, and retry-hidden state, then publish same-key Step data |
|
||||
@@ -275,7 +276,7 @@ Page size, record packing, the number of history loads, and RAF coalescing affec
|
||||
|
||||
| Business | `publication()` | Chat output | History and runtime behavior |
|
||||
|---|---|---|---|
|
||||
| Inbox | `none` | No Node | Recompute instantaneous states along the Reader chain when prepend supplies earlier splices |
|
||||
| Inbox | `none` | No Node | Recompute next-step ID state along the Reader chain when prepend supplies earlier splices; next-turn creates no Chat Context |
|
||||
| Message | Immediate by default | `user`, `steering`, or `context` | Window-gap repair can reclassify the same message key |
|
||||
| Request Prompt | Immediate by default | One `system-prompt` for every header carrying a non-empty system field | A step's first header anchors before its request messages; a later same-step series anchors after its surface rewrite; prepend of the preceding header can correct a partial-window anchor |
|
||||
| Assistant | RAF for scalar chunks and packed runs, immediate for final, none for pure usage/finish | Same-key `assistant-step` with running/settled/interrupted status | Scalar and packed reducers are equivalent; Matches support fallback without `step/start`; Location close produces interruption presentation |
|
||||
@@ -288,7 +289,7 @@ Page size, record packing, the number of history loads, and RAF coalescing affec
|
||||
| Deliverables | Immediate by default | No Node | Tool settlement incrementally updates Turn data; the Turn Tail extension slot reads produced files |
|
||||
| Fallback | Immediate by default | `unknown` JSON row | Covers only append-surface Events; an ordinary business that claimed but has not rendered an Event does not duplicate it |
|
||||
|
||||
Inbox demonstrates that every Event can be a start-only instantaneous-state Context; not every business requires a start/update pair. Reader links each state to the prior same-kind Context instead of inventing a lifecycle ID for the entire Inbox.
|
||||
Inbox demonstrates that every Event can be a start-only instantaneous-state Context; not every business requires a start/update pair. Reader links each next-step state to the prior same-kind Context instead of inventing a lifecycle ID for the entire Inbox. The state itself shares immutable pending splice nodes and one current claimed-batch Set, while unconsumed next-turn input remains outside Conversation because no Chat or Trajectory classification reads it.
|
||||
|
||||
Request Prompt demonstrates shared pure interpretation without shared target State: Chat and Trajectory call `inspectRequestPrompt()` from their own Definitions. The function canonicalizes the full header and classifies model-visible system/tool differences; each target then chooses its own output. Chat materializes every header carrying a non-empty system field, including `series` snapshots that repeat an unchanged header for an explicitly declared series or a post-replacement request, while Trajectory retains the complete request fact and its change classification. Ordinary append-only later Turns do not write another unchanged header. The first header in a Step follows the provider envelope rather than the header Event position: step one uses the owning Turn start and later steps use their Step start, placing the system field before the request's user-role messages; a later header in the same Step stays at its own Event after the surface rewrite that began the new series. When the preceding header is outside a partial window, a non-`initial` header stays at its own Event until prepend supplies that predecessor. Every header is a full snapshot, so a first loaded `resume`, `change`, or `series` header can render its system field without fabricating a comparison to unloaded history.
|
||||
|
||||
@@ -306,9 +307,13 @@ Unknown fallback demonstrates Registry ownership: it handles only append-surface
|
||||
|
||||
## View Builder and React identity
|
||||
|
||||
[`ConversationViewRegistry`](../../../../packages/client/ui-conversation/src/client/conversation/view-registry.ts) creates an independent per-Session builder for each target. The Registry stores factories and shares no Session's ordering or caches.
|
||||
[`ConversationViewRegistry`](../../../../packages/client/ui-conversation/src/client/conversation/view-registry.ts) stores an independent builder factory for each target and shares no Session's ordering or caches.
|
||||
|
||||
The Assembler calls `replace({ nodes, timeline })` on low-frequency complete replacements and `apply({ upserts, timeline })` for ordinary prepend/append flushes. Builders receive only final target Nodes already constructed by Definitions.
|
||||
A shell selection or a target source's first subscriber adds that target to the Session's monotonic active-target set. The Assembler indexes each Context under its sole target but creates no builder, Node, or snapshot for an inactive target. First activation flushes pending target-neutral work, creates the builder, and calls `replace({ nodes, timeline })` once from that target's current Contexts.
|
||||
|
||||
The shell synchronously resolves the persisted selection when a Session binding becomes available, when a cached binding becomes current, or when the View roster changes, then explicitly activates that registered View or the Chat fallback. Tab and focus actions activate their resolved target before updating selection state. A blank Session does not render the View slot, and `ConversationSnapshot.activeTargets` derives only from materialized active snapshots without querying inactive target Contexts for activity.
|
||||
|
||||
Ordinary prepend and append flushes call `apply({ upserts, timeline })` only for active targets. Complete window replacement and Registry rebuild call `replace()` only for active targets. Unsubscription does not remove a target, so returning to an opened View does not rebuild it.
|
||||
|
||||
[`ChatSnapshotBuilder`](../../../../packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts) maintains `order`, a keyed `nodes` store, the turn/step `locations` index, `timeline`, and the `legacy` slice used by StatsLine and mirrored into top-level public compatibility fields.
|
||||
|
||||
@@ -345,15 +350,15 @@ SessionEventLike window
|
||||
-> Context matches + State + Location
|
||||
-> Definition.buildLocationData(step -> turn)
|
||||
-> StepLocation.data / TurnLocation.data
|
||||
-> Definition.buildViewNode() for its declared target
|
||||
-> target View Builder
|
||||
-> Definition.buildViewNode() for each active target
|
||||
-> active target View Builder
|
||||
-> chat: ChatSnapshotBuilder -> ChatView -> keyed ChatNodeSeat
|
||||
-> trajectory: TrajectorySnapshotBuilder -> stages/layout/table
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
Runtime tests pin Definition lifecycle registration, exact-ID append, update-before-start collection followed by forward replay after start, prepend identity, Reader window-gap repair, transitive dependencies, Location closure, Step→Turn data phase order, Location data replacement, publication cadence, illegal withdrawal, and per-target Builders.
|
||||
Runtime tests pin Definition lifecycle registration, exact-ID append, update-before-start collection followed by forward replay after start, prepend identity, Reader window-gap repair, transitive dependencies, Location closure, Step→Turn data phase order, Location data replacement, publication cadence, illegal withdrawal, first-subscription activation, monotonic active targets, and per-target Builders.
|
||||
|
||||
Conversation tests cover every built-in Chat Definition, Assistant Step data, Turn Tail and Deliverables Turn data, Chat ordering and structural sharing, selector isolation, Assistant and Tool running-to-settled identity, nested Code Dispatch, steering, Compaction, Retry, interruption, load-older anchoring, and slot dispatch. Trajectory tests cover its independently registered Message, Assistant, Tool, Compaction, Request-header, and boundary Definitions together with the preserved stage-oriented view model.
|
||||
|
||||
@@ -389,6 +394,8 @@ History-path tests cover complete replace, non-overlapping prepend, complete-ran
|
||||
|
||||
**Reuse one Event Definition across Chat and Trajectory by branching in `buildViewNode(target)`.** Rejected: the views require different business State and intermediate records, so a shared Definition would make each package carry the other's conditions and payloads. Separate target-owned Definitions keep those choices local while sharing the Assembler's ingestion and lifecycle contracts.
|
||||
|
||||
**Deactivate a target when its last subscriber leaves.** Rejected: returning to the View would repeatedly rebuild its complete snapshot. Subscription establishes first use; the target then stays incremental for the remaining Session lifetime.
|
||||
|
||||
**Add a generic layout model above final business Nodes.** Rejected: activity, tail candidacy, and layout enums would centralize current Chat business semantics in the engine again. Final Nodes carry renderer-required data directly and share only identity, ordering, and Location facts.
|
||||
|
||||
**Register the Turn-data Hook only on the Assistant renderer.** Rejected: current-Node Location access is a common capability of the `conversation.chat.node` slot, not one business renderer. The parent Chat entry registers common inject once, and every keyed renderer shares the same strongly typed contract.
|
||||
@@ -407,8 +414,12 @@ Append does not scan historical Contexts; prepend replays only Contexts whose Ma
|
||||
|
||||
Separating State updates from publication cadence folds every live Assistant delta and each historical packed run while materializing at most once per animation frame. Step or Turn close and final Events can immediately publish the latest State.
|
||||
|
||||
An inactive target retains Definition State and a target Context index but no builder, materialized Nodes, or snapshot. The mounted built-in or third-party View activates its own target through normal subscription; previously opened targets continue receiving incremental updates.
|
||||
|
||||
Steps and Turns are stable homes for cross-business aggregates. Turn Tail and Deliverables derive their values without renderer scans of global Nodes; slot-level `useTurnData()` narrows common reads to the current Node's Turn and uses selector equality to isolate unrelated updates.
|
||||
|
||||
Inbox Context retention grows with splice count and claimed message count rather than their cumulative prefixes. This removes duplicate state growth but does not deduplicate message content in durable Session events or bound the loaded event window.
|
||||
|
||||
The cost is new Runtime contracts for Registry, Assembler, Location data, dependency replay, and per-target Builders, plus parent-owned common inject and per-occurrence `hookContext` in UI Slots. Definitions that consume Assistant deltas also maintain equivalent scalar and packed update branches. Definition authors must understand stable IDs, unique scalar starts, forward replay, Step→Turn publication order, read-only Reader access, and the prohibition on Node withdrawal.
|
||||
|
||||
`useTurnData()` does not revoke the standard `useSession` capability from session-scoped renderers, so this boundary relies on API guidance and tests rather than capability isolation. Registry changes remain low-frequency full rebuilds; the Chat Builder still maintains a legacy slice for StatsLine and the top-level public fields, while Trajectory owns target-specific Definitions and a Builder over the shared Session window. Built-in Definitions remain in their respective UI packages, and these compatibility boundaries do not return business interpretation to Session.
|
||||
+20
-9
@@ -18,6 +18,8 @@ Client Runtime 提供 target-neutral 的 Conversation Node 组装引擎,业务
|
||||
|
||||
本 Note 保留实现后仍有价值的方案推导、逐业务适配、职责、算法和取舍。
|
||||
|
||||
Chat 只注册 `next-step` Inbox Definition,因为消息分类是其唯一消费方;`next-turn` splice 仍是持久 Session input,但不会创建 Chat Context。Chat 与 Trajectory 各自维护 target 专属 next-step state。每次插入只把消息 ID 写入不可变 splice 节点。成功 claim 时只 materialize 一次 pending 链,以当前批次替换上一个 claimed Set,并让后续 Context 共享该 Set,直到下一次 claim。AgentLoop 会在领取下一批消息之前追加当前 claim 接纳的全部消息;被拒绝的 claim 不追加 `user/message`,因此后续分类只需当前批次。历史 Context 因而只保留线性 ID state,不再保留累计数组和 Set 快照。
|
||||
|
||||
### 责任分层
|
||||
|
||||
| 层 | 长期职责 | 明确不负责 |
|
||||
@@ -257,8 +259,7 @@ Chat `order` 的结构性变化仍可能重排当前可见 key;纯 data 更新
|
||||
|
||||
| 业务 / `kind` | 稳定 ID | start Match | update Matches | State 与跨 Context 读取 |
|
||||
|---|---|---|---|---|
|
||||
| Next-turn Inbox / `inbox-next-turn` | splice Event seq | 每条目标为 next-turn 的 `agent/inbox/spliced` | 无 | 从 `reader.previous(ownKind)` 的 pending/claimed 瞬间态应用当前 splice |
|
||||
| Next-step Inbox / `inbox-next-step` | splice Event seq | 每条目标为 next-step 的 `agent/inbox/spliced` | 无 | 同样形成逐指令瞬间态,claimed 集合供 Message 读取 |
|
||||
| Next-step Inbox / `inbox-next-step` | splice Event seq | 每条目标为 next-step 的 `agent/inbox/spliced` | 无 | 把消息 ID 追加到持久 splice state;每次 claim 只 materialize 一次,并向 Message 暴露共享的当前 claimed batch |
|
||||
| Message / `input-message` | message ID | append-surface `user/message` | 无 | 根据 source 生成 context message,或读取最近 next-step Inbox 判断 user/steering |
|
||||
| Request Prompt / `request-prompt` | header Event seq | 每条 `request/header` | 无 | 通过 Reader 读取前一条 Request Prompt,保留完整 prompt 状态,并判定 system/tool 变化 |
|
||||
| Assistant / `assistant-step` | `turn:step` | `step/start` | scalar 或 packed `assistant/chunk`、final `assistant/message`、同 step Retry | 聚合 blocks、usage、首 token 时间、final 和 retry 隐藏状态,并发布同 key Step data |
|
||||
@@ -275,7 +276,7 @@ Chat `order` 的结构性变化仍可能重排当前可见 key;纯 data 更新
|
||||
|
||||
| 业务 | `publication()` | Chat 产物 | 历史分页与运行时行为 |
|
||||
|---|---|---|---|
|
||||
| Inbox | `none` | 不生成 Node | prepend 补前序 splice 时沿 Reader 链重算瞬间态 |
|
||||
| Inbox | `none` | 不生成 Node | prepend 补前序 splice 时沿 Reader 链重算 next-step ID state;next-turn 不创建 Chat Context |
|
||||
| Message | 默认 immediate | `user`、`steering` 或 `context` | window gap 修复可让同一 message key 重新分类 |
|
||||
| Request Prompt | 默认 immediate | 每条带非空 system 字段的 header 都生成一个 `system-prompt` | Step 首条 header 锚定在请求消息之前;同 step 后续序列锚定在表层改写之后;prepend 补入前序 header 后可纠正部分窗口的锚点 |
|
||||
| Assistant | scalar chunk 与 packed run 为 RAF,final immediate,纯 usage/finish 为 none | 同 key `assistant-step`,状态为 running/settled/interrupted | scalar 与 packed reducer 等价;缺 `step/start` 可先用 Matches fallback;Location close 生成中断表现 |
|
||||
@@ -288,7 +289,7 @@ Chat `order` 的结构性变化仍可能重排当前可见 key;纯 data 更新
|
||||
| Deliverables | 默认 immediate | 不生成 Node | Tool 结算增量更新所属 Turn data,Turn Tail 扩展槽读取 produced files |
|
||||
| Fallback | 默认 immediate | `unknown` JSON row | 只兜底 append surface,普通业务已认领但暂不可见时不会重复生成 |
|
||||
|
||||
Inbox 展示了“每条 Event 都是一个 start-only 瞬间态 Context”,不是所有业务都需要 start/update 配对。它通过 Reader 与前一个同 kind Context 形成连续 fold,而非给整个 Inbox 人工制造生命周期 ID。
|
||||
Inbox 展示了“每条 Event 都是一个 start-only 瞬间态 Context”,不是所有业务都需要 start/update 配对。每个 next-step state 通过 Reader 与前一个同 kind Context 形成连续 fold,而非给整个 Inbox 人工制造生命周期 ID。state 自身共享不可变 pending splice 节点和一个当前 claimed-batch Set;未消费的 next-turn input 不进入 Conversation,因为 Chat 与 Trajectory 都不读取它来分类。
|
||||
|
||||
Request Prompt 展示了如何在不共享 target State 的前提下共用纯解释逻辑:Chat 与 Trajectory 各自在自己的 Definition 中调用 `inspectRequestPrompt()`。该函数规范化完整 header,并判定面向模型的 system/tool 差异;随后每个 target 自行选择产物。Chat 会物化每条带非空 system 字段的 header,包括为显式声明的序列或表层替换后的请求重复未变 header 的 `series` 快照;Trajectory 则保留完整请求事实及其变化分类。普通的仅追加后续 Turn 不会再次写入未变 header。一个 Step 中的首条 header 遵循提供方信封,而不是 header Event 位置:step one 使用所属 Turn start,后续 step 使用各自的 Step start,把 system 字段放到该请求的 user-role 消息之前;同一 Step 的后续 header 保留在开启新序列的表层改写之后。部分窗口未包含前序 header 时,非 `initial` header 会保留在自身 Event,直到 prepend 补入该前序 header。每条 header 都是完整快照,因此已加载窗口中的首条 `resume`、`change` 或 `series` header 无需凭空构造与未加载历史的比较,也能渲染其 system 字段。
|
||||
|
||||
@@ -306,9 +307,13 @@ Unknown fallback 展示了 Registry ownership:fallback 只处理没有任何
|
||||
|
||||
## View Builder 与 React identity
|
||||
|
||||
[`ConversationViewRegistry`](../../../../packages/client/ui-conversation/src/client/conversation/view-registry.ts) 为每个 target 创建独立的 per-Session builder。Registry 保存 factory,不共享某个 Session 的排序或缓存。
|
||||
[`ConversationViewRegistry`](../../../../packages/client/ui-conversation/src/client/conversation/view-registry.ts) 为每个 target 保存独立的 builder factory,不共享某个 Session 的排序或缓存。
|
||||
|
||||
Assembler 低频完整替换时调用 `replace({ nodes, timeline })`;普通 prepend/append flush 调用 `apply({ upserts, timeline })`。Builder 只接收 Definition 已构造完成的 target Nodes。
|
||||
shell 选择或 target source 的首个 subscriber 会把该 target 加入 Session 单调增长的 active-target set。Assembler 按唯一 target 索引每个 Context,但不会为 inactive target 创建 builder、Node 或 snapshot。首次激活会 flush 尚未发布的 target-neutral 工作、创建 builder,并从该 target 的当前 Context 调用一次 `replace({ nodes, timeline })`。
|
||||
|
||||
Session binding 可用、缓存的 binding 成为 current 或 View roster 变化时,shell 会同步解析持久化选择,再显式激活已注册的偏好 View 或 Chat fallback。Tab 与 focus action 在更新选择状态前先激活解析出的 target。blank Session 不渲染 View slot;`ConversationSnapshot.activeTargets` 只从已物化的 active snapshot 派生,不查询 inactive target Context 的 activity。
|
||||
|
||||
普通 prepend 与 append flush 只对 active target 调用 `apply({ upserts, timeline })`。完整 window replace 与 Registry rebuild 只对 active target 调用 `replace()`。取消订阅不会移除 target,因此返回已打开的 View 不会重建。
|
||||
|
||||
[`ChatSnapshotBuilder`](../../../../packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts) 维护 `order`、keyed `nodes` store、turn/step `locations` index、`timeline`,以及由 StatsLine 使用并镜像到顶层公共兼容字段的 `legacy` slice。
|
||||
|
||||
@@ -345,15 +350,15 @@ SessionEventLike window
|
||||
-> Context matches + State + Location
|
||||
-> Definition.buildLocationData(step -> turn)
|
||||
-> StepLocation.data / TurnLocation.data
|
||||
-> Definition.buildViewNode() for its declared target
|
||||
-> target View Builder
|
||||
-> Definition.buildViewNode() for each active target
|
||||
-> active target View Builder
|
||||
-> chat: ChatSnapshotBuilder -> ChatView -> keyed ChatNodeSeat
|
||||
-> trajectory: TrajectorySnapshotBuilder -> stages/layout/table
|
||||
```
|
||||
|
||||
## 验证
|
||||
|
||||
Runtime tests 固定 Definition 生命周期注册、exact-ID append、update-before-start 收集与 start 后正序 replay、prepend identity、Reader window-gap 修复、传递依赖、Location closure、Step→Turn data phase order、Location data replacement、publication cadence、非法撤回和 per-target Builder。
|
||||
Runtime tests 固定 Definition 生命周期注册、exact-ID append、update-before-start 收集与 start 后正序 replay、prepend identity、Reader window-gap 修复、传递依赖、Location closure、Step→Turn data phase order、Location data replacement、publication cadence、非法撤回、首次订阅 activation、单调 active target 和 per-target Builder。
|
||||
|
||||
Conversation tests 覆盖全部内建 Chat Definition、Assistant Step data、Turn Tail 与 Deliverables Turn data、Chat 排序和结构共享、selector isolation、Assistant/Tool running-to-settled identity、nested Code Dispatch、steering、Compaction、Retry、interruption、load-older anchoring 和 slot dispatch。Trajectory tests 则覆盖它独立注册的 Message、Assistant、Tool、Compaction、Request-header 与 boundary Definition,以及继续保留的 stage-oriented view model。
|
||||
|
||||
@@ -389,6 +394,8 @@ Assembled Web snapshot、GUI 和浏览器场景覆盖真实 plugin graph。浏
|
||||
|
||||
**在同一个 Event Definition 内通过 `buildViewNode(target)` 为 Chat 与 Trajectory 分支。** 拒绝:两种视图需要不同的业务 State 与中间记录,共用 Definition 会迫使每个 package 携带另一边的条件与 payload。target 自有的 Definition 把这些选择留在本地,同时复用 Assembler 的摄入与生命周期约定。
|
||||
|
||||
**最后一个 subscriber 离开时停用 target。** 拒绝:返回该 View 会反复重建完整 snapshot。订阅只确认首次使用;随后 target 在 Session 剩余生命周期中保持增量更新。
|
||||
|
||||
**在最终业务 Node 上再叠一层通用 layout model。** 拒绝:activity、tail candidacy 和 layout enum 会把当前 Chat 的业务语义重新集中到引擎。最终 Node 直接携带 renderer 所需 data,只共享 identity、排序和 Location 事实。
|
||||
|
||||
**只在 Assistant renderer 注册 Turn data Hook。** 拒绝:访问当前 Node Location 是 `conversation.chat.node` slot 的公共能力,不属于某个业务 renderer。父 Chat entry 注册一次 common inject,所有 keyed renderer 共享同一强类型约定。
|
||||
@@ -407,8 +414,12 @@ Append 不扫描历史 Context;prepend 只 replay Match、Location 或 Reader
|
||||
|
||||
State 更新与发布频率分离后,Assistant 的每条 live delta 与每个历史 packed run 都会被 fold,同时每 animation frame 最多 materialize 一次。step/turn close 和 final 可立即发布最新 State。
|
||||
|
||||
inactive target 会保留 Definition State 和 target Context 索引,但不保留 builder、已物化 Node 或 snapshot。已挂载的内建或第三方 View 通过正常订阅激活自己的 target;已经打开的 target 则继续接收增量更新。
|
||||
|
||||
Step/Turn 是业务间共享聚合的稳定宿主。Turn Tail 和 Deliverables 无需由 renderer 扫描全局 Nodes 即可派生值;Slot-level `useTurnData()` 把常见读取限制到当前 Node 所属 Turn,并通过 selector equality 隔离无关更新。
|
||||
|
||||
Inbox Context 的保留量随 splice 数和已 claim 消息数增长,不再随其累计前缀增长。该结构消除了重复 state 增长,但不会对持久 Session event 中的消息正文去重,也不会限制已加载 event window。
|
||||
|
||||
代价是 Runtime 新增 Registry、Assembler、Location data、依赖重放和 per-target Builder 契约,UI Slots 也新增 parent-owned common inject 与 per-occurrence `hookContext`。消费 Assistant delta 的 Definition 还需要维护等价的 scalar 与 packed update 分支。Definition 作者必须理解稳定 ID、唯一 scalar start、正序 replay、Step→Turn 发布顺序、只读 Reader 和 Node 不撤回规则。
|
||||
|
||||
`useTurnData()` 不撤销 session-scoped renderer 的标准 `useSession`,因此该边界依靠 API 引导和测试,而不是能力隔离。Registry 变化仍是低频完整 rebuild;Chat Builder 继续为 StatsLine 和顶层公共字段维护 legacy slice,Trajectory 则在共享 Session 窗口上拥有 target 专属 Definition 与 Builder。内建 Definition 分别留在所属 UI package;这些兼容边界不把业务解释权交还给 Session。
|
||||
+2
-2
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-11-trajectory-conversation-context-assembly.md
|
||||
2026-08-11-trajectory-conversation-context-assembly.md: 7d0aea2fc09f0f04bd5de923bee15c42a773489a
|
||||
2026-08-11-trajectory-conversation-context-assembly.zh.md: 1909243da02093de1a5f1d0857a11d3742258492
|
||||
2026-08-11-trajectory-conversation-context-assembly.md: c041d7a8ba9f39f74cf55f8a35513724eaeb4f54
|
||||
2026-08-11-trajectory-conversation-context-assembly.zh.md: 06e7b801b67b789ddffe991916aceee86cc903f8
|
||||
+9
-7
@@ -18,6 +18,8 @@ Trajectory registers target-owned Conversation Definitions and a `trajectory` Vi
|
||||
|
||||
Each Definition belongs to one target. Chat and Trajectory may recognize the same durable Event family, but they keep separate State and final Node payloads. They share only the Assembler's exact-ID matching, ordered Matches, Location facts, Reader dependencies, publication scheduling, and replace/prepend/append lifecycle.
|
||||
|
||||
Trajectory's target source activates its View Builder on first subscription. Before that subscription, its Definitions maintain current State while the Assembler skips `buildViewNode()` and snapshot assembly. The target remains active after unsubscription, so later visits reuse the incrementally maintained snapshot.
|
||||
|
||||
The existing [Trajectory inspection ledger](../feature/2026-07-27-trajectory-inspection-ledger.md) remains the view model. The Trajectory Builder converts materialized target Nodes into its established `eventNodes`, Requests, Tool schemas, running calls, and Location map; layout, table virtualization, selection, Overview, and inspector behavior do not become generic Conversation contracts.
|
||||
|
||||
### Business Definitions
|
||||
@@ -40,7 +42,7 @@ Assistant chunks update only their `turn:step` Context. Content-bearing chunks r
|
||||
|
||||
Trajectory reconstructs steering from durable inbox history, using the same identity rule as the [Chat steering decision](../feature/2026-08-04-web-context-source-and-steer-marks.md) without sharing Chat's final Node.
|
||||
|
||||
Each `agent/inbox/spliced` Event targeting `next-step` starts an invisible Context identified by its Event seq. Its `start()` reads the nearest earlier inbox Context, applies the splice, and stores the pending identities plus the cumulative set of claimed message IDs. A later user-origin `user/message` reads the nearest earlier inbox Context: a claimed ID produces a Steering Node, while every other user-origin message produces an ordinary User Node.
|
||||
Each `agent/inbox/spliced` Event targeting `next-step` starts an invisible Context identified by its Event seq. Its `start()` reads the nearest earlier inbox Context, appends the splice to persistent pending-ID state, and materializes that state only when a claim replaces the current claimed batch. The AgentLoop appends every admitted message from one claim before it can claim another batch; a rejected claim appends no `user/message`. A later user-origin `user/message` reads the nearest earlier inbox Context: an ID in the current claim produces a Steering Node, while every other user-origin message produces an ordinary User Node.
|
||||
|
||||
A Reader miss while older history remains records a window-gap dependency. When prepend supplies the missing predecessor, the Assembler replays the affected inbox chain and message Contexts in forward Event order. Historical page direction therefore cannot permanently misclassify a message.
|
||||
|
||||
@@ -52,11 +54,11 @@ Let `E` be the loaded raw Event count, `P` one newly prepended page, `D` the num
|
||||
|
||||
| Path | Context work | Target snapshot work | Result |
|
||||
|---|---|---|---|
|
||||
| Initial tail or reconnect replace | Match the loaded window in `O(E × D)` and build State in forward Event order | Build and order `C` contributions | A full replace remains proportional to the loaded window |
|
||||
| Older-page prepend | Match only fresh Events and replay only Contexts whose Match, Location, or Reader answer changed, in `O(P × D + Mᵣ)` | Rebuild the stage snapshot from `C` contributions | Business folding does not restart over all `E` Events |
|
||||
| Live append | Match in `O(D)`, locate the keyed Context in `O(1)`, and update only that State | Replace a same-anchor contribution in `O(1)` before snapshot assembly | Business correlation is independent of loaded Event history |
|
||||
| Initial tail or reconnect replace | Match the loaded window in `O(E × D)` and build State in forward Event order | Inactive: none; active: build and order `C` contributions | A full Context replace remains proportional to the loaded window |
|
||||
| Older-page prepend | Match only fresh Events and replay only Contexts whose Match, Location, or Reader answer changed, in `O(P × D + Mᵣ)` | Inactive: none; active: rebuild the stage snapshot from `C` contributions | Business folding does not restart over all `E` Events |
|
||||
| Live append | Match in `O(D)`, locate the keyed Context in `O(1)`, and update only that State | Inactive: none; active: replace a same-anchor contribution in `O(1)` before snapshot assembly | Business correlation is independent of loaded Event history |
|
||||
|
||||
The Builder stores contributions by Context key and keeps a key-to-position index. A content update with the same anchor replaces one contribution in place; a new contribution or anchor change rebuilds and sorts contribution order. Snapshot assembly then walks `C` contributions, indexes Request headers and Tool schemas with Maps, and handles Compaction boundaries and Turn errors with linear cursors or indexes.
|
||||
First activation builds the current `C` target Contexts without rematching Events and calls `replace()` once. Once active, the Builder stores contributions by Context key and keeps a key-to-position index. A content update with the same anchor replaces one contribution in place; a new contribution or anchor change rebuilds and sorts contribution order. Snapshot assembly then walks `C` contributions, indexes Request headers and Tool schemas with Maps, and handles Compaction boundaries and Turn errors with linear cursors or indexes.
|
||||
|
||||
Final Event and Request ordering keeps a publication's current upper bound at `O(C log C)`. The migration removes repeated reverse lookups and the old raw-history refold, but it does not claim end-to-end `O(1)` publication. Chat retains its existing keyed snapshot behavior and complexity; adding the Trajectory target does not make Chat scan Trajectory Contexts or Nodes.
|
||||
|
||||
@@ -90,7 +92,7 @@ Display memoization and search indexing stay separate. Search must include off-s
|
||||
|
||||
## Verification
|
||||
|
||||
Runtime tests pin target registration, exact-ID append, update-before-start replay, prepend identity, Reader window-gap repair, Location replay, and isolation between Chat and Trajectory snapshots.
|
||||
Runtime tests pin target registration, first-subscription activation, exact-ID append, update-before-start replay, prepend identity, Reader window-gap repair, Location replay, and isolation between Chat and Trajectory snapshots.
|
||||
|
||||
Trajectory Definition and Builder tests pin Assistant streaming and interruption, nested Tool calls and parallel interruption, Compaction and prompt inheritance, Steering classification and Step placement, Request marker order, stable contribution replacement, and prepend expansion. Table, layout, Timeline, and search tests pin deferred Markdown work, throttled index updates, tooltip-time formatting, and stable search results across append and prepend.
|
||||
|
||||
@@ -98,7 +100,7 @@ Trajectory Definition and Builder tests pin Assistant streaming and interruption
|
||||
|
||||
Trajectory business assembly now scales with the changed page or keyed Context instead of restarting from the complete raw Event window. Target-owned Definitions can evolve independently from Chat while retaining one Session window and one set of lifecycle rules. Steering becomes a first-class Trajectory record at its actual Step position without adding steering-specific state to Session.
|
||||
|
||||
The retained stage-oriented Builder still performs work proportional to materialized Trajectory contributions and may sort on publication. The search index still performs a light linear signature pass when its input layout changes. These costs are explicit target-view work, not hidden full Event refolding.
|
||||
After first activation, the retained stage-oriented Builder still performs work proportional to materialized Trajectory contributions and may sort on publication. Before activation, the target retains Context State and one target index but no Builder, materialized Node, or snapshot. The search index still performs a light linear signature pass when its input layout changes.
|
||||
|
||||
Definition authors must provide stable protocol identities. Old Events without a required ID can disappear from the affected Trajectory business view, which is preferable to joining unrelated records or failing history load; producers that require faithful display must log the identity.
|
||||
|
||||
|
||||
+9
-7
@@ -18,6 +18,8 @@ Trajectory 针对共享的 [`ConversationNodeAssembler`](2026-08-09-client-conve
|
||||
|
||||
每个 Definition 只属于一个 target。Chat 与 Trajectory 可以识别同一持久 Event 族,但分别维护自己的 State 和最终 Node payload。它们只共享 Assembler 的精确 ID 匹配、有序 Match、Location 事实、Reader 依赖、发布调度,以及 replace/prepend/append 生命周期。
|
||||
|
||||
Trajectory 的 target source 在首次订阅时激活 View Builder。在此次订阅之前,其 Definition 会维护最新 State,而 Assembler 跳过 `buildViewNode()` 和 snapshot assembly。取消订阅后 target 仍保持 active,因此后续访问会复用持续增量维护的 snapshot。
|
||||
|
||||
既有的 [Trajectory 检查记录表](../feature/2026-07-27-trajectory-inspection-ledger.zh.md)继续作为视图模型。Trajectory Builder 把已物化的 target Node 转换为原有的 `eventNodes`、Requests、Tool schema、运行中调用和 Location map;layout、表格虚拟化、选择、Overview 与检查器行为不会成为通用 Conversation 约定。
|
||||
|
||||
### 业务 Definition
|
||||
@@ -40,7 +42,7 @@ Assistant chunk 只更新对应的 `turn:step` Context。带内容的 chunk 请
|
||||
|
||||
Trajectory 从持久 inbox 历史恢复 steering,使用与 [Chat steering 决策](../feature/2026-08-04-web-context-source-and-steer-marks.zh.md)相同的标识规则,但不共享 Chat 的最终 Node。
|
||||
|
||||
每条目标为 `next-step` 的 `agent/inbox/spliced` Event 都会启动一个以 Event seq 标识的不可见 Context。它的 `start()` 读取最近的前序 inbox Context,应用 splice,并存储待处理标识以及累计的已领取 message ID 集合。后续用户来源的 `user/message` 读取最近的前序 inbox Context:已领取的 ID 生成 Steering Node,其余用户来源消息生成普通 User Node。
|
||||
每条目标为 `next-step` 的 `agent/inbox/spliced` Event 都会启动一个以 Event seq 标识的不可见 Context。它的 `start()` 读取最近的前序 inbox Context,把 splice 追加到持久的 pending ID state,并只在 claim 时 materialize 该 state、替换当前 claimed batch。AgentLoop 会在领取下一批消息之前追加当前 claim 接纳的全部消息;被拒绝的 claim 不追加 `user/message`。后续用户来源的 `user/message` 读取最近的前序 inbox Context:ID 属于当前 claim 时生成 Steering Node,其余用户来源消息生成普通 User Node。
|
||||
|
||||
仍有更早历史时,Reader miss 会记录 window-gap 依赖。prepend 补齐缺失的前驱后,Assembler 按 Event 正序重放受影响的 inbox chain 与 message Context。因此,历史分页方向不会永久错误分类消息。
|
||||
|
||||
@@ -52,11 +54,11 @@ Trajectory 从持久 inbox 历史恢复 steering,使用与 [Chat steering 决
|
||||
|
||||
| 链路 | Context 工作量 | Target snapshot 工作量 | 结果 |
|
||||
|---|---|---|---|
|
||||
| 初始尾页或重连 replace | 以 `O(E × D)` 匹配已加载窗口,并按 Event 正序构造 State | 构造并排序 `C` 个 contribution | 完整 replace 仍与已加载窗口成正比 |
|
||||
| 更早页面 prepend | 只匹配新 Event,并只重放 Match、Location 或 Reader 答案发生变化的 Context,成本为 `O(P × D + Mᵣ)` | 从 `C` 个 contribution 重建 stage snapshot | 业务 fold 不会从头重跑全部 `E` 个 Event |
|
||||
| 实时 append | 以 `O(D)` 匹配,以 `O(1)` 找到 keyed Context,并只更新对应 State | snapshot 组装前,以 `O(1)` 替换 anchor 未变的 contribution | 业务关联成本与已加载 Event 历史无关 |
|
||||
| 初始尾页或重连 replace | 以 `O(E × D)` 匹配已加载窗口,并按 Event 正序构造 State | inactive:无;active:构造并排序 `C` 个 contribution | 完整 Context replace 仍与已加载窗口成正比 |
|
||||
| 更早页面 prepend | 只匹配新 Event,并只重放 Match、Location 或 Reader 答案发生变化的 Context,成本为 `O(P × D + Mᵣ)` | inactive:无;active:从 `C` 个 contribution 重建 stage snapshot | 业务 fold 不会从头重跑全部 `E` 个 Event |
|
||||
| 实时 append | 以 `O(D)` 匹配,以 `O(1)` 找到 keyed Context,并只更新对应 State | inactive:无;active:在 snapshot 组装前以 `O(1)` 替换 anchor 未变的 contribution | 业务关联成本与已加载 Event 历史无关 |
|
||||
|
||||
Builder 按 Context key 保存 contribution,并维护 key-to-position index。anchor 相同的内容更新会原位替换一个 contribution;新增 contribution 或 anchor 变化才会重建并排序 contribution 顺序。随后,snapshot assembly 遍历 `C` 个 contribution,用 Map 索引 Request header 与 Tool schema,并以线性游标或索引处理 Compaction boundary 与 Turn error。
|
||||
首次激活会从当前 `C` 个 target Context 构建 Node,而不会重新匹配 Event,并调用一次 `replace()`。激活后,Builder 按 Context key 保存 contribution,并维护 key-to-position index。anchor 相同的内容更新会原位替换一个 contribution;新增 contribution 或 anchor 变化才会重建并排序 contribution 顺序。随后,snapshot assembly 遍历 `C` 个 contribution,用 Map 索引 Request header 与 Tool schema,并以线性游标或索引处理 Compaction boundary 与 Turn error。
|
||||
|
||||
最终 Event 和 Request 排序使单次发布的当前上界保持为 `O(C log C)`。本次迁移移除了重复反向查找和旧的原始历史 refold,但不声称端到端发布达到 `O(1)`。Chat 保持既有 keyed snapshot 行为与复杂度;增加 Trajectory target 不会让 Chat 扫描 Trajectory Context 或 Node。
|
||||
|
||||
@@ -90,7 +92,7 @@ Context 迁移与下列表现层优化解决的是不同成本。这些优化保
|
||||
|
||||
## 验证
|
||||
|
||||
Runtime 测试固定 target 注册、精确 ID append、先 update 后 start 的 replay、prepend identity、Reader window-gap 修复、Location replay,以及 Chat 与 Trajectory snapshot 隔离。
|
||||
Runtime 测试固定 target 注册、首次订阅 activation、精确 ID append、先 update 后 start 的 replay、prepend identity、Reader window-gap 修复、Location replay,以及 Chat 与 Trajectory snapshot 隔离。
|
||||
|
||||
Trajectory Definition 与 Builder 测试固定 Assistant streaming 与 interruption、嵌套 Tool call 和并行 interruption、Compaction 与 prompt 继承、Steering 分类和 Step 位置、Request 标记顺序、稳定 contribution 替换与 prepend 扩展。Table、layout、Timeline 与搜索测试固定延迟 Markdown 工作、节流索引更新、Tooltip 展示时格式化,以及 append/prepend 期间稳定的搜索结果。
|
||||
|
||||
@@ -98,7 +100,7 @@ Trajectory Definition 与 Builder 测试固定 Assistant streaming 与 interrupt
|
||||
|
||||
Trajectory 业务组装的成本随变化页面或 keyed Context 增长,不再从完整原始 Event 窗口重新开始。target 自有 Definition 可以独立于 Chat 演进,同时继续共享一份 Session 窗口和一套生命周期规则。steering 会在实际所属 Step 位置成为一等 Trajectory record,不需要向 Session 增加 steering 专属状态。
|
||||
|
||||
保留的 stage-oriented Builder 仍会执行与已物化 Trajectory contribution 数量成正比的工作,并可能在发布时排序。输入 layout 变化时,搜索索引仍会执行一次轻量线性签名检查。这些成本是显式的 target view 工作,不是隐藏的完整 Event refold。
|
||||
首次激活后,保留的 stage-oriented Builder 仍会执行与已物化 Trajectory contribution 数量成正比的工作,并可能在发布时排序。激活前,target 保留 Context State 和一个 target 索引,但不保留 Builder、已物化 Node 或 snapshot。输入 layout 变化时,搜索索引仍会执行一次轻量线性签名检查。
|
||||
|
||||
Definition 作者必须提供稳定的协议标识。缺少必要 ID 的旧 Event 可能不会出现在受影响的 Trajectory 业务视图中;与合并无关记录或让历史加载失败相比,这是更安全的退化方式。要求完整展示的生产方必须记录该标识。
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write docs/subsystems/conversation.md
|
||||
conversation.md: 28a7b3d497182f2f560f2b54f89fcfd3091af673
|
||||
conversation.zh.md: 7cf98fe2b18d9fd53e5f49f48330a5585e04c54d
|
||||
conversation.md: df1476537b95690ae2055f367e8586653b99a9a9
|
||||
conversation.zh.md: 784f52975cbb829d8914ef630aa1041693e1de62
|
||||
@@ -20,6 +20,12 @@ The Session Controller owns the contiguous loaded logical-event window. Each `Se
|
||||
|
||||
Chat and Trajectory may recognize the same durable event family, but each keeps its own Definition State and final node payload. Shared target-neutral machinery is limited to identity routing, ordered replay, Location data, predecessor dependencies, and publication cadence.
|
||||
|
||||
## Target activation
|
||||
|
||||
Each Session keeps a monotonic set of active targets. Creating or reading a target source does not activate it. The shell explicitly activates its persisted or newly selected View, while another consumer activates a target through its first source subscription. First activation creates that target's builder and calls `replace()` once from the current target-indexed Contexts. Later flushes call `apply()` for every active target, and unsubscription does not remove one.
|
||||
|
||||
The shell owns View selection and resolves the registered preferred View or Chat fallback before rendering when a binding is created or selected as current, and after View-roster changes. The assembler receives only the resolved target id and does not select Chat or another default target. A third-party View participates through the same selection and activation operations.
|
||||
|
||||
## Replayable event families
|
||||
|
||||
Choose one stable business id before writing the Definition. Every event that contributes to the same Node must carry that id or derive it independently from its own payload; the client must never assign an update to “the latest unfinished” Context.
|
||||
@@ -247,5 +253,6 @@ Add focused tests that establish these outcomes:
|
||||
5. Repeated visible deltas preserve `context.key` and publish at most once per animation frame when requested.
|
||||
6. The keyed renderer consumes `node.data` and constrained Location hooks only; it does not scan the Session event window, Contexts, or Chat Nodes.
|
||||
7. Scalar and packed Assistant history produce the same final State, timing boundaries, and target snapshot, while one packed run remains one Match through replace, prepend, Location replay, and registry rebuild.
|
||||
8. Creating a target source performs no builder work; explicit selection or the first subscription performs one complete replacement, later updates reach every active target, and repeated activation performs no replacement.
|
||||
|
||||
Use [`packages/client/ui-chat/src/client/conversation-nodes/assistant.ts`](../../packages/client/ui-chat/src/client/conversation-nodes/assistant.ts) for streaming and interruption, [`inbox.ts`](../../packages/client/ui-chat/src/client/conversation-nodes/inbox.ts) plus [`message.ts`](../../packages/client/ui-chat/src/client/conversation-nodes/message.ts) for predecessor queries, and [`packages/client/ui-deliverables`](../../packages/client/ui-deliverables) for a Definition that publishes Turn data without creating its own Node.
|
||||
@@ -20,6 +20,12 @@ Session Controller 拥有连续的已加载逻辑 event window。每个 `Session
|
||||
|
||||
Chat 与 Trajectory 可以识别同一个持久 event family,但各自保留自己的 Definition State 与最终 node payload。共享的 target-neutral 机制只包括 identity routing、有序 replay、Location data、predecessor dependency 与 publication cadence。
|
||||
|
||||
## Target 激活
|
||||
|
||||
每个 Session 都保留单调增长的 active target 集合。创建或读取 target source 不会激活它。shell 会显式激活持久化选择或新选择的 View,其他消费者则通过 target source 的首个订阅激活 target。首次激活会创建该 target 的 builder,并从当前按 target 索引的 Context 调用一次 `replace()`。后续 flush 对每个 active target 调用 `apply()`,取消订阅不会移除 target。
|
||||
|
||||
shell 拥有 View 选择,并在 binding 创建、被选为 current 或 View roster 变化时,于渲染前解析已注册的偏好 View 或 Chat fallback。assembler 只接收解析后的 target id,不自行选择 Chat 或其他默认 target。第三方 View 使用相同的选择与激活操作。
|
||||
|
||||
## 可回放 event family
|
||||
|
||||
编写 Definition 前先选定稳定的业务 id。构成同一个 Node 的每条事件都必须携带该 id,或只凭自身 payload 独立推导出该 id;Client 绝不能把 update 猜测为属于“最近一个未完成”的 Context。
|
||||
@@ -247,5 +253,6 @@ Assembler 会记录这项依赖。如果后续 older prepend 带来了更近的
|
||||
5. 重复的可见 delta 保持 `context.key`,并在请求 `animation-frame` 时每帧最多发布一次。
|
||||
6. keyed renderer 只消费 `node.data` 与受限 Location hook,不扫描 Session 事件窗口、Context 或 Chat Node。
|
||||
7. scalar 与 packed Assistant 历史产生相同的最终 State、timing boundary 和 target snapshot;一个 packed run 在 replace、prepend、Location replay 与 registry rebuild 中始终只保留一个 Match。
|
||||
8. 创建 target source 不执行 builder 工作;显式选择或首次订阅执行一次完整 replace,后续更新送达所有 active target,重复激活不会再次 replace。
|
||||
|
||||
流式与中断处理可参考 [`packages/client/ui-chat/src/client/conversation-nodes/assistant.ts`](../../packages/client/ui-chat/src/client/conversation-nodes/assistant.ts),前序查询可参考 [`inbox.ts`](../../packages/client/ui-chat/src/client/conversation-nodes/inbox.ts) 与 [`message.ts`](../../packages/client/ui-chat/src/client/conversation-nodes/message.ts),只发布 Turn data 而不创建自有 Node 的例子见 [`packages/client/ui-deliverables`](../../packages/client/ui-deliverables)。
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-chat/README.md
|
||||
README.md: 4f5e969197453ee030e2deb8a09f36d3327b5ed0
|
||||
README.zh.md: 47ed92366f6c9e0c5b54c8d5095d30c8561bad47
|
||||
README.md: 9fe462316e6ab6d664a43b9fc481e07b01eda093
|
||||
README.zh.md: bad8a9143cd0307cdc5edb3e66bb9984cd5ca2be
|
||||
@@ -8,7 +8,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
The browser Chat target for Conversation assembly. It registers Chat event definitions and snapshot construction, supplies `useChat`, renders transcript nodes and details, and owns Chat-specific stores, actions, localization, and scroll restoration; historical image URLs resolve through the Conversation-owned per-session cache (`ctx.uiConversation.imageUrl`). Its Assistant and Turn Tail definitions fold packed historical Assistant runs without expanding their members. Local submission echoes (`SessionSnapshot.pendingSubmissions`) retain the surface selected when the submit begins: transcript echoes render at the flow tail, steering echoes render with the pending-steering marker, and queued echoes stay out of Chat. Each echo is hidden per render once a user/steering node or queue occurrence carries its prompt `rpcId`, so the handoff is atomic.
|
||||
The browser Chat target for Conversation assembly. It registers Chat event definitions and snapshot construction, supplies `useChat`, renders transcript nodes and details, and owns Chat-specific stores, actions, localization, and scroll restoration; historical image URLs resolve through the Conversation-owned per-session cache (`ctx.uiConversation.imageUrl`). Its Assistant and Turn Tail definitions fold packed historical Assistant runs without expanding their members. Steering classification retains only next-step Inbox IDs through persistent splice state; next-turn splices create no Chat Context. Local submission echoes (`SessionSnapshot.pendingSubmissions`) retain the surface selected when the submit begins: transcript echoes render at the flow tail, steering echoes render with the pending-steering marker, and queued echoes stay out of Chat. Each echo is hidden per render once a user/steering node or queue occurrence carries its prompt `rpcId`, so the handoff is atomic.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
Conversation 组装的浏览器 Chat target。本包注册 Chat event definition 与 snapshot 构造、提供 `useChat`、渲染 transcript node 和详情,并拥有 Chat 专属 store、action、本地化与滚动位置恢复;历史图片 URL 通过 Conversation 持有的按会话缓存(`ctx.uiConversation.imageUrl`)解析。其中 Assistant 与 Turn Tail definition 会直接 fold packed Assistant 历史 run,不展开其成员。本地提交回显(`SessionSnapshot.pendingSubmissions`)保留提交开始时选定的区域:transcript 回显位于消息流末尾,steering 回显带 pending-steering 标记,queued 回显不进入 Chat。一旦 user/steering 节点或 queue occurrence 携带回显的 prompt `rpcId`,该回显即在同一渲染中隐藏,因此交接是原子的。
|
||||
Conversation 组装的浏览器 Chat target。本包注册 Chat event definition 与 snapshot 构造、提供 `useChat`、渲染 transcript node 和详情,并拥有 Chat 专属 store、action、本地化与滚动位置恢复;历史图片 URL 通过 Conversation 持有的按会话缓存(`ctx.uiConversation.imageUrl`)解析。其中 Assistant 与 Turn Tail definition 会直接 fold packed Assistant 历史 run,不展开其成员。steering 分类通过持久 splice state 只保留 next-step Inbox ID;next-turn splice 不创建 Chat Context。本地提交回显(`SessionSnapshot.pendingSubmissions`)保留提交开始时选定的区域:transcript 回显位于消息流末尾,steering 回显带 pending-steering 标记,queued 回显不进入 Chat。一旦 user/steering 节点或 queue occurrence 携带回显的 prompt `rpcId`,该回显即在同一渲染中隐藏,因此交接是原子的。
|
||||
|
||||
## 目录
|
||||
|
||||
|
||||
@@ -2,68 +2,133 @@ import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {
|
||||
ConversationNodeDefinition, ConversationPreviousContext,
|
||||
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { InboxTarget } from '@deepseek-ai/dsh-agent/types'
|
||||
|
||||
interface InboxIdentity {
|
||||
readonly id: string
|
||||
}
|
||||
|
||||
interface InboxSplice {
|
||||
readonly target: InboxTarget
|
||||
readonly start: number
|
||||
readonly removedCount?: number
|
||||
readonly inserted: readonly InboxIdentity[]
|
||||
readonly outcome?: 'canceled'
|
||||
}
|
||||
|
||||
/** Cumulative state after one durable inbox splice. */
|
||||
export interface InboxState {
|
||||
readonly pending: readonly InboxIdentity[]
|
||||
readonly claimed: ReadonlySet<string>
|
||||
interface PendingSnapshot {
|
||||
readonly kind: 'snapshot'
|
||||
readonly ids: readonly string[]
|
||||
}
|
||||
|
||||
interface PendingSplice {
|
||||
readonly kind: 'splice'
|
||||
readonly previous: PendingState
|
||||
readonly start: number
|
||||
readonly removedCount: number
|
||||
readonly inserted: readonly string[]
|
||||
}
|
||||
|
||||
type PendingState = PendingSnapshot | PendingSplice
|
||||
|
||||
/** Persistent next-step state after one durable Inbox splice. */
|
||||
export interface InboxState {
|
||||
/** Persistent splice chain materialized only when a next-step batch is claimed. */
|
||||
readonly pending: PendingState
|
||||
/** Message ids in the current claim, shared until the next claim. */
|
||||
readonly currentClaimed: ReadonlySet<string>
|
||||
}
|
||||
|
||||
const EMPTY_PENDING: PendingState = { kind: 'snapshot', ids: [] }
|
||||
const EMPTY_CURRENT_CLAIMED: ReadonlySet<string> = new Set()
|
||||
|
||||
function materializePending(state: PendingState): string[] {
|
||||
const splices: PendingSplice[] = []
|
||||
let current = state
|
||||
while (current.kind === 'splice') {
|
||||
splices.push(current)
|
||||
current = current.previous
|
||||
}
|
||||
const pending = [...current.ids]
|
||||
for (const splice of splices.reverse()) {
|
||||
pending.splice(splice.start, splice.removedCount, ...splice.inserted)
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
function withoutInserted(
|
||||
claimed: ReadonlySet<string>,
|
||||
inserted: readonly string[],
|
||||
): ReadonlySet<string> {
|
||||
let next: Set<string> | undefined
|
||||
for (const id of inserted) {
|
||||
if (!claimed.has(id)) continue
|
||||
next ??= new Set(claimed)
|
||||
next.delete(id)
|
||||
}
|
||||
return next ?? claimed
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one next-step splice under the AgentLoop's durable event ordering.
|
||||
* An entered claim logs its complete message batch before another claim; a
|
||||
* rejected claim logs no messages, so only the current claim can classify a
|
||||
* later `user/message`.
|
||||
*/
|
||||
function applySplice(
|
||||
previous: ConversationPreviousContext<InboxState> | undefined,
|
||||
splice: InboxSplice,
|
||||
): InboxState {
|
||||
const pending = [...(previous?.state.pending ?? [])]
|
||||
const claimed = new Set(previous?.state.claimed ?? [])
|
||||
const removed = pending.splice(splice.start, splice.removedCount ?? 0, ...splice.inserted)
|
||||
for (const identity of splice.inserted) claimed.delete(identity.id)
|
||||
if (splice.target === 'next-step' && splice.outcome !== 'canceled') {
|
||||
for (const identity of removed) claimed.add(identity.id)
|
||||
const priorPending = previous?.state.pending ?? EMPTY_PENDING
|
||||
const inserted = splice.inserted.map(identity => identity.id)
|
||||
const removedCount = splice.removedCount ?? 0
|
||||
if (removedCount > 0 && splice.outcome !== 'canceled') {
|
||||
const pending = materializePending(priorPending)
|
||||
const removed = pending.splice(splice.start, removedCount, ...inserted)
|
||||
return {
|
||||
pending: { kind: 'snapshot', ids: pending },
|
||||
currentClaimed: new Set(removed),
|
||||
}
|
||||
}
|
||||
return { pending, claimed }
|
||||
}
|
||||
|
||||
function inboxDefinition(target: InboxTarget): ConversationNodeDefinition<InboxState> {
|
||||
const kind = `inbox-${target}`
|
||||
const currentClaimed = withoutInserted(
|
||||
previous?.state.currentClaimed ?? EMPTY_CURRENT_CLAIMED,
|
||||
inserted,
|
||||
)
|
||||
return {
|
||||
kind,
|
||||
match: event => event.type === 'agent/inbox/spliced'
|
||||
&& event.data.target === target
|
||||
? { id: String(event.seq), role: 'start' }
|
||||
: null,
|
||||
start: (_context, match, reader) => {
|
||||
if (match.event.type !== 'agent/inbox/spliced') throw new Error(`${kind} start requires agent/inbox/spliced`)
|
||||
return applySplice(reader.previous<InboxState>(kind), match.event.data)
|
||||
pending: {
|
||||
kind: 'splice',
|
||||
previous: priorPending,
|
||||
start: splice.start,
|
||||
removedCount,
|
||||
inserted,
|
||||
},
|
||||
update: context => context.state,
|
||||
publication: () => 'none',
|
||||
currentClaimed,
|
||||
}
|
||||
}
|
||||
|
||||
/** Cumulative next-turn inbox splice Definition. */
|
||||
export const nextTurnInboxDefinition = inboxDefinition('next-turn')
|
||||
const NEXT_STEP_INBOX_KIND = 'inbox-next-step'
|
||||
|
||||
/** Cumulative next-step inbox splice Definition used to classify steering. */
|
||||
export const nextStepInboxDefinition = inboxDefinition('next-step')
|
||||
/** Persistent next-step Inbox state used to classify the current claimed batch as steering. */
|
||||
export const nextStepInboxDefinition: ConversationNodeDefinition<InboxState> = {
|
||||
kind: NEXT_STEP_INBOX_KIND,
|
||||
match: (event) => {
|
||||
if (event.type === 'agent/inbox/spliced' && event.data.target === 'next-step') {
|
||||
return { id: String(event.seq), role: 'start' }
|
||||
}
|
||||
return null
|
||||
},
|
||||
start: (_context, match, reader) => {
|
||||
if (match.event.type !== 'agent/inbox/spliced') {
|
||||
throw new Error('inbox-next-step start requires agent/inbox/spliced')
|
||||
}
|
||||
return applySplice(reader.previous<InboxState>(NEXT_STEP_INBOX_KIND), match.event.data)
|
||||
},
|
||||
update: context => context.state,
|
||||
publication: () => 'none',
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the two durable Inbox-state contributions.
|
||||
* Register the next-step Inbox state used by Chat message classification.
|
||||
* @param ctx - owning UI Conversation context.
|
||||
*/
|
||||
export function registerInboxConversationNodes(ctx: Context): void {
|
||||
ctx.uiConversation.events.register(nextTurnInboxDefinition)
|
||||
ctx.uiConversation.events.register(nextStepInboxDefinition)
|
||||
}
|
||||
@@ -58,7 +58,8 @@ export const messageDefinition: ConversationNodeDefinition<MessageNode> = {
|
||||
form: contextForm(event.data.source),
|
||||
}
|
||||
}
|
||||
const claimed = reader.previous<InboxState>('inbox-next-step')?.state.claimed.has(String(event.data.id)) === true
|
||||
const claimed = reader.previous<InboxState>('inbox-next-step')
|
||||
?.state.currentClaimed.has(String(event.data.id)) === true
|
||||
return claimed
|
||||
? {
|
||||
kind: 'steering',
|
||||
|
||||
@@ -22,7 +22,7 @@ import { chatViewDefinition } from '../src/client/conversation-nodes/chat-snapsh
|
||||
import { commandDefinition } from '../src/client/conversation-nodes/command.ts'
|
||||
import { compactionDefinition } from '../src/client/conversation-nodes/compaction.ts'
|
||||
import { unknownFallbackDefinition } from '../src/client/conversation-nodes/fallback.ts'
|
||||
import { nextStepInboxDefinition, nextTurnInboxDefinition } from '../src/client/conversation-nodes/inbox.ts'
|
||||
import { nextStepInboxDefinition } from '../src/client/conversation-nodes/inbox.ts'
|
||||
import { messageDefinition } from '../src/client/conversation-nodes/message.ts'
|
||||
import { inspectRequestPrompt } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { requestPromptDefinition } from '../src/client/conversation-nodes/request-prompt.ts'
|
||||
@@ -37,7 +37,6 @@ import type {
|
||||
} from '../src/client/contract/chat-nodes.ts'
|
||||
|
||||
const DEFINITIONS: readonly ConversationNodeDefinition[] = [
|
||||
nextTurnInboxDefinition,
|
||||
nextStepInboxDefinition,
|
||||
messageDefinition,
|
||||
requestPromptDefinition(inspectRequestPrompt),
|
||||
@@ -107,7 +106,7 @@ function packedInputs(entries: readonly SessionLiveEventEntry[]): SessionEventLi
|
||||
function assembler(entries: readonly SessionEventLikeEntry[] = [], hasMore = false): ConversationNodeAssembler {
|
||||
const value = new ConversationNodeAssembler(new TestEventDefinitions(), new TestViewDefinitions())
|
||||
value.replaceWindow(entries, hasMore)
|
||||
value.flush()
|
||||
value.activateTarget('chat')
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -419,6 +418,63 @@ describe('built-in conversation node Definitions', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('replays pending splice chains and scopes steering to the current claim', () => {
|
||||
const first = textMessage('claim-first', 'first')
|
||||
const second = textMessage('claim-second', 'second')
|
||||
const canceled = textMessage('claim-canceled', 'canceled')
|
||||
const requeued = textMessage('claim-requeued', 'requeued')
|
||||
const later = textMessage('claim-later', 'later')
|
||||
const current = snapshot(assembler([
|
||||
at(1, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [first],
|
||||
}),
|
||||
at(2, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 1, inserted: [canceled],
|
||||
}),
|
||||
at(3, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 1, inserted: [second],
|
||||
}),
|
||||
at(4, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 2, removedCount: 1, inserted: [], outcome: 'canceled',
|
||||
}),
|
||||
at(5, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 2, inserted: [],
|
||||
}),
|
||||
at(6, 'user/message', first, { surfaceOp: 'append' }),
|
||||
at(7, 'user/message', second, { surfaceOp: 'append' }),
|
||||
at(8, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [requeued],
|
||||
}),
|
||||
at(9, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 1, inserted: [],
|
||||
}),
|
||||
at(10, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [requeued],
|
||||
}),
|
||||
at(11, 'user/message', requeued, { surfaceOp: 'append' }),
|
||||
at(12, 'user/message', canceled, { surfaceOp: 'append' }),
|
||||
at(13, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled',
|
||||
}),
|
||||
at(14, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [later],
|
||||
}),
|
||||
at(15, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 1, inserted: [],
|
||||
}),
|
||||
at(16, 'user/message', later, { surfaceOp: 'append' }),
|
||||
]))
|
||||
|
||||
expect(current.order.map(key => current.nodes.get(key)).filter(node =>
|
||||
node?.kind === 'user' || node?.kind === 'steering')).toMatchObject([
|
||||
{ kind: 'steering', data: { seq: 6 } },
|
||||
{ kind: 'steering', data: { seq: 7 } },
|
||||
{ kind: 'user', data: { seq: 11 } },
|
||||
{ kind: 'user', data: { seq: 12 } },
|
||||
{ kind: 'steering', data: { seq: 16 } },
|
||||
])
|
||||
})
|
||||
|
||||
it('orders a command-started Turn first steering before its process control', () => {
|
||||
const steering = textMessage('command-task', 'plan this change')
|
||||
const value = assembler([
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md
|
||||
README.md: 629b8b4f7987fc072066e58692396354f7b6ad6a
|
||||
README.zh.md: cb622f0308ddb0a978cfb665105d79aadfb3135a
|
||||
README.md: ce99ede306e0b0aeac24d7b21beacd0a538380b6
|
||||
README.zh.md: 5a2e481071ed3303983d5b57c68690ea9f4c4ab3
|
||||
@@ -29,6 +29,8 @@ English | [中文](README.zh.md)
|
||||
|
||||
The adapter passes each `SessionEventLikeEntry` directly to the assembler. Its outer `type` distinguishes scalar and packed records, while its inner `event` always exposes `type`, `seq`, `time`, and `data`; Definitions receive that inner `SessionEventLike`. Historical replace and prepend accept both entry variants, while live append accepts only `SessionLiveEventEntry`. Every Definition uses the same `match` and `update` methods for both event forms, while `start` receives only a standard event and the assembler rejects a packed start. Definitions that do not consume Assistant deltas return `null` for the packed tags. Replacement windows and revision gaps rebuild from the complete loaded window; contiguous append and prepend revisions use incremental assembly without expanding packed members. The assembler owns Context matching, Turn/Step locations, target node materialization, target activity, and stable target sources. `ConversationSnapshot` contains only target-neutral views and active-target facts; Session lifecycle state remains in `SessionSnapshot`.
|
||||
|
||||
A target becomes active when shell selection resolves it or when its source receives a first subscriber. The assembler replaces that target from current Contexts once and keeps it active for later incremental flushes; creating a source does not activate it and unsubscription does not deactivate it.
|
||||
|
||||
Target packages declaration-merge their snapshot and Location data maps, then register with `ctx.uiConversation.events.register(...)` and `ctx.uiConversation.views.register(...)`. A target reads its Session-owned source with `ctx.uiConversation.binding(binding).target(targetId)`. Registrations are Cordis effects and their returned disposers remove the contribution from the same registry.
|
||||
|
||||
<a id="shell-and-standard-props"></a>
|
||||
@@ -38,6 +40,8 @@ The package registers the optional-Session `conversation` shell, strict Session
|
||||
|
||||
View selection is deterministic: a registered persisted selection wins, otherwise registered `chat` wins, otherwise no View renders. It never chooses the first registered View. Shell phase combines Session lifecycle with the active-target set; no target-specific snapshot is read by the shell.
|
||||
|
||||
The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated.
|
||||
|
||||
The resident composer survives no-Session and Session transitions. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's clipboard projection is mirrored into the per-Session Conversation store. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local image previews or durable image parts as thumbnails, while an edit exposes the literal sent text. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace.
|
||||
|
||||
Default sends commit optimistically: Enter clears the draft, occurrence table, and undo history in the same transaction, keeps the composer in `plain`, and runs the send as a detached attempt, so typing and further sends continue during the flight. `sendSession` registers a Session submission echo (`session.beginSubmission`) with the delivery mode before serializing; Session derives the placement from that mode and its current running state, so idle sends use the transcript, busy Queue sends use QueueDock, and busy Steer sends use the pending-steering surface. It then yields one paint and encodes images through the browser's native `FileReader` data-URL path. Concurrent failures are restored together in submission order until the user edits the restored content; command submissions keep the frozen `submitting` phase. Detached attempts retain their image ids through admission and Session scope disposal. When an echo retires as observed, the durable image cache exposes its preview immediately, fetches the admitted attachment, replaces the preview with the canonical URL, and revokes each URL after its use ends. Direct subagent continuations skip local echoes because their transport does not preserve the browser request id.
|
||||
|
||||
@@ -29,6 +29,8 @@ kind: "package-reference"
|
||||
|
||||
adapter 把每个 `SessionEventLikeEntry` 直接交给 assembler。外层 `type` 区分 scalar 与 packed record,内部 `event` 则统一公开 `type`、`seq`、`time` 与 `data`;Definition 接收这个内部 `SessionEventLike`。历史 replace 与 prepend 接受两种 entry,实时 append 只接受 `SessionLiveEventEntry`。两种 event 都使用 Definition 的同一组 `match` 与 `update` 方法,`start` 则只接收标准 event,assembler 会拒绝 packed start。不消费 Assistant delta 的 Definition 对 packed tag 返回 `null`。replace window 或 revision 断档从完整已加载窗口重建;连续 revision 的 append 和 prepend 使用增量组装,并且不展开 packed member。assembler 拥有 Context 匹配、Turn/Step location、target node 物化、target activity 和稳定 target source。`ConversationSnapshot` 只包含与 target 无关的 View 与 active-target 事实;Session lifecycle 状态仍属于 `SessionSnapshot`。
|
||||
|
||||
shell 选择解析出 target 或 target source 收到首个 subscriber 时,该 target 进入 active 状态。assembler 从当前 Context 对它执行一次 replace,并使它参与后续增量 flush;创建 source 不会激活 target,取消订阅也不会停用 target。
|
||||
|
||||
target package 通过 declaration merge 扩展 snapshot 与 Location data map,再调用 `ctx.uiConversation.events.register(...)` 和 `ctx.uiConversation.views.register(...)`。target 通过 `ctx.uiConversation.binding(binding).target(targetId)` 读取其 Session-owned source。注册属于 Cordis effect,返回的 disposer 从同一个 registry 移除 contribution。
|
||||
|
||||
<a id="shell-and-standard-props"></a>
|
||||
@@ -38,6 +40,8 @@ target package 通过 declaration merge 扩展 snapshot 与 Location data map,
|
||||
|
||||
View 选择规则固定:有效且已注册的持久化选择优先,其次是已注册的 `chat`,否则不渲染 View;绝不选择第一个已注册 View。Shell phase 只组合 Session lifecycle 与 active-target set,不读取任何 target-specific snapshot。
|
||||
|
||||
Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。
|
||||
|
||||
常驻 composer 在无 Session 与有 Session 之间保持挂载。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿的剪贴板投影镜像到逐 Session Conversation store。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并把本地图片预览或持久化图片部分显示为缩略图,编辑态则展示字面发送文本。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。
|
||||
|
||||
默认发送采用乐观提交:Enter 在同一事务里清空草稿、occurrence 表和撤销历史,composer 保持 `plain`,发送作为 detached attempt 运行,发送期间可以继续输入和提交。`sendSession` 在序列化之前用投递模式注册 Session 提交回显(`session.beginSubmission`);Session 根据该模式与当前运行状态推导位置,因此空闲发送进入 transcript,繁忙时 Queue 进入 QueueDock,繁忙时 Steer 进入 pending-steering 区域。随后让出一帧,图片经浏览器原生 `FileReader` data-URL 路径编码。多个并发发送失败时,在用户编辑还原内容之前按提交顺序合并还原;命令提交保持冻结的 `submitting` 阶段。Detached attempt 持有图片 id,直到 admission 完成或 Session scope 销毁。回显以 observed 退休时,durable 图片缓存立即公开预览 URL,同时读取 admitted 附件,随后用规范化 URL 替换预览,并在两个 URL 各自停止使用后撤销。直接 subagent continuation 不创建本地回显,因为其 transport 不保留浏览器 request id。
|
||||
|
||||
@@ -16,7 +16,7 @@ import type {
|
||||
ConversationSessionInjected,
|
||||
} from './contract/slots.ts'
|
||||
import type { InputNotice } from './contract/input.ts'
|
||||
import { createConversationStore } from './stores.ts'
|
||||
import { createConversationStore, readConversationViewPreference } from './stores.ts'
|
||||
import { ConversationController, UnsupportedImageMediaTypeError } from './service.ts'
|
||||
import type { IConversation } from './service.ts'
|
||||
import { ComposerBlockRegistry } from './input/blocks.ts'
|
||||
@@ -30,6 +30,7 @@ import { ConversationRoot } from './skeleton/ConversationRoot.tsx'
|
||||
import { ConversationSession, ConversationSessionHeader } from './skeleton/ConversationSession.tsx'
|
||||
import { InputBar } from './skeleton/InputBar.tsx'
|
||||
import { todoDockEntry } from './skeleton/TodoPanel.tsx'
|
||||
import { resolveActiveView } from './view-selection.ts'
|
||||
import { en, NS, zh, type ConversationKey } from './locales.ts'
|
||||
import { CONVERSATION_SETTINGS_NAMESPACE, type ConversationSettings } from '../submission-settings.ts'
|
||||
|
||||
@@ -129,25 +130,47 @@ export function apply(ctx: Context): void {
|
||||
}
|
||||
return tabs
|
||||
}
|
||||
const activateView = (sessionId: SessionId, preferred: string | null): void => {
|
||||
const active = resolveActiveView(viewTabs(), preferred)
|
||||
if (active !== undefined) uiConversation.binding(sessionId).activate(active.id)
|
||||
}
|
||||
const restoreView = (sessionId: SessionId): void => {
|
||||
activateView(sessionId, readConversationViewPreference(sessionId))
|
||||
}
|
||||
const restoreCurrentView = (): void => {
|
||||
const sessionId = sessions.list.getSnapshot().current
|
||||
if (sessionId !== undefined && sessions.binding(sessionId) !== undefined) {
|
||||
restoreView(sessionId)
|
||||
}
|
||||
}
|
||||
const conversationViews = createSnapshotStore<readonly ViewTab[]>(viewTabs())
|
||||
const refreshViews = (): void => {
|
||||
const current = conversationViews.getSnapshot()
|
||||
const next = viewTabs()
|
||||
if (current.length === next.length
|
||||
const unchanged = current.length === next.length
|
||||
&& current.every((tab, index) => {
|
||||
const candidate = next.at(index)
|
||||
return candidate !== undefined && tab.id === candidate.id && tab.label === candidate.label
|
||||
})) return
|
||||
conversationViews.set(next)
|
||||
})
|
||||
if (!unchanged) conversationViews.set(next)
|
||||
restoreCurrentView()
|
||||
}
|
||||
ctx.effect(() => {
|
||||
let currentSessionId = sessions.list.getSnapshot().current
|
||||
const disposeViews = slots.subscribe('conversation.view', refreshViews)
|
||||
const disposeLocale = ctx.locale.subscribe(refreshViews)
|
||||
const disposeCurrent = sessions.list.subscribe(() => {
|
||||
const nextSessionId = sessions.list.getSnapshot().current
|
||||
if (nextSessionId === currentSessionId) return
|
||||
currentSessionId = nextSessionId
|
||||
restoreCurrentView()
|
||||
})
|
||||
return () => {
|
||||
disposeCurrent()
|
||||
disposeLocale()
|
||||
disposeViews()
|
||||
}
|
||||
}, 'ui-conversation: View roster')
|
||||
}, 'ui-conversation: View selection')
|
||||
|
||||
const inputHub = new InputHub(ctx, t)
|
||||
const composerBlocks = new ComposerBlockRegistry()
|
||||
@@ -159,9 +182,11 @@ export function apply(ctx: Context): void {
|
||||
props: ['inputActions'],
|
||||
resolve: (binding) => {
|
||||
const shell = inputHub.shellFor(binding)
|
||||
const conversation = uiConversation.binding(binding)
|
||||
restoreView(binding.sessionId)
|
||||
return {
|
||||
hooks: {
|
||||
conversation: uiConversation.binding(binding).snapshot,
|
||||
conversation: conversation.snapshot,
|
||||
input: shell.state,
|
||||
},
|
||||
props: { inputActions: shell.actions },
|
||||
@@ -218,9 +243,13 @@ export function apply(ctx: Context): void {
|
||||
'conversation.view': { kind: 'list', scope: 'session' },
|
||||
},
|
||||
store: conversationStore,
|
||||
inject: (sessionId: SessionId, _actions: BoundActions<typeof conversationStore>): ConversationSessionInjected => ({
|
||||
inject: (sessionId: SessionId, actions: BoundActions<typeof conversationStore>): ConversationSessionInjected => ({
|
||||
hooks: { conversationViews },
|
||||
bindDraftMirror: write => inputHub.shell(sessionId).bindMirror(write),
|
||||
openView: (view, focus) => {
|
||||
activateView(sessionId, view)
|
||||
actions.openView(view, focus)
|
||||
},
|
||||
}),
|
||||
}, ConversationSession)
|
||||
|
||||
@@ -233,9 +262,13 @@ export function apply(ctx: Context): void {
|
||||
'conversation.session.header.utilities': { kind: 'list', scope: 'session' },
|
||||
},
|
||||
store: conversationStore,
|
||||
inject: (): ConversationSessionHeaderInjected => ({
|
||||
inject: (sessionId: SessionId, actions: BoundActions<typeof conversationStore>): ConversationSessionHeaderInjected => ({
|
||||
hooks: { conversationViews },
|
||||
open: (id) => { sessions.open(id) },
|
||||
selectView: (view) => {
|
||||
activateView(sessionId, view)
|
||||
actions.setView(view)
|
||||
},
|
||||
}),
|
||||
}, ConversationSessionHeader)
|
||||
|
||||
|
||||
@@ -253,7 +253,7 @@ export interface ConversationViewBuilder<Node extends ConversationViewNode = Con
|
||||
}): Snapshot
|
||||
}
|
||||
|
||||
/** Registry contribution that creates one isolated view builder per Session. */
|
||||
/** Registry contribution that creates an isolated builder when a Session first uses this target. */
|
||||
export interface ConversationViewDefinition<Node extends ConversationViewNode = ConversationViewNode, Snapshot = unknown> {
|
||||
readonly target: string
|
||||
/** @returns a new Session-owned incremental builder. */
|
||||
|
||||
@@ -226,6 +226,8 @@ export interface ConversationSessionInjected {
|
||||
readonly hooks: { readonly conversationViews: ObservableSnapshot<readonly ViewTab[]> }
|
||||
/** Bind input draft persistence to the Session-owned store instance. */
|
||||
bindDraftMirror: (write: (text: string) => void) => () => void
|
||||
/** Select and activate one View while addressing an opaque focus request to it. */
|
||||
openView: (view: string, focus: string) => void
|
||||
}
|
||||
|
||||
/** Business callbacks injected into the strict Session header. */
|
||||
@@ -234,6 +236,8 @@ export interface ConversationSessionHeaderInjected {
|
||||
readonly hooks: { readonly conversationViews: ObservableSnapshot<readonly ViewTab[]> }
|
||||
/** Select a Session through the Session Controller. */
|
||||
open: (sessionId: SessionId) => void
|
||||
/** Select and activate one registered Conversation View. */
|
||||
selectView: (view: string) => void
|
||||
}
|
||||
|
||||
/** Owner share of the resident composer bar. */
|
||||
|
||||
@@ -44,8 +44,9 @@ interface PendingMatch {
|
||||
|
||||
interface ViewState {
|
||||
readonly target: string
|
||||
readonly builder: ConversationViewBuilder
|
||||
readonly definition: ConversationViewDefinition
|
||||
readonly isActive: ((snapshot: unknown) => boolean) | undefined
|
||||
builder: ConversationViewBuilder | undefined
|
||||
snapshot: unknown
|
||||
}
|
||||
|
||||
@@ -158,12 +159,15 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
private readonly contexts = new Map<string, InternalContext>()
|
||||
private readonly contextsByKind = new Map<string, InternalContext[]>()
|
||||
private readonly contextsBySeq = new Map<number, Set<InternalContext>>()
|
||||
private readonly contextsByTarget = new Map<string, Set<InternalContext>>()
|
||||
private readonly inputs = new Map<number, SessionEventLikeEntry>()
|
||||
private readonly locationIndex = new ConversationLocationIndex()
|
||||
private readonly dirty = new Set<InternalContext>()
|
||||
private readonly dirtyByTarget = new Map<string, Set<InternalContext>>()
|
||||
private readonly revised = new Set<InternalContext>()
|
||||
private readonly dependents = new Map<string, Set<InternalContext>>()
|
||||
private readonly views = new Map<string, ViewState>()
|
||||
private readonly activeTargets = new Set<string>()
|
||||
private hasMore = false
|
||||
private replacePending = true
|
||||
private timelineDirty = true
|
||||
@@ -189,8 +193,10 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
this.contexts.clear()
|
||||
this.contextsByKind.clear()
|
||||
this.contextsBySeq.clear()
|
||||
this.contextsByTarget.clear()
|
||||
this.inputs.clear()
|
||||
this.dirty.clear()
|
||||
this.dirtyByTarget.clear()
|
||||
this.revised.clear()
|
||||
this.dependents.clear()
|
||||
this.hasMore = hasMore
|
||||
@@ -201,7 +207,7 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
for (const entry of sorted) this.matchInput(entry)
|
||||
this.replayDependencies()
|
||||
this.revised.clear()
|
||||
for (const context of this.contexts.values()) this.dirty.add(context)
|
||||
for (const context of this.contexts.values()) this.markDirty(context)
|
||||
this.replacePending = true
|
||||
return 'immediate'
|
||||
}
|
||||
@@ -278,68 +284,74 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
}
|
||||
|
||||
/**
|
||||
* Materialize dirty Contexts and advance every registered view builder.
|
||||
* Materialize dirty Contexts and advance every active view builder.
|
||||
* @returns whether any view snapshot was rebuilt or incrementally applied.
|
||||
*/
|
||||
flush(): boolean {
|
||||
if (!this.replacePending && this.dirty.size === 0 && !this.timelineDirty) return false
|
||||
if (this.replacePending) {
|
||||
this.replaceLocationData()
|
||||
const allByTarget = new Map<string, ConversationViewNode[]>()
|
||||
for (const target of this.views.keys()) allByTarget.set(target, [])
|
||||
for (const context of this.contexts.values()) {
|
||||
const target = context.definition.target
|
||||
if (target === undefined || !this.views.has(target)) continue
|
||||
const node = this.buildNode(context, target)
|
||||
context.current.set(target, node)
|
||||
if (node !== null) allByTarget.get(target)?.push(node)
|
||||
}
|
||||
for (const view of this.views.values()) {
|
||||
view.snapshot = view.builder.replace({
|
||||
nodes: allByTarget.get(view.target) ?? [],
|
||||
let published = false
|
||||
for (const target of this.activeTargets) {
|
||||
const view = this.views.get(target)
|
||||
if (view === undefined) continue
|
||||
const builder = view.builder ?? view.definition.create()
|
||||
view.builder = builder
|
||||
view.snapshot = builder.replace({
|
||||
nodes: this.buildTargetNodes(target, this.contextsByTarget.get(target)),
|
||||
timeline: this.locationIndex.snapshot(),
|
||||
})
|
||||
published = true
|
||||
}
|
||||
this.replacePending = false
|
||||
this.dirty.clear()
|
||||
this.dirtyByTarget.clear()
|
||||
this.timelineDirty = false
|
||||
return true
|
||||
return published
|
||||
}
|
||||
|
||||
const upsertsByTarget = new Map<string, ConversationViewNode[]>()
|
||||
for (const target of this.views.keys()) upsertsByTarget.set(target, [])
|
||||
let published = false
|
||||
if (this.applyDirtyLocationData()) this.timelineDirty = true
|
||||
for (const context of this.dirty) {
|
||||
const target = context.definition.target
|
||||
if (target === undefined || !this.views.has(target)) continue
|
||||
const previous = context.current.get(target) ?? null
|
||||
const node = this.buildNode(context, target)
|
||||
if (node === null && previous !== null) {
|
||||
throw new Error(
|
||||
`conversation Definition "${context.kind}" withdrew materialized target "${target}"; return the same key with hidden visibility instead`,
|
||||
)
|
||||
}
|
||||
context.current.set(target, node)
|
||||
if (node !== null) upsertsByTarget.get(target)?.push(node)
|
||||
}
|
||||
this.dirty.clear()
|
||||
const timelineDirty = this.timelineDirty
|
||||
this.timelineDirty = false
|
||||
for (const view of this.views.values()) {
|
||||
const upserts = upsertsByTarget.get(view.target) ?? []
|
||||
for (const target of this.activeTargets) {
|
||||
const view = this.views.get(target)
|
||||
if (view === undefined) continue
|
||||
const builder = view.builder
|
||||
if (builder === undefined) continue
|
||||
const upserts = this.buildTargetUpserts(target, this.dirtyByTarget.get(target))
|
||||
if (upserts.length === 0 && !timelineDirty) continue
|
||||
view.snapshot = view.builder.apply({
|
||||
view.snapshot = builder.apply({
|
||||
upserts,
|
||||
timeline: this.locationIndex.snapshot(),
|
||||
})
|
||||
published = true
|
||||
}
|
||||
this.dirty.clear()
|
||||
this.dirtyByTarget.clear()
|
||||
this.timelineDirty = false
|
||||
return published
|
||||
}
|
||||
|
||||
/**
|
||||
* Add one target to the monotonic active set and materialize its current snapshot.
|
||||
* Pending Context work is flushed before the first complete replacement.
|
||||
* @param target - registered or subsequently registered view target.
|
||||
* @returns whether any active target snapshot changed.
|
||||
*/
|
||||
activateTarget(target: string): boolean {
|
||||
const view = this.views.get(target)
|
||||
if (this.activeTargets.has(target)) return false
|
||||
const published = this.flush()
|
||||
this.activeTargets.add(target)
|
||||
if (view === undefined) return published
|
||||
this.replaceView(view)
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the latest snapshot of a registered target.
|
||||
* @param target - registered view target.
|
||||
* @returns target snapshot, or undefined when no builder is registered.
|
||||
* @returns target snapshot, or undefined before registration or activation.
|
||||
*/
|
||||
snapshot(target: string): unknown {
|
||||
return this.views.get(target)?.snapshot
|
||||
@@ -353,11 +365,13 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
|
||||
/**
|
||||
* Read targets whose owners classify their latest snapshot as visible activity.
|
||||
* @returns active target ids.
|
||||
* @returns target ids contributing visible activity.
|
||||
*/
|
||||
activeTargets(): ReadonlySet<string> {
|
||||
activityTargets(): ReadonlySet<string> {
|
||||
const active = new Set<string>()
|
||||
for (const view of this.views.values()) {
|
||||
for (const target of this.activeTargets) {
|
||||
const view = this.views.get(target)
|
||||
if (view === undefined) continue
|
||||
if (view.isActive?.(view.snapshot) === true) active.add(view.target)
|
||||
}
|
||||
return active
|
||||
@@ -419,6 +433,30 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
return publication
|
||||
}
|
||||
|
||||
private createContext(
|
||||
definition: ConversationNodeDefinition,
|
||||
id: string,
|
||||
key: string,
|
||||
): InternalContext {
|
||||
const context: InternalContext = {
|
||||
key,
|
||||
kind: definition.kind,
|
||||
id,
|
||||
definition,
|
||||
startSeq: undefined,
|
||||
start: undefined,
|
||||
matches: [],
|
||||
state: undefined,
|
||||
revision: 0,
|
||||
current: new Map(),
|
||||
locationData: emptyLocationData(),
|
||||
dependencies: new Map(),
|
||||
}
|
||||
this.contexts.set(key, context)
|
||||
this.indexTargetContext(context)
|
||||
return context
|
||||
}
|
||||
|
||||
private acceptMatch(
|
||||
definition: ConversationNodeDefinition,
|
||||
id: string,
|
||||
@@ -430,23 +468,7 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
if (role === 'start' && context?.start !== undefined) {
|
||||
throw new Error(`conversation Context ${key} received more than one start Match`)
|
||||
}
|
||||
if (context === undefined) {
|
||||
context = {
|
||||
key,
|
||||
kind: definition.kind,
|
||||
id,
|
||||
definition,
|
||||
startSeq: undefined,
|
||||
start: undefined,
|
||||
matches: [],
|
||||
state: undefined,
|
||||
revision: 0,
|
||||
current: new Map(),
|
||||
locationData: emptyLocationData(),
|
||||
dependencies: new Map(),
|
||||
}
|
||||
this.contexts.set(key, context)
|
||||
}
|
||||
context ??= this.createContext(definition, id, key)
|
||||
const match = conversationMatch(
|
||||
key,
|
||||
input,
|
||||
@@ -478,7 +500,7 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
context.revision++
|
||||
this.revised.add(context)
|
||||
}
|
||||
this.dirty.add(context)
|
||||
this.markDirty(context)
|
||||
return definition.publication?.(match) ?? 'immediate'
|
||||
}
|
||||
|
||||
@@ -491,23 +513,7 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
const first = entries[0]
|
||||
if (first === undefined) continue
|
||||
let context = this.contexts.get(key)
|
||||
if (context === undefined) {
|
||||
context = {
|
||||
key,
|
||||
kind: first.definition.kind,
|
||||
id: first.id,
|
||||
definition: first.definition,
|
||||
startSeq: undefined,
|
||||
start: undefined,
|
||||
matches: [],
|
||||
state: undefined,
|
||||
revision: 0,
|
||||
current: new Map(),
|
||||
locationData: emptyLocationData(),
|
||||
dependencies: new Map(),
|
||||
}
|
||||
this.contexts.set(key, context)
|
||||
}
|
||||
context ??= this.createContext(first.definition, first.id, key)
|
||||
let discoveredStart: ConversationStartMatch | undefined
|
||||
const additions = entries
|
||||
.map((entry) => {
|
||||
@@ -538,7 +544,7 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
throw new Error(`conversation Context ${context.key} received an update before its start Match`)
|
||||
}
|
||||
affected.add(context)
|
||||
this.dirty.add(context)
|
||||
this.markDirty(context)
|
||||
}
|
||||
for (const [kind, contexts] of startsByKind) this.indexStartedContexts(kind, contexts)
|
||||
}
|
||||
@@ -549,7 +555,7 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
for (const context of ordered) {
|
||||
if (context.start === undefined) {
|
||||
context.state = undefined
|
||||
this.dirty.add(context)
|
||||
this.markDirty(context)
|
||||
continue
|
||||
}
|
||||
this.replayContext(context)
|
||||
@@ -586,7 +592,24 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
}
|
||||
context.revision++
|
||||
this.revised.add(context)
|
||||
this.markDirty(context)
|
||||
}
|
||||
|
||||
private indexTargetContext(context: InternalContext): void {
|
||||
const target = context.definition.target
|
||||
if (target === undefined) return
|
||||
const contexts = this.contextsByTarget.get(target) ?? new Set<InternalContext>()
|
||||
contexts.add(context)
|
||||
this.contextsByTarget.set(target, contexts)
|
||||
}
|
||||
|
||||
private markDirty(context: InternalContext): void {
|
||||
this.dirty.add(context)
|
||||
const target = context.definition.target
|
||||
if (target === undefined || !this.activeTargets.has(target)) return
|
||||
const contexts = this.dirtyByTarget.get(target) ?? new Set<InternalContext>()
|
||||
contexts.add(context)
|
||||
this.dirtyByTarget.set(target, contexts)
|
||||
}
|
||||
|
||||
private replaceDependencies(context: InternalContext, dependencies: Map<string, Dependency>): void {
|
||||
@@ -759,6 +782,47 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
return node
|
||||
}
|
||||
|
||||
private replaceView(view: ViewState): void {
|
||||
const builder = view.builder ?? view.definition.create()
|
||||
view.builder = builder
|
||||
view.snapshot = builder.replace({
|
||||
nodes: this.buildTargetNodes(view.target, this.contextsByTarget.get(view.target)),
|
||||
timeline: this.locationIndex.snapshot(),
|
||||
})
|
||||
}
|
||||
|
||||
private buildTargetNodes(
|
||||
target: string,
|
||||
contexts: Iterable<InternalContext> | undefined,
|
||||
): ConversationViewNode[] {
|
||||
const nodes: ConversationViewNode[] = []
|
||||
for (const context of contexts ?? []) {
|
||||
const node = this.buildNode(context, target)
|
||||
context.current.set(target, node)
|
||||
if (node !== null) nodes.push(node)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
private buildTargetUpserts(
|
||||
target: string,
|
||||
contexts: Iterable<InternalContext> | undefined,
|
||||
): ConversationViewNode[] {
|
||||
const upserts: ConversationViewNode[] = []
|
||||
for (const context of contexts ?? []) {
|
||||
const previous = context.current.get(target) ?? null
|
||||
const node = this.buildNode(context, target)
|
||||
if (node === null && previous !== null) {
|
||||
throw new Error(
|
||||
`conversation Definition "${context.kind}" withdrew materialized target "${target}"; return the same key with hidden visibility instead`,
|
||||
)
|
||||
}
|
||||
context.current.set(target, node)
|
||||
if (node !== null) upserts.push(node)
|
||||
}
|
||||
return upserts
|
||||
}
|
||||
|
||||
private buildLocationData(
|
||||
context: InternalContext,
|
||||
scope: ConversationLocationDataScope,
|
||||
@@ -817,15 +881,16 @@ export class ConversationNodeAssembler implements ConversationViewSnapshotStore
|
||||
private resetViewBuilders(): void {
|
||||
this.views.clear()
|
||||
for (const definition of this.viewDefinitions.entries()) {
|
||||
const builder = definition.create()
|
||||
this.views.set(definition.target, {
|
||||
const view: ViewState = {
|
||||
target: definition.target,
|
||||
builder,
|
||||
definition,
|
||||
isActive: definition.isActive === undefined
|
||||
? undefined
|
||||
: snapshot => definition.isActive?.(snapshot) === true,
|
||||
snapshot: builder.empty,
|
||||
})
|
||||
builder: undefined,
|
||||
snapshot: undefined,
|
||||
}
|
||||
this.views.set(definition.target, view)
|
||||
}
|
||||
this.replacePending = true
|
||||
}
|
||||
|
||||
@@ -23,8 +23,15 @@ import { ConversationViewRegistry } from './view-registry.ts'
|
||||
/** Observable faces published for one Session's Conversation assembly. */
|
||||
export interface ConversationBinding {
|
||||
readonly snapshot: ObservableSnapshot<ConversationSnapshot>
|
||||
/**
|
||||
* Add one selected target to the Session's monotonic active set.
|
||||
* @param target - registered or subsequently registered Conversation target.
|
||||
*/
|
||||
activate(target: string): void
|
||||
/**
|
||||
* Resolve one target-owned snapshot source.
|
||||
* The first subscriber activates the target unless shell selection already
|
||||
* activated it; activation lasts for the remaining Session lifetime.
|
||||
* @param target - registered Conversation target.
|
||||
* @returns identity-stable source following the target.
|
||||
*/
|
||||
@@ -61,13 +68,21 @@ class BoundConversation implements ConversationBinding {
|
||||
const views = this.viewStore as unknown as { get(key: string): unknown }
|
||||
source = {
|
||||
getSnapshot: () => views.get(target),
|
||||
subscribe: (listener) => { return this.snapshot.subscribe(listener) },
|
||||
subscribe: (listener) => {
|
||||
const unsubscribe = this.snapshot.subscribe(listener)
|
||||
this.activate(target)
|
||||
return unsubscribe
|
||||
},
|
||||
}
|
||||
this.targetSources.set(target, source)
|
||||
}
|
||||
return source as ObservableSnapshot<ConversationViewSnapshotMap[Target] | undefined>
|
||||
}
|
||||
|
||||
activate(target: string): void {
|
||||
if (this.assembler.activateTarget(target)) this.snapshot.set(this.currentSnapshot())
|
||||
}
|
||||
|
||||
rebuild(): void { this.publish(this.assembler.rebuildRegistry()) }
|
||||
|
||||
dispose(): void {
|
||||
@@ -125,7 +140,7 @@ class BoundConversation implements ConversationBinding {
|
||||
private currentSnapshot(): ConversationSnapshot {
|
||||
return {
|
||||
views: this.viewStore,
|
||||
activeTargets: this.assembler.activeTargets(),
|
||||
activeTargets: this.assembler.activityTargets(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
ConversationSessionHeaderSlotProps, ConversationSessionSlotProps,
|
||||
} from '../contract/slots.ts'
|
||||
import { conversationPhase } from '../contract/snapshot.ts'
|
||||
import type { ViewTab } from '../contract/views.ts'
|
||||
import { resolveActiveView } from '../view-selection.ts'
|
||||
import css from './ConversationRoot.module.css'
|
||||
|
||||
/** Full props composed from the strict session body contract. */
|
||||
@@ -23,14 +23,6 @@ interface Breadcrumb {
|
||||
readonly subagent: boolean
|
||||
}
|
||||
|
||||
const DEFAULT_VIEW_ID = 'chat'
|
||||
|
||||
/** Resolve a persisted selection, then registered Chat, without choosing another View. */
|
||||
function resolveActiveView(tabs: readonly ViewTab[], selectedId: string | null): ViewTab | undefined {
|
||||
const selected = selectedId === null ? undefined : tabs.find(view => view.id === selectedId)
|
||||
return selected ?? tabs.find(view => view.id === DEFAULT_VIEW_ID)
|
||||
}
|
||||
|
||||
function deriveAncestry(list: SessionListState, id: SessionId): readonly Breadcrumb[] {
|
||||
const chain: Breadcrumb[] = []
|
||||
const seen = new Set<SessionId>()
|
||||
@@ -65,8 +57,8 @@ function equalBreadcrumbs(left: readonly Breadcrumb[], right: readonly Breadcrum
|
||||
* @returns the hidden blank-session header or visible title and tabs.
|
||||
*/
|
||||
export function ConversationSessionHeader({
|
||||
sessionId, useSession, useSessions, useConversation, useConversationViews, useStore, actions,
|
||||
renderSlot, open, t,
|
||||
sessionId, useSession, useSessions, useConversation, useConversationViews, useStore,
|
||||
renderSlot, open, selectView, t,
|
||||
}: ConversationSessionHeaderProps) {
|
||||
const tabs = useConversationViews(value => value)
|
||||
const selectedId = useStore(s => s.view)
|
||||
@@ -151,7 +143,7 @@ export function ConversationSessionHeader({
|
||||
role="tab"
|
||||
aria-selected={viewTab.id === active?.id}
|
||||
className={clsx(css.tab, viewTab.id === active?.id && css.tabActive)}
|
||||
onClick={() => { actions.setView(viewTab.id) }}
|
||||
onClick={() => { selectView(viewTab.id) }}
|
||||
>
|
||||
{viewTab.label}
|
||||
</button>
|
||||
@@ -172,7 +164,7 @@ export function ConversationSessionHeader({
|
||||
*/
|
||||
export function ConversationSession({
|
||||
useSession, useConversation, useConversationViews, useInput, inputActions, useStore, actions,
|
||||
renderSlot, bindDraftMirror,
|
||||
renderSlot, bindDraftMirror, openView,
|
||||
}: ConversationSessionProps) {
|
||||
const tabs = useConversationViews(value => value)
|
||||
const selectedId = useStore(s => s.view)
|
||||
@@ -196,7 +188,7 @@ export function ConversationSession({
|
||||
<div className={css.viewArea}>
|
||||
{active !== undefined && renderSlot('conversation.view', {
|
||||
viewRequest,
|
||||
openView: actions.openView,
|
||||
openView,
|
||||
completeViewRequest: actions.completeViewRequest,
|
||||
}, { only: active.id })}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
/** Per-session Conversation store shared by the shell body and header. */
|
||||
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ConversationStoreState } from './contract/views.ts'
|
||||
|
||||
const CONVERSATION_STORE_KEY = 'dsh.conversation'
|
||||
|
||||
/** Declared write set for the Conversation shell. */
|
||||
type ConversationActions = {
|
||||
setDraft: (draft: ConversationStoreState, text: string) => void
|
||||
@@ -17,7 +20,7 @@ type ConversationActions = {
|
||||
export function createConversationStore(): EngineStoreHandle<ConversationStoreState, ConversationActions> {
|
||||
return defineStore({
|
||||
init: (): ConversationStoreState => ({ draft: '', view: null, viewRequest: null }),
|
||||
persist: 'dsh.conversation',
|
||||
persist: CONVERSATION_STORE_KEY,
|
||||
actions: {
|
||||
setDraft: (d, text: string) => { d.draft = text },
|
||||
setView: (d, view: string) => { d.view = view },
|
||||
@@ -29,3 +32,21 @@ export function createConversationStore(): EngineStoreHandle<ConversationStoreSt
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the persisted View preference before the Slot store is materialized.
|
||||
* @param sessionId - Session-scoped persistence suffix.
|
||||
* @returns the preferred View id, or null when storage has no usable value.
|
||||
*/
|
||||
export function readConversationViewPreference(sessionId: SessionId): string | null {
|
||||
if (typeof localStorage === 'undefined') return null
|
||||
try {
|
||||
const raw = localStorage.getItem(`${CONVERSATION_STORE_KEY}.${sessionId}`)
|
||||
if (raw === null) return null
|
||||
const stored: unknown = JSON.parse(raw)
|
||||
if (typeof stored !== 'object' || stored === null || !('view' in stored)) return null
|
||||
return typeof stored.view === 'string' ? stored.view : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ViewTab } from './contract/views.ts'
|
||||
|
||||
const DEFAULT_VIEW_ID = 'chat'
|
||||
|
||||
/**
|
||||
* Resolve a preferred registered View, then Chat, without choosing another View.
|
||||
* @param tabs - currently registered Views.
|
||||
* @param selectedId - preferred View identity, when one is stored.
|
||||
* @returns the selected View, Chat fallback, or undefined when neither is registered.
|
||||
*/
|
||||
export function resolveActiveView(
|
||||
tabs: readonly ViewTab[],
|
||||
selectedId: string | null,
|
||||
): ViewTab | undefined {
|
||||
const selected = selectedId === null ? undefined : tabs.find(view => view.id === selectedId)
|
||||
return selected ?? tabs.find(view => view.id === DEFAULT_VIEW_ID)
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import type { SessionBehaviorOverrides } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import {
|
||||
apply, inject, type ComposerBarInjected, type ConversationInjected,
|
||||
type ConversationSessionInjected, type ViewTab,
|
||||
type ConversationSessionHeaderInjected, type ConversationSessionInjected, type ViewTab,
|
||||
} from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types'
|
||||
@@ -51,7 +51,7 @@ async function bench() {
|
||||
|
||||
const feature = await runtime.mount({ inject: [...inject], apply })
|
||||
runtime.renderRoot()
|
||||
const entryOf = (key: 'conversation' | 'conversation.session' | 'conversation.composer.bar') =>
|
||||
const entryOf = (key: 'conversation' | 'conversation.session' | 'conversation.session.header' | 'conversation.composer.bar') =>
|
||||
runtime.slots.entries(key)[0]!
|
||||
const conversationApi = (id: SessionId) => {
|
||||
const entry = entryOf('conversation.session')
|
||||
@@ -66,6 +66,15 @@ async function bench() {
|
||||
const entry = entryOf('conversation')
|
||||
return (entry.inject as unknown as (sessionId: SessionId | undefined) => ConversationInjected)(id)
|
||||
}
|
||||
const headerApi = (id: SessionId) => {
|
||||
const entry = entryOf('conversation.session.header')
|
||||
const instance = runtime.storeOf('conversation.session.header', id) as ConversationInstance
|
||||
const injected = (entry.inject as unknown as (
|
||||
sessionId: SessionId,
|
||||
actions: ConversationActions,
|
||||
) => ConversationSessionHeaderInjected)(id, instance.actions)
|
||||
return { instance, injected }
|
||||
}
|
||||
const composerApi = (id: SessionId | undefined) => {
|
||||
const entry = entryOf('conversation.composer.bar')
|
||||
return (entry.inject as unknown as (sessionId: SessionId | undefined) => ComposerBarInjected)(id)
|
||||
@@ -77,7 +86,7 @@ async function bench() {
|
||||
const viewSource = (id: SessionId): ObservableSnapshot<readonly ViewTab[]> =>
|
||||
conversationApi(id).injected.hooks.conversationViews
|
||||
return {
|
||||
runtime, feature, slots: runtime.slots, entryOf, conversationApi, residentApi, composerApi,
|
||||
runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi,
|
||||
inputApi, viewSource, sessionFake, connectWorkspace,
|
||||
}
|
||||
}
|
||||
@@ -87,11 +96,79 @@ describe('Conversation inject API', () => {
|
||||
const b = await bench()
|
||||
const { injected } = b.conversationApi(ROOT)
|
||||
expect(b.sessionFake.loadOlder).not.toHaveBeenCalled()
|
||||
expect(Object.keys(injected)).toEqual(['hooks', 'bindDraftMirror'])
|
||||
expect(Object.keys(injected)).toEqual(['hooks', 'bindDraftMirror', 'openView'])
|
||||
expect(b.viewSource(ROOT).getSnapshot()).toEqual([])
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('activates a target before committing an explicit View selection', async () => {
|
||||
const b = await bench()
|
||||
const binding = b.runtime.ctx.uiConversation.binding(ROOT)
|
||||
const activate = vi.spyOn(binding, 'activate')
|
||||
const removeChat = b.slots.register(
|
||||
{ name: 'conversation.view', id: 'chat', order: 0 },
|
||||
(() => null) as never,
|
||||
)
|
||||
const removeTrajectory = b.slots.register(
|
||||
{ name: 'conversation.view', id: 'trajectory', order: 10 },
|
||||
(() => null) as never,
|
||||
)
|
||||
await Promise.resolve()
|
||||
activate.mockClear()
|
||||
|
||||
const body = b.conversationApi(ROOT)
|
||||
body.injected.openView('trajectory', 'call-1')
|
||||
expect(activate).toHaveBeenLastCalledWith('trajectory')
|
||||
expect(body.instance.store.getSnapshot()).toMatchObject({
|
||||
view: 'trajectory',
|
||||
viewRequest: { view: 'trajectory', focus: 'call-1' },
|
||||
})
|
||||
|
||||
const header = b.headerApi(ROOT)
|
||||
header.injected.selectView('chat')
|
||||
expect(activate).toHaveBeenLastCalledWith('chat')
|
||||
expect(header.instance.store.getSnapshot().view).toBe('chat')
|
||||
|
||||
removeTrajectory()
|
||||
removeChat()
|
||||
await b.runtime.dispose()
|
||||
})
|
||||
|
||||
it('restores the selected View when a cached Session becomes current', async () => {
|
||||
const b = await bench()
|
||||
const binding = b.runtime.ctx.uiConversation.binding(ROOT)
|
||||
const activate = vi.spyOn(binding, 'activate')
|
||||
const removeChat = b.slots.register(
|
||||
{ name: 'conversation.view', id: 'chat', order: 0 },
|
||||
(() => null) as never,
|
||||
)
|
||||
let removeCustom: (() => void) | undefined
|
||||
try {
|
||||
await b.runtime.flush()
|
||||
localStorage.setItem(`dsh.conversation.${ROOT}`, JSON.stringify({
|
||||
draft: '', view: 'custom', viewRequest: null,
|
||||
}))
|
||||
|
||||
b.runtime.ctx.uiSession.adapter.resolve(ROOT)
|
||||
expect(activate).toHaveBeenLastCalledWith('chat')
|
||||
activate.mockClear()
|
||||
|
||||
removeCustom = b.slots.register(
|
||||
{ name: 'conversation.view', id: 'custom', order: 10 },
|
||||
(() => null) as never,
|
||||
)
|
||||
await b.runtime.flush()
|
||||
expect(activate).not.toHaveBeenCalled()
|
||||
|
||||
await b.runtime.sessions.setCurrent(ROOT)
|
||||
expect(activate).toHaveBeenLastCalledWith('custom')
|
||||
} finally {
|
||||
removeCustom?.()
|
||||
removeChat()
|
||||
await b.runtime.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('submits through the provided input machine and mirrors accepted draft edits', async () => {
|
||||
const b = await bench()
|
||||
const { injected } = b.conversationApi(ROOT)
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
import type { ChunkRowEvent } from '@deepseek-ai/dsh-api-session-controller/types'
|
||||
import type { ChunkRow } from '@deepseek-ai/dsh-session/chunk-rows'
|
||||
import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
|
||||
import { ConversationNodeAssembler } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import { ConversationNodeAssembler as RuntimeConversationNodeAssembler } from '@deepseek-ai/dsh-client-ui-conversation/client'
|
||||
import type {
|
||||
ConversationMatch, ConversationNodeContext,
|
||||
ConversationNodeDefinition, ConversationViewDefinition, ConversationViewNode,
|
||||
@@ -63,6 +63,13 @@ class TestViewDefinitions {
|
||||
}
|
||||
}
|
||||
|
||||
class ConversationNodeAssembler extends RuntimeConversationNodeAssembler {
|
||||
constructor(events: TestEventDefinitions, views: TestViewDefinitions) {
|
||||
super(events, views)
|
||||
for (const view of views.entries()) this.activateTarget(view.target)
|
||||
}
|
||||
}
|
||||
|
||||
function testView(
|
||||
apply = vi.fn(),
|
||||
): ConversationViewDefinition<ConversationViewNode, TestSnapshot> {
|
||||
@@ -92,6 +99,21 @@ function testView(
|
||||
}
|
||||
}
|
||||
|
||||
function trackedView(target: string) {
|
||||
const replace = vi.fn(({ nodes }: { readonly nodes: readonly ConversationViewNode[] }) => nodes)
|
||||
const apply = vi.fn(({ upserts }: { readonly upserts: readonly ConversationViewNode[] }) => upserts)
|
||||
const create = vi.fn(() => ({
|
||||
empty: [] as readonly ConversationViewNode[],
|
||||
replace,
|
||||
apply,
|
||||
}))
|
||||
const definition: ConversationViewDefinition<ConversationViewNode, readonly ConversationViewNode[]> = {
|
||||
target,
|
||||
create,
|
||||
}
|
||||
return { definition, create, replace, apply }
|
||||
}
|
||||
|
||||
function at(seq: number, type: string, data: unknown): SessionEvent {
|
||||
return { seq, time: 1_700_000_000_000 + seq, type, data } as SessionEvent
|
||||
}
|
||||
@@ -139,6 +161,89 @@ function fallbackDefinition(start: () => string): ConversationNodeDefinition<str
|
||||
}
|
||||
|
||||
describe('ConversationNodeAssembler', () => {
|
||||
it('reports a replacement only when an active target has a registered builder', () => {
|
||||
const assembler = new RuntimeConversationNodeAssembler(
|
||||
new TestEventDefinitions([]),
|
||||
new TestViewDefinitions([]),
|
||||
)
|
||||
|
||||
expect(assembler.activateTarget('registered-later')).toBe(false)
|
||||
assembler.replaceWindow([], false)
|
||||
|
||||
expect(assembler.flush()).toBe(false)
|
||||
})
|
||||
|
||||
it('updates only active targets and never deactivates one after first use', () => {
|
||||
type State = { readonly updates: number }
|
||||
const definition = (
|
||||
target: string,
|
||||
buildViewNode: NonNullable<ConversationNodeDefinition<State>['buildViewNode']>,
|
||||
): ConversationNodeDefinition<State> => ({
|
||||
kind: `active-${target}`,
|
||||
target,
|
||||
match: (event) => {
|
||||
const type = event.type as string
|
||||
if (type === 'active/start') return { id: 'one', role: 'start' }
|
||||
if (type === 'active/update') return { id: 'one', role: 'update' }
|
||||
return null
|
||||
},
|
||||
start: () => ({ updates: 0 }),
|
||||
update: context => ({ updates: context.state.updates + 1 }),
|
||||
buildViewNode,
|
||||
})
|
||||
const chat = trackedView('chat')
|
||||
const trajectory = trackedView('trajectory')
|
||||
const build = (target: string) => vi.fn((context: ConversationNodeContext<State>): ConversationViewNode => ({
|
||||
key: context.key,
|
||||
kind: context.kind,
|
||||
id: context.id,
|
||||
target,
|
||||
data: context.state,
|
||||
}))
|
||||
const buildChat = build('chat')
|
||||
const buildTrajectory = build('trajectory')
|
||||
const assembler = new RuntimeConversationNodeAssembler(
|
||||
new TestEventDefinitions([
|
||||
definition('chat', buildChat),
|
||||
definition('trajectory', buildTrajectory),
|
||||
]),
|
||||
new TestViewDefinitions([chat.definition, trajectory.definition]),
|
||||
)
|
||||
|
||||
assembler.replaceWindow([input(at(1, 'active/start', {}))], false)
|
||||
expect(assembler.flush()).toBe(false)
|
||||
expect(chat.create).not.toHaveBeenCalled()
|
||||
expect(trajectory.create).not.toHaveBeenCalled()
|
||||
expect(buildChat).not.toHaveBeenCalled()
|
||||
expect(buildTrajectory).not.toHaveBeenCalled()
|
||||
|
||||
expect(assembler.activateTarget('chat')).toBe(true)
|
||||
expect(chat.replace).toHaveBeenCalledOnce()
|
||||
expect(trajectory.replace).not.toHaveBeenCalled()
|
||||
expect(buildChat).toHaveBeenCalledOnce()
|
||||
expect(buildTrajectory).not.toHaveBeenCalled()
|
||||
|
||||
assembler.append(input(at(2, 'active/update', {})))
|
||||
expect(assembler.flush()).toBe(true)
|
||||
expect(chat.apply).toHaveBeenCalledOnce()
|
||||
expect(trajectory.apply).not.toHaveBeenCalled()
|
||||
expect(buildTrajectory).not.toHaveBeenCalled()
|
||||
|
||||
expect(assembler.activateTarget('trajectory')).toBe(true)
|
||||
expect(trajectory.replace).toHaveBeenCalledOnce()
|
||||
expect((assembler.snapshot('trajectory') as readonly ConversationViewNode[])
|
||||
.map(node => node.data)).toEqual([{ updates: 1 }])
|
||||
|
||||
assembler.append(input(at(3, 'active/update', {})))
|
||||
expect(assembler.flush()).toBe(true)
|
||||
expect(chat.apply).toHaveBeenCalledTimes(2)
|
||||
expect(trajectory.apply).toHaveBeenCalledOnce()
|
||||
expect(assembler.activateTarget('chat')).toBe(false)
|
||||
expect(assembler.activateTarget('trajectory')).toBe(false)
|
||||
expect(chat.replace).toHaveBeenCalledOnce()
|
||||
expect(trajectory.replace).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('appends through an exact business-id Context without replaying unrelated Contexts', () => {
|
||||
const starts = vi.fn((
|
||||
_context: ConversationNodeContext<{ callSeq: number; results: number }>,
|
||||
|
||||
@@ -245,4 +245,40 @@ describe('Conversation registries', () => {
|
||||
expect(rebuild).toHaveBeenCalledTimes(2)
|
||||
rebuild.mockRestore()
|
||||
})
|
||||
|
||||
it('activates each target on explicit selection or first use and never deactivates it', async () => {
|
||||
const { uiConversation, binding, views } = await bootRegistries()
|
||||
const chat = viewDefinition('chat')
|
||||
const trajectory = viewDefinition('trajectory')
|
||||
const createChat = vi.spyOn(chat, 'create')
|
||||
const createTrajectory = vi.spyOn(trajectory, 'create')
|
||||
views.register(chat)
|
||||
const disposeTrajectory = views.register(trajectory)
|
||||
await Promise.resolve()
|
||||
|
||||
const conversation = uiConversation.binding(binding)
|
||||
const chatSource = conversation.target('chat')
|
||||
const trajectorySource = conversation.target('trajectory')
|
||||
expect(createChat).not.toHaveBeenCalled()
|
||||
expect(createTrajectory).not.toHaveBeenCalled()
|
||||
|
||||
conversation.activate('chat')
|
||||
expect(createChat).toHaveBeenCalledOnce()
|
||||
|
||||
const unsubscribeChat = chatSource.subscribe(vi.fn())
|
||||
const trajectoryListener = vi.fn()
|
||||
const unsubscribeTrajectory = trajectorySource.subscribe(trajectoryListener)
|
||||
unsubscribeChat()
|
||||
const unsubscribeTrajectoryAgain = trajectorySource.subscribe(vi.fn())
|
||||
unsubscribeTrajectoryAgain()
|
||||
expect(createChat).toHaveBeenCalledOnce()
|
||||
expect(createTrajectory).toHaveBeenCalledOnce()
|
||||
expect(trajectoryListener).toHaveBeenCalledOnce()
|
||||
|
||||
disposeTrajectory()
|
||||
await Promise.resolve()
|
||||
expect(trajectorySource.getSnapshot()).toBeUndefined()
|
||||
expect(trajectoryListener).toHaveBeenCalledTimes(2)
|
||||
unsubscribeTrajectory()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { createConversationStore } from '../src/client/stores.ts'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { createConversationStore, readConversationViewPreference } from '../src/client/stores.ts'
|
||||
|
||||
const KEY = 'dsh.conversation'
|
||||
|
||||
@@ -54,4 +55,14 @@ describe('createConversationStore', () => {
|
||||
first.actions.setDraft('only first')
|
||||
expect(second.store.getSnapshot().draft).toBe('')
|
||||
})
|
||||
|
||||
it('reads only a usable persisted View preference', () => {
|
||||
const sessionId = 'sess-1' as SessionId
|
||||
const store = createConversationStore().create(sessionId)
|
||||
store.actions.setView('trajectory')
|
||||
expect(readConversationViewPreference(sessionId)).toBe('trajectory')
|
||||
|
||||
localStorage.setItem(`${KEY}.${sessionId}`, '{invalid')
|
||||
expect(readConversationViewPreference(sessionId)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -441,7 +441,8 @@ function assemble(entries: readonly SessionEventLikeEntry[]): FoldSnapshots {
|
||||
{ entries: () => [viewDefinition('chat'), viewDefinition('trajectory')] },
|
||||
)
|
||||
assembler.replaceWindow(entries, false)
|
||||
assembler.flush()
|
||||
assembler.activateTarget('chat')
|
||||
assembler.activateTarget('trajectory')
|
||||
return {
|
||||
chat: assembler.snapshot('chat'),
|
||||
trajectory: assembler.snapshot('trajectory'),
|
||||
|
||||
@@ -203,6 +203,7 @@ function mount(
|
||||
actions={store.actions}
|
||||
renderSlot={renderSlot as never}
|
||||
open={open}
|
||||
selectView={(view) => { store.actions.setView(view) }}
|
||||
t={t}
|
||||
/>
|
||||
)
|
||||
@@ -227,6 +228,7 @@ function mount(
|
||||
actions={store.actions}
|
||||
renderSlot={renderSlot as never}
|
||||
bindDraftMirror={write => wiring.bindMirror(write)}
|
||||
openView={(view, focus) => { store.actions.openView(view, focus) }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -433,8 +435,7 @@ describe('ConversationRoot resident composer', () => {
|
||||
{ ...workspace('second'), title: 'Selected Folder' },
|
||||
],
|
||||
)
|
||||
// Hero chrome present, view ring absent; scroll host already wraps the
|
||||
// resident composer so the blank → active flip does not remount it.
|
||||
// Hero chrome is present and the selected View slot remains absent.
|
||||
const host = b.view.container.querySelector('[data-conversation-scroll]')
|
||||
const header = b.view.container.querySelector('header')
|
||||
expect(host).not.toBeNull()
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveActiveView } from '../src/client/view-selection.ts'
|
||||
import type { ViewTab } from '../src/client/contract/views.ts'
|
||||
|
||||
describe('resolveActiveView', () => {
|
||||
it('resolves the preferred registered View and Chat fallback', () => {
|
||||
const tabs: readonly ViewTab[] = [
|
||||
{ id: 'chat', label: 'Chat' },
|
||||
{ id: 'custom', label: 'Custom' },
|
||||
]
|
||||
|
||||
expect(resolveActiveView(tabs, 'custom')?.id).toBe('custom')
|
||||
expect(resolveActiveView(tabs, 'removed')?.id).toBe('chat')
|
||||
expect(resolveActiveView(tabs, null)?.id).toBe('chat')
|
||||
})
|
||||
|
||||
it('does not choose an arbitrary registered View', () => {
|
||||
expect(resolveActiveView([{ id: 'custom', label: 'Custom' }], null)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -165,7 +165,7 @@ function result(seq: number, callId: string, isError = false, turn = 1): Session
|
||||
function assembler(entries: readonly SessionLiveEventEntry[], hasMore = false): ConversationNodeAssembler {
|
||||
const value = new ConversationNodeAssembler(new TestEventDefinitions(), new TestViewDefinitions())
|
||||
value.replaceWindow(entries, hasMore)
|
||||
value.flush()
|
||||
value.activateTarget('test')
|
||||
return value
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ function entry(seq: number, type: string, data: unknown): SessionLiveEventEntry
|
||||
function snapshot(entries: readonly SessionLiveEventEntry[], hasMore = false): ChatSnapshot {
|
||||
const assembler = new ConversationNodeAssembler(new TestEventDefinitions(), new TestViewDefinitions())
|
||||
assembler.replaceWindow(entries, hasMore)
|
||||
assembler.flush()
|
||||
assembler.activateTarget('chat')
|
||||
const value = assembler.snapshot('chat') as ChatSnapshot | undefined
|
||||
if (value === undefined) throw new Error('chat view was not registered')
|
||||
return value
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-tool/README.md
|
||||
README.md: 773a93801ebc214e2d5c94d52864f5c5dd887100
|
||||
README.zh.md: 88df08d7b5b7d5d3978d90fd4df4cbbb2efeb1fa
|
||||
README.md: 895274748d8ee5b7bece16e5b76836966cc52663
|
||||
README.zh.md: f4cf11cabdb94f45c9b11e7f7538ad5042a791e6
|
||||
@@ -61,7 +61,7 @@ The package realizes one dispatch rule: atomic Tool views are keyed by wire Tool
|
||||
|
||||
### Details and cards
|
||||
|
||||
The package fills `conversation.details.tool` with `ToolDetails`. Row and Details renderers share one pure card model for each terminal, read, diff, search, and web card. These models validate raw call arguments, result content, failure state, persisted metadata, Code Dispatch `parentCallId`, and Session path facts. Unsupported or malformed inputs use flattened Tool result text. Card-specific limits and fallback rules remain in the owning [terminal](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md), [diff](../../../.agents/notes/implemented/feature/2026-07-30-web-diff-card.md), [read](../../../.agents/notes/implemented/feature/2026-07-30-web-read-card-frontend.md), [search](../../../.agents/notes/implemented/feature/2026-07-30-web-search-card.md), [web](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md), and [question](../../../.agents/notes/implemented/feature/2026-07-29-ask-question-web-presentation.md) notes.
|
||||
The package fills `conversation.details.tool` with `ToolDetails`. Row and Details renderers share one pure card model for each terminal, read, diff, search, and web card. These models validate raw call arguments, result content, failure state, persisted metadata, Code Dispatch `parentCallId`, and Session path facts. Generic rows retain the original `argsRaw` reference and format their input body only while it is expanded; structured cards skip generic-body formatting. Unsupported or malformed inputs use flattened Tool result text. Card-specific limits and fallback rules remain in the owning [terminal](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md), [diff](../../../.agents/notes/implemented/feature/2026-07-30-web-diff-card.md), [read](../../../.agents/notes/implemented/feature/2026-07-30-web-read-card-frontend.md), [search](../../../.agents/notes/implemented/feature/2026-07-30-web-search-card.md), [web](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.md), and [question](../../../.agents/notes/implemented/feature/2026-07-29-ask-question-web-presentation.md) notes.
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、冻结的 `block`
|
||||
|
||||
### 详情与卡片
|
||||
|
||||
本包通过 `ToolDetails` 填充 `conversation.details.tool`。行 renderer 与 Details renderer 分别为 terminal、read、diff、search 和 web 卡片复用同一个纯 card model。这些 model 校验原始调用参数、结果内容、失败状态、持久 metadata、Code Dispatch `parentCallId` 与 Session 路径事实。不受支持或格式错误的输入使用压平的工具结果文本。各类卡片的上限与 fallback 规则仍由对应的 [terminal](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md)、[diff](../../../.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md)、[read](../../../.agents/notes/implemented/feature/2026-07-30-web-read-card-frontend.zh.md)、[search](../../../.agents/notes/implemented/feature/2026-07-30-web-search-card.zh.md)、[web](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md) 与 [question](../../../.agents/notes/implemented/feature/2026-07-29-ask-question-web-presentation.zh.md) 笔记负责。
|
||||
本包通过 `ToolDetails` 填充 `conversation.details.tool`。行 renderer 与 Details renderer 分别为 terminal、read、diff、search 和 web 卡片复用同一个纯 card model。这些 model 校验原始调用参数、结果内容、失败状态、持久 metadata、Code Dispatch `parentCallId` 与 Session 路径事实。Generic row 保留原始 `argsRaw` 引用,只在展开期间格式化 input body;结构化卡片跳过 generic body 格式化。不受支持或格式错误的输入使用压平的工具结果文本。各类卡片的上限与 fallback 规则仍由对应的 [terminal](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.zh.md)、[diff](../../../.agents/notes/implemented/feature/2026-07-30-web-diff-card.zh.md)、[read](../../../.agents/notes/implemented/feature/2026-07-30-web-read-card-frontend.zh.md)、[search](../../../.agents/notes/implemented/feature/2026-07-30-web-search-card.zh.md)、[web](../../../.agents/notes/implemented/feature/2026-07-30-web-result-card-frontend.zh.md) 与 [question](../../../.agents/notes/implemented/feature/2026-07-29-ask-question-web-presentation.zh.md) 笔记负责。
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -15,7 +15,9 @@ import {
|
||||
diffBlockLabels, readBlockLabels, searchBlockLabels, webBlockLabels,
|
||||
} from '../models/primitive-labels.ts'
|
||||
import type { AskQuestionCardModel } from '../models/ask-question-card-model.ts'
|
||||
import type { ToolRowState, ToolRowVariant } from '../models/tool-call-model.ts'
|
||||
import {
|
||||
formatToolBody, type ToolRowState, type ToolRowVariant,
|
||||
} from '../models/tool-call-model.ts'
|
||||
import type { WebCardModelProps } from '../models/web-card-model.ts'
|
||||
import { AskQuestionCard } from './AskQuestionCard.tsx'
|
||||
import css from './ToolRow.module.css'
|
||||
@@ -36,8 +38,8 @@ export interface ToolRowProps {
|
||||
* error row, whose collapsed summary is the failure line instead.
|
||||
*/
|
||||
summarySuffix?: string | null | undefined
|
||||
/** Expanded-body input text; null = no input section. */
|
||||
body: string | null
|
||||
/** Original argument JSON formatted only while the row is expanded. */
|
||||
bodyRaw?: string | null | undefined
|
||||
/** Flattened result text for the expanded Output section; null/absent = no output section. */
|
||||
output?: string | null | undefined
|
||||
/** Ask-user transcript card; card fields are mutually exclusive and replace text sections. */
|
||||
@@ -94,7 +96,7 @@ export function ToolRow({
|
||||
title,
|
||||
summary,
|
||||
summarySuffix,
|
||||
body,
|
||||
bodyRaw,
|
||||
output,
|
||||
askQuestion,
|
||||
errorSummary,
|
||||
@@ -124,8 +126,12 @@ export function ToolRow({
|
||||
const askQuestionBody = askQuestion ?? null
|
||||
const outputText = output ?? null
|
||||
const card = askQuestionBody ?? terminalBody ?? diffBody ?? readBody ?? searchBody ?? webBody
|
||||
const expandable = body !== null || outputText !== null || card !== null
|
||||
const expandable = bodyRaw != null || outputText !== null || card !== null
|
||||
const open = expanded && expandable
|
||||
const bodyText = useMemo(
|
||||
() => open && card === null && bodyRaw != null ? formatToolBody(variant, bodyRaw) : null,
|
||||
[bodyRaw, card, open, variant],
|
||||
)
|
||||
const status = stateStatus(state, t)
|
||||
// A failure must replace, not supplement, the normal summary.
|
||||
const failureLine = state === 'error' ? errorSummary ?? null : null
|
||||
@@ -156,7 +162,7 @@ export function ToolRow({
|
||||
}
|
||||
// The code variant's program renders through CodeBlock (shiki), so only its
|
||||
// output joins the IN/OUT card; every other variant's input does too.
|
||||
const cardBody = variant === 'code' ? null : body
|
||||
const cardBody = variant === 'code' ? null : bodyText
|
||||
return (
|
||||
<div className={css.root} data-variant={variant} data-tool={toolName} data-state={state}>
|
||||
{status !== null && <span className={css.visuallyHidden}>{status}</span>}
|
||||
@@ -235,9 +241,9 @@ export function ToolRow({
|
||||
? <WebBlock {...webBody} labels={webLabels} className={css.webBody} />
|
||||
: (
|
||||
<>
|
||||
{variant === 'code' && body !== null && (
|
||||
{variant === 'code' && bodyText !== null && (
|
||||
<div className={css.bodyScroll}>
|
||||
<CodeBlock code={body} lang="typescript" copyLabel={t('copy')} copiedLabel={t('copied')} className={css.codeBody} />
|
||||
<CodeBlock code={bodyText} lang="typescript" copyLabel={t('copy')} copiedLabel={t('copied')} className={css.codeBody} />
|
||||
</div>
|
||||
)}
|
||||
{(cardBody !== null || outputText !== null) && (
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* Pure row-model derivation for tool summary rows: variant classification,
|
||||
* one-line summary, expanded-body text, and flattened result output from the
|
||||
* frozen call slice. Input material comes from the call ARGUMENTS; output and
|
||||
* error material from the settled result node. A supported terminal call gets
|
||||
* its expanded body from `terminalCardModel` instead.
|
||||
* one-line summary, expansion-time body input, and flattened result output
|
||||
* from the frozen call slice. Input material comes from the call ARGUMENTS;
|
||||
* output and error material from the settled result node. A supported terminal
|
||||
* call gets its expanded body from `terminalCardModel` instead.
|
||||
*/
|
||||
// The block union's defining home is runtime (fold-product types); this
|
||||
// contract only forwards it (type-definition authority stays with the layer
|
||||
@@ -92,8 +92,8 @@ export interface ToolRowModel {
|
||||
* relative values against the session cwd before opening.
|
||||
*/
|
||||
filePath: string | undefined
|
||||
/** Expanded-body input text (pretty args); null = no input section. */
|
||||
body: string | null
|
||||
/** Original argument JSON retained for expansion-time body formatting. */
|
||||
bodyRaw: string | null
|
||||
/** Flattened result text ({@link resultText}); null while running or when the result carries no text. */
|
||||
output: string | null
|
||||
/** First line of the result text on an error row; null for every other state. */
|
||||
@@ -196,7 +196,13 @@ function deriveFilePath(variant: ToolRowVariant, argsRaw: string): string | unde
|
||||
return picked === undefined ? undefined : firstLine(picked)
|
||||
}
|
||||
|
||||
function deriveBody(variant: ToolRowVariant, argsRaw: string): string | null {
|
||||
/**
|
||||
* Format one argument payload when its generic input body becomes visible.
|
||||
* @param variant - row presentation selected for the Tool name.
|
||||
* @param argsRaw - original argument JSON or incomplete raw text.
|
||||
* @returns display body, or null for empty input.
|
||||
*/
|
||||
export function formatToolBody(variant: ToolRowVariant, argsRaw: string): string | null {
|
||||
if (argsRaw === '') return null
|
||||
const parsed = parseArgs(argsRaw)
|
||||
if (parsed === undefined) return argsRaw
|
||||
@@ -238,12 +244,13 @@ export function toolRowModel(toolName: string, block: ToolCallBlock, cwd?: strin
|
||||
// would erase the collapsed error row's summary slot.
|
||||
const output = done ? (resultText(block) || null) : null
|
||||
const errorSummary = state === 'error' && output !== null ? firstLine(output) : null
|
||||
const bodyRaw = argsRaw === '' ? null : argsRaw
|
||||
return {
|
||||
variant,
|
||||
titleKey: toolTitleKey ?? VARIANT_TITLE_KEYS[variant],
|
||||
summary,
|
||||
filePath: deriveFilePath(variant, argsRaw),
|
||||
body: deriveBody(variant, argsRaw),
|
||||
bodyRaw,
|
||||
output,
|
||||
errorSummary,
|
||||
state,
|
||||
|
||||
@@ -51,7 +51,7 @@ export function GenericToolCard({ toolName, block, cwd, home, openFile, inspect,
|
||||
// Single-file tools never expose an args body — the path link is the only
|
||||
// args interaction. A card is not an args body: a read/write/edit row is
|
||||
// single-file AND carries a card, so the card expands under the path link.
|
||||
body={singleFile ? null : model.body}
|
||||
bodyRaw={singleFile ? null : model.bodyRaw}
|
||||
output={model.output}
|
||||
errorSummary={model.errorSummary}
|
||||
terminal={terminal}
|
||||
|
||||
@@ -186,7 +186,7 @@ export function AskQuestionRow({ toolName, block, inspect, t }: AskQuestionRowPr
|
||||
icon={<IconQuestionOutline14 />}
|
||||
title={t('ask.rowTitle')}
|
||||
summary={summary}
|
||||
body={transcript === null ? model.body : null}
|
||||
bodyRaw={transcript === null ? model.bodyRaw : null}
|
||||
output={transcript === null ? model.output : null}
|
||||
askQuestion={transcript}
|
||||
state={state}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, type KeyboardEvent } from 'react'
|
||||
import { useMemo, useState, type KeyboardEvent } from 'react'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
terminalCardModel,
|
||||
terminalFailed,
|
||||
} from '../models/terminal-card-model.ts'
|
||||
import { toolRowModel, type ToolRowState } from '../models/tool-call-model.ts'
|
||||
import { formatToolBody, toolRowModel, type ToolRowState } from '../models/tool-call-model.ts'
|
||||
import { CONVERSATION_NS as NS } from '../../locale.ts'
|
||||
import css from './bash-sample.module.css'
|
||||
|
||||
@@ -58,9 +58,15 @@ export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }:
|
||||
// body; background acknowledgements and malformed calls remain collapsed.
|
||||
const genericBody = terminal === null
|
||||
&& (model.state === 'error' || isSettledPersistentShellCall(block))
|
||||
&& (model.body !== null || model.output !== null)
|
||||
&& (model.bodyRaw !== null || model.output !== null)
|
||||
const expandable = terminal !== null || genericBody
|
||||
const open = expanded && expandable
|
||||
const body = useMemo(
|
||||
() => open && genericBody && model.bodyRaw !== null
|
||||
? formatToolBody(model.variant, model.bodyRaw)
|
||||
: null,
|
||||
[genericBody, model.bodyRaw, model.variant, open],
|
||||
)
|
||||
const failureLine = model.state === 'error' ? model.errorSummary : null
|
||||
const toggleExpand = () => {
|
||||
setExpanded(v => !v)
|
||||
@@ -115,13 +121,13 @@ export function BashRow({ toolName, block, sessionId, useSessions, inspect, t }:
|
||||
)
|
||||
: (
|
||||
<div className={css.ioCard}>
|
||||
{model.body !== null && (
|
||||
{body !== null && (
|
||||
<div className={css.ioSection}>
|
||||
<span className={css.ioLabel}>{t('row.input')}</span>
|
||||
<span className={css.ioText}>{model.body}</span>
|
||||
<span className={css.ioText}>{body}</span>
|
||||
</div>
|
||||
)}
|
||||
{model.body !== null && model.output !== null && (
|
||||
{body !== null && model.output !== null && (
|
||||
<span className={css.ioDivider} aria-hidden />
|
||||
)}
|
||||
{model.output !== null && (
|
||||
|
||||
@@ -23,7 +23,6 @@ export function FileMutationRow({ toolName, block, cwd, home, openFile, inspect,
|
||||
icon={<IconEditOutline16 size={14} />}
|
||||
title={t(model.titleKey)}
|
||||
summary={model.summary}
|
||||
body={null}
|
||||
output={model.output}
|
||||
errorSummary={model.errorSummary}
|
||||
diff={diff}
|
||||
|
||||
@@ -23,7 +23,6 @@ export function ReadRow({ toolName, block, cwd, home, openFile, inspect, t }: Re
|
||||
icon={<IconBrowseOutline16 size={14} />}
|
||||
title={t(model.titleKey)}
|
||||
summary={model.summary}
|
||||
body={null}
|
||||
output={model.output}
|
||||
errorSummary={model.errorSummary}
|
||||
read={read}
|
||||
|
||||
@@ -28,7 +28,6 @@ export function SearchRow({ toolName, block, inspect, t }: SearchRowProps) {
|
||||
? SEARCH_TITLE_KEYS.grep
|
||||
: toolName === 'glob' ? SEARCH_TITLE_KEYS.glob : model.titleKey)}
|
||||
summary={model.summary}
|
||||
body={null}
|
||||
// ToolRow ignores output when a structured card is present; otherwise it
|
||||
// preserves the generic fallback for errors and legacy results.
|
||||
output={model.output}
|
||||
|
||||
@@ -58,7 +58,7 @@ export function TodoRow({ toolName, block, inspect, t }: TodoRowProps) {
|
||||
title={t('todo.rowTitle')}
|
||||
summary={summary.text}
|
||||
summarySuffix={summary.extra > 0 ? `+${summary.extra}` : null}
|
||||
body={model.body}
|
||||
bodyRaw={model.bodyRaw}
|
||||
output={model.output}
|
||||
errorSummary={model.errorSummary}
|
||||
state={model.state}
|
||||
|
||||
@@ -29,7 +29,6 @@ export function WebRow({ toolName, block, inspect, t }: WebRowProps) {
|
||||
? WEB_TITLE_KEYS.web_search
|
||||
: toolName === 'web_fetch' ? WEB_TITLE_KEYS.web_fetch : model.titleKey)}
|
||||
summary={model.summary}
|
||||
body={null}
|
||||
output={model.output}
|
||||
errorSummary={model.errorSummary}
|
||||
web={web}
|
||||
|
||||
@@ -45,7 +45,7 @@ function bashProps(block: RunningToolCall | ToolResultNode): BashRowProps {
|
||||
describe('Tool presentation tails', () => {
|
||||
it('ToolRow stopped state renders the warning dot in the leading slot', () => {
|
||||
const view = render(
|
||||
<ToolRow t={t} variant="bash" icon={<i data-testid="icon" />} title="Bash" summary="s" body={null} state="stopped" />,
|
||||
<ToolRow t={t} variant="bash" icon={<i data-testid="icon" />} title="Bash" summary="s" state="stopped" />,
|
||||
)
|
||||
expect(view.queryByTestId('icon')).toBeNull()
|
||||
expect(view.container.querySelector('[data-state="stopped"]')).not.toBeNull()
|
||||
|
||||
@@ -5,13 +5,16 @@ import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import type { RunningToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts'
|
||||
import { classifyTool, resultText, toolRowModel } from '../src/client/tool/models/tool-call-model.ts'
|
||||
import {
|
||||
classifyTool, formatToolBody, resultText, toolRowModel,
|
||||
} from '../src/client/tool/models/tool-call-model.ts'
|
||||
import { ToolRow } from '../src/client/tool/components/ToolRow.tsx'
|
||||
import { GenericToolCard, type GenericToolCardProps } from '../src/client/tool/toolviews/GenericToolCard.tsx'
|
||||
import { zh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
const t: GenericToolCardProps['t'] = makeTranslate(zh, commonZh)
|
||||
@@ -163,14 +166,17 @@ describe('tool-call-model', () => {
|
||||
})
|
||||
|
||||
it('body pretty-prints JSON args, keeps raw non-JSON, null when empty', () => {
|
||||
expect(toolRowModel('bash', running({ argsRaw: '{"a":1}' })).body).toBe('{\n "a": 1\n}')
|
||||
expect(toolRowModel('bash', running({ argsRaw: 'raw' })).body).toBe('raw')
|
||||
expect(toolRowModel('bash', running({ argsRaw: '' })).body).toBeNull()
|
||||
expect(toolRowModel('bash', result({ call: null })).body).toBeNull()
|
||||
expect(formatToolBody('bash', toolRowModel('bash', running({ argsRaw: '{"a":1}' })).bodyRaw ?? ''))
|
||||
.toBe('{\n "a": 1\n}')
|
||||
expect(formatToolBody('bash', toolRowModel('bash', running({ argsRaw: 'raw' })).bodyRaw ?? ''))
|
||||
.toBe('raw')
|
||||
expect(toolRowModel('bash', running({ argsRaw: '' })).bodyRaw).toBeNull()
|
||||
expect(toolRowModel('bash', result({ call: null })).bodyRaw).toBeNull()
|
||||
})
|
||||
|
||||
it('a code row with an empty program falls back to the args JSON envelope', () => {
|
||||
expect(toolRowModel('run_code', running({ name: 'run_code', argsRaw: '{"code":""}' })).body)
|
||||
const model = toolRowModel('run_code', running({ name: 'run_code', argsRaw: '{"code":""}' }))
|
||||
expect(formatToolBody(model.variant, model.bodyRaw ?? ''))
|
||||
.toBe('{\n "code": ""\n}')
|
||||
})
|
||||
|
||||
@@ -228,7 +234,7 @@ describe('ToolRow', () => {
|
||||
const rowProps = {
|
||||
t,
|
||||
variant: 'bash' as const, icon: <i data-testid="tool-icon" />, title: 'Bash',
|
||||
summary: 'List files', body: '{\n "a": 1\n}', state: 'ok' as const,
|
||||
summary: 'List files', bodyRaw: '{"a":1}', state: 'ok' as const,
|
||||
}
|
||||
|
||||
it('renders leading icon, title and summary while collapsed', () => {
|
||||
@@ -252,6 +258,28 @@ describe('ToolRow', () => {
|
||||
expect(view.getByText('List files')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('formats the argument body only while expanding it', () => {
|
||||
const stringify = vi.spyOn(JSON, 'stringify')
|
||||
const bodyFormatCalls = () => stringify.mock.calls.filter(
|
||||
([value, replacer, space]) => typeof value === 'object'
|
||||
&& value !== null
|
||||
&& 'a' in value
|
||||
&& (value as { a?: unknown }).a === 1
|
||||
&& replacer === null
|
||||
&& space === 2,
|
||||
).length
|
||||
const view = render(<ToolRow {...rowProps} />)
|
||||
expect(bodyFormatCalls()).toBe(0)
|
||||
|
||||
fireEvent.click(view.getByRole('button'))
|
||||
expect(bodyFormatCalls()).toBe(1)
|
||||
expect(view.getByText(/"a": 1/)).toBeTruthy()
|
||||
|
||||
fireEvent.click(view.getByRole('button'))
|
||||
expect(bodyFormatCalls()).toBe(1)
|
||||
expect(view.queryByText(/"a": 1/)).toBeNull()
|
||||
})
|
||||
|
||||
it('running keeps the icon (row sweep carries the signal); error swaps in a StateDot', () => {
|
||||
const runningView = render(<ToolRow {...rowProps} state="running" />)
|
||||
expect(runningView.queryByTestId('tool-icon')).not.toBeNull()
|
||||
@@ -264,7 +292,7 @@ describe('ToolRow', () => {
|
||||
})
|
||||
|
||||
it('non-expandable rows render a passive leading slot and no row button', () => {
|
||||
const view = render(<ToolRow {...rowProps} body={null} />)
|
||||
const view = render(<ToolRow {...rowProps} bodyRaw={null} />)
|
||||
expect(view.queryByRole('button')).toBeNull()
|
||||
expect(view.container.querySelector('[aria-expanded]')).toBeNull()
|
||||
expect(view.queryByTestId('tool-icon')).not.toBeNull()
|
||||
@@ -391,7 +419,7 @@ describe('ToolRow', () => {
|
||||
expect(inputOnly.getByText('输入')).toBeTruthy()
|
||||
expect(inputOnly.queryByText('输出')).toBeNull()
|
||||
cleanup()
|
||||
const outputOnly = render(<ToolRow {...rowProps} body={null} output="only out" />)
|
||||
const outputOnly = render(<ToolRow {...rowProps} bodyRaw={null} output="only out" />)
|
||||
fireEvent.click(outputOnly.getByRole('button'))
|
||||
expect(outputOnly.queryByText('输入')).toBeNull()
|
||||
expect(outputOnly.getByText('输出')).toBeTruthy()
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-trajectory/README.md
|
||||
README.md: cb11a8186f32761b6af208ae79196feff8f098d5
|
||||
README.zh.md: 5b02e965b3d4e041b7a405d210bace366551cecb
|
||||
README.md: 73bacf0761e2427b0c2632ed274de68986058ebd
|
||||
README.zh.md: 8672ff0787472b284ccb4639876f7fc3097af9e1
|
||||
@@ -43,7 +43,7 @@ A fixed Overview above the ledger projects real record start/duration timing fro
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
The view is a pure projection: Trajectory-owned Definitions assemble business records from the shared Session window — including durable cancellation-finalized prefixes, chunk-only interruption fallbacks, and interrupted Tool records — so Trajectory neither reads nor changes the Chat conversation snapshot.
|
||||
The view is a pure projection: Trajectory-owned Definitions assemble business records from the shared Session window — including durable cancellation-finalized prefixes, chunk-only interruption fallbacks, and interrupted Tool records — so Trajectory neither reads nor changes the Chat conversation snapshot. Its steering classifier retains only next-step Inbox IDs through persistent splice state and shares each current claimed batch across later Contexts.
|
||||
|
||||
### Virtual rows
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ kind: "package-reference"
|
||||
<details>
|
||||
<summary>实现细节——点击展开</summary>
|
||||
|
||||
视图是纯投影:Trajectory 自有的 Definition 从共享 Session 窗口组装业务记录——包括持久化的取消定稿前缀、只能从分片恢复的打断前缀与被打断的工具记录——因此 Trajectory 既不读取也不改变 Chat 会话快照。
|
||||
视图是纯投影:Trajectory 自有的 Definition 从共享 Session 窗口组装业务记录——包括持久化的取消定稿前缀、只能从分片恢复的打断前缀与被打断的工具记录——因此 Trajectory 既不读取也不改变 Chat 会话快照。其 steering 分类器通过持久 splice state 只保留 next-step Inbox ID,并让后续 Context 共享当前 claimed batch。
|
||||
|
||||
### 虚拟行
|
||||
|
||||
|
||||
@@ -21,33 +21,105 @@ interface InboxSplice {
|
||||
readonly outcome?: 'canceled'
|
||||
}
|
||||
|
||||
interface PendingSnapshot {
|
||||
readonly kind: 'snapshot'
|
||||
readonly ids: readonly string[]
|
||||
}
|
||||
|
||||
interface PendingSplice {
|
||||
readonly kind: 'splice'
|
||||
readonly previous: PendingState
|
||||
readonly start: number
|
||||
readonly removedCount: number
|
||||
readonly inserted: readonly string[]
|
||||
}
|
||||
|
||||
type PendingState = PendingSnapshot | PendingSplice
|
||||
|
||||
interface InboxState {
|
||||
readonly pending: readonly InboxIdentity[]
|
||||
readonly claimed: ReadonlySet<string>
|
||||
/** Persistent splice chain materialized only when a next-step batch is claimed. */
|
||||
readonly pending: PendingState
|
||||
/** Message ids in the current claim, shared until the next claim. */
|
||||
readonly currentClaimed: ReadonlySet<string>
|
||||
}
|
||||
|
||||
type MessageNode = UserMessageNode | SteeringMessageNode | ContextMessageNode
|
||||
|
||||
const EMPTY_PENDING: PendingState = { kind: 'snapshot', ids: [] }
|
||||
const EMPTY_CURRENT_CLAIMED: ReadonlySet<string> = new Set()
|
||||
|
||||
function materializePending(state: PendingState): string[] {
|
||||
const splices: PendingSplice[] = []
|
||||
let current = state
|
||||
while (current.kind === 'splice') {
|
||||
splices.push(current)
|
||||
current = current.previous
|
||||
}
|
||||
const pending = [...current.ids]
|
||||
for (const splice of splices.reverse()) {
|
||||
pending.splice(splice.start, splice.removedCount, ...splice.inserted)
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
function withoutInserted(
|
||||
claimed: ReadonlySet<string>,
|
||||
inserted: readonly string[],
|
||||
): ReadonlySet<string> {
|
||||
let next: Set<string> | undefined
|
||||
for (const id of inserted) {
|
||||
if (!claimed.has(id)) continue
|
||||
next ??= new Set(claimed)
|
||||
next.delete(id)
|
||||
}
|
||||
return next ?? claimed
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one next-step splice under the AgentLoop's durable event ordering.
|
||||
* An entered claim logs its complete message batch before another claim; a
|
||||
* rejected claim logs no messages, so only the current claim can classify a
|
||||
* later `user/message`.
|
||||
*/
|
||||
function applySplice(
|
||||
previous: ConversationPreviousContext<InboxState> | undefined,
|
||||
splice: InboxSplice,
|
||||
): InboxState {
|
||||
const pending = [...(previous?.state.pending ?? [])]
|
||||
const claimed = new Set(previous?.state.claimed ?? [])
|
||||
const removed = pending.splice(splice.start, splice.removedCount ?? 0, ...splice.inserted)
|
||||
for (const identity of splice.inserted) claimed.delete(identity.id)
|
||||
if (splice.outcome !== 'canceled') {
|
||||
for (const identity of removed) claimed.add(identity.id)
|
||||
const priorPending = previous?.state.pending ?? EMPTY_PENDING
|
||||
const inserted = splice.inserted.map(identity => identity.id)
|
||||
const removedCount = splice.removedCount ?? 0
|
||||
if (removedCount > 0 && splice.outcome !== 'canceled') {
|
||||
const pending = materializePending(priorPending)
|
||||
const removed = pending.splice(splice.start, removedCount, ...inserted)
|
||||
return {
|
||||
pending: { kind: 'snapshot', ids: pending },
|
||||
currentClaimed: new Set(removed),
|
||||
}
|
||||
}
|
||||
const currentClaimed = withoutInserted(
|
||||
previous?.state.currentClaimed ?? EMPTY_CURRENT_CLAIMED,
|
||||
inserted,
|
||||
)
|
||||
return {
|
||||
pending: {
|
||||
kind: 'splice',
|
||||
previous: priorPending,
|
||||
start: splice.start,
|
||||
removedCount,
|
||||
inserted,
|
||||
},
|
||||
currentClaimed,
|
||||
}
|
||||
return { pending, claimed }
|
||||
}
|
||||
|
||||
const trajectoryInboxDefinition: ConversationNodeDefinition<InboxState> = {
|
||||
kind: 'trajectory-inbox-next-step',
|
||||
match: event => event.type === 'agent/inbox/spliced'
|
||||
&& event.data.target === 'next-step'
|
||||
? { id: String(event.seq), role: 'start' }
|
||||
: null,
|
||||
match: (event) => {
|
||||
if (event.type === 'agent/inbox/spliced' && event.data.target === 'next-step') {
|
||||
return { id: String(event.seq), role: 'start' }
|
||||
}
|
||||
return null
|
||||
},
|
||||
start: (_context, match, reader) => {
|
||||
if (match.event.type !== 'agent/inbox/spliced') {
|
||||
throw new Error('trajectory-inbox-next-step start requires agent/inbox/spliced')
|
||||
@@ -84,7 +156,7 @@ const trajectoryMessageDefinition: ConversationNodeDefinition<MessageNode> = {
|
||||
}
|
||||
}
|
||||
const claimed = reader.previous<InboxState>('trajectory-inbox-next-step')
|
||||
?.state.claimed.has(String(event.data.id)) === true
|
||||
?.state.currentClaimed.has(String(event.data.id)) === true
|
||||
return claimed
|
||||
? {
|
||||
kind: 'steering',
|
||||
|
||||
@@ -97,7 +97,7 @@ function assembler(events: readonly SessionEventLikeEntry[]): ConversationNodeAs
|
||||
new TestViewDefinitions(),
|
||||
)
|
||||
value.replaceWindow(events, false)
|
||||
value.flush()
|
||||
value.activateTarget('trajectory')
|
||||
return value
|
||||
}
|
||||
|
||||
@@ -508,4 +508,70 @@ describe('Trajectory conversation Definitions', () => {
|
||||
? request.promptChange?.kind
|
||||
: undefined)).toEqual(['initial', undefined])
|
||||
})
|
||||
|
||||
it('replays pending splice chains and scopes steering to the current claim', () => {
|
||||
const message = (id: string, text: string) => ({
|
||||
id,
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text }],
|
||||
source: { kind: 'user' },
|
||||
})
|
||||
const first = message('claim-first', 'first')
|
||||
const second = message('claim-second', 'second')
|
||||
const canceled = message('claim-canceled', 'canceled')
|
||||
const requeued = message('claim-requeued', 'requeued')
|
||||
const later = message('claim-later', 'later')
|
||||
const current = snapshot(assembler([
|
||||
at(1, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [first],
|
||||
}),
|
||||
at(2, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 1, inserted: [canceled],
|
||||
}),
|
||||
at(3, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 1, inserted: [second],
|
||||
}),
|
||||
at(4, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 2, removedCount: 1, inserted: [], outcome: 'canceled',
|
||||
}),
|
||||
at(5, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 2, inserted: [],
|
||||
}),
|
||||
at(6, 'user/message', first),
|
||||
at(7, 'user/message', second),
|
||||
at(8, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [requeued],
|
||||
}),
|
||||
at(9, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 1, inserted: [],
|
||||
}),
|
||||
at(10, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [requeued],
|
||||
}),
|
||||
at(11, 'user/message', requeued),
|
||||
at(12, 'user/message', canceled),
|
||||
at(13, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 1, inserted: [], outcome: 'canceled',
|
||||
}),
|
||||
at(14, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, inserted: [later],
|
||||
}),
|
||||
at(15, 'agent/inbox/spliced', {
|
||||
target: 'next-step', start: 0, removedCount: 1, inserted: [],
|
||||
}),
|
||||
at(16, 'user/message', later),
|
||||
]))
|
||||
|
||||
expect(current.eventNodes.filter(node =>
|
||||
node.kind === 'user' || node.kind === 'steering').map(node => ({
|
||||
kind: node.kind,
|
||||
seq: node.seq,
|
||||
}))).toEqual([
|
||||
{ kind: 'steering', seq: 6 },
|
||||
{ kind: 'steering', seq: 7 },
|
||||
{ kind: 'user', seq: 11 },
|
||||
{ kind: 'user', seq: 12 },
|
||||
{ kind: 'steering', seq: 16 },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -264,6 +264,7 @@ async function bench(snapshot = historySnapshot(NODES)) {
|
||||
}
|
||||
const binding: ConversationBinding = {
|
||||
snapshot: conversationStore,
|
||||
activate: () => {},
|
||||
target: target => targetSources[target],
|
||||
}
|
||||
vi.spyOn(uiConversation, 'binding').mockReturnValue(binding)
|
||||
@@ -389,6 +390,7 @@ function mount(fixture: Awaited<ReturnType<typeof bench>>) {
|
||||
actions={conversation.actions}
|
||||
renderSlot={() => null}
|
||||
open={vi.fn()}
|
||||
selectView={conversation.actions.setView}
|
||||
t={tConversation}
|
||||
/>
|
||||
<ConversationSession
|
||||
@@ -398,6 +400,7 @@ function mount(fixture: Awaited<ReturnType<typeof bench>>) {
|
||||
actions={conversation.actions}
|
||||
renderSlot={renderSlot}
|
||||
bindDraftMirror={() => () => {}}
|
||||
openView={conversation.actions.openView}
|
||||
/>
|
||||
</>,
|
||||
)
|
||||
|
||||
@@ -100,7 +100,7 @@ function matched(input: SessionLiveEventEntry, role: ConversationMatch['role']):
|
||||
function assembler(entries: readonly SessionLiveEventEntry[], hasMore = false): ConversationNodeAssembler {
|
||||
const value = new ConversationNodeAssembler(new TestEventDefinitions(), new TestViewDefinitions())
|
||||
value.replaceWindow(entries, hasMore)
|
||||
value.flush()
|
||||
value.activateTarget('chat')
|
||||
return value
|
||||
}
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/core/agent-loop/README.md
|
||||
README.md: a37d75545b4c1eccb4363c7ff2f09ae102f480db
|
||||
README.zh.md: a209e6a99d96cb8790a19b0ebb043332d619026f
|
||||
README.md: 60d1e75a5038500a42244a45fb077e1eb71da092
|
||||
README.zh.md: 166ba6ff366f9a8c8c687b4521bb04b591814851
|
||||
@@ -107,7 +107,7 @@ Creation is one rollback-covered transaction: construct a private session, concr
|
||||
|
||||
### Turn and step flow
|
||||
|
||||
The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. `agent/pre-step` decides what enters the step; each successful model call appends one `assistant/message` anchor citing its chunk seqs, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results, and result context remain model-ordered.
|
||||
The driver owns one agent for its lifetime and runs inside `ctx.agents.withInitiator(agent, ...)`. At a turn boundary it opens the durable turn, then atomically claims pending next-step input plus one queued prompt; between steps it claims only next-step input. `agent/pre-step` decides what enters the step. An entered decision appends its complete `user/message` batch before the driver can claim again, while a rejected decision appends none. Each successful model call appends one `assistant/message` anchor citing its chunk seqs, and a cancelled stream appends an `interrupted: true` anchor with the delivered prefix so the next request contains what the user saw. Within a step, exclusive calls form barriers and parallel-safe calls use the bounded rolling pool; policy, durable results, and result context remain model-ordered.
|
||||
|
||||
### Failure and cancellation
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ const handle = await ctx.agents.create({
|
||||
|
||||
### 轮次与步骤流程
|
||||
|
||||
驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤;每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。
|
||||
驱动器在其整个生命周期内拥有一个 agent,并在 `ctx.agents.withInitiator(agent, ...)` 内运行。在轮次边界,它先打开持久轮次,再原子领取待处理的 next-step 输入与一条排队提示词;在步骤之间则只领取 next-step 输入。`agent/pre-step` 决定什么进入该步骤。进入步骤的决定会在驱动器再次领取消息前追加完整的 `user/message` 批次,被拒绝的决定则不追加任何消息。每次成功的模型调用都恰好追加一个引用其分片 seq 的 `assistant/message` 锚点,被取消的流则追加带 `interrupted: true` 的锚点并携带已交付前缀,使下一次请求包含用户看到的内容。在步骤内,独占调用形成屏障,并行安全调用使用有界滚动池;策略、持久结果与结果上下文保持模型顺序。
|
||||
|
||||
### 失败与取消
|
||||
|
||||
|
||||
@@ -512,6 +512,55 @@ describe('adapter registration, routing, and accepted-input ownership', () => {
|
||||
expect(steeringSources).toEqual([{ kind: 'plugin', plugin: 'goal' }])
|
||||
})
|
||||
|
||||
it('records each admitted next-step batch before the following claim', async () => {
|
||||
const adapter = new MockAdapter([
|
||||
toolCallResponse('c1', 'steer_next', {}),
|
||||
toolCallResponse('c2', 'steer_next', {}),
|
||||
textResponse('done'),
|
||||
])
|
||||
const ctx = await harness(adapter)
|
||||
const steering = [
|
||||
createUserMessage({ content: [{ type: 'text', text: 'first steer' }], source: { kind: 'user' } }),
|
||||
createUserMessage({ content: [{ type: 'text', text: 'second steer' }], source: { kind: 'user' } }),
|
||||
]
|
||||
const agent = ctx.agentLoop.create(SessionId('claim-order'), { provider: 'mock', model: 'mock' })
|
||||
let execution = 0
|
||||
ctx.tools.register(defineContentToolFixture({
|
||||
name: 'steer_next',
|
||||
description: '',
|
||||
parameters: {},
|
||||
async execute() {
|
||||
const message = steering[execution]
|
||||
execution += 1
|
||||
if (message !== undefined) agent.steer(message)
|
||||
return []
|
||||
},
|
||||
}))
|
||||
|
||||
send(agent, 'go')
|
||||
await waitForIdle(ctx, agent)
|
||||
|
||||
const events = agent.session.events
|
||||
const claims = events.flatMap(event => event.type === 'agent/inbox/spliced'
|
||||
&& event.data.target === 'next-step'
|
||||
&& event.data.outcome !== 'canceled'
|
||||
&& (event.data.removedCount ?? 0) > 0
|
||||
? [event]
|
||||
: [])
|
||||
expect(claims).toHaveLength(2)
|
||||
for (const [index, message] of steering.entries()) {
|
||||
const claim = claims[index]
|
||||
const admitted = events.find(event =>
|
||||
event.type === 'user/message' && event.data.id === message.id)
|
||||
expect(claim).toBeDefined()
|
||||
expect(admitted).toBeDefined()
|
||||
if (claim === undefined || admitted === undefined) continue
|
||||
expect(admitted.seq).toBeGreaterThan(claim.seq)
|
||||
const nextClaim = claims[index + 1]
|
||||
if (nextClaim !== undefined) expect(admitted.seq).toBeLessThan(nextClaim.seq)
|
||||
}
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
describe('turn numbering continues across seeded sessions', () => {
|
||||
|
||||
Reference in new issue
Block a user