Merge commit '05380955d3d59a536c6c4f12def7c1586daaa613' into auto-review-per-call

# Conflicts:
#	docs/subsystems/session-projection.i18n.yaml
#	docs/subsystems/session-projection.md
#	docs/subsystems/session-projection.zh.md
#	packages/client/ui-conversation/tests/input-bar.client.spec.tsx
#	packages/client/ui-permission-presets/README.i18n.yaml
#	packages/client/ui-permission-presets/README.md
#	packages/client/ui-permission-presets/README.zh.md
#	packages/client/ui-permission-presets/tests/browser-plugin.client.spec.ts
#	packages/client/ui-tool/README.i18n.yaml
#	packages/client/ui-tool/README.md
#	packages/client/ui-tool/README.zh.md
#	packages/client/ui-tool/src/client/tool/components/ToolRow.tsx
#	packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx
#	packages/client/ui-tool/tests/tool-row.client.spec.tsx
#	packages/extensions/tool-cordis/src/api-catalog.ts
#	packages/session/session-projection/README.i18n.yaml
#	packages/session/session-projection/README.md
#	packages/session/session-projection/README.zh.md
#	packages/session/session-projection/src/index.ts
#	packages/session/session-projection/tests/registry.spec.ts
This commit is contained in:
pku-xht committed 2026-08-31 22:07:28 +08:00
commit 3f610869b6
212 files changed
+5214 -769

No files matched your search

@@ -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-07-25-web-input-machine-and-slash-pipeline.md
2026-07-25-web-input-machine-and-slash-pipeline.md: 3508de5e8a3980a87c344c5b76c060f6119ee686
2026-07-25-web-input-machine-and-slash-pipeline.zh.md: eebfdae780157dfd0dace1386169c5fee8c1d564
2026-07-25-web-input-machine-and-slash-pipeline.md: 69899efcda42eb1087aaa68d1eba8c08dd14f361
2026-07-25-web-input-machine-and-slash-pipeline.zh.md: 7e37dd67a2d5a7943a8c601a890d2de7489b227d
@@ -48,7 +48,7 @@ Calls that stay un-evented (registry registration → explicit call → await):
A trigger/menu/pick pipeline with zero knowledge of "commands":
- The service holds only the source registry (`InputTriggerSource{trigger: '/'|'@', name, order?, candidates, onPick, matchSpace?, matchEnter?}`; (trigger,name) unique; the optional `order` sorts the roster — lower first, default 0, ties keep registration order — and that sorted roster is both group order and polling order) and `sessionOf(sctx)`. Implementing a match hook IS the declaration of participation in space/enter adjudication; the pipeline polls in roster order, the first non-undefined answer wins, and no claimant means the default sink. matchSpace is synchronous (space fires mid-keystroke; hot cache only); matchEnter is asynchronous (it may await the source's own warmup, and a warmup failure rejects).
- The controller holds the single authoritative hit (span included; retained for Space after the menu closes), the per-session menu store, the candidate-fetch generation, keyboard arbitration (combobox mode: focus stays in the composer surface, ↑↓/Enter/Escape are intercepted and all pass the IME composition guard, with the single exception Shift+Enter unconditionally going first), and pick orchestration (outcome → self-dispatched bail events). `toggleSource(name, syntheticHit)` is the chrome-launch path: it seeds only that registered source over the caller's composer selection and publishes `launcher = name` until close; ordinary typed tracking clears the launcher and restores the full trigger roster. Both paths render the same MenuView and execute the same `onPick` chain. A `dismiss()` verb backs MenuView's injected `onDismiss` (a pointer down outside both the menu and the surrounding composer card closes the menu; MenuView also localizes group titles through the `slash.menu` locale namespace and clamps its height to the viewport space above the composer via ui-primitives' `useAnchoredMaxHeight`); at each session scope's birth it runs `warm(projection)` once over the source roster — within that scope the projection holds only the stable sessionId, with no published/capability transitions; the scope disposer tears down the controller.
- The controller holds the single authoritative hit (span included; retained for Space after the menu closes), the per-session menu store, the candidate-fetch generation, keyboard arbitration (combobox mode: focus stays in the composer surface; ↑↓/Enter/Escape are intercepted; Tab settles a highlighted completion, using the candidate's drill action when available and its ordinary pick otherwise, while no highlight preserves native focus traversal; all arbitration passes the IME composition guard, with the single exception Shift+Enter unconditionally going first), and pick orchestration (outcome → self-dispatched bail events). `toggleSource(name, syntheticHit)` is the chrome-launch path: it seeds only that registered source over the caller's composer selection and publishes `launcher = name` until close; ordinary typed tracking clears the launcher and restores the full trigger roster. Both paths render the same MenuView and execute the same `onPick` chain. A `dismiss()` verb backs MenuView's injected `onDismiss` (a pointer down outside both the menu and the surrounding composer card closes the menu; MenuView also localizes group titles through the `slash.menu` locale namespace and clamps its height to the viewport space above the composer via ui-primitives' `useAnchoredMaxHeight`); at each session scope's birth it runs `warm(projection)` once over the source roster — within that scope the projection holds only the stable sessionId, with no published/capability transitions; the scope disposer tears down the controller.
- Trigger-detection word boundaries (`user@host` and URL `/` never trigger) and the guard tiers (plain: `/` everywhere + `@` inline / claimed: `/` suppressed, `@` live / frozen: none) are the frozen pure core.
### hub / facade: the resident shell and the strict-session input body
@@ -48,7 +48,7 @@ Status: implemented
对「命令」零知识的触发/菜单/pick 流水线:
- 服务只有 source 注册表(`InputTriggerSource{trigger: '/'|'@', name, order?, candidates, onPick, matchSpace?, matchEnter?}`;(trigger,name) 唯一;可选 `order` 对 roster 排序——越小越靠前、默认 0、同值保持注册序——排序后的 roster 同时是组序与轮询序)与 `sessionOf(sctx)`。实现 match 钩子即参与空格/回车裁决的声明;流水线按 roster 序轮询,首个非 undefined 应答胜出,无人认领落 default sink。matchSpace 同步(空格在击键中触发,只许热缓存);matchEnter 异步(可 await 源自身预热,预热失败即 reject)。
- controller 持有唯一权威 hit(含 span;菜单关闭后为 Space 保留)、每会话 menu store、候选 fetch generation、键盘仲裁(combobox 模式:焦点始终在编辑器表面,↑↓/Enter/Escape 拦截且全程过 IME composition 守卫,唯一例外 Shift+Enter 无条件先行),以及 pick 编排(outcome → 自派 bail 事件)。`toggleSource(name, syntheticHit)` 是 chrome launcher 路径:它基于调用方的编辑器 selection,只 seed 对应的已注册 source,并发布 `launcher = name` 直至关闭;普通的键入式 tracking 会清除 launcher 并恢复完整的 trigger roster。两条路径渲染同一个 MenuView,并执行同一条 `onPick` 链。`dismiss()` 动词支撑 MenuView 注入的 `onDismiss`(指针落在菜单与所在 composer 卡片之外即关闭菜单;MenuView 还经 `slash.menu` locale 命名空间本地化组标题,并经 ui-primitives 的 `useAnchoredMaxHeight` 把高度收敛到 composer 上方的视口空间);每个会话作用域出生时对 source roster 做一次 `warm(projection)`,projection 在该 scope 内只有稳定的 sessionId,无 published/能力跃迁;scope disposer 拆除 controller。
- controller 持有唯一权威 hit(含 span;菜单关闭后为 Space 保留)、每会话 menu store、候选 fetch generation、键盘仲裁(combobox 模式:焦点始终在编辑器表面;↑↓/Enter/Escape 会被拦截;Tab 会选定高亮补全项,候选项可下钻时走 drill 动作,否则走普通 pick,无高亮时保留原生焦点遍历;所有仲裁都经过 IME composition 守卫,唯一例外是 Shift+Enter 无条件先行),以及 pick 编排(outcome → 自派 bail 事件)。`toggleSource(name, syntheticHit)` 是 chrome launcher 路径:它基于调用方的编辑器 selection,只 seed 对应的已注册 source,并发布 `launcher = name` 直至关闭;普通的键入式 tracking 会清除 launcher 并恢复完整的 trigger roster。两条路径渲染同一个 MenuView,并执行同一条 `onPick` 链。`dismiss()` 动词支撑 MenuView 注入的 `onDismiss`(指针落在菜单与所在 composer 卡片之外即关闭菜单;MenuView 还经 `slash.menu` locale 命名空间本地化组标题,并经 ui-primitives 的 `useAnchoredMaxHeight` 把高度收敛到 composer 上方的视口空间);每个会话作用域出生时对 source roster 做一次 `warm(projection)`,projection 在该 scope 内只有稳定的 sessionId,无 published/能力跃迁;scope disposer 拆除 controller。
- 触发检测词边界(`user@host`、URL `/` 永不触发)、守卫分档(plain:`/` 到处 + `@` 行内 / claimed:`/` 抑制、`@` 活 / frozen:全无)为冻结纯核。
### hub / facade:常驻外壳与严格会话输入体
@@ -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
@@ -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.
@@ -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,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
@@ -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.
@@ -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,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
@@ -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.
@@ -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 .agents/notes/implemented/feature/2026-08-05-durable-web-schedule.md
2026-08-05-durable-web-schedule.md: 2a07d8257df6e940b316749a9b96a13abaf201dc
2026-08-05-durable-web-schedule.zh.md: c3a37f69ab74e5ededb7ca89c45ad9acfd029251
2026-08-05-durable-web-schedule.md: bac4a5cfd8965032dad2cf689ca42b1f8e5da1e3
2026-08-05-durable-web-schedule.zh.md: 266a90d3a56caccda56be9fe648c059939b8155f
@@ -60,7 +60,7 @@ Dispatch records queue admission, not model completion or user receipt. Framing
### Read-only Web catalog
The Schedule overlay enables the otherwise-disabled [`dsh-client-ui-schedule`](../../../../packages/client/ui-schedule/README.md) client together with the Host service. The complete active projection also feeds [`dsh-client-ui-workspace`](../../../../packages/client/ui-workspace/README.md). This note owns that opt-in read-only presentation boundary: the projection is current active state, not a dispatch or delivery receipt, so ordinary Assistant turns remain the delivery presentation.
The Schedule overlay enables the otherwise-disabled [`dsh-client-ui-schedule`](../../../../packages/client/ui-schedule/README.md) client together with the Host service. The complete active projection also feeds [`dsh-client-ui-workspace`](../../../../packages/client/ui-workspace/README.md). This note owns that opt-in read-only presentation boundary: the projection is current active state, not a dispatch or delivery receipt, so ordinary Assistant turns remain the delivery presentation. The catalog is a fixed `document.body` portal whose left edge follows the trigger when space permits and shifts left to retain a 16px viewport margin near the right edge. `useAnchoredPosition` owns measurement and resize, captured-scroll, panel-resize, and cleanup behavior; Schedule supplies the trigger and portal refs, bottom placement, a 5px gap, and the existing inside/outside dismissal boundary without adding a general popover abstraction.
## Alternatives considered
@@ -80,7 +80,7 @@ The Schedule overlay enables the otherwise-disabled [`dsh-client-ui-schedule`](.
## Verification
Package tests pin strict replay, one-shot and Every transitions, creation-anchor arithmetic, latest-only catch-up, multi-record batching, fork suffixes, id reuse, offset and local-calendar profiles, IANA validation, daylight-saving gaps and overlaps, time bounds, timer segmentation, wall-clock movement, overdue admission, fixed framing, enqueue and append failures, barrier recovery, projection registration and restoration, registration rollback, and quiescent disposal at per-file 100% coverage. A property test compares Every calculation and replay across varied intervals and skipped spans. A production JSONL restart test proves one overdue reminder dispatches through the real Agent lifecycle and does not redispatch after another restart. Focused client suites own catalog and sidebar behavior. Keyless assembled Web scenarios retain ordinary After/At/Every delivery evidence plus one Schedule-catalog smoke for overlay reachability, the current header catalog, ordinary/search alarms, narrow dark layout, and one live empty update.
Package tests pin strict replay, one-shot and Every transitions, creation-anchor arithmetic, latest-only catch-up, multi-record batching, fork suffixes, id reuse, offset and local-calendar profiles, IANA validation, daylight-saving gaps and overlaps, time bounds, timer segmentation, wall-clock movement, overdue admission, fixed framing, enqueue and append failures, barrier recovery, projection registration and restoration, registration rollback, and quiescent disposal at per-file 100% coverage. A property test compares Every calculation and replay across varied intervals and skipped spans. A production JSONL restart test proves one overdue reminder dispatches through the real Agent lifecycle and does not redispatch after another restart. Focused client suites own catalog and sidebar behavior, including the body portal, spacious left alignment, portal-inside pointer handling, outside dismissal, Escape, live empty, and timer cleanup. The shared primitive suite owns the positioning hook's resize, captured-scroll, panel-resize, and cleanup lifecycle. Keyless assembled Web scenarios retain ordinary After/At/Every delivery evidence plus one 900×900 Schedule-catalog smoke for overlay reachability, fixed portal placement, right-edge clamping, width and overflow, ordinary/search alarms, narrow dark layout, a light-theme browser screenshot, and one live empty update.
## Consequences
@@ -60,7 +60,7 @@ dispatch 记录的是队列准入,而不是模型完成或用户收到提醒
### 只读 Web 目录
Schedule overlay 会把默认禁用的 [`dsh-client-ui-schedule`](../../../../packages/client/ui-schedule/README.zh.md) client 与 Host 服务一同启用。完整活动 projection 也会交给 [`dsh-client-ui-workspace`](../../../../packages/client/ui-workspace/README.zh.md)。本 Note 拥有这条 opt-in 只读呈现边界:该 projection 表示当前活动状态,而非 dispatch 或交付回执,因此普通 Assistant 轮次仍是交付呈现。
Schedule overlay 会把默认禁用的 [`dsh-client-ui-schedule`](../../../../packages/client/ui-schedule/README.zh.md) client 与 Host 服务一同启用。完整活动 projection 也会交给 [`dsh-client-ui-workspace`](../../../../packages/client/ui-workspace/README.zh.md)。本 Note 拥有这条 opt-in 只读呈现边界:该 projection 表示当前活动状态,而非 dispatch 或交付回执,因此普通 Assistant 轮次仍是交付呈现。目录是挂到 `document.body` 的 fixed portal;空间足够时左边缘跟随触发按钮,靠近视口右侧时向左避让并保留 16px 边距。`useAnchoredPosition` 拥有测量以及 resize、捕获阶段 scroll、面板 resize 与清理行为;Schedule 提供触发器与 portal ref、bottom 放置、5px 间距和既有内外 dismissal 边界,不增加通用 popover 抽象。
## 已考虑的替代方案
@@ -80,7 +80,7 @@ Schedule overlay 会把默认禁用的 [`dsh-client-ui-schedule`](../../../../pa
## 验证
包测试以逐文件 100% coverage 固定严格回放、一次性与 Every 状态转换、创建锚点运算、只追赶最新一次、多记录批处理、fork 后缀、id 复用、偏移量与本地日历 profile、IANA 校验、夏令时缺口与重叠、时间边界、timer 分段、墙钟变化、overdue 准入、固定 framing、入队与 append 失败、barrier 恢复、projection 注册与恢复、注册 rollback 和完全停稳的 dispose。属性测试会在不同间隔与跳过跨度下比较 Every 计算与回放。production JSONL restart 测试证明一条 overdue 提醒会经过真实 Agent 生命周期 dispatch,并且再次 restart 后不会重复 dispatch。聚焦 client suite 拥有目录与侧边栏行为。无密钥组装 Web 场景保留普通 After/At/Every 交付证据,再由一个 Schedule 目录 smoke 覆盖 overlay 可达性、当前 header 目录、普通/搜索闹钟、窄屏暗色布局与一次 live empty 更新。
包测试以逐文件 100% coverage 固定严格回放、一次性与 Every 状态转换、创建锚点运算、只追赶最新一次、多记录批处理、fork 后缀、id 复用、偏移量与本地日历 profile、IANA 校验、夏令时缺口与重叠、时间边界、timer 分段、墙钟变化、overdue 准入、固定 framing、入队与 append 失败、barrier 恢复、projection 注册与恢复、注册 rollback 和完全停稳的 dispose。属性测试会在不同间隔与跳过跨度下比较 Every 计算与回放。production JSONL restart 测试证明一条 overdue 提醒会经过真实 Agent 生命周期 dispatch,并且再次 restart 后不会重复 dispatch。聚焦 client suite 拥有目录与侧边栏行为,包括 body portal、空间充足时的左对齐、portal 内指针处理、外部 dismissal、Escape、live empty 与 timer 清理。共享 primitive suite 拥有定位 hook 的 resize、捕获阶段 scroll、面板 resize 与清理生命周期。无密钥组装 Web 场景保留普通 After/At/Every 交付证据,再由一个 900×900 Schedule 目录 smoke 覆盖 overlay 可达性、fixed portal 定位、右侧钳制、宽度与 overflow、普通/搜索闹钟、窄屏暗色布局、浅色主题浏览器截图与一次 live empty 更新。
## 后果
@@ -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/feature/2026-08-20-web-streaming-fence-highlight.md
2026-08-20-web-streaming-fence-highlight.md: ccc961da1febba3611e3e558087b586c6f1f474b
2026-08-20-web-streaming-fence-highlight.zh.md: e5d29545bf659ed572d052f1212d68d344d49b5a
2026-08-20-web-streaming-fence-highlight.md: aa44a8c7ea91ff4913d92449d62a6ebf9406e922
2026-08-20-web-streaming-fence-highlight.zh.md: 88bae36928ac8d00960e529addeb4f30240e3579
@@ -10,17 +10,18 @@ While a reply streamed, `MarkdownText` stripped the fence language before `CodeB
## Decision
Streaming fences highlight incrementally through grammar-state resumption; the settled arm is unchanged.
Streaming fences parse, tokenize, and reconcile from retained frontiers; the settled output is unchanged.
- **`StreamingHighlightSession`** (`packages/client/ui-primitives/src/markdown/highlight.ts`) exploits that TextMate tokenization is line-based and forward-only: a line's tokens depend only on its own text and the grammar state entering it, so appended text never changes a completed line's tokens. The session caches completed lines' spans plus shiki's `GrammarState` after them (`getLastGrammarState`), and each update tokenizes newly completed text via `codeToTokensBase(…, { grammarState })` plus the still-growing last line. Per-chunk cost excludes the completed prefix; the result is token-identical to a from-scratch tokenization. Non-append input and a resolved-grammar change reset the cache and re-tokenize fully. Each run carries the style shiki's HTML arm would assign it — the css-variables color plus the markup font-style bits the theme lets through (bold/italic/underline; markdown fences carry them); whitespace-only runs fold into their following token as shiki's default `mergeWhitespaces` does (its underlined/struck-whitespace exemption cannot occur under this theme, whose only underline rule styles inline-link scopes that tokenize spaced text as one run); and a CRLF cut never leaks its `\r` into the last completed line, matching shiki's own line splitting — so the streaming spans and the settled `codeToHtml` swap render one identical span tree.
- **`CodeBlock`** gains a `streaming` prop: it renders the session's spans as a `pre.shiki.css-variables` React tree with the same attributes shiki's HTML emits, holds the session and per-line elements in refs, and reuses a retained line's element identity so React leaves that line's DOM untouched. Unknown or absent languages keep the identical-geometry plain arm; a lazy grammar renders plain until it registers, then the existing `useSyncExternalStore` load signal re-renders into highlight — one plain→highlighted transition, no flicker back.
- **`render.tsx`** passes `lang` and `context.streaming` to fences. Wrong-grammar transients are structurally impossible: a fence whose info string is still mid-chunk (`` ```py `` completing to `` ```python ``) has no content yet — content only exists after the info line's newline, which finalizes the language — and the empty-value fence keeps the stock `<pre>`. The streaming CodeBlock instance survives every chunk because streaming render keys are source offsets. `` ```math `` fences and TeX stay literal until the settled pass; the language banner shows the fence language during streaming.
- **`IncrementalMarkdownParser`** (`packages/client/ui-primitives/src/markdown/incremental.ts`) recognizes a parser-confirmed final unclosed top-level fence after the ordinary tail parse. Completed content remains in the retained `code` node; only the last completed line and current partial line pass through the caller's GFM grammar, preserving its newline, indentation, CRLF, and value semantics without re-parsing the fence prefix. A closing delimiter, non-append input, nested/container fence, or ambiguous reconstruction returns to the ordinary tail parse.
- **`StreamingHighlightSession`** (`packages/client/ui-primitives/src/markdown/highlight.ts`) exploits that TextMate tokenization is line-based and forward-only: a line's tokens depend only on its own text and the grammar state entering it, so appended text never changes a completed line's tokens. The session caches completed lines' spans plus shiki's `GrammarState` after them (`getLastGrammarState`); `updateFrame` publishes only newly completed lines plus the still-growing last line, while the compatibility `update` method materializes the complete result. Per-chunk tokenization excludes the completed prefix; the result is token-identical to a from-scratch tokenization. Non-append input and a resolved-grammar change reset the cache and re-tokenize fully. Each run carries the style shiki's HTML arm would assign it — the css-variables color plus the markup font-style bits the theme lets through (bold/italic/underline; markdown fences carry them); whitespace-only runs fold into their following token as shiki's default `mergeWhitespaces` does (its underlined/struck-whitespace exemption cannot occur under this theme, whose only underline rule styles inline-link scopes that tokenize spaced text as one run); and a CRLF cut never leaks its `\r` into the last completed line, matching shiki's own line splitting.
- **`CodeBlock`** renders the delta frames as a `pre.shiki.css-variables` React tree with the same attributes and token spans shiki's HTML emits. Completed lines seal into fixed-size React fragments; later updates reuse those fragment elements and reconcile only a bounded pending group plus the mutable tail. Unknown or absent languages keep the identical-geometry plain arm; a lazy grammar renders plain until it registers, then the existing `useSyncExternalStore` load signal re-renders into highlight — one plain→highlighted transition, no flicker back. Group size is an internal reconciliation unit, not a deployment policy or content limit.
- **`render.tsx` and `MarkdownText`** pass `lang` and `context.streaming` to fences and key both streaming and settled top-level blocks by source offset. Wrong-grammar transients are structurally impossible: a fence whose info string is still mid-chunk (`` ```py `` completing to `` ```python ``) has no content yet — content only exists after the info line's newline, which finalizes the language — and the empty-value fence keeps the stock `<pre>`. `` ```math `` fences and TeX stay literal until the settled pass; the language banner shows the fence language during streaming.
The settle swap re-renders through `highlightToHtml`: same tokens, same span tree, so the swap is visually invisible and never touches the code content.
The final full-document parse still resolves document-wide references and math. When that parse produces the same fence code and language, the source-offset key preserves its `CodeBlock` instance and the component reuses the complete streamed React tree; cold settled fences continue through `highlightToHtml`.
## Testing
Package tests cover incremental/from-scratch equivalence across multiline grammar state, blank lines, CRLF, and markup styles; cache identity and reset/lazy paths; streaming/settled token-tree parity; DOM retention; and plain or math fallbacks. The assembled Web browser snapshot boots the real Web composition, streams a TypeScript fence through the Host and SSE path, pauses the deterministic LLM adapter while the reply is still active, and snapshots Chromium's Shiki token tree before verifying that settlement preserves it. The `tests/fixtures/markdown-dom/*.streaming.txt` fixtures pin the intentional streaming divergence from their react-markdown origin: the Shiki span tree and visible language banner replace the plain arm.
Package tests bound the grammar input accumulated across 800 open-fence lines, compare each incremental result with a full parse, and cover indented delimiters, CRLF split across chunks, closure fallback, and non-append reset. Highlighter tests cover incremental/from-scratch equivalence across multiline grammar state, blank lines, CRLF, and markup styles; delta identity and reset/lazy paths; fixed-group DOM retention; streamed-to-settled DOM identity; and plain or math fallbacks. The assembled Web browser snapshot boots the real Web composition, streams a TypeScript fence through the Host and SSE path, pauses the deterministic LLM adapter while the reply is still active, and snapshots Chromium's Shiki token tree before verifying that settlement preserves it. The `tests/fixtures/markdown-dom/*.streaming.txt` fixtures pin the intentional streaming divergence from their react-markdown origin: the Shiki span tree and visible language banner replace the plain arm.
## Alternatives considered
@@ -28,10 +29,12 @@ Package tests cover incremental/from-scratch equivalence across multiline gramma
**Highlight only frozen (closed, settled-position) fences during streaming.** Bounded cost, but an unclosed fence pins the incremental parser's tail, so the actively growing fence — the one on screen — would stay plain until the reply finishes, failing the issue's "识别语言后即可增量高亮".
**Keep only a fixed window of highlighted lines and turn the older prefix into plain text.** This bounds live token DOM and can reduce layout further, but changes already rendered content, complicates selection across the window boundary, and makes a tunable presentation policy part of `CodeBlock`. Retained parser, tokenizer, and React frontiers remove the avoidable repeated work without discarding colors; the complete token DOM remains an explicit limitation rather than a hidden semantic change.
**Move highlighting to a worker or async pass.** Rejected when shiki was adopted ([synchronous highlighting note](../process/2026-07-26-web-syntax-highlighting-shiki.md)); an async swap also reintroduces the plain→colored→plain flicker class this change must avoid.
**Build the settled HTML string incrementally and keep `dangerouslySetInnerHTML`.** Exact settled parity for free, but React replaces the whole `innerHTML` per chunk, so the browser re-parses and rebuilds every line's DOM each time — O(fence) DOM churn that forfeits the token-level win the session provides.
## Consequences
Streaming code is readable as it arrives: tokens color as soon as the language is known, completed lines never re-tokenize or re-render, and the finalize swap is invisible for fences. The package owns a small mirror of shiki's HTML-arm conventions — the `pre` attributes and the whitespace fold — pinned by the arm-parity test, so a shiki upgrade that changes either fails loud there instead of drifting the two arms apart. The streaming DOM-parity fixtures pin Shiki span trees as an intentional divergence from their react-markdown origin. The still-growing last line re-tokenizes per chunk (bounded by one line), and a pathological single-line fence still degrades to full re-tokenization per chunk — the same degradation class the incremental block parser accepts for a single giant block.
Streaming code is readable as it arrives: tokens color as soon as the language is known; completed top-level fence content neither re-parses nor re-tokenizes; sealed React groups keep their elements and DOM; and settlement preserves the highlighted tree. The package owns a small mirror of shiki's HTML-arm conventions — the `pre` attributes and the whitespace fold — pinned by the arm-parity test, so a shiki upgrade that changes either fails loud there instead of drifting the two arms apart. The streaming DOM-parity fixtures pin Shiki span trees as an intentional divergence from their react-markdown origin. The retained DOM still grows with final token count, so browser style and layout work is not length-independent. Nested/container fences use the ordinary tail parser, and the still-growing last line re-tokenizes per chunk; a pathological single-line fence therefore remains the worst case.
@@ -10,17 +10,18 @@ Status: implemented
## Decision
流式围栏通过 grammar state 续接实现增量高亮;定稿臂保持不变。
流式围栏从保留的解析、tokenize 与 reconcile 前沿继续推进;定稿输出保持不变。
- **`StreamingHighlightSession`**(`packages/client/ui-primitives/src/markdown/highlight.ts`)利用 TextMate tokenize 按行、且只向前推进的性质:一行的 token 只取决于该行文本与进入该行时的 grammar state,因此追加的文本永远不会改变已完成行的 token。会话缓存已完成行的 span 以及其后的 shiki `GrammarState`(`getLastGrammarState`),每次更新通过 `codeToTokensBase(…, { grammarState })` tokenize 新完成的文本,外加仍在增长的最后一行。每分片成本不包含已完成的前缀;结果与从头 tokenize 逐 token 一致。非追加输入与解析后语法变化会重置缓存并完整重新 tokenize。每个 run 携带 shiki HTML 臂会赋予它的样式——css-variables 颜色加上主题放行的 markup 字体位(bold/italic/underline;markdown 围栏会携带它们);纯空白 run 并入其后的 token,与 shiki 默认的 `mergeWhitespaces` 一致(其对带下划线/删除线空白的豁免在该主题下不可能出现:主题唯一的 underline 规则作用于 inline-link scope,其含空格文本整体成一个 run);CRLF 切割点的 `\r` 绝不进入最后一个已完成行,与 shiki 自身的行切分一致——因此流式 span 与定稿 `codeToHtml` 换入的 span 树完全一致。
- **`CodeBlock`** 新增 `streaming` prop:把会话的 span 渲染为带有 shiki HTML 同款属性的 `pre.shiki.css-variables` React 树,用 ref 持有会话与逐行元素,并复用保留行的元素标识,让 React 完全不触碰该行的 DOM。未知或缺失语言保持几何一致的纯文本臂;懒加载语法在注册前渲染纯文本,注册后由既有的 `useSyncExternalStore` 加载信号触发重渲染进入高亮——只有一次纯文本→高亮的转换,不会闪回。
- **`render.tsx`** 向围栏传递 `lang` 与 `context.streaming`。错误语法的瞬时着色在结构上不可能出现:info string 尚在分片中途的围栏(`` ```py `` 补全为 `` ```python ``)还没有内容——内容只在 info 行的换行之后才存在,而该换行恰恰定格了语言——空值围栏保持原生 `<pre>`。流式渲染 key 是源偏移,围栏的 CodeBlock 实例因此跨分片存活。`` ```math `` 围栏与 TeX 在定稿前保持字面量;语言横幅在流式期间显示围栏语言。
- **`IncrementalMarkdownParser`**(`packages/client/ui-primitives/src/markdown/incremental.ts`)会在普通尾部解析后识别经 parser 确认、位于末尾且未闭合的顶层 fence。已完成内容保留在既有 `code` node 中;只有最后一个已完成行与当前未完成行再次进入调用方的 GFM grammar,因此无需重新解析 fence 前缀,也能保留其换行、缩进、CRLF 与 value 语义。出现闭合分隔符、非追加输入、嵌套/容器内 fence 或无法明确重建时,会回到普通尾部解析。
- **`StreamingHighlightSession`**(`packages/client/ui-primitives/src/markdown/highlight.ts`)利用 TextMate tokenize 按行、且只向前推进的性质:一行的 token 只取决于该行文本与进入该行时的 grammar state,因此追加的文本永远不会改变已完成行的 token。会话缓存已完成行的 span 以及其后的 shiki `GrammarState`(`getLastGrammarState`);`updateFrame` 只发布新完成行与仍在增长的最后一行,兼容方法 `update` 则物化完整结果。每分片 tokenize 成本不包含已完成的前缀;结果与从头 tokenize 逐 token 一致。非追加输入与解析后语法变化会重置缓存并完整重新 tokenize。每个 run 携带 shiki HTML 臂会赋予它的样式——css-variables 颜色加上主题放行的 markup 字体位(bold/italic/underline;markdown 围栏会携带它们);纯空白 run 并入其后的 token,与 shiki 默认的 `mergeWhitespaces` 一致(其对带下划线/删除线空白的豁免在该主题下不可能出现:主题唯一的 underline 规则作用于 inline-link scope,其含空格文本整体成一个 run);CRLF 切割点的 `\r` 绝不进入最后一个已完成行,与 shiki 自身的行切分一致。
- **`CodeBlock`** 把增量 frame 渲染为带有 shiki HTML 同款属性与 token span 的 `pre.shiki.css-variables` React 树。已完成行会封入固定大小的 React fragment;后续更新复用这些 fragment element,只 reconcile 一个有界的待完成分组与可变尾部。未知或缺失语言保持几何一致的纯文本臂;懒加载语法在注册前渲染纯文本,注册后由既有的 `useSyncExternalStore` 加载信号触发重渲染进入高亮——只有一次纯文本→高亮的转换,不会闪回。分组大小只是内部 reconcile 单元,不是部署策略或内容上限。
- **`render.tsx` 与 `MarkdownText`** 向围栏传递 `lang` 与 `context.streaming`,并让流式和定稿的顶层 block 都按源偏移设置 key。错误语法的瞬时着色在结构上不可能出现:info string 尚在分片中途的围栏(`` ```py `` 补全为 `` ```python ``)还没有内容——内容只在 info 行的换行之后才存在,而该换行恰恰定格了语言——空值围栏保持原生 `<pre>`。`` ```math `` 围栏与 TeX 在定稿前保持字面量;语言横幅在流式期间显示围栏语言。
定稿切换经 `highlightToHtml` 重渲染:token 相同、span 树相同,切换在视觉上不可见,也绝不触碰代码内容。
最终的全量文档解析仍会解决跨文档引用与数学语法。当该解析产生相同的 fence 代码与语言时,源偏移 key 会保留其 `CodeBlock` 实例,组件则复用完整的流式 React 树;冷启动的定稿 fence 继续使用 `highlightToHtml`。
## Testing
包测试覆盖跨多行 grammar state、空行、CRLF 与 markup 样式的增量/从头等价性,缓存标识与重置/懒加载路径,流式/定稿 token 树一致性,DOM 保留,以及纯文本和 math 回退。组装后的 Web 浏览器快照会启动真实 Web 组合,让 TypeScript 围栏经过 Host 与 SSE 路径流式传输,在回复仍活跃时暂停确定性 LLM 适配器并对 Chromium 中的 Shiki token 树做快照,然后验证定稿保留该 token 树。`tests/fixtures/markdown-dom/*.streaming.txt` fixture 锁定相对 react-markdown 来源的一项有意分叉:Shiki span 树与可见语言横幅取代纯文本臂。
包测试会约束 800 行未闭合 fence 的累计 grammar 输入量、逐次比较增量结果与全量解析,并覆盖缩进分隔符、跨分片 CRLF、闭合回退与非追加重置。高亮测试覆盖跨多行 grammar state、空行、CRLF 与 markup 样式的增量/从头等价性,delta 标识与重置/懒加载路径,固定分组的 DOM 保留,从流式到定稿的 DOM 标识,以及纯文本和 math 回退。组装后的 Web 浏览器快照会启动真实 Web 组合,让 TypeScript 围栏经过 Host 与 SSE 路径流式传输,在回复仍活跃时暂停确定性 LLM 适配器并对 Chromium 中的 Shiki token 树做快照,然后验证定稿保留该 token 树。`tests/fixtures/markdown-dom/*.streaming.txt` fixture 锁定相对 react-markdown 来源的一项有意分叉:Shiki span 树与可见语言横幅取代纯文本臂。
## Alternatives considered
@@ -28,10 +29,12 @@ Status: implemented
**流式期间只高亮已冻结(闭合且位置定格)的围栏。** 成本有界,但未闭合围栏会钉住增量解析器的尾部,于是正在增长的围栏——屏幕上的那个——要等回复结束才高亮,不满足 issue 的"识别语言后即可增量高亮"。
**只保留固定窗口内的高亮行,并把更早的前缀转成纯文本。** 这能限制流式 token DOM 并进一步降低布局成本,但会改变已经渲染的内容、让跨窗口边界的选择更复杂,还会把可调的展示策略塞进 `CodeBlock`。保留解析、tokenize 与 React 前沿可以在不丢颜色的情况下消除可避免的重复工作;完整 token DOM 被明确记录为限制,而不是隐藏的语义变化。
**把高亮移到 worker 或异步流程。** 采纳 shiki 时已否决([同步高亮笔记](../process/2026-07-26-web-syntax-highlighting-shiki.zh.md));异步换入还会重新引入本变更必须避免的纯文本→彩色→纯文本闪烁类问题。
**增量拼接定稿 HTML 字符串并继续使用 `dangerouslySetInnerHTML`。** 白得定稿一致性,但 React 每个分片都会整体替换 `innerHTML`,浏览器每次重新解析并重建所有行的 DOM——O(围栏) 的 DOM 翻搅,抵消了会话在 token 层的收益。
## Consequences
流式代码随到达即可读:语言一经识别 token 即着色,已完成行绝不重新 tokenize 或重渲染,定稿切换对围栏而言不可见。该包持有一小份 shiki HTML 臂约定的镜像——`pre` 属性与空白折叠——由双臂一致性测试锁定,shiki 升级若改变任一处会在该测试处响亮失败,而不是让两臂悄然漂移。流式 DOM 一致性 fixture 锁定 Shiki span 树,这是相对其 react-markdown 来源的一项有意分叉。仍在增长的最后一行每分片重新 tokenize(以一行为界);病态的单行超长围栏仍退化为每分片完整重新 tokenize——与增量块解析器对单个巨型块接受的是同一退化类。
流式代码随到达即可读:语言一经识别 token 即着色;顶层 fence 的已完成内容不再重新解析或 tokenize;封存的 React 分组保留其 element 与 DOM;定稿也会保留高亮树。该包持有一小份 shiki HTML 臂约定的镜像——`pre` 属性与空白折叠——由双臂一致性测试锁定,shiki 升级若改变任一处会在该测试处响亮失败,而不是让两臂悄然漂移。流式 DOM 一致性 fixture 锁定 Shiki span 树,这是相对其 react-markdown 来源的一项有意分叉。保留的 DOM 仍随最终 token 数增长,因此浏览器 style 与 layout 工作量并非与长度无关。嵌套/容器内 fence 使用普通尾部解析器,仍在增长的最后一行则会每分片重新 tokenize;病态的单行超长 fence 因而仍是最坏情况。
@@ -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/feature/2026-08-25-loaded-turn-chat-navigation.md
2026-08-25-loaded-turn-chat-navigation.md: 5d9d93b07f7a8c527bf7376bf111c6a709afa4d1
2026-08-25-loaded-turn-chat-navigation.zh.md: 21dba024710b306848fee9bc4fe1f16913c475b3
2026-08-25-loaded-turn-chat-navigation.md: b01e64d23fbc87f61c0de5b32cdf293c8d0afa94
2026-08-25-loaded-turn-chat-navigation.zh.md: 85397c4a33cbc4ff1a08d253845f0112fe9b051b
@@ -18,7 +18,7 @@ The rail renders the complete loaded Turn set with a 10px natural interval and n
The rail sits against the scrollport's right edge and centers on the band the sticky composer leaves visible. That band is the scrollport's own height minus the seat's, so ConversationRoot publishes `--dsh-conversation-viewport-height` beside the `--dsh-composer-height` it already measures on the same element, and the rail centers on their difference instead of a viewport height that ignores the Session header.
The active mark follows a reading line near the top of the shared Chat scrollport. A scroll frame resolves the owning Turn with one hit test at that line, falling back to a single row scan where layout cannot answer, so cost does not grow with the number of marks. Flow-height changes that move rows across the line without a scroll event resync through the existing column observer. Scroll updates are coalesced with `requestAnimationFrame`; reaching the bottom selects the final loaded Turn. Activating a mark computes the target node's position in the existing scroll coordinate system, moves that same scrollport, and records the resulting Chat scroll-restoration anchor.
The active mark follows a reading line near the top of the shared Chat scrollport. A pinned frame selects the final loaded Turn from scroll distance before reading any row geometry; streaming and other observed height changes can therefore follow the floor without a hit test or scan. Away from the floor, a scroll frame resolves the owning Turn with one hit test at the reading line, falling back to a single row scan where layout cannot answer, so cost does not grow with the number of marks. Flow-height changes that move rows across the line without a scroll event resync through the existing column observer. Scroll updates are coalesced with `requestAnimationFrame`. Activating a mark computes the target node's position in the existing scroll coordinate system, moves that same scrollport, and records the resulting Chat scroll-restoration anchor.
Every Turn remains an accessible button even when dense marks visually overlap. The rail maps pointer height to the nearest loaded Turn, while keyboard focus and activation operate the individual buttons. Hover and focus show a compact prompt-and-response preview, the active mark is longer and darker, the rail is hidden when the Chat container is at most 900px wide, and reduced-motion preferences disable redistribution and mark-entry animation.
@@ -42,4 +42,4 @@ Desktop-width Chat views can jump among all currently loaded Turns and inspect a
## Testing
Builder tests pin the accumulated projection, the bounded preview, and preview freshness under an in-place chunk update. Component tests pin the published items, accessible previews, scroll-coordinate jumps, DOM identity, and percentage redistribution after prepend. The long-interaction Chromium scenario pins the real paginated boundary, prompt completion after `Load earlier`, stable-mark movement, keyboard activation, active-state update, and the narrow-container hide. The multi-Turn recorded Web snapshot includes the navigation landmark and buttons.
Builder tests pin the accumulated projection, the bounded preview, and preview freshness under an in-place chunk update. Component tests pin the published items, accessible previews, scroll-coordinate jumps, DOM identity, percentage redistribution after prepend, and a pinned `ResizeObserver` update that rejects every row-geometry read. The long-interaction Chromium scenario pins the real paginated boundary, prompt completion after `Load earlier`, stable-mark movement, keyboard activation, active-state update, and the narrow-container hide. The multi-Turn recorded Web snapshot includes the navigation landmark and buttons.
@@ -18,7 +18,7 @@ Chat snapshot 构建层为当前已加载且含可见 transcript node 的每个
轨道紧贴滚动视口右缘,并在粘性输入区之外的可见区间内垂直居中。该区间等于滚动视口自身高度减去输入区高度,因此 ConversationRoot 在同一元素上除已有的 `--dsh-composer-height` 外再发布 `--dsh-conversation-viewport-height`,轨道按两者之差居中,而不是按忽略 Session 头部的视口高度居中。
活跃刻度跟随共享 Chat 滚动区顶部附近的阅读线。每个滚动帧用一次命中测试解析该行所属 Turn,布局无法作答时退化为一次行扫描,成本不随刻度数量增长。图片加载、工具卡展开等不产生滚动事件的高度变化,通过既有的 column observer 重新同步。滚动更新由 `requestAnimationFrame` 合并;到达底部时选择最后一个已加载 Turn。激活刻度会在现有滚动坐标系中计算目标 node 的位置,移动同一个滚动区,并记录由此产生的 Chat 滚动恢复锚点。
活跃刻度跟随共享 Chat 滚动区顶部附近的阅读线。跟随底部的 frame 会先按滚动距离选中最后一个已加载 Turn,不读取任何行几何;流式输出及其他被 observer 捕获的高度变化因此无需命中测试或扫描即可追随底部。离开底部后,每个滚动 frame 用一次命中测试解析阅读线所属 Turn,布局无法作答时退化为一次行扫描,成本不随刻度数量增长。不产生滚动事件却让行跨过阅读线的高度变化通过既有的 column observer 重新同步。滚动更新由 `requestAnimationFrame` 合并。激活刻度会在现有滚动坐标系中计算目标 node 的位置,移动同一个滚动区,并记录由此产生的 Chat 滚动恢复锚点。
即使密集刻度在视觉上重叠,每个 Turn 仍是可访问的按钮。轨道把指针高度映射到最近的已加载 Turn,键盘聚焦和激活则作用于各个按钮。悬停或聚焦显示紧凑的问题与回复预览,活跃刻度更长、更深;Chat 容器宽度不超过 900px 时隐藏轨道,用户偏好减少动态效果时关闭重排和刻度入场动画。
@@ -42,4 +42,4 @@ Chat snapshot 构建层为当前已加载且含可见 transcript node 的每个
## 测试
构建层测试固定累积投影、预览截断,以及原地 chunk 更新后的预览新鲜度。组件测试固定已发布条目、可访问预览、滚动坐标跳转、DOM 身份以及前插后的百分比重排。长交互 Chromium 场景固定真实分页边界、`加载更早` 后补齐问题、稳定刻度移动、键盘激活、活跃状态更新与窄容器隐藏。多 Turn 的 Web 录制快照包含导航 landmark 和按钮。
构建层测试固定累积投影、预览截断,以及原地 chunk 更新后的预览新鲜度。组件测试固定已发布条目、可访问预览、滚动坐标跳转、DOM 身份、前插后的百分比重排,以及拒绝任何行几何读取的底部跟随 `ResizeObserver` 更新。长交互 Chromium 场景固定真实分页边界、`加载更早` 后补齐问题、稳定刻度移动、键盘激活、活跃状态更新与窄容器隐藏。多 Turn 的 Web 录制快照包含导航 landmark 和按钮。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# 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/feature/2026-08-30-web-turn-rail-outline-jump.md
2026-08-30-web-turn-rail-outline-jump.md: af2a464513d108429859c4f9ed8b4bfc58175e3c
2026-08-30-web-turn-rail-outline-jump.zh.md: b63b1c1f656689997b8a8266ee332dfdb47d4035
@@ -0,0 +1,35 @@
# Agent Note: Full-session turn rail with outline projection and jump paging
Status: implemented
English | [中文](2026-08-30-web-turn-rail-outline-jump.zh.md)
## Problem
The web chat's turn rail derived its marks from the loaded event window, and the window is a paged suffix of the log (50-message tail, `Load earlier` per page). In a long session the rail therefore named only the most recent turns: history that had not been paged in was invisible to navigation, unreachable except by clicking `Load earlier` repeatedly, and the rail squeezed whatever it did show into a fixed frame by compressing mark spacing to percentages, so a many-turn session degenerated into an unreadable dense strip.
## Decision
Three cooperating pieces, each useful alone.
**Data: the `turnOutline` session projection.** `packages/session/session-turn-outline` registers one pure fold on `ctx.sessionProjections`: every `turn/start` appends an entry (skipping boundaries that do not advance the turn number, keeping the outline strictly increasing), the turn's first human `user/message` fills the prompt preview, and the newest text-bearing `assistant/message` buffers a response draft that `turn/end` commits (`turn/end` itself carries no text). Preview budgets mirror the rail card's clamps — one prompt line at 50 characters, up to three response lines at 120, an ellipsis marking a clip — and match the loaded-turn previews so a turn shows the same words before and after its events load. The wire value is the bare entry array so draft-only state changes keep its identity, and the feed's identity gate (below) then holds pushes to three per turn: boundary, prompt, settled response. The value rides the existing projection carriers — tail-page seed, `session/projection` control frames, projcache — and the web-app bundle mounts the plugin. `seq` is the `turn/start` event seq: the loop logs it before the turn's prompt and steps, so paging a window back through that seq loads the whole turn.
**Change-feed identity gate (session-projection).** Each live unit cell keeps `[previousView, currentView]` raw outputs. When a state reference changes, the drive shifts current to previous; while a change listener exists it computes `view(nextState)` once, stores current, and emits only when the two outputs differ by `Object.is`. Without listeners, current becomes `undefined` without evaluating `view`, so the first later computed value publishes conservatively; catch-up folding invalidates current in the same way. This lets a unit buffer working fields (the response draft) in state behind an identity-stable projection instead of pushing its whole value per streamed assistant message; units whose views build fresh objects per call are unaffected. The alternative — value-equality dedup in the carrier by serialized comparison — is rejected because every quiet change would pay for full serialization.
**Paging: `Session.loadThrough(seq)`.** The session-controller client gains a jump loader beside `loadOlder()`: it loops the existing prepend pager in 200-message pages (`JUMP_PAGE_MESSAGES`) until `baseSeq <= seq`, lowers a shared low-water target when called again mid-jump, stops on a page that leaves `baseSeq` unmoved (the no-progress guard against an empty page still claiming history), and reports busy through the existing `loadingOlder` snapshot bit. No wire change: seqs are dense, so the client computes everything from `beforeSeq` arithmetic.
**View: merge, jump, and the fixed-pitch rail.** `mergeTurnRailItems` (ui-chat, view layer — the conversation snapshot still never carries projection values) unions the outline with the loaded rail items into `TurnRailItem`s discriminated by `anchor: loaded(key) | unloaded(seq)`; loaded wins per turn, and the outline prompt fills a mid-turn window head's empty preview. Activating an unloaded mark releases bottom ownership on the click itself (jumping into history is leaving the live tail; otherwise the pinned-scroll snap racing the first prepend's compensation would call `toBottom` and cancel the jump), holds the reader's place with the existing paging anchor, calls `loadThrough`, and lands after React commits — no height estimation: a mid-paging landing pins the target row as the paging anchor so later chunks and the `Load earlier` button's unmount cannot drift it, and the loader's completion runs one final correction unless the reader already scrolled off the target (settlement otherwise repages once per head movement, then falls back to the nearest rendered turn). The rail itself keeps a fixed 10px pitch: the ladder scrolls inside the old frame geometry behind a hidden scrollbar, gradient fades mark each still-scrollable end, the hover preview compensates the rail scroll, and the active mark keeps itself centred while the pointer is off the rail. Unloaded marks render short and dimmed with a `Load and jump to turn N` label and pulse while their jump pages.
## Alternatives considered
**Sparse or segmented windows** (load only the target turn's neighbourhood): rejected — window contiguity is the foundation the transport validation, assembler, timeline, and scroll anchoring all share; a discontiguous window is a different architecture, deferred until sessions outgrow full paging.
**A `minSeq` page bound on the wire** (one targeted request instead of the client loop): rejected for v1 — the loop needs no protocol change, yields natural per-chunk progress, and Codex's TUI uses the same recursive page-pull shape for its jump-to-start; the single unbounded frame can be revisited if round trips ever dominate.
**A dedicated outline RPC**: rejected — the projection seam already provides the consistency cut with the tail page, live push, persistence, and capability-absence fallback that a bespoke endpoint would have to rebuild.
**Estimated row heights for jump positioning**: rejected — transcript rows vary wildly (tool cards, images, code), so estimation jitters; landing after commit is exact and matches Codex's deferred `pending_scroll_chunk` realization.
## Consequences
The rail is now session-scoped rather than window-scoped, at the cost of a whole-value projection that grows with the session (up to ~600 bytes per turn at full CJK preview budgets, pushed at most three times per turn); splitting previews into an on-demand read is deferred until multi-thousand-turn sessions need it. A deep jump still loads every intervening page — the contiguous-window contract — so jumping to turn 1 of a huge session materializes the whole transcript, as manual paging always did. Assemblies without the projection plugin keep the old loaded-only rail. Coverage: projection unit + Loader-composition + HMR specs in the new package, `loadThrough` loop specs in session-controller, merge and jump specs in ui-chat (including the settle correction and busy lifecycle), and a browser contract in the chat-scroll e2e that drives a keyboard jump from an 88-turn fixture's tail to its unloaded first turn and asserts the landing geometry and rail fades.
@@ -0,0 +1,35 @@
# Agent Note: 基于大纲投影与跳转分页的整会话轮次导航栏
Status: implemented
[English](2026-08-30-web-turn-rail-outline-jump.md) | 中文
## Problem
Web 聊天的轮次导航栏从已加载的事件窗口推导刻度,而窗口是日志的分页后缀(50 条 message 的尾页,每次 `加载更早` 一页)。长会话里导航栏因此只列出最近的轮次:尚未分页载入的历史对导航不可见,除了反复点 `加载更早` 无法到达,且导航栏把已显示的刻度按百分比压缩进固定外框,多轮会话退化成不可读的密集条带。
## Decision
三个相互配合、各自独立可用的部分。
**数据:`turnOutline` 会话投影。** `packages/session/session-turn-outline` 在 `ctx.sessionProjections` 上注册一个纯 fold:每个 `turn/start` 追加一个条目(跳过未推进轮次号的边界,保持大纲严格递增),该轮首条人类 `user/message` 填入提示词预览,最新一条带文本的 `assistant/message` 缓冲为回复草稿、由 `turn/end` 提交(`turn/end` 自身不带文本)。预览预算对齐导航卡片的截断——提示词一行 50 字符、回复至多三行 120 字符、被裁剪时补省略号——并与已加载轮次的预览一致,同一轮在事件载入前后显示相同的文字。wire 值是裸条目数组,纯草稿的状态变化因此保持其身份,配合下述变更流身份门把推送压到每轮三次:开轮、提示词、落定回复。值搭现有投影载体——尾页 seed、`session/projection` 控制帧、projcache——web-app bundle 挂载该插件。`seq` 是 `turn/start` 事件的 seq:loop 先记它再记该轮的提示词与步骤,窗口向后分页越过该 seq 即载入整轮。
**变更流身份门(session-projection)。** 每个实时单元 cell 保存 `[previousView, currentView]` 原始输出。state 引用变化时,drive 先把 current 移到 previous;存在变更 listener 时只计算一次 `view(nextState)` 并写入 current,两个输出通过 `Object.is` 判定为不同时才发出通知。没有 listener 时不计算 `view`,而是把 current 写成 `undefined`,因此之后首次计算出的值会保守地发布;补折叠也以相同方式使 current 失效。这让单元可以把工作字段(回复草稿)缓冲在身份稳定投影之后的 state 里,而不是每条流式助手消息都推送整值;view 每次新建对象的单元不受影响。备选——在载体侧按序列化比较去重——被否决,因为每次安静变化都要付一次完整序列化。
**分页:`Session.loadThrough(seq)`。** session-controller 客户端在 `loadOlder()` 旁新增跳转加载器:按 200 条 message 一页(`JUMP_PAGE_MESSAGES`)循环现有 prepend 分页器直到 `baseSeq <= seq`,跳转中再次调用会下调共享低水位目标,遇到 `baseSeq` 未动的页即停(对空页仍声称有历史的无进展守卫),忙碌状态复用现有 `loadingOlder` 快照位。零 wire 改动:seq 稠密,客户端仅凭 `beforeSeq` 算术即可。
**视图:合并、跳转与固定间距导航栏。** `mergeTurnRailItems`(ui-chat,视图层——会话快照仍不携带投影值)把大纲与已加载条目并成以 `anchor: loaded(key) | unloaded(seq)` 判别的 `TurnRailItem`;同轮已加载者优先,大纲提示词填补窗口头部半轮的空预览。激活未加载刻度在点击当下即交出钉底所有权(跳进历史就是离开活跃尾部;否则钉底吸附与首个 prepend 补偿的竞态会触发 `toBottom` 取消跳转),再用现有分页锚点稳住读者位置、调用 `loadThrough`、在 React 提交后落点——不做任何高度估算:分页中途的落点把目标行钉为分页锚点,后续分片与 `加载更早` 按钮的卸载都不会使落点漂移,加载器完结时再做一次最终校正,除非读者已主动滚离目标(settlement 否则按窗口头每前进一次重发一次分页,再兜底落到最近的已渲染轮次)。导航栏本身保持固定 10px 间距:阶梯在原外框几何内隐藏滚动条滚动,渐变淡出标示仍可滚动的端点,悬浮预览补偿导航栏滚动量,指针不在栏上时活跃刻度自动保持居中。未加载刻度以短而暗的形态呈现,标签为「加载并跳转到第 N 轮」,其跳转分页期间脉冲闪烁。
## Alternatives considered
**稀疏/分段窗口**(只加载目标轮附近):拒绝——窗口连续性是 transport 校验、assembler、timeline 与滚动锚定共同依赖的地基;不连续窗口是另一套架构,推迟到会话规模超出全量分页时再议。
**wire 上加 `minSeq` 页边界**(单发定向请求替代客户端循环):v1 拒绝——循环零协议改动、自带逐片进度,Codex TUI 的跳到开头也是同款递归拉页形态;若往返耗时成为瓶颈再重启无界单帧方案。
**专用大纲 RPC**:拒绝——投影 seam 已自带与尾页的一致性切面、实时推送、持久化与能力缺席回退,专用端点得重造这一切。
**估算行高定位跳转**:拒绝——transcript 行高方差极大(工具卡、图片、代码),估算必抖;提交后落点零误差,且与 Codex 延迟兑现的 `pending_scroll_chunk` 同构。
## Consequences
导航栏从窗口口径变为会话口径,代价是随会话增长的整值投影(全中文预览预算下每轮上限约 600 字节,每轮至多推送三次);把预览拆成按需读取推迟到数千轮量级的会话真正需要时。深跳仍会加载沿途所有页——连续窗口契约——跳到超长会话的第 1 轮会实体化整个 transcript,与手动翻页的终态相同。未挂载该投影插件的装配保留旧的仅已加载导航。覆盖:新包的投影单元 + Loader 组合 + HMR 测试、session-controller 的 loadThrough 循环测试、ui-chat 的合并与跳转测试(含 settle 校正与忙碌生命周期),以及 chat-scroll e2e 里的浏览器契约——在 88 轮 fixture 的尾部用键盘跳到未加载的第 1 轮,断言落点几何与导航栏渐变。
@@ -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/process/2026-08-08-native-windows-pull-request-ci.md
2026-08-08-native-windows-pull-request-ci.md: ff01add055b6daa3cd2ea1dd774c4c8973388113
2026-08-08-native-windows-pull-request-ci.zh.md: 5378607687d03f1c98b4f6abc0b65b5d8e9ed2bb
2026-08-08-native-windows-pull-request-ci.md: ade3b19bc1adbcd75ec7d3908670b9664186cba8
2026-08-08-native-windows-pull-request-ci.zh.md: 10db2657a7f02813152d2905693627e44ce6caf7
@@ -18,9 +18,9 @@ Every pull request also starts four independent native jobs on the organization-
`windows-build` and `windows-native-tests` are dependencies of `all checks passed`; their workspace-build and targeted native-process results are blocking. `windows-coverage` remains an ordinary job but is absent from aggregate `needs`, so its 100%-per-file result stays red and visible without delaying the required verdict. `windows-observational` is also absent from aggregate `needs` and uses `continue-on-error` because Linux owns the blocking static, documentation, package, and built-artifact verdicts.
`windows-coverage` completes a workspace build before [in-job partitioned coverage](2026-08-18-in-job-partitioned-coverage.md) starts four single-worker instrumented shards beside a two-worker exempt-heavy gate. Both coverage gates set Vitest's default per-test and polling budgets to 30 seconds. `windows-observational` owns its own workspace build and production-site validation, starts the independent static gates together, and caps `publint` at eight workers. Its built-bin smoke starts only after every other observational gate settles; the smoke's `needs` edge still requires a successful build, while its `after` edges preserve the diagnostic after another gate fails. This keeps bounded real-application startup measurements from competing with tool-catalog, NodeNext, package, and documentation processes. The script-only translation-pairing merge suite runs in the exempt-heavy gate because it imports only `scripts/` sources and child processes; V8 instrumentation contributes no threshold coverage there but magnifies Git-process latency. Lefthook concurrency fixtures retain their outcomes with 30-second case budgets and a 10-second process-ready probe, while the installer allows five seconds for a preempted lock owner to publish its record after exclusive creation. Directory-picker composition gives its debounced config write an explicit 15-second poll budget; workspace-context composition fixtures use a test-owned signal without an unrelated one-second deadline. The LSP sources and the ACL-sandbox sources remain in the Windows denominator: stub-based failure-path suites carry every in-process ACL-sandbox file to 100%, and only the runner entry stays excluded — it executes exclusively as a spawned child outside the instrumented run, its behavior pinned end-to-end by the runner suite. Narrow annotated V8 ignores cover only unreachable branches (peer-platform arms and lifecycle-unreachable guards), with their behavior tests retained on the owning platform.
`windows-coverage` runs [in-job partitioned coverage](2026-08-18-in-job-partitioned-coverage.md) without a preceding build, matching the Linux coverage lane: four single-worker instrumented shards beside a two-worker exempt-heavy gate; workspace imports resolve to `src` through the tsconfig paths map, and the lib-consuming suites self-skip on unbuilt checkouts. Both coverage gates raise Vitest's per-test, expect.poll, and hook budgets through `DSH_COVERAGE_TEST_TIMEOUT_MS=90000`. `windows-observational` owns its own workspace build and production-site validation, starts the independent static gates together, and caps `publint` at eight workers. Its built-bin smoke starts only after every other observational gate settles; the smoke's `needs` edge still requires a successful build, while its `after` edges preserve the diagnostic after another gate fails. This keeps bounded real-application startup measurements from competing with tool-catalog, NodeNext, package, and documentation processes. The script-only translation-pairing merge suite runs in the exempt-heavy gate because it imports only `scripts/` sources and child processes; V8 instrumentation contributes no threshold coverage there but magnifies Git-process latency. Lefthook concurrency fixtures retain their outcomes with 30-second case budgets and a 10-second process-ready probe, while the installer allows five seconds for a preempted lock owner to publish its record after exclusive creation. Directory-picker composition gives its debounced config write an explicit 15-second poll budget; workspace-context composition fixtures use a test-owned signal without an unrelated one-second deadline. The LSP sources and the ACL-sandbox sources remain in the Windows denominator: stub-based failure-path suites carry every in-process ACL-sandbox file to 100%, and only the runner entry stays excluded — it executes exclusively as a spawned child outside the instrumented run, its behavior pinned end-to-end by the runner suite. Narrow annotated V8 ignores cover only unreachable branches (peer-platform arms and lifecycle-unreachable guards), with their behavior tests retained on the owning platform.
The 16-core allocation is the measured capacity point for this inventory. Six-worker coverage trials produced complete passes in 6 minutes 27 seconds and 7 minutes 50 seconds, while exact-head trials with four, three, and two concurrent workers inside one instrumented Vitest process exposed unreliable fixtures and worker exits. Separate single-worker child processes retain process isolation. Historical sixteen-shard samples reduced instrumented coverage to 112.66–122.01 seconds. The pull-request coverage job schedules four instrumented children plus two exempt workers after the build, while the self-hosted complete reference runs its unsharded coverage gates serially with one worker. A six-partition pull-request profile creates enough process and type-aware lint contention to violate bounded test deadlines. Sixteen instrumented shards plus two exempt workers would exceed a 16-core allocation before system overhead. A 32-core comparison reduced aggregate gate time by only 1.47 seconds and still triggered the CJS-lexer fatal inside a fork worker, so additional cores did not provide a reliable wall-clock improvement.
The 16-core allocation is the measured capacity point for this inventory. Six-worker coverage trials produced complete passes in 6 minutes 27 seconds and 7 minutes 50 seconds, while exact-head trials with four, three, and two concurrent workers inside one instrumented Vitest process exposed unreliable fixtures and worker exits. Separate single-worker child processes retain process isolation. Historical sixteen-shard samples reduced instrumented coverage to 112.66–122.01 seconds. The pull-request coverage job schedules four instrumented children plus two exempt workers without a preceding build, while the self-hosted complete reference runs its unsharded coverage gates serially with one worker. A six-partition pull-request profile creates enough process and type-aware lint contention to violate bounded test deadlines. Sixteen instrumented shards plus two exempt workers would exceed a 16-core allocation before system overhead. A 32-core comparison reduced aggregate gate time by only 1.47 seconds and still triggered the CJS-lexer fatal inside a fork worker, so additional cores did not provide a reliable wall-clock improvement.
The first native run exposed two failures hidden by the compatibility lane. Documentation projection tests derived an image basename by splitting only on `/`; they now use Node's platform basename. Chokidar consumers received `%TEMP%` through the `C:\\Users\\RUNNER~1` 8.3 alias while libuv returned the long directory name, tripping its Windows event-path assertion. Shared settings and credentials watchers, plus Cordis module and exact-config HMR, now canonicalize the existing native watch base or deepest existing ancestor before opening the watcher and preserve a missing suffix, while file access and diagnostics retain the configured path. Module HMR attaches listeners and awaits the main watcher's ready event before plugin startup settles, so an immediate post-boot edit cannot race the initial scan. HMR acceptance derives expected identities through the same asynchronous native realpath operation, avoiding a synchronous Windows spelling that can retain the 8.3 alias.
@@ -52,6 +52,6 @@ Shiki disables lazy TextMate-regex compilation and warms each boot grammar befor
Wine preserves the required aggregate's existing critical path and job identity. Native coverage and observational results can still be pending or red when `all checks passed` turns green, so branch protection consumes Wine plus the targeted native build and process checks while reviewers and follow-up automation consume the remaining native results.
Every pull request nevertheless receives a real NT kernel, NTFS, PowerShell, Windows process, native addon, and supported-source coverage signal. The native jobs duplicate setup and repeat builds across the build, coverage, and observational workspaces, but they lower each job's process count and expose path, watcher, lifecycle, and fixture defects hidden by the compatibility lane.
Every pull request nevertheless receives a real NT kernel, NTFS, PowerShell, Windows process, native addon, and supported-source coverage signal. The native jobs duplicate setup across the build, coverage, and observational workspaces and repeat builds in the build and observational ones, but they lower each job's process count and expose path, watcher, lifecycle, and fixture defects hidden by the compatibility lane.
Maintainers must preserve two intentional execution topologies: the Wine snapshot uses Linux installation plus a hoisted layout to reach win32 binaries, while the native jobs use separate immutable workspaces on the organization-owned 16-core Windows runner. A failure unique to either topology must be classified against that boundary rather than weakened or silently skipped.
@@ -18,9 +18,9 @@ Status: implemented
`windows-build` 与 `windows-native-tests` 是 `all checks passed` 的依赖项;其工作区构建和定向原生进程结果具有阻断性。`windows-coverage` 仍是常规作业,但不在聚合流程的 `needs` 中,因此逐文件 100% 覆盖率结果会保持红灯并可见,却不会延迟必需判定。`windows-observational` 同样不在聚合流程的 `needs` 中,并使用 `continue-on-error`,因为静态检查、文档、包与构建产物的阻断性判定由 Linux 负责。
`windows-coverage` 会先完成一次工作区构建,再由[job 内分区覆盖率](2026-08-18-in-job-partitioned-coverage.zh.md)启动 4 个单 worker 插桩分片,并与一个双 worker 的豁免重型门禁并行运行。两项覆盖率门禁都将 Vitest 默认的单测试和轮询时间预算设为 30 秒。`windows-observational` 拥有自己的工作区构建和生产网站验证,会一起启动相互独立的静态门禁,并将 `publint` 限制为最多 8 个 worker。其 built-bin 冒烟测试只在其他所有观测性门禁结算后启动;冒烟测试的 `needs` 边仍要求构建成功,而 `after` 边会在其他门禁失败后保留这项诊断。这可避免有界的真实应用启动测量与 tool-catalog、NodeNext、包及文档进程争抢资源。translation-pairing 合并套件只导入 `scripts/` 源码和子进程,因此放入豁免重型套件门禁;V8 插桩不会为它贡献任何阈值覆盖率,却会放大 Git 进程延迟。Lefthook 并发 fixture 保留原有结果,采用 30 秒单用例预算与 10 秒进程就绪探测;安装器则允许被抢占的 lock 持有者在独占创建后用 5 秒发布记录。directory-picker 组合为防抖配置写入提供显式的 15 秒轮询预算;workspace-context 组合 fixture 使用测试自有、没有无关 1 秒截止时间的信号。LSP 源码与 ACL 沙箱源码仍计入 Windows 分母:基于 stub 的失败路径套件把每个进程内 ACL 沙箱文件都带到 100%,只有 runner 入口保持排除——它只作为 spawn 出的子进程在插桩运行之外执行,其行为由 runner 套件端到端钉住。窄范围且带注释的 V8 ignore 只覆盖不可达分支(另一平台专属分支、生命周期内不可达的防御守卫),其行为测试仍保留在所属平台。
`windows-coverage` 与 Linux 覆盖率通道一致,不先构建工作区就运行[job 内分区覆盖率](2026-08-18-in-job-partitioned-coverage.zh.md):4 个单 worker 插桩分片与一个双 worker 的豁免重型门禁并行运行;工作区导入通过 tsconfig paths 映射解析到 `src`,消费构建产物的套件在未构建的检出上会自跳。两项覆盖率门禁都通过 `DSH_COVERAGE_TEST_TIMEOUT_MS=90000` 提高 Vitest 的单测试、expect.poll 与 hook 预算。`windows-observational` 拥有自己的工作区构建和生产网站验证,会一起启动相互独立的静态门禁,并将 `publint` 限制为最多 8 个 worker。其 built-bin 冒烟测试只在其他所有观测性门禁结算后启动;冒烟测试的 `needs` 边仍要求构建成功,而 `after` 边会在其他门禁失败后保留这项诊断。这可避免有界的真实应用启动测量与 tool-catalog、NodeNext、包及文档进程争抢资源。translation-pairing 合并套件只导入 `scripts/` 源码和子进程,因此放入豁免重型套件门禁;V8 插桩不会为它贡献任何阈值覆盖率,却会放大 Git 进程延迟。Lefthook 并发 fixture 保留原有结果,采用 30 秒单用例预算与 10 秒进程就绪探测;安装器则允许被抢占的 lock 持有者在独占创建后用 5 秒发布记录。directory-picker 组合为防抖配置写入提供显式的 15 秒轮询预算;workspace-context 组合 fixture 使用测试自有、没有无关 1 秒截止时间的信号。LSP 源码与 ACL 沙箱源码仍计入 Windows 分母:基于 stub 的失败路径套件把每个进程内 ACL 沙箱文件都带到 100%,只有 runner 入口保持排除——它只作为 spawn 出的子进程在插桩运行之外执行,其行为由 runner 套件端到端钉住。窄范围且带注释的 V8 ignore 只覆盖不可达分支(另一平台专属分支、生命周期内不可达的防御守卫),其行为测试仍保留在所属平台。
16 核配置是这项清单经实测选定的容量规格。使用 6 个 coverage worker 的试验分别以 6 分 27 秒和 7 分 50 秒跑出完整通过结果,而在单个插桩 Vitest 进程内使用 4 个、3 个和 2 个并发 worker 的分支头精确试验暴露出不稳定的 fixture 与 worker 退出。相互独立的单 worker 子进程保留进程隔离。历史上的 16 分片样本把插桩覆盖率缩短到 112.66–122.01 秒。拉取请求覆盖率作业会在构建后调度 4 个插桩子进程和 2 个豁免 worker,而自托管完整参考流程会用 1 个 worker 串行运行未分片的覆盖率门禁。拉取请求若采用 6 分片配置,就会产生足以违反有界测试截止时间的进程与类型感知 lint 争用。16 个插桩分片加 2 个豁免 worker 会在计入系统开销前就超过 16 核分配。32 核对比仅将聚合门禁时间缩短 1.47 秒,且仍在 fork worker 内触发 CJS lexer 致命故障,因此增加核心数没有带来可靠的墙钟时间改善。
16 核配置是这项清单经实测选定的容量规格。使用 6 个 coverage worker 的试验分别以 6 分 27 秒和 7 分 50 秒跑出完整通过结果,而在单个插桩 Vitest 进程内使用 4 个、3 个和 2 个并发 worker 的分支头精确试验暴露出不稳定的 fixture 与 worker 退出。相互独立的单 worker 子进程保留进程隔离。历史上的 16 分片样本把插桩覆盖率缩短到 112.66–122.01 秒。拉取请求覆盖率作业会在没有前置构建的情况下调度 4 个插桩子进程和 2 个豁免 worker,而自托管完整参考流程会用 1 个 worker 串行运行未分片的覆盖率门禁。拉取请求若采用 6 分片配置,就会产生足以违反有界测试截止时间的进程与类型感知 lint 争用。16 个插桩分片加 2 个豁免 worker 会在计入系统开销前就超过 16 核分配。32 核对比仅将聚合门禁时间缩短 1.47 秒,且仍在 fork worker 内触发 CJS lexer 致命故障,因此增加核心数没有带来可靠的墙钟时间改善。
首次原生运行暴露出两项被兼容性通道掩盖的故障。文档投影测试此前只按 `/` 拆分来派生图片 basename;现在改为使用 Node 根据平台计算的 basename。Chokidar 消费方收到的 `%TEMP%` 以 `C:\\Users\\RUNNER~1` 这个 8.3 别名表示,而 libuv 返回的是长目录名,导致其 Windows 事件路径断言失败。共享的设置 watcher 与凭据 watcher,以及 Cordis 的模块 HMR(热模块替换)与精确配置 HMR,现在都会在打开 watcher 前规范化现有的原生监听基准路径或层级最深的现有祖先路径,并保留尚不存在的后缀;文件访问和诊断仍使用配置路径。模块 HMR 会挂接监听器并等待主 watcher 的 ready 事件,之后插件启动才会完成,因此启动后立即发生的编辑无法与初始扫描形成竞态。HMR 验收通过相同的异步原生 realpath 操作派生预期身份,避免同步 Windows 路径写法仍保留 8.3 别名。
@@ -52,6 +52,6 @@ Shiki 会禁用 TextMate 正则的延迟编译,并在用户内容进入保持
Wine 保留必需聚合流程现有的关键路径和作业身份。`all checks passed` 变绿时,原生覆盖率与观测性结果仍可能处于待处理或红灯状态,因此分支保护采用 Wine 加定向原生构建和进程检查,而评审者和后续自动化采用其余原生结果。
尽管如此,每个拉取请求都会获得真实 NT 内核、NTFS、PowerShell、Windows 进程、原生插件和受支持源码覆盖率信号。原生作业会重复设置流程,并在构建、覆盖率与观测性工作区中重复构建,但它们会降低每个作业的进程数,并暴露兼容性通道掩盖的路径、watcher、生命周期与 fixture 缺陷。
尽管如此,每个拉取请求都会获得真实 NT 内核、NTFS、PowerShell、Windows 进程、原生插件和受支持源码覆盖率信号。原生作业会在构建、覆盖率与观测性工作区中重复设置流程,并在构建与观测性工作区中重复构建,但它们会降低每个作业的进程数,并暴露兼容性通道掩盖的路径、watcher、生命周期与 fixture 缺陷。
维护者必须保留两种有意设计的执行拓扑:Wine 快照使用 Linux 安装加 hoisted 布局来触达 win32 二进制文件,而原生作业在组织自有的 16 核 Windows 运行器上使用相互独立的不可变工作区。任一拓扑独有的失败都必须依据该边界分类,不得削弱或静默跳过。
@@ -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/process/2026-08-10-event-directed-pr-review-status.md
2026-08-10-event-directed-pr-review-status.md: 3ed6038929d3c2c1e9cd82182978262ee363f5ab
2026-08-10-event-directed-pr-review-status.zh.md: 1fa8650057e53ab894c597b712720a3ee7a5c46a
2026-08-10-event-directed-pr-review-status.md: 47f6f1731b037ae55a994c3373c0f99917da98dd
2026-08-10-event-directed-pr-review-status.zh.md: 8062ab5b1f2efdfcba92f0675af700e59a358d25
@@ -16,7 +16,7 @@ The Issue lifecycle workflow treats review webhooks as commands. `pull_request.r
Ordinary subscribed pull-request events remain forward-only implementation signals: they can move `Inbox`, `Backlog`, or `Ready` to `In progress`, but they cannot move `In review` backward. Review-request commands can move any earlier active status to `In review`. Changes-requested commands can move earlier active statuses forward to `In progress` and can move `In review` back only when the latest status event for the target Project was written by the configured lifecycle actor. A human or unknown latest actor preserves the current status.
The handler resolves only exact same-repository `Fixes`, `Closes`, or `Resolves` references. It does not alter terminal statuses, add an Issue with no Project status, depend on PR metadata validity, query `reviewDecision`, reconstruct review rounds, look up pull requests from Issues, or run a scheduled reconciler.
The status projection resolves only exact same-repository `Fixes`, `Closes`, or `Resolves` references. It does not alter terminal statuses, add an Issue with no Project status, depend on PR metadata validity, query `reviewDecision`, reconstruct review rounds, look up pull requests from Issues, or run a scheduled reconciler. [PR-opened Issue start dates](2026-08-31-pr-opened-issue-start-dates.md) own the separate date initialization for every same-repository Issue reference.
[Issue lifecycle](../../../../.github/workflows/issue-lifecycle.yml) remains unsubscribed from `pull_request.ready_for_review`; neither event command depends on that action. [Issue policy](../../../../.github/workflows/issue-policy.yml) retains `ready_for_review` because it owns required-check enforcement when a human pull request enters review.
@@ -16,7 +16,7 @@ Issue 生命周期工作流把评审 webhook 视为命令。`pull_request.review
工作流订阅的普通 PR 事件仍是只向前推进的实现信号:它们可以将 `Inbox`、`Backlog` 或 `Ready` 推进至 `In progress`,但不能让 `In review` 倒退。请求评审命令可将任意较早的活跃状态推进至 `In review`。请求修改命令可将较早的活跃状态推进至 `In progress`;它也可以让 `In review` 状态回退,但仅在目标 Project 的最新状态事件由配置的生命周期执行主体写入时进行。若最新状态事件的执行主体是人工用户或未知主体,则保留当前状态。
处理器仅解析同一仓库内严格匹配的 `Fixes`、`Closes` 或 `Resolves` 引用。它不会更改终态、将没有 Project 状态的 Issue 添加到 Project、依赖 PR 元数据是否有效、查询 `reviewDecision`、重建评审轮次、从 Issue 反向查找 PR,或运行定时协调器。
状态投影仅解析同一仓库内严格匹配的 `Fixes`、`Closes` 或 `Resolves` 引用。它不会更改终态、将没有 Project 状态的 Issue 添加到 Project、依赖 PR 元数据是否有效、查询 `reviewDecision`、重建评审轮次、从 Issue 反向查找 PR,或运行定时协调器。独立的日期初始化由[在 PR 创建时设置 Issue 开始日期](2026-08-31-pr-opened-issue-start-dates.zh.md)负责,并处理每个同仓库 Issue 引用。
[Issue 生命周期](../../../../.github/workflows/issue-lifecycle.yml)仍不订阅 `pull_request.ready_for_review`;两条事件命令均不依赖该动作。[Issue 策略](../../../../.github/workflows/issue-policy.yml)保留 `ready_for_review`,因为人工提交的 PR 进入评审时,该工作流负责执行必需检查门禁。
@@ -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/process/2026-08-18-in-job-partitioned-coverage.md
2026-08-18-in-job-partitioned-coverage.md: 33824f0aa6f3541df8ca2e0cc8c417b40b5d7933
2026-08-18-in-job-partitioned-coverage.zh.md: c32738462f7e33d9377d314a9ded5f82cebe9db3
2026-08-18-in-job-partitioned-coverage.md: ded8d4a84d24fa42f6b48ac56472c9e54925772b
2026-08-18-in-job-partitioned-coverage.zh.md: cf37d61744ab6482d67423275fa8ffb52cb851e0
@@ -18,7 +18,7 @@ When partitioning is enabled, `scripts/run-gates.ts` selects `pnpm run test:cove
The coordinator waits for every child, validates that the blob directory contains exactly the expected files, and then runs one `vitest --merge-reports ... --coverage` command. Only that merged command applies the repository's per-file statement, branch, function, and line thresholds, so a partition is never judged against an intentionally partial inventory.
`DSH_COVERAGE_MAX_WORKERS` continues to size the uninstrumented exempt gate and the ordinary non-partitioned path; it does not resize partition children. Native Windows gives the exempt gate two workers and admits four concurrent outer gates. The workspace build and production-site validation start immediately; both coverage gates wait for the complete build. The instrumented suite contains packer assertions over built `lib/` output, so this dependency prevents it from reading a partially emitted package closure, while also preventing the exempt gate's temporary Oxlint probes from racing source compilation. The observational inventory waits only for both coverage gates to settle, so it still runs after a coverage failure; each gate's `needs` dependencies remain pass-required. Linux overlaps four instrumented partition processes with two exempt workers, restoring the ordinary path's former four-way instrumented concurrency while keeping every instrumented process single-worker.
`DSH_COVERAGE_MAX_WORKERS` continues to size the uninstrumented exempt gate and the ordinary non-partitioned path; it does not resize partition children. Native Windows gives the exempt gate two workers and admits four concurrent outer gates. In the complete reference, the workspace build and production-site validation start immediately and both coverage gates wait for the complete build; the wait also keeps the exempt gate's temporary Oxlint probes from racing source compilation. The pull-request coverage job runs the same zero-build coverage as Linux: workspace imports resolve to `src` through the tsconfig paths map, and the lib-consuming suites — the exempt gate's packer image assertions and full-corpus import sweep, and the instrumented corpus's client-bundle artifact check — self-skip on unbuilt checkouts. The observational inventory waits only for both coverage gates to settle, so it still runs after a coverage failure; each gate's `needs` dependencies remain pass-required. Linux overlaps four instrumented partition processes with two exempt workers, restoring the ordinary path's former four-way instrumented concurrency while keeping every instrumented process single-worker.
## Failure and output semantics
@@ -30,7 +30,7 @@ A normal failed test still emits a blob through `--coverage.reportOnFailure`, al
`scripts/coverage-partitions.spec.ts` pins argument construction, package-script separator removal, one-worker partitions, weighted longest-processing-time assignment (including a case that fails when assignment ignores recorded weights), the single merged threshold command, failed-test merging, failure diagnostics before complete-blob validation, waiting for sibling partitions after a spawn failure, and link-safe cleanup. `scripts/run-gates.spec.ts` pins opt-in selection, invalid-count rejection, both native Windows coverage gates' complete-build dependency, the complete Windows inventory with its blocking split, and unbuffered streamed output. React fake-timer cases that can move between partitions advance timers inside `act()`; geometry-dependent portal tests stub their element rectangles so a different shard schedule cannot turn deferred updates or jsdom coordinates into coverage-only failures.
Completed native Windows comparisons measured two partitions near 405 seconds and sixteen partitions at 112.66–122.01 seconds under the earlier gate ordering; those values compare partition latency, not the current peak. The current post-build phase runs four instrumented partition processes beside two exempt workers, for six coverage execution units. Sixteen partitions would raise that phase to eighteen before any still-running production-site work or system overhead. Four partitions keep separate-process isolation and match Linux, at the cost of a longer single-job coverage wall time; the trade-off is accepted to reduce vitest worker startup failures under high self-hosted concurrency. Two Linux samples measured the conservative two-partition configuration at 276.68 and 282.27 seconds; that configuration was stable but halved the ordinary path's four instrumented workers. Four partitions restore that fan-out, for six total coverage execution units on the 16-core hosted runner and at most 36 across the failover VM's six runner instances. These values come from completed runs or fixed capacity bounds; an unfinished run crossing an arbitrary elapsed-time mark is not evidence for increasing concurrency.
Completed native Windows comparisons measured two partitions near 405 seconds and sixteen partitions at 112.66–122.01 seconds under the earlier gate ordering; those values compare partition latency, not the current peak. The current coverage phase runs four instrumented partition processes beside two exempt workers, for six coverage execution units. Sixteen partitions would raise that phase to eighteen before any still-running production-site work or system overhead. Four partitions keep separate-process isolation and match Linux, at the cost of a longer single-job coverage wall time; the trade-off is accepted to reduce vitest worker startup failures under high self-hosted concurrency. Two Linux samples measured the conservative two-partition configuration at 276.68 and 282.27 seconds; that configuration was stable but halved the ordinary path's four instrumented workers. Four partitions restore that fan-out, for six total coverage execution units on the 16-core hosted runner and at most 36 across the failover VM's six runner instances. These values come from completed runs or fixed capacity bounds; an unfinished run crossing an arbitrary elapsed-time mark is not evidence for increasing concurrency.
## Alternatives considered
@@ -46,6 +46,6 @@ Completed native Windows comparisons measured two partitions near 405 seconds an
Coverage pays one Vitest startup/configuration cost per partition and one report-merge cost, but it avoids another workflow topology and keeps one final threshold verdict. Partition output may interleave, while the partition start labels and Vitest file identities retain attribution.
Linux and Windows use the same coordinator with platform-specific partition counts and surrounding worker budgets. Native Windows starts both coverage gates after the complete build because its instrumented corpus can consume built artifacts; Linux's dedicated coverage job does not share a workspace with a concurrent build. Local coverage stays simple unless a caller explicitly chooses the partitioned package script and supplies a valid count greater than one.
Linux and Windows use the same coordinator with platform-specific partition counts and surrounding worker budgets. Both pull-request coverage lanes run without a preceding build; the complete reference (serial-windows standby) still starts its coverage gates after the build gate so the lib-consuming suites execute against real artifacts. Local coverage stays simple unless a caller explicitly chooses the partitioned package script and supplies a valid count greater than one.
Future tuning starts from completed runs at one fixed configuration. Slow progress alone never raises partition count or outer concurrency, because repeated restarts would erase the only evidence needed to choose a stable setting.
@@ -18,7 +18,7 @@ Status: implemented
协调器等待全部子进程结束,验证 blob 目录只包含预期文件,然后执行一次 `vitest --merge-reports ... --coverage`。只有这条合并命令应用仓库的逐文件语句、分支、函数与行阈值,因此系统不会拿有意不完整的测试清单单独判定任一分区。
`DSH_COVERAGE_MAX_WORKERS` 继续控制无插桩豁免门禁和普通非分区路径的规模,不会调整分区子进程。原生 Windows 为豁免门禁分配 2 个 worker,并允许 4 道外层门禁并发。工作区构建与生产网站验证会立即启动;两道覆盖率门禁都等待完整构建。插桩套件包含针对已构建 `lib/` 输出的打包器断言,因此这项依赖可避免它读取只完成部分产出的包闭包,也可避免豁免门禁的临时 Oxlint 探针与源码编译竞态。观测性清单只等待两道覆盖率门禁结算,因此在覆盖率失败后仍会运行;各门禁自身的 `needs` 依赖仍要求前置门禁通过。Linux 让 4 个插桩分区进程与 2 个豁免 worker 重叠运行,在保持每个插桩进程只有 1 个 worker 的同时,恢复普通路径原有的 4 路插桩并发。
`DSH_COVERAGE_MAX_WORKERS` 继续控制无插桩豁免门禁和普通非分区路径的规模,不会调整分区子进程。原生 Windows 为豁免门禁分配 2 个 worker,并允许 4 道外层门禁并发。在完整参考流程中,工作区构建与生产网站验证会立即启动,两道覆盖率门禁都等待完整构建;这次等待也能避免豁免门禁的临时 Oxlint 探针与源码编译竞态。拉取请求覆盖率 job 与 Linux 一样以零构建方式运行:工作区导入通过 tsconfig paths 映射解析到 `src`,而消费构建产物的套件——豁免门禁的打包器镜像断言与全语料导入 sweep,以及插桩语料的 client-bundle 产物校验——在未构建的检出上会自跳。观测性清单只等待两道覆盖率门禁结算,因此在覆盖率失败后仍会运行;各门禁自身的 `needs` 依赖仍要求前置门禁通过。Linux 让 4 个插桩分区进程与 2 个豁免 worker 重叠运行,在保持每个插桩进程只有 1 个 worker 的同时,恢复普通路径原有的 4 路插桩并发。
## 失败与输出语义
@@ -30,7 +30,7 @@ Status: implemented
`scripts/coverage-partitions.spec.ts` 固定了参数构造、包脚本分隔符移除、单 worker 分区、加权最长处理时间分配(含一个在分配忽略记录权重时必然失败的用例)、唯一一次合并阈值命令、失败测试合并、完整 blob 校验前的失败诊断、spawn 失败后等待兄弟分区,以及链接安全清理。`scripts/run-gates.spec.ts` 固定了显式启用、非法数量拒绝、两道原生 Windows 覆盖率门禁对完整构建的依赖、完整 Windows 清单及其阻断性划分,以及不缓冲的流式输出。可能在分区间移动的 React fake-timer 用例会在 `act()` 内推进计时器;依赖几何位置的 portal 测试会固定元素矩形,使不同分片调度不会把延迟更新或 jsdom 坐标变成只在覆盖率运行中出现的失败。
已完成的原生 Windows 对比中,双分区耗时约 405 秒,16 分区耗时 112.66–122.01 秒;这些数据来自先前的门禁顺序,只用于比较分区延迟,不代表当前峰值。当前的构建后阶段会让 4 个插桩分区进程与 2 个豁免 worker 并行,共形成 6 个覆盖率执行单元。若改为 16 个分区,则在尚未结束的生产网站工作或系统开销计入之前,该阶段就会达到 18 个执行单元。4 个分区保留独立进程隔离并与 Linux 对齐,代价是单 job 覆盖率墙钟更长;这是为了降低自托管高并发下 vitest worker 启动失败而接受的取舍。两个 Linux 样本中,保守的双分区配置耗时 276.68 秒和 282.27 秒;该配置运行稳定,却把普通路径原有的 4 个插桩 worker 减半。4 个分区恢复这份并发,使 16 核托管 runner 上的覆盖率执行单元总数为 6,故障切换虚拟机的 6 个 runner 实例最多合计 36 个执行单元。这些数值来自完整运行或固定容量上限;运行尚未结束时跨过任意耗时刻度,不构成增加并发的证据。
已完成的原生 Windows 对比中,双分区耗时约 405 秒,16 分区耗时 112.66–122.01 秒;这些数据来自先前的门禁顺序,只用于比较分区延迟,不代表当前峰值。当前的覆盖率阶段会让 4 个插桩分区进程与 2 个豁免 worker 并行,共形成 6 个覆盖率执行单元。若改为 16 个分区,则在尚未结束的生产网站工作或系统开销计入之前,该阶段就会达到 18 个执行单元。4 个分区保留独立进程隔离并与 Linux 对齐,代价是单 job 覆盖率墙钟更长;这是为了降低自托管高并发下 vitest worker 启动失败而接受的取舍。两个 Linux 样本中,保守的双分区配置耗时 276.68 秒和 282.27 秒;该配置运行稳定,却把普通路径原有的 4 个插桩 worker 减半。4 个分区恢复这份并发,使 16 核托管 runner 上的覆盖率执行单元总数为 6,故障切换虚拟机的 6 个 runner 实例最多合计 36 个执行单元。这些数值来自完整运行或固定容量上限;运行尚未结束时跨过任意耗时刻度,不构成增加并发的证据。
## 曾考虑的替代方案
@@ -46,6 +46,6 @@ Status: implemented
每个分区都要支付 1 次 Vitest 启动与配置开销,最后还要执行 1 次报告合并,但它不引入另一套工作流拓扑,并保留唯一的最终阈值判定。分区输出可能交错,但分区启动标签和 Vitest 文件标识仍可用于归因。
Linux 与 Windows 使用相同的协调器,并各自设置分区数量与外围 worker 预算。原生 Windows 会在完整构建之后启动两道覆盖率门禁,因为其插桩语料可能消费构建产物;Linux 的专用覆盖率 job 不会与同一工作区中的并发构建共享目录。本地覆盖率默认保持简单;只有调用方显式选择分区包脚本并提供大于 1 的合法数量时,才启用分区。
Linux 与 Windows 使用相同的协调器,并各自设置分区数量与外围 worker 预算。两条拉取请求覆盖率通道都以零构建方式运行;完整参考流程(serial-windows standby)仍在构建门禁之后启动其覆盖率门禁,使消费构建产物的套件对真实产物执行。本地覆盖率默认保持简单;只有调用方显式选择分区包脚本并提供大于 1 的合法数量时,才启用分区。
未来调优从一个固定配置的完整运行开始。进度缓慢本身绝不会提高分区数量或外层并发,因为反复重启会抹掉选择稳定设置所需的唯一证据。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# 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/process/2026-08-31-pr-opened-issue-start-dates.md
2026-08-31-pr-opened-issue-start-dates.md: f8976b8b0499aa5c68c9637e8571805b78ce6d48
2026-08-31-pr-opened-issue-start-dates.zh.md: 3142bad5007cbbdd27e1f564bc3ccec9101d3d79
@@ -0,0 +1,39 @@
# Agent Note: PR-opened Issue start dates
Status: implemented
English | [中文](2026-08-31-pr-opened-issue-start-dates.zh.md)
## Problem
The Issue Project records planned work in a `Start date` field, but adding or linking an Issue does not provide a date value. A pull request can identify both Issues it resolves and Issues that supply related implementation context, and either relationship marks the start of repository work.
Updating the field on every pull-request event would assign dates to existing work after edits, pushes, or reopenings. Replacing an existing date would also discard a manually planned date or a date recorded by an earlier pull request.
## Decision
The Issue lifecycle workflow initializes `Start date` only for `pull_request.opened`. It reads the pull request's live body, retains every same-repository reference that resolves to an Issue, converts `created_at` to a calendar date in the configured Project time zone, ensures the Issue is a Project item, and writes the configured Date field only when the current value is empty.
The configuration names the Project field and time zone. Missing configuration fails when the policy module loads; a missing field, a non-Date field, an invalid timestamp, or a failed API request fails the workflow at the first relevant pull request.
[Event-directed PR review status commands](2026-08-10-event-directed-pr-review-status.md) continue to own Status transitions. Date initialization includes resolving and informational Issue references, runs for Draft and automated pull requests, and does not depend on PR policy enforcement.
## Verification
[Issue-management tests](../../../../.github/issue-management/policy.test.mjs) cover the Shanghai date boundary, opened-only dispatch, all retained Issue references, empty-value writes, existing-value preservation, missing Project items, invalid field configuration, and the GraphQL mutation variables. [Workflow tests](../../../../scripts/ci-workflow.spec.ts) require the `pull_request.opened` subscription.
## Alternatives considered
**Use a built-in Project workflow.** The built-in workflows own fixed Project item and Status transitions; the repository workflow already owns authenticated GraphQL mutations and can supply the PR creation date.
**Process every subscribed PR event or run a reconciler.** Later events would fill dates for existing pull requests and references added after creation, but they would make the field a repair projection instead of a record created with the pull request and would add repeated Project reads.
**Update only resolving Issue references.** Informational references also identify Issues whose implementation work begins with the pull request, so the date initializer uses the existing all-reference set while Status transitions retain resolving-only semantics.
**Overwrite an existing date.** A later pull request must not replace a manual plan or the date written for earlier work, so the mutation follows an empty-value read.
## Consequences
Only pull requests opened after the workflow ships initialize dates. References added after creation and existing open pull requests remain unchanged, and the workflow does not scan existing Project items or pull requests.
The empty-value read makes retries idempotent in ordinary operation. ProjectV2 has no conditional field update, so simultaneous pull requests that reference the same empty Issue can both write; per-PR concurrency does not serialize that Issue, and the last mutation can win.
@@ -0,0 +1,39 @@
# Agent Note: 在 PR 创建时设置 Issue 开始日期
Status: implemented
[English](2026-08-31-pr-opened-issue-start-dates.md) | 中文
## 问题
Issue Project 使用 `Start date` 字段记录已规划工作的开始日期,但加入或关联 Issue 不会提供日期值。PR 可以同时标识它所解决的 Issue 和提供相关实现上下文的 Issue;两种关系都表示仓库工作已经开始。
如果每个 PR 事件都更新该字段,编辑、推送或重新打开 PR 会为已有工作补上日期。覆盖已有日期还会丢弃人工规划的日期或较早 PR 记录的日期。
## 决策
Issue 生命周期工作流仅在 `pull_request.opened` 时初始化 `Start date`。工作流读取 PR 的实时正文,保留每个能解析为 Issue 的同仓库引用,把 `created_at` 按配置的 Project 时区转换为日历日期,确保 Issue 是 Project item,并仅在当前值为空时写入配置的 Date 字段。
配置指定 Project 字段和时区。配置缺失会在策略模块加载时失败;字段缺失、字段不是 Date 类型、时间戳无效或 API 请求失败会让首个相关 PR 的工作流失败。
[由事件直接指定的 PR 评审状态命令](2026-08-10-event-directed-pr-review-status.zh.md)继续负责 Status 转换。日期初始化同时包含解决型和信息型 Issue 引用,对 Draft PR 和自动化 PR 同样运行,也不依赖 PR 策略检查是否生效。
## 验证
[Issue 管理测试](../../../../.github/issue-management/policy.test.mjs)覆盖上海时区日期边界、仅 opened 分派、全部保留的 Issue 引用、空值写入、已有值保留、Project item 缺失、字段配置无效和 GraphQL mutation 变量。[工作流测试](../../../../scripts/ci-workflow.spec.ts)要求保留 `pull_request.opened` 订阅。
## 考虑过的替代方案
**使用 Project 内置工作流。** 内置工作流负责固定的 Project item 和 Status 转换;仓库工作流已经负责经过身份验证的 GraphQL mutation,并且能够提供 PR 创建日期。
**处理每个已订阅 PR 事件或运行协调器。** 后续事件可以为已有 PR 和创建后新增的引用补上日期,但这会让该字段成为修复型投影,而不是随 PR 创建的记录,并且会增加重复 Project 读取。
**仅更新解决型 Issue 引用。** 信息型引用同样标识随该 PR 开始实现工作的 Issue,因此日期初始化使用现有的全部引用集合,Status 转换仍只处理解决型引用。
**覆盖已有日期。** 后续 PR 不得替换人工计划或为较早工作写入的日期,因此 mutation 先读取并只处理空值。
## 后果
只有工作流发布后新建的 PR 会初始化日期。创建后新增的引用和现有开放 PR 保持不变,工作流不会扫描已有 Project item 或 PR。
空值读取使重试在通常情况下保持幂等。ProjectV2 没有条件字段更新,因此同时引用同一个空日期 Issue 的 PR 可能都会写入;按 PR 设置的并发控制不会串行化该 Issue,最后一次 mutation 可能胜出。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# 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/process/2026-08-31-serial-windows-notices-timeout-budget.md
2026-08-31-serial-windows-notices-timeout-budget.md: 184004122bf8050fa00038b7c57ae680748463f8
2026-08-31-serial-windows-notices-timeout-budget.zh.md: 4fc00ed25cc24ef76e43a0099a362b8be0e59e3e
@@ -0,0 +1,30 @@
# Agent Note: serial-windows notices timeout budget and generator store-scan cost
Status: implemented
English | [中文](2026-08-31-serial-windows-notices-timeout-budget.zh.md)
## Problem
The `serial / windows (self-hosted standby)` master lane failed its `test:coverage` gate four times in a week (runs 33333033178, 33311481884, 33352293522, 33353113100), always on the same case: `scripts/gen-third-party-notices.spec.ts > THIRD_PARTY_NOTICES.md > matches what the generator produces from the current manifests`, with `Error: Test timed out in 5000ms`. Measured test wall times on the shared Windows host were 4149–8853 ms against Vitest's default 5000 ms per-test budget. All other 26 cases in the file finished in 0–3 ms, and the passing run two hours later (33360033028) had the same code green.
The lane runs the complete unsharded Windows gate inventory serially with `DSH_COVERAGE_MAX_WORKERS=1`, so `render()` regenerates `THIRD_PARTY_NOTICES.md` from the workspace manifests and the installed pnpm store on a host shared by 32 runners. The cold path is dominated by `workspaceLinkedManifest`, which re-ran `loadWorkspaceManifests()` — a glob plus reads and JSON-parses of every workspace `package.json` — once per cache-missing external dependency name: 130 names × 270 manifests ≈ 35k file operations, on top of a `.pnpm` store scan per name. Under v8 coverage instrumentation and shared-host I/O contention that crossed the 5 s default.
The lane also had no `DSH_COVERAGE_TEST_TIMEOUT_MS`, unlike the pull-request `windows-coverage` lane ([ci.yml](../../../../.github/workflows/ci.yml)) which grants 90000 ms, so the serial reference ran the same coverage inventory at the strictest budget of any lane.
## Decision
Two changes:
1. [scripts/gen-third-party-notices.ts](../../../../scripts/gen-third-party-notices.ts) loads the workspace manifests once in `render()` and threads the map through `collectNpmDeps` → `installedMetadata` → `installedManifest` → `workspaceLinkedManifest` instead of reloading it per external dependency name. The cold `render()` wall time on the same checkout fell from ~893 ms to ~86 ms with byte-identical output (verified by diffing the rendered documents before and after the change).
2. [ci-master.yml](../../../../.github/workflows/ci-master.yml) `serial-windows` step "Run complete unsharded Windows gate inventory serially" gains `DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'`, matching the pull-request `windows-coverage` lane budget. This extends the per-test, expect.poll, and hook budget mechanism defined by [the Windows lane hook and Lefthook budget note](../testing/2026-08-29-windows-lane-hook-and-lefthook-budget.md) to a second lane; that note records which lanes set the env. `scripts/ci-workflow.spec.ts` pins this env with a `toMatchObject` assertion; removing the env turns the spec red (negative control exercised).
## Alternatives considered
- **Raise the lane budget only** - rejected as the sole fix: it would mask the O(names × manifests) reload for every lane that runs the generator, including the pre-commit hook and the standalone `--check` path.
- **Module-level cache for `loadWorkspaceManifests()`** - rejected in favor of explicit threading, which keeps the single-load contract visible at the call site and avoids a second hidden cache next to `workspaceLinkedManifestCache`.
## Consequences
The generator resolves installed metadata from one manifest load per `render()` call, and clears the name-keyed linked-manifest cache at the start of each call so the cache cannot outlive the map it was resolved from. The serial-windows lane runs the coverage inventory at the same 90000 ms per-test budget as the pull-request coverage lane. `THIRD_PARTY_NOTICES.md` bytes are unchanged; the freshness spec still compares `render()` against the committed document.
@@ -0,0 +1,30 @@
# Agent Note:serial-windows 的 notices 超时预算与 generator store 扫描成本
Status: implemented
[English](2026-08-31-serial-windows-notices-timeout-budget.md) | 中文
## Problem
`serial / windows (self-hosted standby)` master lane 一周内四次失败在 `test:coverage` gate(run 33333033178、33311481884、33352293522、33353113100),失败用例每次都相同:`scripts/gen-third-party-notices.spec.ts > THIRD_PARTY_NOTICES.md > matches what the generator produces from the current manifests`,报 `Error: Test timed out in 5000ms`。共享 Windows 主机上该用例实测 4149–8853 ms,超出 Vitest 默认的 5000 ms 单测预算。文件其余 26 个用例全部 0–3 ms 通过,两小时后的 passing run(33360033028)用同一份代码全绿。
该 lane 以 `DSH_COVERAGE_MAX_WORKERS=1` 串行跑完整的无分片 Windows gate 清单,`render()` 要从 workspace manifest 和已安装的 pnpm store 全量重生成 `THIRD_PARTY_NOTICES.md`,而主机被 32 个 runner 共享。冷路径的代价集中在 `workspaceLinkedManifest`:它对每个未缓存的外部依赖名重跑一遍 `loadWorkspaceManifests()`——glob 并读取、解析全部 workspace `package.json`——即 130 名 × 270 manifest ≈ 3.5 万次文件操作,另加每个名字一次 `.pnpm` store 扫描。叠加 v8 覆盖率插桩与共享主机 I/O 争抢后越过 5 秒默认值。
该 lane 还没有 `DSH_COVERAGE_TEST_TIMEOUT_MS`,而 pull-request 的 `windows-coverage` lane([ci.yml](../../../../.github/workflows/ci.yml))给的是 90000 ms——于是这条 serial 参考 lane 用全仓库最紧的预算跑同一份 coverage 清单。
## Decision
两处改动:
1. [scripts/gen-third-party-notices.ts](../../../../scripts/gen-third-party-notices.ts) 在 `render()` 里只加载一次 workspace manifest,把 map 沿 `collectNpmDeps` → `installedMetadata` → `installedManifest` → `workspaceLinkedManifest` 显式传递,不再按外部依赖名逐个重载。同一 checkout 下冷 `render()` 墙钟从约 893 ms 降到约 86 ms,输出逐字节一致(改动前后渲染结果 diff 验证)。
2. [ci-master.yml](../../../../.github/workflows/ci-master.yml) `serial-windows` 的 "Run complete unsharded Windows gate inventory serially" 步骤增加 `DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'`,与 pull-request `windows-coverage` lane 对齐。这是把 [Windows 覆盖率 lane 的 hook 预算与 Lefthook 套件预算 note](../testing/2026-08-29-windows-lane-hook-and-lefthook-budget.zh.md) 定义的 per-test、expect.poll 与 hook 预算机制扩展到第二个 lane;该 note 记录了哪些 lane 设置此 env。`scripts/ci-workflow.spec.ts` 用 `toMatchObject` 断言钉住该 env;删掉 env 会让 spec 变红(已做负例验证)。
## Alternatives considered
- **只放宽 lane 预算** - 否决作为唯一修复:会掩盖所有运行 generator 的 lane 上的 O(名×manifest) 重载成本,包括 pre-commit hook 与独立 `--check` 路径。
- **给 `loadWorkspaceManifests()` 加模块级缓存** - 否决,改用显式传递:把「单次加载」契约留在调用点可见,避免在 `workspaceLinkedManifestCache` 之外再加一层隐藏缓存。
## Consequences
generator 每次 `render()` 调用只加载一次 manifest 来解析已安装元数据,并在调用开头清空按名字作键的 linked-manifest 缓存,使缓存不会活过它解析自的那份 map。serial-windows lane 与 pull-request coverage lane 一样按 90000 ms 单测预算跑 coverage 清单。`THIRD_PARTY_NOTICES.md` 字节不变;新鲜度 spec 仍把 `render()` 与已提交文档逐字节比较。
@@ -0,0 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# 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/process/2026-08-31-windows-coverage-flaky-test-budgets.md
2026-08-31-windows-coverage-flaky-test-budgets.md: 475bd79adf2721202d860d3c7bc86e1e4b68d6c2
2026-08-31-windows-coverage-flaky-test-budgets.zh.md: 2a16ba8c6ea983d7ad457eb579c9e5e367cf4d68
@@ -0,0 +1,51 @@
# Agent Note: deterministic assertions and dispose budgets for the Windows coverage lane
Status: implemented
English | [中文](2026-08-31-windows-coverage-flaky-test-budgets.zh.md)
## Problem
The `windows node 24 / coverage` lane is excluded from `all-checks-passed.needs` because it is unstable, not because its verdict is unimportant. The instability is a set of timing-sensitive tests that pass on a quiet runner and fail on a contended one. Two failure shapes recur across many PRs (3184, 3185, 3179, 3181) and are unrelated to the PR diffs that trigger them:
1. `packages/session/session-projection-cache/tests/cache.spec.ts` — `SessionProjectionCache` writes are fail-soft and fire-and-forget (the event listener calls `void flushSoft(...)`, `coldSnapshot` calls `void this.put(...)`). Six tests asserted the durable outcome after a fixed `settle()` of 40 ms. On a contended runner the write does not drain within 40 ms, so the mock assertion fails with `AssertionError: expected "Mock" to be called with arguments: [ StringContaining{…} ]` at the `expect(warn).toHaveBeenCalledWith(...)` lines, or the stored-row assertion reads a stale cut. These are the two cache.spec cases that fail on every affected run.
2. `packages/sdk/client/tests/sdk-client.spec.ts` and `packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts` — dispose ladder tests launch a real child process and pass tight confirmation budgets (`disposeGraceMs: 100`–`300`). On a contended runner the child's exit edge after SIGKILL can arrive after the budget, so `close()` rejects with `runtime process did not exit within 100ms after SIGKILL` even though the child was reaped correctly. The product defaults are `disposeEofGraceMs: 6000` / `disposeGraceMs: 3000`; the tight values were test-only speed choices that misreport slow reaps as dispose failures.
A separate, historical coverage gap in `packages/workflow/workflow-worker-thread` (host.ts/index.ts below the per-file 100% gate) was tracked as part of this lane's instability. Investigation in this change found that the local reproduction was a DSH-session environment artifact, not a code defect: the session exports `TSX_TSCONFIG_PATH` pointing at the DSH staging checkout's tsconfig, which redirects the tsx-in-worker resolution of workspace bare specifiers to the staging copy and drops their named exports. With `TSX_TSCONFIG_PATH` unset, `workflow-worker-thread.spec.ts` passes 54/54. The Windows-side reports of that gap predate the ReFS clone install (#3342) and have not recurred since; any recurrence needs Windows-side per-line uncovered lists before it can be attributed.
## Decision
Replace every fixed-wait assertion in cache.spec.ts with `vi.waitFor` polling of the observable outcome, with a 5 s timeout (the same pattern the file already used for the cold-read write-back cases since `7746ed64f0`). The two mock-assertion cases poll for the warning call itself:
```ts ignore-check
await vi.waitFor(() => {
expect(warn).toHaveBeenCalledWith(expect.stringContaining('turn/end write for "fail-soft" failed'))
}, { timeout: 5_000 })
```
The polling assertion still fails when the condition never becomes true — the negative case (an impossible string) times out and fails the test — so the fail-soft contract stays enforced.
For the dispose-ladder tests, pass the product-default budgets instead of the tight test-only values:
- `sdk-client.spec.ts`: `disposeGraceMs` `100` → `3_000` (bounds-profile case), `1_000` → `3_000` (SIGTERM ladder), `300` → `3_000` (SIGKILL escalation).
- `subagent-dsh-sdk.spec.ts`: the concurrent diagnostic-isolation case uses `DEFAULT_SHUTDOWN_TIMEOUT_MS` / `DEFAULT_DISPOSE_EOF_GRACE_MS` / `DEFAULT_DISPOSE_GRACE_MS` from `run.ts` instead of `100`/`200`/`200`.
The dispose.spec.ts negative cases (`disposeGraceMs: 10` with a fake child that never exits) still verify that a truly stuck child fails the ladder within its budget; only the real-child tests with overly tight budgets were widened.
## Verification
- cache.spec.ts: 17/17 pass locally; negative case (impossible warning string) fails via the `vi.waitFor` timeout.
- sdk-client.spec.ts: 42/42 pass locally; dispose.spec.ts 16/16 pass (the 10 ms refused/accepted negative cases still fail correctly).
- subagent-dsh-sdk.spec.ts: 55/55 pass locally.
- workflow-worker-thread.spec.ts: 54/54 pass locally with `TSX_TSCONFIG_PATH` unset — no code change made for the historical coverage gap.
- CI on this PR: the windows coverage lane should stop failing on these tests.
## Alternatives considered
**Keep the fixed settle windows and rerun flaky lanes.** Reruns eventually pass, but every affected PR pays a re-run cycle and the lane stays excluded from `all-checks-passed.needs`. The polled assertion costs nothing when the write is prompt and removes the timing dependency entirely, matching the file's existing `vi.waitFor` pattern from `7746ed64f0`.
**Keep the tight dispose budgets and treat SIGKILL timeouts as runner faults.** A truly stuck child must still fail the ladder, which the fake-child negative cases in dispose.spec.ts already cover at 10 ms. The real-child cases were widened to the product defaults because they measure the ladder's escalation, not a performance bound, and a contended runner's exit edge is not a code defect.
## Consequences
The windows coverage lane keeps its per-file 100% gate while its tests no longer depend on a 40 ms wall-clock window or a 100–300 ms SIGKILL confirmation. The two cache.spec mock-assertion cases and the concurrent subagent-dsh-sdk case stop failing under runner contention, so the lane's flake rate drops without weakening any assertion: every polled condition still fails on timeout, and every dispose negative case still bounds a stuck child.
@@ -0,0 +1,51 @@
# Agent Note:Windows coverage lane 的确定性断言与 dispose 预算
Status: implemented
[English](2026-08-31-windows-coverage-flaky-test-budgets.md) | 中文
## Problem
`windows node 24 / coverage` lane 不在 `all-checks-passed.needs` 里,是因为它不稳定,而不是它的结论不重要。不稳定来自一组对时序敏感的测试:在空闲 runner 上通过,在争抢的 runner 上失败。两种失败形态在多个 PR(3184、3185、3179、3181)反复出现,与触发它们的 PR diff 无关:
1. `packages/session/session-projection-cache/tests/cache.spec.ts` —— `SessionProjectionCache` 的写入是 fail-soft 且 fire-and-forget(事件监听器调 `void flushSoft(...)`,`coldSnapshot` 调 `void this.put(...)`)。六个测试在固定 `settle()` 40 ms 后断言持久化结果。争抢的 runner 上写入 40 ms 内没有排空,mock 断言以 `AssertionError: expected "Mock" to be called with arguments: [ StringContaining{…} ]` 失败(在 `expect(warn).toHaveBeenCalledWith(...)` 行),或 stored-row 断言读到陈旧 cut。这正是每次受影响 run 都失败的 cache.spec 两个用例。
2. `packages/sdk/client/tests/sdk-client.spec.ts` 与 `packages/subagent/subagent-dsh-sdk/tests/subagent-dsh-sdk.spec.ts` —— dispose 梯子测试启动真实子进程并传入紧的确认预算(`disposeGraceMs: 100`–`300`)。争抢的 runner 上 SIGKILL 后子进程的退出边缘可能晚于预算到达,于是 `close()` 以 `runtime process did not exit within 100ms after SIGKILL` reject,即使子进程已被正确回收。产品默认是 `disposeEofGraceMs: 6000` / `disposeGraceMs: 3000`;紧值是测试只为提速的选择,却把慢回收误报成 dispose 失败。
另有一个历史性的覆盖率缺口在 `packages/workflow/workflow-worker-thread`(host.ts/index.ts 低于 per-file 100% 门禁),曾被当作本 lane 不稳定的一部分跟踪。本次调查发现本机复现是 DSH 会话的环境假象而非代码缺陷:会话导出了指向 DSH staging checkout tsconfig 的 `TSX_TSCONFIG_PATH`,把 tsx-in-worker 对 workspace bare specifier 的解析重定向到 staging 副本并丢掉了 named exports。unset `TSX_TSCONFIG_PATH` 后 `workflow-worker-thread.spec.ts` 54/54 通过。Windows 侧对该缺口的报告早于 ReFS clone 安装(#3342),此后未再出现;任何复发都需要 Windows 侧逐行未覆盖清单才能归因。
## Decision
把 cache.spec.ts 里每个固定等待断言改成用 `vi.waitFor` 轮询可观察结果,超时 5 s(与该文件自 `7746ed64f0` 起在 cold-read write-back 用例中使用的模式一致)。两个 mock 断言用例轮询警告调用本身:
```ts ignore-check
await vi.waitFor(() => {
expect(warn).toHaveBeenCalledWith(expect.stringContaining('turn/end write for "fail-soft" failed'))
}, { timeout: 5_000 })
```
轮询断言在条件永远不成立时仍会失败——负例(不可能的字符串)超时并使测试失败——所以 fail-soft 契约仍被强制。
对 dispose 梯子测试,改用产品默认预算,去掉只属于测试的紧值:
- `sdk-client.spec.ts`:`disposeGraceMs` `100` → `3_000`(bounds-profile 用例)、`1_000` → `3_000`(SIGTERM 梯子)、`300` → `3_000`(SIGKILL 升级)。
- `subagent-dsh-sdk.spec.ts`:并发诊断隔离用例改用 `run.ts` 的 `DEFAULT_SHUTDOWN_TIMEOUT_MS` / `DEFAULT_DISPOSE_EOF_GRACE_MS` / `DEFAULT_DISPOSE_GRACE_MS`,而不是 `100`/`200`/`200`。
dispose.spec.ts 的负例(`disposeGraceMs: 10`,fake child 永不退出)仍验证真正卡住的子进程会在预算内使梯子失败;只有真实子进程用例的过紧预算被放宽。
## Verification
- cache.spec.ts:本地 17/17 通过;负例(不可能的警告字符串)经 `vi.waitFor` 超时失败。
- sdk-client.spec.ts:本地 42/42 通过;dispose.spec.ts 16/16 通过(10 ms refused/accepted 负例仍正确失败)。
- subagent-dsh-sdk.spec.ts:本地 55/55 通过。
- workflow-worker-thread.spec.ts:unset `TSX_TSCONFIG_PATH` 后本地 54/54 通过——历史覆盖率缺口未改代码。
- CI on this PR:windows coverage lane 应不再因这些测试失败。
## Alternatives considered
**保留固定 settle 窗口并重跑 flaky lane。** 重跑最终会通过,但每个受影响的 PR 都要付出一次重跑周期,lane 仍被排除在 `all-checks-passed.needs` 之外。轮询断言在写入及时时零成本,并完全消除时序依赖,与该文件自 `7746ed64f0` 起已有的 `vi.waitFor` 模式一致。
**保留紧 dispose 预算并把 SIGKILL 超时当作 runner 故障。** 真正卡住的子进程仍必须让梯子失败——dispose.spec.ts 的 fake-child 负例已用 10 ms 覆盖。真实子进程用例放宽到产品默认,因为它们测的是梯子的升级路径而不是性能上限,争抢 runner 上的退出边缘不是代码缺陷。
## Consequences
windows coverage lane 保留 per-file 100% 门禁,而其测试不再依赖 40 ms 墙钟窗口或 100–300 ms 的 SIGKILL 确认。cache.spec 两个 mock 断言用例与 subagent-dsh-sdk 并发用例在 runner 争抢下不再失败,lane 的 flake 率下降而不削弱任何断言:每个轮询条件超时仍失败,每个 dispose 负例仍约束卡住的子进程。
@@ -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/testing/2026-08-29-windows-lane-hook-and-lefthook-budget.md
2026-08-29-windows-lane-hook-and-lefthook-budget.md: 6886e3ad4958d20a88a66df6a9e02f5a60a36a6a
2026-08-29-windows-lane-hook-and-lefthook-budget.zh.md: 56c1e625d92f01e24f2268deb5d03040278da6af
2026-08-29-windows-lane-hook-and-lefthook-budget.md: 40ebba25e459abd6d9ae755f831e703aa826ae39
2026-08-29-windows-lane-hook-and-lefthook-budget.zh.md: c14be5da098920dbb7360c01bbb94f0bc22f700b
@@ -24,7 +24,7 @@ A `git` or `node` spawn spike on the shared-volume runners no longer decides eit
Both budgets widen what counts as an acceptable duration, so a real slowdown into tens of seconds now passes where the previous ceilings would have caught it. That detection is traded away deliberately: those ceilings were firing on host contention rather than on regressions.
The hook change applies wherever `DSH_COVERAGE_TEST_TIMEOUT_MS` is set, which today is the Windows coverage lane alone. Lanes that leave it unset keep every Vitest default, including the 10 s hook budget.
The hook change applies wherever `DSH_COVERAGE_TEST_TIMEOUT_MS` is set: the Windows coverage lane in [ci.yml](../../../../.github/workflows/ci.yml) and the `serial-windows` master standby in [ci-master.yml](../../../../.github/workflows/ci-master.yml) ([the serial-windows notices timeout note](../process/2026-08-31-serial-windows-notices-timeout-budget.md) records the second lane's adoption). Lanes that leave it unset keep every Vitest default, including the 10 s hook budget.
## Alternatives considered
@@ -24,7 +24,7 @@ Lefthook 套件取 `{ timeout: 90_000 }`,与 [`.github/workflows/ci.yml`](../.
两份预算都放宽了「多长算可接受」,因此一个退化到几十秒的真实变慢现在会通过,而此前的上限会拦住它。这项检测能力是有意换掉的:那些上限触发的是宿主机争抢,不是回归。
hook 的改动在所有设置了 `DSH_COVERAGE_TEST_TIMEOUT_MS` 的地方生效,目前仅 Windows 覆盖率 lane 一处。不设置它的 lane 保持全部 Vitest 默认值,包括 10 秒的 hook 预算。
hook 的改动在所有设置了 `DSH_COVERAGE_TEST_TIMEOUT_MS` 的地方生效:[ci.yml](../../../../.github/workflows/ci.yml) 的 Windows 覆盖率 lane,以及 [ci-master.yml](../../../../.github/workflows/ci-master.yml) 的 `serial-windows` master standby([serial-windows notices 超时 note](../process/2026-08-31-serial-windows-notices-timeout-budget.zh.md) 记录了第二个 lane 的采用)。不设置它的 lane 保持全部 Vitest 默认值,包括 10 秒的 hook 预算。
## 备选方案
+2
View File
@@ -5,6 +5,8 @@
"projectTitle": "DSH Issue Management",
"lifecycleActor": "dsh-issue-management",
"priorityField": "Priority",
"startDateField": "Start date",
"projectTimeZone": "Asia/Shanghai",
"allowUnassignedOwner": true,
"statuses": [
"Inbox",
+110 -8
View File
@@ -52,6 +52,13 @@ for (const status of ['In progress', 'In review']) {
if (typeof config.lifecycleActor !== 'string' || !config.lifecycleActor) {
throw new Error('config.lifecycleActor 未设置')
}
if (typeof config.startDateField !== 'string' || !config.startDateField) {
throw new Error('config.startDateField 未设置')
}
if (typeof config.projectTimeZone !== 'string' || !config.projectTimeZone) {
throw new Error('config.projectTimeZone 未设置')
}
Intl.DateTimeFormat('en-US', { timeZone: config.projectTimeZone })
/**
* Return Markdown outside balanced details elements.
@@ -215,6 +222,29 @@ export function nextResolvingIssueStatus(currentStatus, command, currentStatusAc
return currentIndex >= 0 && currentIndex < targetIndex ? target : null
}
/**
* Convert a GitHub timestamp to a Project date in one configured time zone.
* @param {string} timestamp ISO timestamp.
* @param {string} timeZone IANA time-zone name.
* @returns {string} Calendar date in YYYY-MM-DD form.
*/
export function projectDate(timestamp, timeZone = config.projectTimeZone) {
const instant = new Date(timestamp)
if (Number.isNaN(instant.getTime())) throw new Error(`无效的 PR 创建时间:${timestamp}`)
const parts = Object.fromEntries(
new Intl.DateTimeFormat('en-US', {
timeZone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
.formatToParts(instant)
.filter((part) => part.type !== 'literal')
.map((part) => [part.type, part.value]),
)
return `${parts.year}-${parts.month}-${parts.day}`
}
function stripIgnoredMarkdown(body) {
const lines = body.replace(/<!--[\s\S]*?-->/g, '').split(/\r?\n/)
const kept = []
@@ -437,7 +467,7 @@ async function issueSnapshot(number, status = undefined) {
}
}
async function projectContext(number, includeStatusActor = false) {
async function projectContext(number, includeStatusActor = false, includeStartDate = false) {
const data = await graphql(
`query(
$organization: String!
@@ -445,6 +475,8 @@ async function projectContext(number, includeStatusActor = false) {
$number: Int!
$project: Int!
$includeStatusActor: Boolean!
$includeStartDate: Boolean!
$startDateField: String!
) {
organization(login: $organization) {
projectV2(number: $project) {
@@ -452,7 +484,8 @@ async function projectContext(number, includeStatusActor = false) {
title
fields(first: 50) {
nodes {
... on ProjectV2SingleSelectField { id name options { id name } }
... on ProjectV2Field { id name dataType }
... on ProjectV2SingleSelectField { id name dataType options { id name } }
}
}
}
@@ -477,6 +510,10 @@ async function projectContext(number, includeStatusActor = false) {
fieldValueByName(name: "Status") {
... on ProjectV2ItemFieldSingleSelectValue { name optionId }
}
startDateValue: fieldValueByName(name: $startDateField)
@include(if: $includeStartDate) {
... on ProjectV2ItemFieldDateValue { date }
}
}
}
}
@@ -488,6 +525,8 @@ async function projectContext(number, includeStatusActor = false) {
number,
project: config.projectNumber,
includeStatusActor,
includeStartDate,
startDateField: config.startDateField,
},
)
const project = data.organization?.projectV2
@@ -496,15 +535,24 @@ async function projectContext(number, includeStatusActor = false) {
if (!issue) throw new Error(`#${number} 不存在`)
const statusField = project.fields.nodes.find((field) => field?.name === 'Status')
if (!statusField) throw new Error('Project 缺少 Status 字段')
const startDateField = includeStartDate
? project.fields.nodes.find((field) => field?.name === config.startDateField)
: null
if (includeStartDate && !startDateField) {
throw new Error(`Project 缺少 ${config.startDateField} 字段`)
}
if (startDateField && startDateField.dataType !== 'DATE') {
throw new Error(`Project ${config.startDateField} 字段必须为 Date`)
}
const item = issue.projectItems.nodes.find((candidate) => candidate.project.id === project.id)
const latestStatusEvent = issue.timelineItems?.nodes
?.filter((event) => event?.project?.id === project.id)
.at(-1)
const statusActor =
latestStatusEvent?.status === item?.fieldValueByName?.name
latestStatusEvent && latestStatusEvent.status === item?.fieldValueByName?.name
? (latestStatusEvent.actor?.login ?? null)
: null
return { project, issue, statusField, item, statusActor }
return { project, issue, statusField, startDateField, item, statusActor }
}
async function projectStatus(number) {
@@ -512,8 +560,8 @@ async function projectStatus(number) {
return context.item?.fieldValueByName?.name ?? null
}
async function ensureProjectItem(number) {
const context = await projectContext(number)
async function ensureProjectItem(number, includeStartDate = false) {
const context = await projectContext(number, false, includeStartDate)
if (context.item) return context
const data = await graphql(
`mutation($projectId: ID!, $contentId: ID!) {
@@ -525,10 +573,58 @@ async function ensureProjectItem(number) {
)
return {
...context,
item: { id: data.addProjectV2ItemById.item.id, fieldValueByName: null },
item: {
id: data.addProjectV2ItemById.item.id,
fieldValueByName: null,
startDateValue: null,
},
}
}
/**
* Initialize one Issue's Project Start date when it is empty.
* @param {number} number Same-repository Issue number.
* @param {string} date Date in YYYY-MM-DD form.
* @returns {Promise<void>} Resolves after the conditional Project update.
*/
export async function initializeIssueStartDate(number, date) {
const context = await ensureProjectItem(number, true)
if (context.item.startDateValue?.date) return
await graphql(
`mutation($projectId: ID!, $itemId: ID!, $fieldId: ID!, $date: Date!) {
updateProjectV2ItemFieldValue(input: {
projectId: $projectId,
itemId: $itemId,
fieldId: $fieldId,
value: {date: $date}
}) { projectV2Item { id } }
}`,
{
projectId: context.project.id,
itemId: context.item.id,
fieldId: context.startDateField.id,
date,
},
)
}
/**
* Initialize every referenced Issue from a newly opened PR.
* @param {{createdAt: string, references: {all: number[]}}} pull Pull-request snapshot.
* @param {string} action Pull-request event action.
* @param {(number: number, date: string) => Promise<void>} initialize Date writer.
* @returns {Promise<void>} Resolves after all eligible Issues are processed.
*/
export async function initializePullRequestStartDates(
pull,
action,
initialize = initializeIssueStartDate,
) {
if (action !== 'opened') return
const date = projectDate(pull.createdAt)
for (const number of pull.references.all) await initialize(number, date)
}
async function updateStatus(context, status) {
const option = context.statusField.options.find((candidate) => candidate.name === status)
if (!option) throw new Error(`Status 不存在:${status}`)
@@ -631,7 +727,10 @@ async function pullRequestSnapshot(number) {
async function lifecyclePullRequestSnapshot(number) {
const pull = await api(`/repos/${config.organization}/${config.repository}/pulls/${number}`)
return resolvingReferencesSnapshot(number, pull)
return {
...(await resolvingReferencesSnapshot(number, pull)),
createdAt: pull.created_at,
}
}
async function transitionResolvingIssues(pull, command) {
@@ -683,6 +782,9 @@ async function runLifecycle(eventName, event) {
if (!command) return
const pull = await lifecyclePullRequestSnapshot(event.pull_request.number)
await transitionResolvingIssues(pull, command)
if (eventName === 'pull_request') {
await initializePullRequestStartDates(pull, event.action)
}
}
}
+139
View File
@@ -3,8 +3,11 @@ import test from 'node:test'
import {
countVisibleUnits,
initializeIssueStartDate,
initializePullRequestStartDates,
nextResolvingIssueStatus,
parseReferences,
projectDate,
retainIssueReferences,
resolvingIssueStatusCommand,
requiresPullRequestPolicy,
@@ -13,6 +16,63 @@ import {
validatePullRequest,
} from './policy.mjs'
const projectGraphqlData = ({
projectItem = true,
startDate = null,
startDateField = true,
startDateType = 'DATE',
} = {}) => ({
organization: {
projectV2: {
id: 'project-id',
title: 'DSH Issue Management',
fields: {
nodes: [
{ id: 'status-field-id', name: 'Status', dataType: 'SINGLE_SELECT', options: [] },
...(startDateField
? [{ id: 'start-date-field-id', name: 'Start date', dataType: startDateType }]
: []),
],
},
},
},
repository: {
issue: {
id: 'issue-id',
projectItems: {
nodes: projectItem
? [
{
id: 'item-id',
project: { id: 'project-id' },
fieldValueByName: { name: 'Inbox', optionId: 'inbox-option-id' },
startDateValue: startDate === null ? null : { date: startDate },
},
]
: [],
},
},
},
})
const mockGraphql = (t, resolve) => {
const requests = []
const previousToken = process.env.GH_TOKEN
process.env.GH_TOKEN = 'test-token'
t.after(() => {
if (previousToken === undefined) delete process.env.GH_TOKEN
else process.env.GH_TOKEN = previousToken
})
t.mock.method(globalThis, 'fetch', async (url, options) => {
assert.equal(url, 'https://api.github.com/graphql')
assert.equal(options.headers.Authorization, 'Bearer test-token')
const request = JSON.parse(options.body)
requests.push(request)
return Response.json({ data: resolve(request, requests.length - 1) })
})
return requests
}
const withDetails = (summary) =>
`${summary}\n\n<details><summary>验收与细节</summary>待补充。</details>`
@@ -171,6 +231,85 @@ test('separates resolving and informational references', () => {
)
})
test('converts PR creation timestamps to Shanghai Project dates', () => {
assert.equal(projectDate('2026-08-27T15:59:59Z', 'Asia/Shanghai'), '2026-08-27')
assert.equal(projectDate('2026-08-27T16:00:00Z', 'Asia/Shanghai'), '2026-08-28')
assert.throws(() => projectDate('invalid', 'Asia/Shanghai'), /无效的 PR 创建时间/)
})
test('initializes every referenced Issue only for a PR opened event', async () => {
const writes = []
const pull = {
createdAt: '2026-08-27T16:00:00Z',
references: { all: [4, 7, 12] },
}
const initialize = async (number, date) => writes.push({ number, date })
await initializePullRequestStartDates(pull, 'opened', initialize)
assert.deepEqual(writes, [
{ number: 4, date: '2026-08-28' },
{ number: 7, date: '2026-08-28' },
{ number: 12, date: '2026-08-28' },
])
for (const action of ['edited', 'synchronize', 'reopened']) {
await initializePullRequestStartDates(pull, action, initialize)
}
assert.equal(writes.length, 3)
})
test('writes an empty Project Start date with the configured field', async (t) => {
const requests = mockGraphql(t, (request) => {
if (request.query.includes('query(')) return projectGraphqlData()
return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'item-id' } } }
})
await initializeIssueStartDate(42, '2026-08-28')
assert.equal(requests.length, 2)
assert.match(requests[1].query, /value: \{date: \$date\}/)
assert.deepEqual(requests[1].variables, {
projectId: 'project-id',
itemId: 'item-id',
fieldId: 'start-date-field-id',
date: '2026-08-28',
})
})
test('preserves an existing Project Start date', async (t) => {
const requests = mockGraphql(t, () => projectGraphqlData({ startDate: '2026-08-01' }))
await initializeIssueStartDate(42, '2026-08-28')
assert.equal(requests.length, 1)
})
test('adds a referenced Issue to the Project before setting Start date', async (t) => {
const requests = mockGraphql(t, (request) => {
if (request.query.includes('query(')) return projectGraphqlData({ projectItem: false })
if (request.query.includes('addProjectV2ItemById')) {
return { addProjectV2ItemById: { item: { id: 'new-item-id' } } }
}
return { updateProjectV2ItemFieldValue: { projectV2Item: { id: 'new-item-id' } } }
})
await initializeIssueStartDate(42, '2026-08-28')
assert.equal(requests.length, 3)
assert.deepEqual(requests[1].variables, { projectId: 'project-id', contentId: 'issue-id' })
assert.equal(requests[2].variables.itemId, 'new-item-id')
})
test('rejects a missing or non-Date Start date field', async (t) => {
let response = projectGraphqlData({ startDateField: false })
const requests = mockGraphql(t, () => response)
await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Project 缺少 Start date 字段/)
response = projectGraphqlData({ startDateType: 'TEXT' })
await assert.rejects(initializeIssueStartDate(42, '2026-08-28'), /Start date 字段必须为 Date/)
assert.equal(requests.length, 2)
})
test('does not treat pull request references as Issue associations', () => {
const references = {
all: [123, 1180, 1181],
+1
View File
@@ -208,6 +208,7 @@ jobs:
shell: pwsh
env:
DSH_COVERAGE_MAX_WORKERS: '1'
DSH_COVERAGE_TEST_TIMEOUT_MS: '90000'
DSH_GATE_CONCURRENCY: '1'
DSH_PUBLINT_CONCURRENCY: '1'
run: pnpm run check:ci:windows-complete
+5 -3
View File
@@ -531,9 +531,11 @@ jobs:
} else {
pnpm install --frozen-lockfile
}
- name: Build before coverage
shell: pwsh
run: pnpm run build
# No build before coverage, matching the Linux lane: workspace imports
# resolve to src through the tsconfig paths map, and the lib-consuming
# suites (webworker-packer image-loadable, webworker-runtime
# transform-corpus, client ui-trajectory client-bundle) self-skip on
# unbuilt checkouts.
- name: Run Windows coverage
shell: pwsh
run: pnpm run check:ci:coverage
+1 -1
View File
@@ -50,7 +50,7 @@ describe('web e2e: Full access confirmation', () => {
const access = page.locator('button[aria-label^="访问模式"]').first()
await access.waitFor({ timeout: 10_000 })
expect(await access.getAttribute('aria-label')).toBe('访问模式,当前:可写入工作区')
expect(await access.getAttribute('aria-label')).toBe('访问模式,当前:工作区内修改')
await access.click()
await page.getByRole('menuitem', { name: '完全权限' }).click()
+29 -28
View File
@@ -195,43 +195,44 @@ describe('web e2e: long Chat interaction contract', () => {
const turnNavigation = page.getByRole('navigation', { name: 'Turn navigation' })
await turnNavigation.waitFor({ state: 'visible', timeout: 15_000 })
const initialTurnButtons = turnNavigation.getByRole('button')
const initialTurnCount = await initialTurnButtons.count()
expect(initialTurnCount).toBeGreaterThan(1)
expect(await initialTurnButtons.last().getAttribute('aria-current')).toBe('true')
const firstTurnButton = initialTurnButtons.first()
const firstTurnLabel = await firstTurnButton.getAttribute('aria-label')
if (firstTurnLabel === null) throw new Error('first Turn navigation mark has no accessible label')
const firstTurn = Number(firstTurnLabel.match(/^Jump to turn (\d+)$/)?.[1])
expect(Number.isSafeInteger(firstTurn)).toBe(true)
// The whole-log outline offers every fixture turn before any paging, with
// the live tail mark current.
const marks = turnNavigation.getByRole('button')
await expect.poll(() => marks.count(), { timeout: 15_000 }).toBe(FIXTURE_TURNS)
expect(await marks.last().getAttribute('aria-current')).toBe('true')
// The oldest turn is an unloaded mark whose outline preview already
// carries both the prompt and the settled response.
const firstTurnButton = turnNavigation
.getByRole('button', { name: 'Load and jump to turn 1', exact: true })
await firstTurnButton.focus()
const preview = page.getByRole('tooltip')
await preview.waitFor({ state: 'visible', timeout: 5_000 })
// The first loaded Turn may begin mid-Turn at a page boundary. Its mark is
// still useful with the loaded response and gains the prompt after prepend.
expect(await preview.textContent()).toContain(`Turn ${String(firstTurn)}`)
expect(await preview.textContent()).toContain(FIXTURE.markers.assistant(firstTurn))
expect(await preview.textContent()).toContain(FIXTURE.markers.user(1))
expect(await preview.textContent()).toContain(FIXTURE.markers.assistant(1))
const firstTurnPosition = await firstTurnButton.evaluate(button => (
button.parentElement?.style.getPropertyValue('--turn-position') ?? ''
button.parentElement?.style.getPropertyValue('--turn-natural-position') ?? ''
))
expect(firstTurnPosition).toBe('0%')
expect(firstTurnPosition).toBe('0px')
const loadEarlier = page.getByRole('button', { name: 'Load earlier', exact: true })
const loadedMarks = turnNavigation.getByRole('button', { name: /^Jump to turn / })
const loadedBefore = await loadedMarks.count()
await loadEarlier.click()
await expect.poll(() => turnNavigation.getByRole('button').count(), { timeout: 15_000 })
.toBeGreaterThan(initialTurnCount)
const stableFirstTurnButton = turnNavigation.getByRole('button', { name: firstTurnLabel })
expect(await stableFirstTurnButton.evaluate(button => (
button.parentElement?.style.getPropertyValue('--turn-position') ?? ''
))).not.toBe(firstTurnPosition)
await stableFirstTurnButton.focus()
await expect.poll(() => preview.textContent(), { timeout: 5_000 })
.toContain(FIXTURE.markers.user(firstTurn))
expect(await preview.textContent()).toContain(FIXTURE.markers.assistant(firstTurn))
await stableFirstTurnButton.press('Enter')
await expect.poll(() => stableFirstTurnButton.getAttribute('aria-current'), { timeout: 5_000 }).toBe('true')
// Paging converts marks to their loaded form without moving the
// fixed-pitch ladder.
await expect.poll(() => loadedMarks.count(), { timeout: 15_000 }).toBeGreaterThan(loadedBefore)
expect(await firstTurnButton.evaluate(button => (
button.parentElement?.style.getPropertyValue('--turn-natural-position') ?? ''
))).toBe(firstTurnPosition)
// Activating the still-unloaded oldest mark pages the rest in and lands
// on the turn's own row.
await firstTurnButton.focus()
await firstTurnButton.press('Enter')
const firstLoaded = turnNavigation.getByRole('button', { name: 'Jump to turn 1', exact: true })
await firstLoaded.waitFor({ timeout: 60_000 })
await expect.poll(() => firstLoaded.getAttribute('aria-current'), { timeout: 15_000 }).toBe('true')
await expect.poll(
() => page.locator(`[data-chat-turn="${String(firstTurn)}"][data-chat-flow-kind="user"]`).count(),
() => page.locator('[data-chat-turn="1"][data-chat-flow-kind="user"]').count(),
{ timeout: 5_000 },
).toBe(1)
@@ -42,6 +42,7 @@ const LIVE_TOOL_DONE = 'CHAT_SCROLL_TOOL_STREAM_DONE'
const TOOL_READY_FILE = '.chat-scroll-tool-ready'
const TOOL_RELEASE_FILE = '.chat-scroll-tool-release'
const INPUTS_SESSION_ID = 'chat-scroll-inputs-e2e'
const RAIL_SESSION_ID = 'chat-scroll-rail-e2e'
const FLING_SESSION_ID = 'chat-scroll-fling-e2e'
const LIVE_FLING_PROMPT = 'CHAT_SCROLL_FLING_USER Keep streaming while I fling back through older output.'
const LIVE_FLING_FIRST = 'CHAT_SCROLL_FLING_STREAM_FIRST'
@@ -557,6 +558,68 @@ describe('web e2e: long Chat scroll contract', () => {
})
}, 180_000)
it.skipIf(MODE === 'record')('offers every outline turn on the rail and jumps to an unloaded one', async () => {
await withScrollWorld({
failureShot: 'web-e2e-turn-rail-jump',
seeds: [{ fixture: HISTORY_FIXTURE, id: RAIL_SESSION_ID }],
}, async (world) => {
await openSeed(world.page, HISTORY_FIXTURE, HISTORY_FIXTURE.markers.assistant(HISTORY_FIXTURE.turns))
await expectBottom(world.page)
// The whole-log outline reaches the rail before any paging: one mark
// per fixture turn, the oldest still in its load-and-jump form.
const rail = world.page.getByRole('navigation', { name: 'Turn navigation' })
await expect.poll(() => rail.getByRole('button').count(), { timeout: 15_000 })
.toBe(HISTORY_FIXTURE.turns)
const firstUnloaded = rail.getByRole('button', { name: 'Load and jump to turn 1', exact: true })
expect(await firstUnloaded.count()).toBe(1)
// Fixed pitch: the ladder keeps its natural height, scrolls inside the
// frame, and (following the active tail mark) fades its upper end.
expect(await rail.evaluate(nav => nav.style.getPropertyValue('--turn-natural-height')))
.toBe(`${String((HISTORY_FIXTURE.turns - 1) * 10 + 12)}px`)
const railScroller = rail.locator('[class*="scroller"]')
await expect.poll(() => railScroller.evaluate(el => el.scrollHeight > el.clientHeight)).toBe(true)
await expect.poll(() => rail.locator('[class*="fadeTop"]').count(), { timeout: 15_000 }).toBe(1)
// Activate the unloaded mark by keyboard: pointer input belongs to the
// rail frame, while each mark is the keyboard/AT destination. Focus
// first shows the outline-backed preview: prompt and settled response
// both travel ahead of the events.
const beforeRows = await loadedFlowRows(world.page)
await firstUnloaded.focus()
const tooltip = world.page.getByRole('tooltip')
await expect.poll(() => tooltip.count(), { timeout: 15_000 }).toBe(1)
expect(await tooltip.textContent()).toContain(HISTORY_FIXTURE.markers.user(1))
expect(await tooltip.textContent()).toContain(HISTORY_FIXTURE.markers.assistant(1))
await world.page.keyboard.press('Enter')
// The jump pages history in and lands on turn 1: its mark flips to the
// loaded label and becomes current, the window grew, and the turn-1
// user row sits at the reading line.
const firstLoaded = rail.getByRole('button', { name: 'Jump to turn 1', exact: true })
await expect.poll(() => firstLoaded.count(), { timeout: 60_000 }).toBe(1)
await expect.poll(() => firstLoaded.getAttribute('aria-current'), { timeout: 15_000 }).toBe('true')
expect(await loadedFlowRows(world.page)).toBeGreaterThan(beforeRows)
// Drop mark focus so its hover/focus preview (which echoes the prompt
// marker) leaves the DOM before the transcript count below.
await firstLoaded.evaluate((el) => { (el as HTMLElement).blur() })
await expect.poll(() => world.page.getByRole('tooltip').count(), { timeout: 15_000 }).toBe(0)
await nextPaint(world.page)
const marker = world.page.locator('[data-conversation-scroll]')
.getByText(HISTORY_FIXTURE.markers.user(1), { exact: false })
expect(await marker.count()).toBe(1)
const scrollport = await world.page.locator('[data-conversation-scroll]').boundingBox()
const row = await marker.boundingBox()
if (scrollport === null || row === null) throw new Error('turn-1 row or scrollport has no layout box')
expect(row.y - scrollport.y).toBeGreaterThanOrEqual(0)
expect(row.y - scrollport.y).toBeLessThanOrEqual(160)
// The rail followed the landing to the ladder top, so the fade now
// marks the other (downward) end.
await expect.poll(() => rail.locator('[class*="fadeBottom"]').count(), { timeout: 15_000 }).toBe(1)
assertClean(world)
})
}, 180_000)
it.skipIf(MODE === 'record')('keeps streaming ownership and tool disclosure state across a long scroll-away cycle', async () => {
await withScrollWorld({
failureShot: 'web-e2e-chat-scroll-live-tool',
@@ -18,8 +18,8 @@
- img
- text: 关闭
- text: 权限 选择新会话的默认权限模式
- button "可写入工作区":
- text: 可写入工作区
- button "工作区内修改":
- text: 工作区内修改
- img
- text: 语言
- button "中文":
@@ -43,15 +43,19 @@ describe('web e2e: /goal human transcript presentation', () => {
await scaffold?.close()
})
it('shows the bare input and result from a fresh session without a model turn', async () => {
it('completes with Tab and shows the bare input and result without a model turn', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-goal-command-presentation'))
await expect.poll(() => page.getByText('Into the Unknown', { exact: false }).count(), {
timeout: 15_000,
}).toBe(1)
const input = page.locator('[data-composer-input]').first()
await input.fill('/goal')
await input.press('Enter')
await input.fill('/go')
const menu = page.getByRole('listbox', { name: 'Trigger suggestions' })
await menu.getByRole('option', { name: 'goal set or view the goal for a long-running task' })
.waitFor({ timeout: 10_000 })
await input.press('Tab')
await expect.poll(() => input.textContent()).toBe('/goal ')
await expect.poll(() => menu.count()).toBe(0)
await input.press('Enter')
const commandInput = page.locator('[data-command-input]')
+36 -8
View File
@@ -1,6 +1,6 @@
/** Keyless assembled-Web evidence for conversational Schedule delivery. */
import { readFile } from 'node:fs/promises'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, Page } from 'playwright'
@@ -29,6 +29,7 @@ import {
type WebScaffold,
} from './scaffold.ts'
import {
REPO_ROOT,
connectFreshWorkspace,
conversationContextKey,
saveFailureShot,
@@ -708,18 +709,34 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
const catalog = page.getByRole('list', { name: 'Active reminders' })
await catalog.waitFor({ timeout: 10_000 })
expect(await catalog.getByRole('listitem').count()).toBe(3)
const lightLayout = await catalog.evaluate((element) => {
const box = element.getBoundingClientRect()
const lightLayout = await page.evaluate(() => {
const triggerElement = document.querySelector('button[aria-label="3 reminders"]')
const catalogElement = document.querySelector('[aria-label="Active reminders"]')
if (!(triggerElement instanceof HTMLElement) || !(catalogElement instanceof HTMLElement)) {
throw new Error('active reminder trigger or catalog is not mounted')
}
const triggerBox = triggerElement.getBoundingClientRect()
const catalogBox = catalogElement.getBoundingClientRect()
const viewport = window.innerWidth
return {
width: box.width,
right: box.right,
viewport: window.innerWidth,
bodyPortal: catalogElement.parentElement === document.body,
position: getComputedStyle(catalogElement).position,
triggerLeft: triggerBox.left,
catalogLeft: catalogBox.left,
catalogRight: catalogBox.right,
width: catalogBox.width,
viewport,
expectedLeft: Math.min(Math.max(16, triggerBox.left), viewport - catalogBox.width - 16),
scrollWidth: document.documentElement.scrollWidth,
background: getComputedStyle(element).backgroundColor,
background: getComputedStyle(catalogElement).backgroundColor,
}
})
expect(lightLayout.bodyPortal).toBe(true)
expect(lightLayout.position).toBe('fixed')
expect(lightLayout.width).toBe(336)
expect(lightLayout.right).toBeLessThanOrEqual(lightLayout.viewport)
expect(lightLayout.catalogLeft).toBe(lightLayout.expectedLeft)
expect(lightLayout.catalogLeft).toBeLessThan(lightLayout.triggerLeft)
expect(lightLayout.catalogRight).toBeLessThanOrEqual(lightLayout.viewport - 16)
expect(lightLayout.scrollWidth).toBeLessThanOrEqual(lightLayout.viewport)
expect(lightLayout.background).not.toBe('rgba(0, 0, 0, 0)')
const longRow = catalog.getByRole('listitem').filter({ hasText: 'Join release review' })
@@ -760,6 +777,17 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
}))
expect(scrollLayout.scrollHeight).toBeGreaterThan(scrollLayout.clientHeight)
const evidenceDir = join(REPO_ROOT, '.artifacts')
await mkdir(evidenceDir, { recursive: true })
await writeFile(
join(evidenceDir, 'web-e2e-schedule-catalog-left-alignment.json'),
`${JSON.stringify(lightLayout, null, 2)}\n`,
)
await page.screenshot({
path: join(evidenceDir, 'web-e2e-schedule-catalog-left-alignment.png'),
fullPage: true,
})
await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
const darkBackground = await catalog.evaluate(element => getComputedStyle(element).backgroundColor)
expect(darkBackground).not.toBe('rgba(0, 0, 0, 0)')
+2 -2
View File
@@ -62,7 +62,7 @@ describe('web e2e: settings modal and General preferences', () => {
expect(await trigger.getAttribute('aria-expanded')).toBe('true')
// General is active by default; Permission, Language and Appearance are functional.
expect(await dialog.getByRole('button', { name: '通用设置' }).getAttribute('aria-current')).toBe('true')
await dialog.getByRole('button', { name: '可写入工作区' }).waitFor({ timeout: 10_000 })
await dialog.getByRole('button', { name: '工作区内修改' }).waitFor({ timeout: 10_000 })
await expect.poll(() => dialog.getByText('语言', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
await expect.poll(() => dialog.getByText('外观', { exact: true }).count(), { timeout: 5_000 }).toBe(1)
const openDocument = dialog.getByRole('button', { name: '打开配置文件' })
@@ -150,7 +150,7 @@ describe('web e2e: settings modal and General preferences', () => {
await page.getByRole('button', { name: '设置', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.waitFor({ timeout: 10_000 })
const selector = dialog.getByRole('button', { name: '可写入工作区' })
const selector = dialog.getByRole('button', { name: '工作区内修改' })
await selector.waitFor({ timeout: 10_000 })
await expect.poll(() => selector.isEnabled(), { timeout: 5_000 }).toBe(true)
await selector.click()
+54 -15
View File
@@ -24,28 +24,48 @@ const MODE = webSnapshotMode()
const PROVIDER = 'streaming-fence-highlight-test'
const MODEL = 'streaming-fence'
const PROMPT = 'Stream one TypeScript fence for the highlighting snapshot.'
const OPEN_REPLY = '```ts\nconst first: number = 1\nconst second = "two"\nlet tail'
const FIRST_REPLY = '```ts\nconst first: number = 1\n'
const OPEN_REPLY = `${FIRST_REPLY}const second = "two"\nlet tail`
const REPLY = `${OPEN_REPLY}\n\`\`\``
/** Deterministic model response held after the visible fence body arrives. */
/** Deterministic model response held after each visible fence-growth frame. */
class StreamingFenceAdapter extends LlmAdapter {
private resolvePaused!: () => void
private resolveContinuation!: () => void
private continued = false
readonly paused = new Promise<void>((resolve) => { this.resolvePaused = resolve })
private readonly continuation = new Promise<void>((resolve) => { this.resolveContinuation = resolve })
private resolveFirstPaused!: () => void
private resolveFirstContinuation!: () => void
private resolveSecondPaused!: () => void
private resolveSecondContinuation!: () => void
private firstContinued = false
private secondContinued = false
readonly firstPaused = new Promise<void>((resolve) => { this.resolveFirstPaused = resolve })
readonly secondPaused = new Promise<void>((resolve) => { this.resolveSecondPaused = resolve })
private readonly firstContinuation = new Promise<void>((resolve) => { this.resolveFirstContinuation = resolve })
private readonly secondContinuation = new Promise<void>((resolve) => { this.resolveSecondContinuation = resolve })
grow(): void {
if (this.firstContinued) return
this.firstContinued = true
this.resolveFirstContinuation()
}
finish(): void {
if (this.secondContinued) return
this.secondContinued = true
this.resolveSecondContinuation()
}
continue(): void {
if (this.continued) return
this.continued = true
this.resolveContinuation()
this.grow()
this.finish()
}
override async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
yield { type: 'block-start', index: 0, blockType: 'text' }
yield { type: 'text-delta', index: 0, text: OPEN_REPLY }
this.resolvePaused()
await this.continuation
yield { type: 'text-delta', index: 0, text: FIRST_REPLY }
this.resolveFirstPaused()
await this.firstContinuation
yield { type: 'text-delta', index: 0, text: OPEN_REPLY.slice(FIRST_REPLY.length) }
this.resolveSecondPaused()
await this.secondContinuation
if (options.signal?.aborted === true) throw options.signal.reason
yield { type: 'text-delta', index: 0, text: '\n```' }
yield { type: 'block-end', index: 0, block: { type: 'text', text: REPLY } }
@@ -115,12 +135,26 @@ describe.skipIf(MODE === 'record')('web e2e: streaming code-fence highlighting',
const settled = scaffold.whenTurnSettled(30_000)
await writeComposerDraft(page, input, PROMPT)
await input.press('Enter')
await adapter.paused
await adapter.firstPaused
const streaming = page.locator('[data-streaming="true"]')
await streaming.waitFor({ timeout: 10_000 })
const block = streaming.locator('.md-code-block').filter({ hasText: 'const first' })
await block.locator('pre.shiki span[style]').first().waitFor({ timeout: 10_000 })
await block.evaluate((element) => {
element.setAttribute('data-stream-block-retained', 'true')
element.querySelector('pre.shiki')?.setAttribute('data-stream-pre-retained', 'true')
element.querySelector('pre.shiki .line')?.setAttribute('data-stream-line-retained', 'true')
})
adapter.grow()
await adapter.secondPaused
await expect.poll(() => block.locator('pre.shiki .line').count()).toBe(3)
expect(await block.evaluate(element => ({
block: element.getAttribute('data-stream-block-retained'),
pre: element.querySelector('pre.shiki')?.getAttribute('data-stream-pre-retained'),
line: element.querySelector('pre.shiki .line')?.getAttribute('data-stream-line-retained'),
}))).toEqual({ block: 'true', pre: 'true', line: 'true' })
const midTree = await fenceTree(block)
expect(midTree.language).toBe('ts')
expect(midTree.lines).toHaveLength(3)
@@ -133,12 +167,17 @@ describe.skipIf(MODE === 'record')('web e2e: streaming code-fence highlighting',
MODE,
)
adapter.continue()
adapter.finish()
await settled
await expect.poll(() => page.locator('[data-streaming="true"]').count(), { timeout: 10_000 }).toBe(0)
const settledBlock = page.locator('.md-code-block').filter({ hasText: 'const first' })
await settledBlock.locator('pre.shiki').waitFor({ timeout: 10_000 })
expect(await fenceTree(settledBlock)).toEqual(midTree)
expect(await settledBlock.evaluate(element => ({
block: element.getAttribute('data-stream-block-retained'),
pre: element.querySelector('pre.shiki')?.getAttribute('data-stream-pre-retained'),
line: element.querySelector('pre.shiki .line')?.getAttribute('data-stream-line-retained'),
}))).toEqual({ block: 'true', pre: 'true', line: 'true' })
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
await assertFixtureInventory(SNAPSHOT_DIR, ['mid-stream.expected.md'])
+2 -2
View File
@@ -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/config-catalog.md
config-catalog.md: becb47fcb526a9c77c7b84c92d39393acb057bbd
config-catalog.zh.md: e1c8cc0ec9d1dc9923f423b9f5c6db294629b2df
config-catalog.md: 8a0a4dabd49b85ccb1639dde45bf8c69b4b3b346
config-catalog.zh.md: 43e082efa2e29fbf38db680edb8d8583a1d1611d
+1
View File
@@ -3355,6 +3355,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
- `@deepseek-ai/dsh-session-checkpoint-policy` — requires `llm` · `sessionPersistence` · `sessions` · `tools` ([`packages/session/session-checkpoint-policy/src/index.ts`](../packages/session/session-checkpoint-policy/src/index.ts))
- `@deepseek-ai/dsh-session-projection` ([`packages/session/session-projection/src/index.ts`](../packages/session/session-projection/src/index.ts))
- `@deepseek-ai/dsh-session-stats` — requires `sessionProjections` ([`packages/session/session-stats/src/index.ts`](../packages/session/session-stats/src/index.ts))
- `@deepseek-ai/dsh-session-turn-outline` — requires `sessionProjections` ([`packages/session/session-turn-outline/src/index.ts`](../packages/session/session-turn-outline/src/index.ts))
- `@deepseek-ai/dsh-skill-badge` — requires `skills` ([`packages/skill/skill-badge/src/index.ts`](../packages/skill/skill-badge/src/index.ts))
- `@deepseek-ai/dsh-storage` ([`packages/storage/storage/src/index.ts`](../packages/storage/storage/src/index.ts))
- `@deepseek-ai/dsh-subagent` ([`packages/subagent/subagent/src/index.ts`](../packages/subagent/subagent/src/index.ts))
+1
View File
@@ -3357,6 +3357,7 @@ export interface Config {
- `@deepseek-ai/dsh-session-checkpoint-policy` — 需要 `llm` · `sessionPersistence` · `sessions` · `tools`([`packages/session/session-checkpoint-policy/src/index.ts`](../packages/session/session-checkpoint-policy/src/index.ts))
- `@deepseek-ai/dsh-session-projection`([`packages/session/session-projection/src/index.ts`](../packages/session/session-projection/src/index.ts))
- `@deepseek-ai/dsh-session-stats` — 需要 `sessionProjections`([`packages/session/session-stats/src/index.ts`](../packages/session/session-stats/src/index.ts))
- `@deepseek-ai/dsh-session-turn-outline` — 需要 `sessionProjections`([`packages/session/session-turn-outline/src/index.ts`](../packages/session/session-turn-outline/src/index.ts))
- `@deepseek-ai/dsh-skill-badge` — 需要 `skills`([`packages/skill/skill-badge/src/index.ts`](../packages/skill/skill-badge/src/index.ts))
- `@deepseek-ai/dsh-storage`([`packages/storage/storage/src/index.ts`](../packages/storage/storage/src/index.ts))
- `@deepseek-ai/dsh-subagent`([`packages/subagent/subagent/src/index.ts`](../packages/subagent/subagent/src/index.ts))
+2 -2
View File
@@ -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/module-graph.md
module-graph.md: be3c720863c870d2fed5326f7e5dc9dae31c7db0
module-graph.zh.md: 558497103306b0b727d57fa6fd9716f98fb347db
module-graph.md: 202dc13e49b0b6d51d0a2e186bc043632f43d174
module-graph.zh.md: f5061f86b7ca3a64f1e5869b1a9bfd2c549d692c
+6
View File
@@ -297,6 +297,7 @@ flowchart TD
pkg_session_title_all_prompts_llm["session-title-all-prompts-llm"]
pkg_session_title_first_prompt_llm["session-title-first-prompt-llm"]
pkg_session_title_llm["session-title-llm"]
pkg_session_turn_outline["session-turn-outline"]
end
subgraph group_settings["packages/settings"]
pkg_settings["settings"]
@@ -531,6 +532,10 @@ flowchart TD
pkg_session_stats --> pkg_llm
pkg_session_stats --> pkg_session
pkg_session_stats --> pkg_session_projection
pkg_session_turn_outline --> pkg_invariants
pkg_session_turn_outline --> pkg_llm
pkg_session_turn_outline --> pkg_session
pkg_session_turn_outline --> pkg_session_projection
pkg_settings_file --> pkg_atomic_write
pkg_settings_file --> pkg_home_paths
pkg_settings_file --> pkg_invariants
@@ -1441,6 +1446,7 @@ flowchart TD
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
| [`session-stats`](../packages/session/session-stats) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`settings-file`](../packages/settings/settings-file) | `settings` | [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`settings`](../packages/settings/settings) |
| [`shell`](../packages/shell/shell) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) |
| [`workspace`](../packages/workspace/workspace) | `workspace` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) |
+6
View File
@@ -299,6 +299,7 @@ flowchart TD
pkg_session_title_all_prompts_llm["session-title-all-prompts-llm"]
pkg_session_title_first_prompt_llm["session-title-first-prompt-llm"]
pkg_session_title_llm["session-title-llm"]
pkg_session_turn_outline["session-turn-outline"]
end
subgraph group_settings["packages/settings"]
pkg_settings["settings"]
@@ -533,6 +534,10 @@ flowchart TD
pkg_session_stats --> pkg_llm
pkg_session_stats --> pkg_session
pkg_session_stats --> pkg_session_projection
pkg_session_turn_outline --> pkg_invariants
pkg_session_turn_outline --> pkg_llm
pkg_session_turn_outline --> pkg_session
pkg_session_turn_outline --> pkg_session_projection
pkg_settings_file --> pkg_atomic_write
pkg_settings_file --> pkg_home_paths
pkg_settings_file --> pkg_invariants
@@ -1443,6 +1448,7 @@ flowchart TD
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
| [`session-stats`](../packages/session/session-stats) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`invariants`](../packages/runtime-diagnostics/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`settings-file`](../packages/settings/settings-file) | `settings` | [`atomic-write`](../packages/util/atomic-write), [`home-paths`](../packages/util/home-paths), [`invariants`](../packages/runtime-diagnostics/invariants), [`settings`](../packages/settings/settings) |
| [`shell`](../packages/shell/shell) | `shell` | [`invariants`](../packages/runtime-diagnostics/invariants), [`sandbox`](../packages/sandbox/sandbox), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess) |
| [`workspace`](../packages/workspace/workspace) | `workspace` | [`invariants`](../packages/runtime-diagnostics/invariants), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) |
+2 -2
View File
@@ -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
+7
View File
@@ -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.
+7
View File
@@ -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 -2
View File
@@ -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/session-projection.md
session-projection.md: b41f79302c05a49224e31e7c73d40a26315b2482
session-projection.zh.md: 0081b2d0a98512477c6199c75bfd4f22ee88be0b
session-projection.md: ecd6e98e2923ab458138ccfaacb9e292563df96f
session-projection.zh.md: aa932471910cd77baa433dc0f42744256d458744
+11 -8
View File
@@ -47,7 +47,10 @@ interface ProjectionDefinition<
/** Validates the wire payload before it leaves the host. */
viewSchema: ZodType<SessionProjectionMap[K]>
/**
* State → wire payload (the read-side projection).
* State → wire payload (the read-side projection). The live drive keeps
* the two latest raw results and compares them with `Object.is`; an
* object-valued view must reuse its reference to suppress publication
* across internal-only state changes.
* @param state - the current state.
* @returns the whole current value for this unit's key.
*/
@@ -83,10 +86,10 @@ interface ProjectionSnapshot {
```ts type-equiv
/**
* Change-feed listener: one unit publishes one value for one session. `value`
* is the schema-validated `view` output; `seq` is the unit's watermark at
* emission. `publication` distinguishes an event-driven state change from an
* explicit same-watermark republish after an external view dependency changes.
* Change-feed listener: one unit publishes one value for one session. An
* event-driven publication occurs only when the raw `view` result changes by
* `Object.is`; an explicit republish emits the current view at the same
* watermark after an external dependency changes. `value` is schema-validated.
*/
type ProjectionChangeListener = (
session: Session,
@@ -97,7 +100,7 @@ type ProjectionChangeListener = (
) => void
```
`snapshot(session)` is fully synchronous: a carrier reads it in the same tick as its page slice, so `asOfSeq` covers both reads at one sequence number. It returns only client views, and every value passes its unit's `viewSchema` before return. `stateOf(session, key)` reads one live host state without computing unrelated views; callers must not mutate the borrowed reference. Event-driven publications fire once per client-visible unit whose state *reference* changed for each committed event; `apply` must return the same reference when its state did not change. A registration's `republish(session)` recomputes only its current wire view and publishes it at the existing watermark without appending an event.
`snapshot(session)` is fully synchronous: a carrier reads it in the same tick as its page slice, so `asOfSeq` covers both reads at one sequence number. It returns only client views, and every value passes its unit's `viewSchema` before return. `stateOf(session, key)` reads one live host state without computing unrelated views; callers must not mutate the borrowed reference. When a client-visible unit's state reference changes, the live drive computes one raw view while listeners exist and publishes only when that result changes by `Object.is`; `apply` must return the same state reference when nothing changed, and an object-valued view must reuse its reference across internal-only state changes. A registration's `republish(session)` recomputes only its current wire view, makes that raw result the identity baseline for the next event, and publishes it at the existing watermark without appending an event.
Session Controller clients keep ordinary projection frames and history baselines under a strict higher-sequence-wins rule, so an equal-cut history page cannot overwrite or clear an existing row. A frame marked `republish: true` may replace an equal-sequence row. The complete baseline that opens a replacement control-stream generation is authoritative at an equal sequence and clears keys it omits.
@@ -181,7 +184,7 @@ Source: [`packages/session/session-projection-cache/src/index.ts`](../../package
### `ctx.sessionProjections` — `SessionProjectionRegistry`
`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. A registration handle can explicitly republish its current wire view at the same watermark when an external dependency changes. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A host reader either declares `sessionProjections` in its plugin `inject` or fails explicitly when the registry or required key is absent. Contributors may preserve optional registration through `ctx.inject(['sessionProjections'], ...)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.
`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive). A changed state reference computes the next client view; the change feed is notified only when its raw result changes by `Object.is`. A registration handle can explicitly republish and cache its current wire view at the same watermark when an external dependency changes. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A host reader either declares `sessionProjections` in its plugin `inject` or fails explicitly when the registry or required key is absent. Contributors may preserve optional registration through `ctx.inject(['sessionProjections'], ...)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.
```ts cordis-catalog
/**
@@ -207,7 +210,7 @@ register< K extends Exclude<keyof SessionProjectionStateMap, keyof SessionProjec
/**
* Subscribe to the change feed. The registration is an effect on the
* calling context's fiber.
* @param listener - called for event-driven client-visible changes and explicit republishes.
* @param listener - called for raw-view identity changes and explicit republishes.
* @returns the exact disposer that unsubscribes.
*/
onChanged(listener: ProjectionChangeListener): () => void
+11 -8
View File
@@ -47,7 +47,10 @@ interface ProjectionDefinition<
/** Validates the wire payload before it leaves the host. */
viewSchema: ZodType<SessionProjectionMap[K]>
/**
* State → wire payload (the read-side projection).
* State → wire payload (the read-side projection). The live drive keeps
* the two latest raw results and compares them with `Object.is`; an
* object-valued view must reuse its reference to suppress publication
* across internal-only state changes.
* @param state - the current state.
* @returns the whole current value for this unit's key.
*/
@@ -83,10 +86,10 @@ interface ProjectionSnapshot {
```ts type-equiv
/**
* Change-feed listener: one unit publishes one value for one session. `value`
* is the schema-validated `view` output; `seq` is the unit's watermark at
* emission. `publication` distinguishes an event-driven state change from an
* explicit same-watermark republish after an external view dependency changes.
* Change-feed listener: one unit publishes one value for one session. An
* event-driven publication occurs only when the raw `view` result changes by
* `Object.is`; an explicit republish emits the current view at the same
* watermark after an external dependency changes. `value` is schema-validated.
*/
type ProjectionChangeListener = (
session: Session,
@@ -97,7 +100,7 @@ type ProjectionChangeListener = (
) => void
```
`snapshot(session)` 完全同步:载体在切出页面切片的同一 tick 内读取它,因此 `asOfSeq` 使两次读取使用同一个序号。它只返回客户端视图,并在返回前通过各单元的 `viewSchema` 校验。`stateOf(session, key)` 可在不计算无关视图的情况下读取一份实时 host 状态;调用方不得修改这一借用引用。对于每个已提交事件,事件驱动的发布会为每个状态*引用*已变化的客户端可见单元触发一次;状态未变时,`apply` 必须返回同一引用。注册句柄的 `republish(session)` 只重新计算其当前 wire 视图,并在现有水位发布,不追加事件。
`snapshot(session)` 完全同步:载体在切出页面切片的同一 tick 内读取它,因此 `asOfSeq` 使两次读取使用同一个序号。它只返回客户端视图,并在返回前通过各单元的 `viewSchema` 校验。`stateOf(session, key)` 可在不计算无关视图的情况下读取一份实时 host 状态;调用方不得修改这一借用引用。客户端可见单元的 state 引用变化时,live drive 只在存在 listener 时计算一次原始 view,并且仅在该结果通过 `Object.is` 判定为变化时发布;状态未变时,`apply` 必须返回同一 state 引用,对象 view 若要在仅内部 state 变化时抑制发布就必须复用其引用。注册句柄的 `republish(session)` 只重新计算当前 wire view,把该原始结果设为后续事件的 identity baseline,并在现有水位发布,不追加事件。
Session Controller 客户端对普通投影帧与历史 baseline 严格采用更高序列胜出规则,因此同切面历史页不能覆盖或清除现有行。带 `republish: true` 标记的帧可以替换同序列行。替换 control stream 新一代开头的完整 baseline 在同序列具有权威性,并会清除其中省略的 key。
@@ -181,7 +184,7 @@ Source: [`packages/session/session-projection-cache/src/index.ts`](../../package
### `ctx.sessionProjections` — `SessionProjectionRegistry`
`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive), and a changed state reference in a client-visible unit notifies the change feed with the schema-validated view. A registration handle can explicitly republish its current wire view at the same watermark when an external dependency changes. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A host reader either declares `sessionProjections` in its plugin `inject` or fails explicitly when the registry or required key is absent. Contributors may preserve optional registration through `ctx.inject(['sessionProjections'], ...)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.
`ctx.sessionProjections`: the projection unit table and its drive. The service subscribes to `session/event` once; every committed event passes every registered unit's `apply` (eager drive). A changed state reference computes the next client view; the change feed is notified only when its raw result changes by `Object.is`. A registration handle can explicitly republish and cache its current wire view at the same watermark when an external dependency changes. Cells build lazily — a unit registered after events flowed, or a session older than the registry, folds `init` over the in-memory log on first touch (event or read). Registration is an effect (disposer rides the calling fiber): an unloaded domain plugin's key disappears from snapshots and clients read it as capability absence. A host reader either declares `sessionProjections` in its plugin `inject` or fails explicitly when the registry or required key is absent. Contributors may preserve optional registration through `ctx.inject(['sessionProjections'], ...)`. Registrants sharing a key share one unit and are counted: the same tool package mounted in N agent presets registers N times, and the key survives until the last one unloads.
```ts cordis-catalog
/**
@@ -207,7 +210,7 @@ register< K extends Exclude<keyof SessionProjectionStateMap, keyof SessionProjec
/**
* Subscribe to the change feed. The registration is an effect on the
* calling context's fiber.
* @param listener - called for event-driven client-visible changes and explicit republishes.
* @param listener - called for raw-view identity changes and explicit republishes.
* @returns the exact disposer that unsubscribes.
*/
onChanged(listener: ProjectionChangeListener): () => void
@@ -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/api/session-controller/README.md
README.md: 2f2192cde2941019c9687738f8e3f5e50ddd6d8e
README.zh.md: 273d304d3cd3bbcbadd3e40202d8d923f3a27498
README.md: 94e8697cd7f5bf75746edd5d691956e680d9b261
README.zh.md: 0228ca15624413fcd5cb6e17afb8aaf0a28f780a
+1 -1
View File
@@ -27,7 +27,7 @@ History pages and follow opening snapshots carry a discriminated `SessionHistory
Each endpoint states its activation policy. List, search, attachment, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Queue mutation and cancellation require live state; model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Create and fork are the only operations that create a new Agent directly. The skill catalog instead uses a live Agent when present or the recorded preset's standing scope when cold, so listing never starts an Agent.
The Client adapter exposes `SessionEventStream`, a Gateway `RemoteJournalStream` bound to one ordinary or direct-subagent address. It opens follow before the initial page, publishes only contiguous `replace`, `prepend`, and `append` changes, and repairs reconnect or sequence gaps through a tail page. Ordinary records cover `[event.seq, event.seq]`; packed rows cover `[event.seq, event.seq + memberCount - 1]`. A business, persistence, or unresolved continuity failure terminates the stream, while only physical carrier loss selects automatic resumption. `SessionControlStream` is a Gateway `RemoteSnapshotStream`; every generation opens with a complete process-local baseline, so reconnect replaces queue, jobs, and projection state instead of treating transient values as durable events.
The Client adapter exposes `SessionEventStream`, a Gateway `RemoteJournalStream` bound to one ordinary or direct-subagent address. It opens follow before the initial page, publishes only contiguous `replace`, `prepend`, and `append` changes, and repairs reconnect or sequence gaps through a tail page. Backwards paging has two verbs: `loadOlder()` pulls one 50-message page, and `loadThrough(seq)` — the turn-jump loader — loops 200-message pages until the window covers the target seq, lowering a shared target on repeated calls, stopping on a page that makes no progress, and reporting busy through the same `loadingOlder` snapshot bit. Ordinary records cover `[event.seq, event.seq]`; packed rows cover `[event.seq, event.seq + memberCount - 1]`. A business, persistence, or unresolved continuity failure terminates the stream, while only physical carrier loss selects automatic resumption. `SessionControlStream` is a Gateway `RemoteSnapshotStream`; every generation opens with a complete process-local baseline, so reconnect replaces queue, jobs, and projection state instead of treating transient values as durable events.
The Session object also carries local submission echoes: `session.beginSubmission` inserts one into `SessionSnapshot.pendingSubmissions` synchronously, before the caller serializes and prompts, so a conversation UI can show the message on the submit click's own frame. Session derives each echo's `transcript`, `queued`, or `steering` placement from its current running state and the requested delivery mode, then retains that placement while serialization is in flight. The prompt's `requestId` is the correlation identity: the Host echoes it as the durable user source's `rpcId`, and queue occurrences project it as `SessionQueuedItem.rpcId`. An echo retires one animation frame after its durable event or queue occurrence is observed (the delay keeps it renderable until the replacement is ready), immediately when its identified prompt fails or is abandoned, and as failed on disposal; each retirement fires the registered `onRetire` callback exactly once. Echoes are Client memory only; reload and reconnect rebuild the conversation from durable events alone.
+1 -1
View File
@@ -27,7 +27,7 @@ kind: "package-reference"
每个 endpoint 都声明自己的激活策略。列表、搜索、附件、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。queue 变更与取消要求 live 状态;模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。只有 create 与 fork 会直接创建新 Agent。skill 目录则优先使用已有 live Agent,否则使用所记录 preset 的常驻 scope,因此列表查询绝不会启动 Agent。
Client adapter 提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend` 和 `append` 变更,并通过 tail page 修复重连或 seq 缺口。普通 record 覆盖 `[event.seq, event.seq]`,packed row 覆盖 `[event.seq, event.seq + memberCount - 1]`。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 queue、jobs 和 projection 状态,而不会把瞬态值当作 durable event。
Client adapter 提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend` 和 `append` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页 50 条 message,而 `loadThrough(seq)`——轮次跳转加载器——按 200 条 message 一页循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。普通 record 覆盖 `[event.seq, event.seq]`,packed row 覆盖 `[event.seq, event.seq + memberCount - 1]`。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 queue、jobs 和 projection 状态,而不会把瞬态值当作 durable event。
Session 对象还承载本地提交回显:`session.beginSubmission` 在调用方序列化与 prompt 之前,同步把一条回显写入 `SessionSnapshot.pendingSubmissions`,会话 UI 因此能在点击提交的当帧显示消息。Session 根据当前运行状态与请求的投递模式推导每条回显的 `transcript`、`queued` 或 `steering` 位置,并在序列化期间保留该位置。prompt 的 `requestId` 是关联标识:Host 把它回显为 durable user source 的 `rpcId`,queue occurrence 也把它投影为 `SessionQueuedItem.rpcId`。回显在观察到其 durable event 或 queue occurrence 后延迟一个动画帧退休,该延迟保证替代内容就绪前回显仍可渲染;带标识的 prompt 失败或被放弃时立即退休,销毁时按 failed 退休;每次退休恰好触发一次注册的 `onRetire` 回调。回显只存在于 Client 内存;刷新与重连只从 durable event 重建会话。
@@ -119,6 +119,15 @@ export interface ISession {
* @returns completion; failures land in snapshot.openState/loadingOlder.
*/
loadOlder(): Promise<void>
/**
* Page history backwards until the window covers `seq` (inclusive) — the
* turn-jump loader. Repeated calls while a jump is paging lower its shared
* target and return the in-flight completion; `snapshot.loadingOlder` is
* the busy signal for the whole jump.
* @param seq - durable event seq the window must reach (a turn's `turn/start` seq).
* @returns completion once covered, exhausted, superseded, or failed soft.
*/
loadThrough(seq: number): Promise<void>
/**
* Execute one slash-command line against this session's agent — pure
* admission semantics (the host executor durably logs the lifecycle).
@@ -38,6 +38,9 @@ import { SessionQueueMirror } from './queue-mirror.ts'
/** Messages requested per history page. */
export const PAGE_MESSAGES = 50
/** Messages requested per page while a turn jump loops backwards (fewer, larger round trips). */
export const JUMP_PAGE_MESSAGES = 200
/** Manager-owned observers of a Session object's local state edges. */
export interface SessionOptions {
/** Catalog-discovered address selecting non-activating subagent transport. */
@@ -78,6 +81,10 @@ export class Session implements SessionFace {
* passes drop all writes once the generation moves on. */
private openGeneration = 0
private loadingOlder = false
/** Shared low-water target of the running jump loop; null when no jump is paging. */
private jumpTargetSeq: number | null = null
/** The running jump loop's completion, shared by retargeting callers. */
private jumpPromise: Promise<void> | null = null
/** Authoritative stream-only inbox snapshot; pending work never hits history. */
private readonly queueMirror = new SessionQueueMirror()
private running = false
@@ -369,6 +376,52 @@ export class Session implements SessionFace {
}
}
/** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */
loadThrough(seq: number): Promise<void> {
if (this.openState !== 'open' || !this.hasMore || this.baseSeq <= seq) return Promise.resolve()
if (this.jumpPromise !== null) {
// Retarget the running loop to the lowest requested seq.
this.jumpTargetSeq = Math.min(this.jumpTargetSeq ?? seq, seq)
return this.jumpPromise
}
// A plain single-page pull owns the busy flag; the jump does not queue
// behind it (the caller retries once it settles) and must leave no
// target behind — only the loop's finally clears that field, and no
// loop starts here.
if (this.loadingOlder) return Promise.resolve()
this.jumpTargetSeq = seq
this.loadingOlder = true
this.notifier.markDirty()
// Stale-pass guard (the doOpen pattern): a resync mid-loop replaces the
// stream generation; this pass then stops instead of paging the new
// generation toward its old target.
const generation = this.openGeneration
this.jumpPromise = (async () => {
try {
while (this.hasMore && this.jumpTargetSeq !== null && this.baseSeq > this.jumpTargetSeq) {
if (generation !== this.openGeneration) return
const events = this.events
if (events === undefined) return
const before = this.baseSeq
await events.prepend({ beforeSeq: this.baseSeq, maxMessages: JUMP_PAGE_MESSAGES })
// No-progress guard: an empty or dropped page that still claims more
// history must end the loop, not spin it.
if (this.baseSeq >= before) return
}
} catch (error) {
if (!isRemoteFailure(error)) {
console.error('[session-controller] loadThrough failed:', error)
}
} finally {
this.jumpTargetSeq = null
this.jumpPromise = null
this.loadingOlder = false
this.notifier.markDirty()
}
})()
return this.jumpPromise
}
/** Rebuild an opened history source after address replacement.
* Invalidates any in-flight open first; queue state belongs to the independently
* reconnecting control stream and remains untouched. */
@@ -538,7 +538,7 @@ describe('Session control projection frames', () => {
return frames
}
it('broadcasts a frame per changed unit with the causing seq, and none for same-reference applies', async () => {
it('broadcasts changed view references with the causing seq and skips same-reference applies', async () => {
const { ctx, session } = await harness(true)
ctx.sessionProjections.register(lastUserUnit())
const proxy = remote(ctx)
@@ -554,6 +554,7 @@ describe('Session control projection frames', () => {
now.mockReturnValue(200)
session.append('turn/start', { turn: 1 })
now.mockReturnValue(300)
// The equal payload is a new object, so Object.is still treats its view as changed.
seedMessages(session, 1)
now.mockRestore()
@@ -5,7 +5,7 @@ import type { SessionEvent } from '@deepseek-ai/dsh-session/types'
import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client'
import { RemoteStreamCarrierError } from '@deepseek-ai/dsh-api-gateway/client'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import { Session, type SessionOptions } from '../src/client/sessions/session.ts'
import { JUMP_PAGE_MESSAGES, Session, type SessionOptions } from '../src/client/sessions/session.ts'
import { FakeApiClient, deferred, err, fakeRemote, ok } from './fake-api.client.ts'
import { entries, ev, historyValue, plainTurn } from './event-script.client.ts'
@@ -254,6 +254,145 @@ describe('paging', () => {
}
})
it('loadThrough pages repeatedly until the window covers the target seq', async () => {
const oldest = plainTurn(0, 0, '最旧问', '最旧答')
const middle = plainTurn(6, 1, '中问', '中答')
const newest = plainTurn(12, 2, '新问', '新答')
const { api, session } = makeSession()
api.onHistory = (payload) => {
if (payload.beforeSeq === undefined) return histResponse(newest, true)
return payload.beforeSeq === 12 ? histResponse(middle, true) : histResponse(oldest, false)
}
await session.open()
const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
api.onHistory = (payload) => {
api.onHistory = payload2 => payload2.beforeSeq === 12 ? histResponse(middle, true) : histResponse(oldest, false)
void payload
return gate.promise
}
const jump = session.loadThrough(0)
expect(session.getSnapshot().loadingOlder).toBe(true)
gate.resolve(ok(historyValue(middle, true)))
await jump
const snapshot = session.getSnapshot()
expect(snapshot.loadingOlder).toBe(false)
expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq))
expect(api.callsOf('session.history')).toMatchObject([
{ beforeSeq: 12, maxMessages: JUMP_PAGE_MESSAGES },
{ beforeSeq: 6, maxMessages: JUMP_PAGE_MESSAGES },
])
})
it('loadThrough is a no-op when the window already covers the target or the session is not open', async () => {
const { api, session } = makeSession()
await session.loadThrough(0) // cold: no-op
expect(api.calls).toEqual([])
api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
await session.open()
const calls = api.calls.length
await session.loadThrough(6) // baseSeq is already 6
await session.loadThrough(9) // inside the window
expect(api.calls.length).toBe(calls)
})
it('loadThrough retargets a running jump to the lowest requested seq and shares its completion', async () => {
const oldest = plainTurn(0, 0, 'a', 'b')
const middle = plainTurn(6, 1, 'c', 'd')
const { api, session } = makeSession()
api.onHistory = () => histResponse(plainTurn(12, 2, 'e', 'f'), true)
await session.open()
const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
api.onHistory = () => {
api.onHistory = () => histResponse(oldest, false)
return gate.promise
}
const first = session.loadThrough(6)
const second = session.loadThrough(0)
gate.resolve(ok(historyValue(middle, true)))
await Promise.all([first, second])
expect(eventSeqs(session)).toEqual([...oldest, ...middle].map(event => event.seq).concat([12, 13, 14, 15, 16, 17]))
expect(api.callsOf('session.history')).toHaveLength(2)
})
it('loadThrough refused by a busy pager leaves no target behind for later jumps', async () => {
const middle = plainTurn(6, 1, 'c', 'd')
const { api, session } = makeSession()
api.onHistory = () => histResponse(plainTurn(12, 2, 'e', 'f'), true)
await session.open()
// A plain single-page pull holds the busy flag while the jump is refused.
const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
api.onHistory = () => gate.promise
const older = session.loadOlder()
await session.loadThrough(0) // refused: must not park seq 0 anywhere
gate.resolve(ok(historyValue(middle, true)))
await older
// A later jump to a nearer seq pages exactly to it — a leaked 0 target
// would keep pulling three-event pages all the way to the head.
api.onHistory = (payload) => {
const start = ((payload as { beforeSeq?: number }).beforeSeq ?? 0) - 3
return histResponse(
[ev.user(start, `u${String(start)}`), ev.user(start + 1, `u${String(start + 1)}`), ev.user(start + 2, `u${String(start + 2)}`)],
start > 0,
)
}
await session.loadThrough(4)
// Covered at seq 3 (≤ 4) after one page; a leaked 0 target would add a
// third call at beforeSeq 3 and pull the head to 0.
expect(api.callsOf('session.history').map(call => (call as { beforeSeq?: number }).beforeSeq))
.toEqual([12, 6])
expect(eventSeqs(session)[0]).toBe(3)
})
it('loadThrough stops paging when the event stream generation moves mid-loop', async () => {
const { api, session } = makeSession()
api.onHistory = () => histResponse(plainTurn(12, 2, 'x', 'y'), true)
await session.open()
const gate = deferred<Awaited<ReturnType<FakeApiClient['onHistory']>>>()
api.onHistory = () => gate.promise
const jump = session.loadThrough(0)
// The address is rebuilt while the first page is in flight.
api.onHistory = () => histResponse(plainTurn(12, 2, 'x', 'y'), true)
const rebuilt = session.resync()
gate.resolve(ok(historyValue(plainTurn(6, 1, 'c', 'd'), true)))
await jump
await rebuilt
// The stale loop must not page the new generation toward its old target:
// history calls are the gated page and the resync tail only.
expect(api.callsOf('session.history')).toHaveLength(1)
expect(session.getSnapshot().loadingOlder).toBe(false)
})
it('loadThrough stops on a page that makes no progress instead of looping', async () => {
const { api, session } = makeSession()
api.onHistory = payload => payload.beforeSeq === undefined
? histResponse(plainTurn(12, 2, 'x', 'y'), true)
: histResponse([], true) // empty page still claiming more history
await session.open()
await session.loadThrough(0)
expect(session.getSnapshot().loadingOlder).toBe(false)
expect(api.callsOf('session.history')).toHaveLength(1)
})
it('loadThrough fails soft on a thrown page and clears its busy state', async () => {
const { api, session } = makeSession()
api.onHistory = () => histResponse(plainTurn(12, 2, 'x', 'y'), true)
await session.open()
api.onHistory = () => Promise.reject(new Error('page wire down'))
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
try {
await session.loadThrough(0)
expect(errorSpy).toHaveBeenCalled()
expect(session.getSnapshot().loadingOlder).toBe(false)
} finally {
errorSpy.mockRestore()
}
})
it('ignores loadOlder while one is in flight (single request)', async () => {
const { api, session } = makeSession()
api.onHistory = () => histResponse(plainTurn(6, 1, 'x', 'y'), true)
+5
View File
@@ -76,6 +76,11 @@
- id: session-stats
name: '@deepseek-ai/dsh-session-stats'
# Whole-log turn outline for the chat turn rail (the turnOutline
# projection key): every turn stays navigable before its events page in.
- id: session-turn-outline
name: '@deepseek-ai/dsh-session-turn-outline'
# Resolve bind host, SSH launch, and display once at boot, then mount the
# matching dual-face directory picker. Mount -native or -browse directly in
# an overlay to pin the interaction.
+1
View File
@@ -108,6 +108,7 @@
"@deepseek-ai/dsh-session-reference": "workspace:^",
"@deepseek-ai/dsh-session-log-export": "workspace:^",
"@deepseek-ai/dsh-session-stats": "workspace:^",
"@deepseek-ai/dsh-session-turn-outline": "workspace:^",
"@deepseek-ai/dsh-api-session-controller": "workspace:^",
"@deepseek-ai/dsh-api-settings-controller": "workspace:^",
"@deepseek-ai/dsh-api-workspace-controller": "workspace:^",
+2 -2
View File
@@ -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: 756b09ee1bc1f849d507bc06faad6d5365f0b851
README.zh.md: 6e6278c5fe3f7a31c4e7f4485aa6ebe0dcf95f60
+11 -2
View File
@@ -8,13 +8,14 @@ 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
- [System prompt row](#system-prompt-row)
- [Turn token usage](#turn-token-usage)
- [Turn Process Folding](#turn-process-folding)
- [Scroll ownership](#scroll-ownership)
- [Model Experience](#model-experience)
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
- [Dev Note](#dev-note)
@@ -42,6 +43,13 @@ Settings → General exposes a persisted `Normal` / `Compact` conversation-displ
-----
<a id="scroll-ownership"></a>
## Scroll ownership
Chat restores semantic anchors across history prepend and renderer remounts. While the reader is pinned to the floor, `ResizeObserver` follows the new floor and selects the latest loaded Turn without reading row geometry. Once the reader moves away, flow-height changes preserve the top position and the reading-line geometry selects the active Turn ([loaded-Turn navigation](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.md)).
-----
<a id="model-experience"></a>
## Model Experience
@@ -55,7 +63,8 @@ None; Chat presentation does not assemble or mutate provider requests.
<a id="known-limitations-and-deferred-work"></a>
- **The view reflects the loaded Session window** — older transcript nodes become available only after Session Controller loads the preceding event page. Turn navigation likewise represents only loaded Turns; loading an earlier page preserves existing Turn marks and redistributes the complete loaded set in a compact rail without an unloaded-history placeholder. Marks stay 10px apart until the loaded set exceeds the available height, then compress to fit.
- **The transcript reflects the loaded Session window** — older transcript nodes become available only after Session Controller loads the preceding event page. Turn navigation is wider than the window: the rail merges the loaded Turns with the host `turnOutline` projection, so every started Turn gets a fixed-pitch mark (10px apart; a ladder taller than the frame scrolls inside it with gradient fades), and activating an unloaded mark pages history through the Turn's `turn/start` seq before landing on its row. Without the projection (assemblies not mounting `dsh-session-turn-outline`) the rail falls back to loaded Turns only.
- **Rail previews are card-sized** — one prompt line (50 characters) and up to three response lines (120), on loaded and unloaded Turns alike; an unloaded Turn's response arrives from the outline only once the Turn settled, so an open Turn previews its prompt (or just the Turn number) until then.
<a id="dev-note"></a>
+11 -2
View File
@@ -8,13 +8,14 @@ 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`,该回显即在同一渲染中隐藏,因此交接是原子的。
## 目录
- [系统提示词行](#system-prompt-row)
- [轮次 token 用量](#turn-token-usage)
- [轮次过程折叠](#turn-process-folding)
- [滚动归属](#scroll-ownership)
- [模型体验](#model-experience)
- [已知限制与暂缓事项](#known-limitations-and-deferred-work)
- [开发备注](#dev-note)
@@ -42,6 +43,13 @@ Chat 会为每个非空的初始或恢复请求、显式消息序列起点或真
-----
<a id="scroll-ownership"></a>
## 滚动归属
Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点。读者跟随底部时,`ResizeObserver` 追随新的底部,并且无需读取行几何就选中最后一个已加载 Turn;读者离开底部后,高度变化会保持顶部位置,再由阅读线几何选择活跃 Turn([已加载 Turn 导航](../../../.agents/notes/implemented/feature/2026-08-25-loaded-turn-chat-navigation.zh.md))。
-----
<a id="model-experience"></a>
## 模型体验
@@ -55,7 +63,8 @@ Chat 会为每个非空的初始或恢复请求、显式消息序列起点或真
<a id="known-limitations-and-deferred-work"></a>
- **视图只反映已加载的 Session 窗口**——只有 Session Controller 加载前一页 event 后,更早的 transcript node 才会出现。轮次导航同样只表示已加载的 Turn;加载更早一页时,已有 Turn 刻度保持身份不变,完整的已加载集合在紧凑轨道中重新排布,不显示未加载历史占位。刻度默认相隔 10px,仅在已加载集合超过可用高度时压缩间距。
- **transcript 只反映已加载的 Session 窗口**——只有 Session Controller 加载前一页 event 后,更早的 transcript node 才会出现。轮次导航比窗口更宽:轨道把已加载的 Turn 与宿主 `turnOutline` 投影合并,每个已开始的 Turn 都有固定间距刻度(相隔 10px;阶梯高于外框时在框内滚动并以渐变淡出标示可滚方向),激活未加载刻度会先把历史分页拉到该 Turn 的 `turn/start` seq 再落到它的行上。没有该投影时(未挂载 `dsh-session-turn-outline` 的装配),轨道回退到仅显示已加载 Turn。
- **导航预览按卡片尺寸截断**——提示词一行(50 字符)、回复至多三行(120 字符),已加载与未加载 Turn 一致;未加载 Turn 的回复要等该轮落定后才随大纲到达,进行中的轮次在此之前只预览提示词(或仅轮次号)。
<a id="dev-note"></a>
+1
View File
@@ -78,6 +78,7 @@
"@deepseek-ai/dsh-llm-retry": "workspace:^",
"@deepseek-ai/dsh-session": "workspace:^",
"@deepseek-ai/dsh-session-stats": "workspace:^",
"@deepseek-ai/dsh-session-turn-outline": "workspace:^",
"@deepseek-ai/dsh-token-meter": "workspace:^",
"@deepseek-ai/dsh-tools": "workspace:^",
"@deepseek-ai/dsh-util-workspace-path": "workspace:^",
@@ -125,6 +125,7 @@ export function apply(ctx: Context): void {
if (!result.ok) throw new Error(`path open failed: ${result.error.message}`)
},
loadOlder: () => { void session.loadOlder() },
loadThrough: seq => session.loadThrough(seq),
loadImage: Object.assign(
(attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment),
{ peek: (attachment: ImageAttachmentRef) => ctx.uiConversation.peekImageUrl(sessionId, attachment) },
@@ -7,10 +7,11 @@ import type {
} from '@deepseek-ai/dsh-client-ui-conversation/client'
import { Button, IconChevronDownOutline14, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ChatViewSlotProps } from '../contract/slots.ts'
import type { ChatSnapshot, TurnNavigationItem } from '../contract/snapshot.ts'
import type { ChatSnapshot } from '../contract/snapshot.ts'
import { PendingSteeringBubble, PendingSubmissionBubble } from './MessageItem.tsx'
import { ChatNodeSeat } from './ChatNodeSeat.tsx'
import { TurnNavigator } from './TurnNavigator.tsx'
import { mergeTurnRailItems, type TurnRailItem } from './turn-rail-items.ts'
import { formatRunDuration } from './message-chrome.ts'
import css from './ChatView.module.css'
@@ -202,8 +203,8 @@ function TurnStatus({ startTime, t }: {
* ordered business Node crosses the keyed renderer seat.
*/
export function ChatView({
useSession, useChat, useSessions, useStore, actions, renderSlot, sessionId, openFile, loadOlder, loadImage, openView, chatScroll, forkAt,
fileMentions, useTranscriptView, t,
useSession, useChat, useSessions, useStore, actions, renderSlot, sessionId, openFile, loadOlder, loadThrough,
loadImage, openView, chatScroll, forkAt, fileMentions, useTranscriptView, useProjection, t,
}: ChatViewSlotProps) {
const order = useChat(s => s.order)
const nodeStore = useChat(s => s.nodes)
@@ -211,6 +212,13 @@ export function ChatView({
// both the data and its change signal: the array identity moves only when a
// Turn enters, leaves, or changes its preview.
const turnNavigationItems = useChat(s => s.navigation.items())
// Host-computed whole-log outline; the merge is view-layer only (the
// conversation snapshot never carries projection values).
const turnOutline = useProjection('turnOutline')
const railItems = useMemo(
() => mergeTurnRailItems(turnNavigationItems, turnOutline),
[turnNavigationItems, turnOutline],
)
const timeline = useChat(s => s.timeline)
const inbox = useSession(s => s.queue)
// Workspace root off the session list row: path summaries display relative to it.
@@ -295,6 +303,15 @@ export function ChatView({
/** Paging anchor: semantic row/position at click, updated by reader scrolls
* while the request is pending and restored after the prepend lands. */
const anchorRef = useRef<PagingAnchor | null>(null)
/** Unloaded-turn jump in flight: target turn plus its load-through seq. */
const pendingJumpRef = useRef<{ turn: number; seq: number } | null>(null)
/** Whether the in-flight jump already landed mid-paging (settle then only corrects an untouched landing). */
const jumpLandedRef = useRef(false)
const [busyJumpTurn, setBusyJumpTurn] = useState<number | null>(null)
/** Bumped when a loadThrough completion settles, after its last page's commit. */
const [jumpSettleTick, setJumpSettleTick] = useState(0)
/** Window head at the last settle-time repage; an unmoved head falls back instead of repaging forever. */
const jumpRepageHeadRef = useRef<number | null>(null)
const firstSeqRef = useRef<number | null>(null)
const openedRef = useRef(false)
const lastKeyRef = useRef<string | null>(null)
@@ -321,6 +338,11 @@ export function ChatView({
return
}
const el = scrollerOf(local)
if (el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_THRESHOLD + 1) {
const latest = turnNavigationItems.at(-1)?.turn ?? first.turn
setActiveTurn(current => current === latest ? current : latest)
return
}
const readingLine = el.getBoundingClientRect().top + Math.min(96, el.clientHeight * 0.2)
const reading = turnAtLine(local, readingLine)
// No row reaches the line yet: the flow head still owns the mark. Otherwise
@@ -333,9 +355,6 @@ export function ChatView({
next = item.turn
}
}
if (el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_THRESHOLD + 1) {
next = turnNavigationItems.at(-1)?.turn ?? next
}
setActiveTurn(current => current === next ? current : next)
}, [turnNavigationItems])
@@ -367,6 +386,9 @@ export function ChatView({
const toBottom = (el: HTMLElement): void => {
anchorRef.current = null
// Returning to the live tail supersedes a jump still landing.
pendingJumpRef.current = null
setBusyJumpTurn(current => current === null ? current : null)
el.scrollTop = el.scrollHeight
observedTopRef.current = el.scrollTop
atBottomRef.current = true
@@ -375,6 +397,57 @@ export function ChatView({
setActiveTurn(turnNavigationItems.at(-1)?.turn ?? null)
}
// Land a row at the reading line and republish scroll-derived state. A
// latest-ref, so navigateToTurn's identity stays stable for the memoized rail.
const landOnRowRef = useRef<(local: HTMLElement, el: HTMLElement, row: HTMLElement, turn: number) => void>(
() => {},
)
landOnRowRef.current = (local, el, row, turn) => {
el.scrollTop += flowTop(row, el) - 24
observedTopRef.current = el.scrollTop
const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_THRESHOLD + 1
atBottomRef.current = isAtBottom
setAtBottom(isAtBottom)
setActiveTurn(turn)
const position = isAtBottom ? null : scrollPosition(local, el)
if (isAtBottom) chatScroll.save(null)
else if (position !== null) chatScroll.save(position)
}
/**
* Land the pending jump once its Turn has a rendered anchor row; false
* while it must keep waiting. Mid-jump landings (`settle` false) keep the
* jump armed with the target row as the paging anchor, so later chunks and
* the load-earlier button's unmount re-land on the same row; the settling
* call clears the jump.
*/
const realizePendingJump = (local: HTMLElement, el: HTMLElement, settle: boolean): boolean => {
const pending = pendingJumpRef.current
if (pending === null) return true
const item = railItems.find(candidate => candidate.turn === pending.turn)
if (item === undefined || item.anchor.kind !== 'loaded') return false
const row = anchorElement(local, item.anchor.key)
if (row === null) return false
if (settle) {
pendingJumpRef.current = null
setBusyJumpTurn(null)
const held = anchorRef.current
const landedEarlier = jumpLandedRef.current
jumpLandedRef.current = false
anchorRef.current = null
// A reader who moved off an already-landed target mid-jump keeps their
// place; a first landing, or an untouched one, takes the correction.
if (!landedEarlier || held?.key === item.anchor.key) {
landOnRowRef.current(local, el, row, pending.turn)
}
return true
}
landOnRowRef.current(local, el, row, pending.turn)
jumpLandedRef.current = true
anchorRef.current = { key: item.anchor.key, top: flowTop(row, el) }
return true
}
useLayoutEffect(() => {
const local = listRef.current
/* v8 ignore next -- ref-null guard: React attaches the ref before layout effects run. */
@@ -416,6 +489,11 @@ export function ChatView({
const row = anchorElement(local, anchor.key)
if (row !== null) el.scrollTop += flowTop(row, el) - anchor.top
observedTopRef.current = el.scrollTop
// A jump chunk lands here: scroll to the target once its rows exist;
// until then keep holding the reader's row for the next chunk.
if (!realizePendingJump(local, el, false) && row !== null) {
anchorRef.current = { key: anchor.key, top: flowTop(row, el) }
}
firstSeqRef.current = firstSeq
/* v8 ignore next -- ?? arm: a prepend adds nodes, so the flow list here is never empty. */
lastKeyRef.current = lastKey
@@ -437,7 +515,13 @@ export function ChatView({
followSigRef.current = followSig
// Follow new flow content while pinned; do NOT re-pin on every render
// merely because atBottomRef is true (scroll threshold → setState → snap).
if (appendedUser || appendedSteering || appendedSubmission || (tipMoved && atBottomRef.current)) toBottom(el)
if (appendedUser || appendedSteering || appendedSubmission || (tipMoved && atBottomRef.current)) {
toBottom(el)
return
}
// A jump whose target committed outside the anchored-prepend path (for
// example after a mid-jump toBottom dropped the held anchor) lands here.
if (pendingJumpRef.current !== null) realizePendingJump(local, el, false)
})
const onScrollRef = useRef(() => {})
@@ -531,6 +615,53 @@ export function ChatView({
if (!loadingOlder) anchorRef.current = null
}, [loadingOlder])
// Jump settlement: every loadThrough completion bumps the tick after its
// last page's commit, and a plain pull's loadingOlder flip re-settles a
// jump it made wait. A still-pending jump is realized now, held while a
// plain load-earlier pull owns the pager (its completion retries below),
// repaged once per head movement, or landed on the nearest rendered Turn
// at or after the target (failure, exhausted history, or a Turn with no
// visible row).
useEffect(() => {
const pending = pendingJumpRef.current
const local = listRef.current
if (pending === null || local === null) return
const el = scrollerOf(local)
// The settling landing runs after the load-earlier button's unmount
// commit, so the target row cannot drift once the jump clears.
if (realizePendingJump(local, el, true)) return
const uncovered = firstSeq === null || firstSeq > pending.seq
if (uncovered && hasMore) {
// A plain pull owns the pager right now: hold the jump (busy stays)
// instead of degrading to a wrong landing.
if (loadingOlder) return
if (jumpRepageHeadRef.current !== firstSeq) {
jumpRepageHeadRef.current = firstSeq
const held = pagingAnchor(local, el)
if (held !== null && held.dataset.chatAnchorKey !== undefined) {
anchorRef.current = { key: held.dataset.chatAnchorKey, top: flowTop(held, el) }
}
void loadThrough(pending.seq).finally(() => { setJumpSettleTick(tick => tick + 1) })
return
}
}
for (const row of local.querySelectorAll<HTMLElement>('[data-chat-turn]:not([hidden])')) {
const turn = Number(row.dataset.chatTurn)
if (!Number.isSafeInteger(turn) || turn < pending.turn) continue
landOnRowRef.current(local, el, row, turn)
break
}
pendingJumpRef.current = null
setBusyJumpTurn(null)
// Snapshot values are read at settle time; the completion tick is the trigger.
}, [jumpSettleTick])
// A jump held while a plain pull owned the pager waits in the effect
// above; the pull's completion is its retry signal.
useEffect(() => {
if (!loadingOlder && pendingJumpRef.current !== null) setJumpSettleTick(tick => tick + 1)
}, [loadingOlder])
const loadOlderAnchored = (): void => {
const local = listRef.current
/* v8 ignore next -- ref-null guard: the paging button renders inside the list tree. */
@@ -548,35 +679,51 @@ export function ChatView({
}
// Identity feeds the memoized rail; a fresh closure per render would defeat it.
const navigateToTurn = useCallback((item: TurnNavigationItem): void => {
const navigateToTurn = useCallback((item: TurnRailItem): void => {
const local = listRef.current
if (local === null) return
const row = anchorElement(local, item.anchorKey)
if (row === null) return
const el = scrollerOf(local)
el.scrollTop += flowTop(row, el) - 24
observedTopRef.current = el.scrollTop
if (item.anchor.kind === 'unloaded') {
// Jumping into history is leaving the live tail: release bottom
// ownership on the click itself, or the pinned-scroll snap (a
// non-reader scroll delivery during the first prepend's compensation)
// would call toBottom and cancel the jump.
atBottomRef.current = false
setAtBottom(false)
// Hold the reader's place through the paging chunks; the layout effect
// lands on the target once its rows commit.
const held = pagingAnchor(local, el)
if (held !== null && held.dataset.chatAnchorKey !== undefined) {
anchorRef.current = { key: held.dataset.chatAnchorKey, top: flowTop(held, el) }
}
pendingJumpRef.current = { turn: item.turn, seq: item.anchor.seq }
jumpRepageHeadRef.current = null
jumpLandedRef.current = false
setBusyJumpTurn(item.turn)
void loadThrough(item.anchor.seq).finally(() => { setJumpSettleTick(tick => tick + 1) })
return
}
const row = anchorElement(local, item.anchor.key)
if (row === null) return
// A loaded-mark click supersedes any jump still landing.
pendingJumpRef.current = null
setBusyJumpTurn(current => current === null ? current : null)
landOnRowRef.current(local, el, row, item.turn)
// A pending older page still has to compensate the prepended height, so
// navigation moves that anchor to the new position instead of dropping it.
const landed = loadingOlder ? pagingAnchor(local, el) : null
anchorRef.current = landed === null || landed.dataset.chatAnchorKey === undefined
? null
: { key: landed.dataset.chatAnchorKey, top: flowTop(landed, el) }
const isAtBottom = el.scrollHeight - el.scrollTop - el.clientHeight <= FOLLOW_THRESHOLD + 1
atBottomRef.current = isAtBottom
setAtBottom(isAtBottom)
setActiveTurn(item.turn)
const position = isAtBottom ? null : scrollPosition(local, el)
if (isAtBottom) chatScroll.save(null)
else if (position !== null) chatScroll.save(position)
}, [loadingOlder, chatScroll])
}, [loadingOlder, loadThrough])
return (
<div className={css.root}>
<div ref={listRef} className={css.scroll}>
<TurnNavigator
items={turnNavigationItems}
items={railItems}
activeTurn={activeTurn}
busyTurn={busyJumpTurn}
onNavigate={navigateToTurn}
t={t}
/>
@@ -8,7 +8,7 @@
pointer-events: none;
}
.rail {
.frame {
/* The band a reader actually sees: the scrollport minus the sticky composer
stack covering its floor. ConversationRoot publishes both measurements on
the scrollport; the fallbacks carry the first paint before its observer
@@ -24,9 +24,9 @@
padding, so the rail gives that inset back and keeps 12px of its own. */
right: calc(12px - (var(--dsh-composer-side-clearance) + 16px));
width: 28px;
/* Never taller than the band it centers in: a short window (a tall composer,
a low viewport) shrinks the rail instead of pushing marks under the
composer or above the scrollport. */
/* Fixed-pitch marks never compress: a ladder taller than the band scrolls
inside this frame instead of pushing marks under the composer or above
the scrollport. */
height: min(
var(--turn-natural-height),
max(0px, calc(var(--turn-rail-band) - 64px)),
@@ -38,14 +38,46 @@
transition: height 220ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
.marks {
/* The frame's inner scroller: no visible scrollbar, no scroll chaining into
the transcript, and gradient fades over the ends that can still scroll. */
.scroller {
position: absolute;
inset: var(--turn-rail-inset) 0;
inset: 0;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-width: none;
}
.scroller::-webkit-scrollbar {
display: none;
}
.fadeTop {
mask-image: linear-gradient(to bottom, transparent 0, #000 24px, #000 100%);
}
.fadeBottom {
mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 24px), transparent 100%);
}
.fadeTop.fadeBottom {
mask-image: linear-gradient(
to bottom,
transparent 0,
#000 24px,
#000 calc(100% - 24px),
transparent 100%
);
}
.marks {
position: relative;
height: var(--turn-natural-height);
}
.markPosition {
position: absolute;
top: min(var(--turn-natural-position), var(--turn-position));
top: calc(var(--turn-natural-position) + var(--turn-rail-inset));
right: 0;
left: 0;
height: 10px;
@@ -83,11 +115,21 @@
transition: width 140ms ease, background-color 140ms ease;
}
/* Ordered before hover/active so those states keep their stronger tick. */
.markUnloaded::before {
width: 8px;
opacity: 0.6;
}
.markPreview::before {
width: 18px;
background: var(--dsw-alias-label-tertiary);
}
.markBusy::before {
animation: dsh-turn-mark-busy 1s ease-in-out infinite;
}
.markActive::before {
width: 20px;
background: var(--dsw-alias-label-primary);
@@ -108,13 +150,14 @@
.preview {
position: absolute;
/* Centered on its mark (mark positions are measured inside the rail inset),
then held clear of both rail ends. */
/* Centered on its mark. Mark positions live in the scrolled ladder, so the
frame-level preview subtracts the scroller's offset, then holds clear of
both frame ends. */
top: clamp(
0px,
calc(
min(var(--turn-natural-position), var(--turn-position))
+ var(--turn-rail-inset) - var(--turn-preview-height) / 2
var(--turn-natural-position) + var(--turn-rail-inset)
- var(--turn-scroll-top, 0px) - var(--turn-preview-height) / 2
),
calc(100% - var(--turn-preview-height))
);
@@ -143,14 +186,14 @@
.previewPrompt {
font: var(--dsw-font-xs-strong-13);
-webkit-line-clamp: 2;
-webkit-line-clamp: 1;
}
.previewResponse {
margin-top: 4px;
color: var(--dsw-alias-label-caption);
font: var(--dsw-font-xxs-12);
-webkit-line-clamp: 2;
-webkit-line-clamp: 3;
}
@keyframes dsh-turn-mark-enter {
@@ -163,6 +206,12 @@
to { opacity: 1; transform: translateX(0); }
}
@keyframes dsh-turn-mark-busy {
0%,
100% { opacity: 1; }
50% { opacity: 0.35; }
}
@container (max-width: 900px) {
.slot {
display: none;
@@ -170,11 +219,14 @@
}
@media (prefers-reduced-motion: reduce) {
.rail,
.frame,
.scroller,
.markPosition,
.mark::before,
.markBusy::before,
.preview {
transition: none;
animation: none;
scroll-behavior: auto;
}
}
@@ -1,107 +1,198 @@
import {
memo, useId, useState, type CSSProperties, type MouseEvent, type PointerEvent,
memo, useEffect, useId, useRef, useState,
type CSSProperties, type MouseEvent, type PointerEvent,
} from 'react'
import type { ChatViewSlotProps } from '../contract/slots.ts'
import type { TurnNavigationItem } from '../contract/snapshot.ts'
import type { TurnRailItem } from './turn-rail-items.ts'
import css from './TurnNavigator.module.css'
interface TurnNavigatorProps {
readonly items: readonly TurnNavigationItem[]
readonly items: readonly TurnRailItem[]
readonly activeTurn: number | null
readonly onNavigate: (item: TurnNavigationItem) => void
/** Turn whose jump is still paging history in; its mark pulses. */
readonly busyTurn: number | null
readonly onNavigate: (item: TurnRailItem) => void
readonly t: ChatViewSlotProps['t']
}
/** Resting gap between neighbouring marks before the rail compresses to fit. */
/** Fixed pitch between neighbouring marks; overflow scrolls inside the frame. */
const TURN_SPACING_PX = 10
/** Rail padding above the first mark and below the last one, per end. */
const RAIL_INSET_PX = 6
/** Fade band the mask reserves at a scrollable end. */
const FADE_PX = 24
type TurnPositionStyle = CSSProperties & {
readonly '--turn-natural-position': string
readonly '--turn-position': string
}
type TurnRailStyle = CSSProperties & {
type TurnFrameStyle = CSSProperties & {
readonly '--turn-natural-height': string
readonly '--turn-rail-inset': string
readonly '--turn-scroll-top': string
}
function itemPosition(index: number, count: number): TurnPositionStyle {
const ratio = count <= 1 ? 0 : index / (count - 1)
return {
'--turn-natural-position': `${String(index * TURN_SPACING_PX)}px`,
'--turn-position': `${String(ratio * 100)}%`,
}
function itemPosition(index: number): TurnPositionStyle {
return { '--turn-natural-position': `${String(index * TURN_SPACING_PX)}px` }
}
function railSize(count: number): TurnRailStyle {
function frameStyle(count: number, scrollTop: number): TurnFrameStyle {
return {
'--turn-natural-height': `${String((count - 1) * TURN_SPACING_PX + 2 * RAIL_INSET_PX)}px`,
'--turn-rail-inset': `${String(RAIL_INSET_PX)}px`,
'--turn-scroll-top': `${String(scrollTop)}px`,
}
}
function itemAtPointer(
items: readonly TurnNavigationItem[],
rail: HTMLElement,
items: readonly TurnRailItem[],
frame: HTMLElement,
scrollTop: number,
clientY: number,
): TurnNavigationItem | undefined {
const rect = rail.getBoundingClientRect()
const usableHeight = Math.max(1, rect.height - 2 * RAIL_INSET_PX)
const ratio = Math.max(0, Math.min(1, (clientY - rect.top - RAIL_INSET_PX) / usableHeight))
return items[Math.round(ratio * (items.length - 1))]
): TurnRailItem | undefined {
const rect = frame.getBoundingClientRect()
const offset = clientY - rect.top + scrollTop - RAIL_INSET_PX
const index = Math.max(0, Math.min(items.length - 1, Math.round(offset / TURN_SPACING_PX)))
return items[index]
}
function TurnNavigatorRail({ items, activeTurn, onNavigate, t }: TurnNavigatorProps) {
/** Scroll state the mask fades and follow logic read together. */
interface RailScrollState {
readonly top: number
readonly canScrollUp: boolean
readonly canScrollDown: boolean
}
const RAIL_AT_REST: RailScrollState = { top: 0, canScrollUp: false, canScrollDown: false }
function railScrollState(scroller: HTMLElement): RailScrollState {
const top = scroller.scrollTop
return {
top,
canScrollUp: top > 1,
canScrollDown: top < scroller.scrollHeight - scroller.clientHeight - 1,
}
}
function sameRailScrollState(left: RailScrollState, right: RailScrollState): boolean {
return left.top === right.top
&& left.canScrollUp === right.canScrollUp
&& left.canScrollDown === right.canScrollDown
}
function TurnNavigatorRail({ items, activeTurn, busyTurn, onNavigate, t }: TurnNavigatorProps) {
const [previewTurn, setPreviewTurn] = useState<number | null>(null)
const [scrollState, setScrollState] = useState<RailScrollState>(RAIL_AT_REST)
const scrollerRef = useRef<HTMLDivElement | null>(null)
/** While the pointer works the rail, follow must not move it under the hand. */
const pointerInsideRef = useRef(false)
const previewId = useId()
const syncScrollState = (): void => {
const scroller = scrollerRef.current
if (scroller === null) return
const next = railScrollState(scroller)
setScrollState(current => sameRailScrollState(current, next) ? current : next)
}
// Frame resizes (band/composer changes) move the overflow edges without a
// scroll event; item count changes move the content height the same way.
useEffect(() => {
const scroller = scrollerRef.current
if (scroller === null || typeof ResizeObserver === 'undefined') return
const observer = new ResizeObserver(syncScrollState)
observer.observe(scroller)
return () => { observer.disconnect() }
}, [])
useEffect(syncScrollState, [items.length])
// Keep the active mark visible: centre it whenever it leaves the scrollport,
// unless the reader's pointer is working the rail.
useEffect(() => {
const scroller = scrollerRef.current
const index = items.findIndex(item => item.turn === activeTurn)
if (scroller === null || index < 0 || pointerInsideRef.current) return
const markTop = index * TURN_SPACING_PX + RAIL_INSET_PX
const viewTop = scroller.scrollTop
const viewHeight = scroller.clientHeight
if (viewHeight <= 0 || (markTop >= viewTop + FADE_PX && markTop <= viewTop + viewHeight - FADE_PX)) return
const target = Math.max(0, markTop - viewHeight / 2)
const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches
if (typeof scroller.scrollTo === 'function') {
scroller.scrollTo({ top: target, behavior: reduced ? 'auto' : 'smooth' })
} else {
scroller.scrollTop = target
}
syncScrollState()
}, [activeTurn, items])
if (items.length < 2) return null
const previewIndex = items.findIndex(item => item.turn === previewTurn)
const preview = previewIndex < 0 ? undefined : items[previewIndex]
const previewPosition = previewIndex < 0 ? undefined : itemPosition(previewIndex, items.length)
const previewPosition = previewIndex < 0 ? undefined : itemPosition(previewIndex)
const previewAtPointer = (event: PointerEvent<HTMLElement>): void => {
setPreviewTurn(itemAtPointer(items, event.currentTarget, event.clientY)?.turn ?? null)
const scrollTop = scrollerRef.current?.scrollTop ?? 0
setPreviewTurn(itemAtPointer(items, event.currentTarget, scrollTop, event.clientY)?.turn ?? null)
}
const navigateAtPointer = (event: MouseEvent<HTMLElement>): void => {
const item = itemAtPointer(items, event.currentTarget, event.clientY)
const scrollTop = scrollerRef.current?.scrollTop ?? 0
const item = itemAtPointer(items, event.currentTarget, scrollTop, event.clientY)
if (item !== undefined) onNavigate(item)
}
const fadeClasses = [css.scroller]
if (scrollState.canScrollUp) fadeClasses.push(css.fadeTop)
if (scrollState.canScrollDown) fadeClasses.push(css.fadeBottom)
return (
<div className={css.slot}>
<nav
className={css.rail}
style={railSize(items.length)}
className={css.frame}
style={frameStyle(items.length, scrollState.top)}
aria-label={t('chat.turnNavigation.label')}
onClick={navigateAtPointer}
onPointerMove={previewAtPointer}
onPointerLeave={() => { setPreviewTurn(null) }}
onPointerEnter={() => { pointerInsideRef.current = true }}
onPointerLeave={() => {
pointerInsideRef.current = false
setPreviewTurn(null)
}}
>
<div className={css.marks}>
{items.map((item, index) => {
const active = item.turn === activeTurn
const showingPreview = item.turn === previewTurn
const markClass = active
? `${css.mark} ${css.markActive}`
: showingPreview ? `${css.mark} ${css.markPreview}` : css.mark
return (
<div key={item.turn} className={css.markPosition} style={itemPosition(index, items.length)}>
<button
type="button"
className={markClass}
aria-label={t('chat.turnNavigation.jump', { turn: item.turn })}
aria-current={active ? 'true' : undefined}
aria-describedby={showingPreview ? previewId : undefined}
onClick={(event) => {
event.stopPropagation()
onNavigate(item)
}}
onFocus={() => { setPreviewTurn(item.turn) }}
onBlur={() => { setPreviewTurn(null) }}
/>
</div>
)
})}
<div
ref={scrollerRef}
className={fadeClasses.join(' ')}
onScroll={() => { syncScrollState() }}
>
<div className={css.marks}>
{items.map((item, index) => {
const active = item.turn === activeTurn
const showingPreview = item.turn === previewTurn
const classes = [css.mark]
if (item.anchor.kind === 'unloaded') classes.push(css.markUnloaded)
if (active) classes.push(css.markActive)
else if (showingPreview) classes.push(css.markPreview)
if (item.turn === busyTurn) classes.push(css.markBusy)
return (
<div key={item.turn} className={css.markPosition} style={itemPosition(index)}>
<button
type="button"
className={classes.join(' ')}
aria-label={t(
item.anchor.kind === 'loaded' ? 'chat.turnNavigation.jump' : 'chat.turnNavigation.jumpLoad',
{ turn: item.turn },
)}
aria-current={active ? 'true' : undefined}
aria-busy={item.turn === busyTurn ? 'true' : undefined}
aria-describedby={showingPreview ? previewId : undefined}
onClick={(event) => {
event.stopPropagation()
onNavigate(item)
}}
onFocus={() => { setPreviewTurn(item.turn) }}
onBlur={() => { setPreviewTurn(null) }}
/>
</div>
)
})}
</div>
</div>
{preview !== undefined && previewPosition !== undefined && (
<div id={previewId} role="tooltip" className={css.preview} style={previewPosition}>
@@ -117,9 +208,12 @@ function TurnNavigatorRail({ items, activeTurn, onNavigate, t }: TurnNavigatorPr
}
/**
* Compact rail of the currently loaded Turns with hover and focus previews.
* Fixed-pitch rail of every known Turn — loaded marks scroll, unloaded marks
* page history in first — with hover and focus previews. Overflow scrolls
* inside the frame, gradient fades marking each scrollable end, and the
* active mark keeps itself in view while the pointer is elsewhere.
*
* Memoized because it renders two host elements per loaded Turn while the
* Memoized because it renders two host elements per Turn while the
* enclosing view re-renders on every streaming delta: without the guard a long
* session rebuilds hundreds of marks per commit for a rail that only changes
* when a Turn is added, removed, or becomes active. Its props must therefore
@@ -0,0 +1,88 @@
/**
* View-layer union of the host turn outline and the loaded rail items. The
* conversation snapshot never carries projection values, so this merge is the
* one place the rail's two sources meet: the `turnOutline` projection names
* every turn of the session, and the loaded window supplies anchors and
* richer previews for the turns it holds.
*/
import type {} from '@deepseek-ai/dsh-session-turn-outline/client'
import type { TurnNavigationItem } from '../contract/snapshot.ts'
/** One rail mark: a loaded Turn scrolls to its row; an unloaded one pages history through its seq first. */
export interface TurnRailItem {
readonly turn: number
/** Bounded prompt preview (loaded window first, outline fallback). */
readonly prompt: string
/** Bounded response preview (loaded window first, outline fallback). */
readonly response: string
/** How the rail reaches the Turn. */
readonly anchor:
| { readonly kind: 'loaded'; readonly key: string }
| { readonly kind: 'unloaded'; readonly seq: number }
}
const EMPTY_ITEMS: readonly TurnRailItem[] = []
/**
* Structurally narrow one wire outline entry (projection values cross the
* wire). `turn` and `seq` are the load-bearing fields — a mark cannot exist
* or jump without them — so their damage drops the entry; the previews are
* decorative, so a malformed one degrades to `''` and the turn stays
* navigable by number.
*/
function outlineEntry(value: unknown): { turn: number; seq: number; prompt: string; response: string } | undefined {
if (typeof value !== 'object' || value === null) return undefined
const entry = value as { turn?: unknown; seq?: unknown; prompt?: unknown; response?: unknown }
if (typeof entry.turn !== 'number' || !Number.isSafeInteger(entry.turn) || entry.turn < 0) return undefined
if (typeof entry.seq !== 'number' || !Number.isSafeInteger(entry.seq) || entry.seq < 0) return undefined
return {
turn: entry.turn,
seq: entry.seq,
prompt: typeof entry.prompt === 'string' ? entry.prompt : '',
response: typeof entry.response === 'string' ? entry.response : '',
}
}
/** Wire outline entries, or none when the projection is absent or malformed. */
function outlineEntries(outline: unknown): readonly unknown[] {
return Array.isArray(outline) ? outline : EMPTY_ITEMS
}
/**
* Merge the host outline with the loaded rail items into the full ladder.
* A turn present in both sides keeps the loaded anchor, taking an outline
* preview only where the window's own is empty (a mid-Turn window head, or a
* turn whose loaded nodes carry no text); turns on one side only pass
* through. Result ascends by turn.
* @param loaded - loaded-window rail items (timeline order).
* @param outline - `turnOutline` projection value, treated as wire data.
* @returns every known turn, ascending; a stable empty array when none.
*/
export function mergeTurnRailItems(
loaded: readonly TurnNavigationItem[],
outline: unknown,
): readonly TurnRailItem[] {
const byTurn = new Map<number, TurnRailItem>()
for (const raw of outlineEntries(outline)) {
const entry = outlineEntry(raw)
if (entry === undefined) continue
byTurn.set(entry.turn, {
turn: entry.turn,
prompt: entry.prompt,
response: entry.response,
anchor: { kind: 'unloaded', seq: entry.seq },
})
}
for (const item of loaded) {
const preview = byTurn.get(item.turn)
byTurn.set(item.turn, {
turn: item.turn,
prompt: item.prompt !== '' ? item.prompt : preview?.prompt ?? '',
response: item.response !== '' ? item.response : preview?.response ?? '',
anchor: { kind: 'loaded', key: item.anchorKey },
})
}
if (byTurn.size === 0) return EMPTY_ITEMS
return [...byTurn.values()].sort((left, right) => left.turn - right.turn)
}
@@ -118,6 +118,8 @@ export interface ChatViewInjected {
openDetails: (target: SelectionTarget) => void
openFile: (path: string) => Promise<void>
loadOlder: () => void
/** Jump loader: page history back through seq; resolves when the window covers it. */
loadThrough: (seq: number) => Promise<void>
loadImage: MessageImageLoader
chatScroll: {
save: (position: ChatScrollPosition | null) => void
@@ -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',
@@ -2,30 +2,55 @@ import type { ChatNode } from '../contract/chat-nodes.ts'
import type { ChatLocationNodeIndex, ChatNodeStore, TurnNavigationItem } from '../contract/snapshot.ts'
/**
* Preview budget per field. The rail clamps two short lines, so anything past
* this is invisible; copying whole transcripts into navigation state would
* Preview budgets, sized to the rail card's clamps (one prompt line, up to
* three response lines) and mirrored by the turnOutline projection so a turn
* shows the same words before and after its events load. Anything past a
* budget is invisible; copying whole transcripts into navigation state would
* otherwise grow with the loaded window on every structural update.
*/
const PREVIEW_LIMIT = 160
const PROMPT_PREVIEW_LIMIT = 50
const RESPONSE_PREVIEW_LIMIT = 120
/** Join rendered text until the preview budget is met, then stop reading. */
function preview(parts: Iterable<string>): string {
/** Join rendered text, collapse whitespace, and cap at `limit` with a trailing ellipsis when clipped. */
// Deliberate mirror of the turnOutline projection's preview(): the wire
// boundary forbids sharing code with the host package.
/* jscpd:ignore-start */
function preview(parts: Iterable<string>, limit: number): string {
let text = ''
let unread = false
for (const part of parts) {
text += text === '' ? part : ` ${part}`
if (text.length >= PREVIEW_LIMIT) break
if (text.length >= limit * 2) {
unread = true
break
}
// Per-part bound: this runs on every structural rail update, so one huge
// text block must not be concatenated (and regex-normalized) whole for a
// preview this short.
const clipped = part.length > limit * 2
const chunk = clipped ? part.slice(0, limit * 2) : part
text += text === '' ? chunk : ` ${chunk}`
if (clipped) {
unread = true
break
}
}
return text.replace(/\s+/g, ' ').trim().slice(0, PREVIEW_LIMIT)
const normalized = text.replace(/\s+/g, ' ').trim()
if (normalized.length > limit - 1) return `${normalized.slice(0, limit - 1).trimEnd()}…`
return unread ? `${normalized}…` : normalized
}
/* jscpd:ignore-end */
function promptText(node: ChatNode): string {
if (node.kind !== 'user') return ''
return preview(node.data.content.flatMap(block => block.type === 'text' ? [block.text] : []))
return preview(node.data.content.flatMap(block => block.type === 'text' ? [block.text] : []), PROMPT_PREVIEW_LIMIT)
}
function responseText(node: ChatNode): string {
if (node.kind !== 'assistant-step') return ''
return preview(node.data.blocks.flatMap(block => block.kind === 'text' ? [block.text] : []))
return preview(
node.data.blocks.flatMap(block => block.kind === 'text' ? [block.text] : []),
RESPONSE_PREVIEW_LIMIT,
)
}
/**
@@ -31,6 +31,7 @@ export const zh = {
'chat.deepDiving': '深度求索中...',
'chat.turnNavigation.label': '轮次导航',
'chat.turnNavigation.jump': '跳转到第 {turn} 轮',
'chat.turnNavigation.jumpLoad': '加载并跳转到第 {turn} 轮',
'chat.turnNavigation.turn': '第 {turn} 轮',
'settings.transcript.title': '对话显示',
'settings.transcript.description': '控制已完成轮次的过程内容',
@@ -147,6 +148,7 @@ export const en = {
'chat.deepDiving': 'Deep diving...',
'chat.turnNavigation.label': 'Turn navigation',
'chat.turnNavigation.jump': 'Jump to turn {turn}',
'chat.turnNavigation.jumpLoad': 'Load and jump to turn {turn}',
'chat.turnNavigation.turn': 'Turn {turn}',
'settings.transcript.title': 'Conversation display',
'settings.transcript.description': 'Controls process content in completed turns',
@@ -35,6 +35,7 @@ type ChatActions = ChatInstance['actions']
function sessionFakeFor() {
return {
loadOlder: vi.fn<ISession['loadOlder']>(() => Promise.resolve()),
loadThrough: vi.fn<ISession['loadThrough']>(() => Promise.resolve()),
readAttachment: vi.fn<ISession['readAttachment']>(() => Promise.resolve({
ok: true,
value: { attachment: ATTACHMENT, data: Uint8Array.of(1) },
@@ -92,6 +93,9 @@ describe('Chat inject API', () => {
injected.loadOlder()
expect(b.session.loadOlder).toHaveBeenCalledOnce()
void injected.loadThrough(42)
expect(b.session.loadThrough).toHaveBeenCalledWith(42)
injected.forkAt(17)
await vi.waitFor(() => {
expect(b.runtime.sessions.calls).toContainEqual({ method: 'open', args: [ROOT] })
@@ -222,6 +222,9 @@ function makeHarness(
const openDetails = vi.fn<(t: SelectionTarget) => void>()
const openFile = vi.fn<(path: string) => Promise<void>>().mockResolvedValue(undefined)
const loadOlder = vi.fn()
const loadThrough = vi.fn<(seq: number) => Promise<void>>().mockResolvedValue(undefined)
// Mutable outline holder: tests swap the value and drive a re-render via set().
let outlineValue: unknown
const openView = vi.fn<(view: string, focus: string) => void>()
// In-memory scroll memory matching the apply.ts per-session map contract.
let savedScroll: ReturnType<ChatViewSlotProps['chatScroll']['read']> = null
@@ -348,7 +351,7 @@ function makeHarness(
createSnapshotStore<SessionPendingInteractionSnapshot>(new Map()),
),
useWorkspaces: emptyWorkspaces(),
useProjection: (() => undefined),
useProjection: () => outlineValue,
useInput: (() => { throw new Error('unused') }),
inputActions: {
setDraft: () => {},
@@ -368,6 +371,7 @@ function makeHarness(
openDetails,
openFile,
loadOlder,
loadThrough,
loadImage: vi.fn(() => Promise.reject(new Error('not used'))),
chatScroll,
forkAt,
@@ -396,7 +400,8 @@ function makeHarness(
const setSelection = (next: SelectionTarget | null): void => { chat.actions.select(next) }
return {
set, setSession: session.set, setChat: chatSource.set, ChatView, props,
openDetails, openFile, loadOlder, openView,
openDetails, openFile, loadOlder, loadThrough, openView,
setOutline: (value: unknown) => { outlineValue = value },
chatScroll, forkAt, setSelection, toolOwners,
setTranscriptView: (mode: TranscriptViewMode) => { transcriptView.set(mode) },
setNodeRenderer: (renderer: React.ComponentProps<typeof ChatNodeSeat>['renderSlot']) => {
@@ -573,7 +578,7 @@ describe('ChatView', () => {
const view = render(<h.ChatView {...h.props} />)
const second = view.getByRole('button', { name: '跳转到第 2 轮' })
const secondPosition = second.parentElement as HTMLElement
expect(secondPosition.style.getPropertyValue('--turn-position')).toBe('0%')
expect(secondPosition.style.getPropertyValue('--turn-natural-position')).toBe('0px')
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
const metrics = installScrollMetrics(scroller, 1_000, 300)
@@ -593,8 +598,156 @@ describe('ChatView', () => {
})
const movedSecond = view.getByRole('button', { name: '跳转到第 2 轮' })
expect(movedSecond.parentElement).toBe(secondPosition)
// Fixed pitch: the mark moves one slot down and never compresses.
expect(secondPosition.style.getPropertyValue('--turn-natural-position')).toBe('10px')
expect(secondPosition.style.getPropertyValue('--turn-position')).toBe('50%')
})
it('extends the rail with unloaded outline turns, pages on click, and falls back when nothing lands', async () => {
const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)]
const h = makeHarness({ nodes: later }, { hasMore: true })
h.setOutline([
{ turn: 1, seq: 0, prompt: 'first prompt from outline', response: 'first answer from outline' },
{ turn: 2, seq: 4, prompt: 'second prompt from outline', response: '' },
{ turn: 3, seq: 8, prompt: 'third prompt', response: 'third response' },
])
const view = render(<h.ChatView {...h.props} />)
const first = view.getByRole('button', { name: '加载并跳转到第 1 轮' })
view.getByRole('button', { name: '加载并跳转到第 2 轮' })
const third = view.getByRole('button', { name: '跳转到第 3 轮' })
expect(third.getAttribute('aria-current')).toBe('true')
fireEvent.focus(first)
// An unloaded turn previews both sides from the outline.
expect(view.getByRole('tooltip').textContent).toContain('first prompt from outline')
expect(view.getByRole('tooltip').textContent).toContain('first answer from outline')
fireEvent.click(first)
expect(h.loadThrough).toHaveBeenCalledWith(0)
expect(first.getAttribute('aria-busy')).toBe('true')
// The fake loader never delivers rows: settlement repages once for the
// unmoved head, then lands on the nearest rendered turn and un-busies.
await act(async () => {})
expect(h.loadThrough.mock.calls).toEqual([[0], [0]])
expect(first.getAttribute('aria-busy')).toBeNull()
expect(view.getByRole('button', { name: '跳转到第 3 轮' }).getAttribute('aria-current')).toBe('true')
})
it('a jump from the pinned tail releases bottom ownership so the follow snap cannot cancel it', async () => {
const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)]
const h = makeHarness({ nodes: later }, { hasMore: true })
h.setOutline([
{ turn: 1, seq: 0, prompt: 'first prompt', response: '' },
{ turn: 3, seq: 8, prompt: 'third prompt', response: '' },
])
let releaseJump: (() => void) | undefined
h.loadThrough.mockImplementation(() => new Promise<void>((resolve) => { releaseJump = resolve }))
const view = render(<h.ChatView {...h.props} />)
// Pinned to the tail on open: the back-to-bottom control is absent.
expect(view.queryByRole('button', { name: '回到底部' })).toBeNull()
const first = view.getByRole('button', { name: '加载并跳转到第 1 轮' })
fireEvent.click(first)
// The click itself leaves the tail...
expect(view.getByRole('button', { name: '回到底部' })).toBeTruthy()
// ...so a non-reader scroll delivery at the floor (the first prepend's
// compensation fires one) no longer snaps to the tail and cancel the jump.
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLElement
fireEvent.scroll(scroller)
expect(first.getAttribute('aria-busy')).toBe('true')
await act(async () => { releaseJump?.() })
})
it('holds a jump issued while a plain pull owns the pager and resumes it when the pull settles', async () => {
const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)]
const h = makeHarness({ nodes: later }, { hasMore: true, loadingOlder: true })
h.setOutline([
{ turn: 1, seq: 0, prompt: 'first prompt', response: '' },
{ turn: 3, seq: 8, prompt: 'third prompt', response: '' },
])
const view = render(<h.ChatView {...h.props} />)
const first = view.getByRole('button', { name: '加载并跳转到第 1 轮' })
fireEvent.click(first)
// The session-side guard refuses the busy-pager jump instantly, yet the
// mark stays busy instead of degrading to the nearest loaded turn.
await act(async () => {})
expect(h.loadThrough.mock.calls).toEqual([[0]])
expect(first.getAttribute('aria-busy')).toBe('true')
// The plain pull settles: the flip re-settles the jump, which repages.
act(() => { h.setSession({ loadingOlder: false }) })
await act(async () => {})
expect(h.loadThrough.mock.calls).toEqual([[0], [0]])
expect(first.getAttribute('aria-busy')).toBeNull()
})
it('scrolls the fixed-pitch rail inside its frame with gradient fades at the scrollable ends', () => {
const h = makeHarness(
{ nodes: [userInTurn(8, 'latest prompt', 60), assistant(9, 'latest response', 60)] },
{ hasMore: true },
)
h.setOutline(Array.from({ length: 60 }, (_, index) => ({
turn: index + 1,
seq: index * 4,
prompt: `p${String(index + 1)}`,
response: '',
})))
const view = render(<h.ChatView {...h.props} />)
const nav = view.getByRole('navigation', { name: '轮次导航' })
// 60 marks at the fixed 10px pitch: the ladder keeps its natural height.
expect(nav.style.getPropertyValue('--turn-natural-height')).toBe('602px')
const scroller = nav.querySelector('[class*="scroller"]') as HTMLElement
Object.defineProperty(scroller, 'scrollHeight', { value: 602, configurable: true })
Object.defineProperty(scroller, 'clientHeight', { value: 300, configurable: true })
scroller.scrollTop = 0
fireEvent.scroll(scroller)
expect(scroller.className).toContain('fadeBottom')
expect(scroller.className).not.toContain('fadeTop')
scroller.scrollTop = 150
fireEvent.scroll(scroller)
expect(scroller.className).toContain('fadeTop')
expect(scroller.className).toContain('fadeBottom')
expect(nav.style.getPropertyValue('--turn-scroll-top')).toBe('150px')
// Pointer mapping subtracts the rail scroll: y=94 with scrollTop 150 is
// natural offset 238px → the 25th mark.
vi.spyOn(nav, 'getBoundingClientRect').mockReturnValue({ top: 0 } as DOMRect)
fireEvent.pointerMove(nav, { clientY: 94 })
expect(view.getByRole('tooltip').textContent).toContain('p25')
})
it('lands a jump on its turn once the paged rows commit', async () => {
const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)]
const h = makeHarness({ nodes: later }, { hasMore: true })
h.setOutline([
{ turn: 1, seq: 0, prompt: 'first prompt', response: '' },
{ turn: 3, seq: 8, prompt: 'third prompt', response: '' },
])
let releaseJump: (() => void) | undefined
h.loadThrough.mockImplementation(() => new Promise<void>((resolve) => { releaseJump = resolve }))
const view = render(<h.ChatView {...h.props} />)
fireEvent.click(view.getByRole('button', { name: '加载并跳转到第 1 轮' }))
expect(h.loadThrough).toHaveBeenCalledWith(0)
// The paged window commits: turn 1's rows and rail item enter the snapshot.
act(() => {
h.setChat({
nodes: [userInTurn(0, 'first prompt', 1), assistant(1, 'first response', 1), ...later],
turnTimings: new Map([[1, { startTime: 1_000 }], [3, { startTime: 8_000 }]]),
})
})
const first = view.getByRole('button', { name: '跳转到第 1 轮' })
expect(first.getAttribute('aria-current')).toBe('true')
// The mark stays busy until the jump settles: the loader's completion
// runs the final landing correction after the load-earlier button leaves.
expect(first.getAttribute('aria-busy')).toBe('true')
await act(async () => { releaseJump?.() })
// Only the busy lifecycle is asserted after settlement: jsdom's zero
// geometry makes the rAF active-turn resync read "at bottom" and hand the
// mark to the last turn, so aria-current here is timing-dependent under
// instrumentation; the landing position contract lives in the browser e2e.
expect(first.getAttribute('aria-busy')).toBeNull()
})
it('hands a windowless tool result to the Tool seat with an empty tool name', () => {
@@ -2179,6 +2332,58 @@ describe('ChatView', () => {
expect(observe).toHaveBeenCalledTimes(1)
})
it('pinned dynamic-height updates select the latest Turn without reading row geometry', () => {
let notify: (() => void) | undefined
let nextFrame = 0
const frames = new Map<number, FrameRequestCallback>()
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
nextFrame += 1
frames.set(nextFrame, callback)
return nextFrame
})
vi.stubGlobal('cancelAnimationFrame', (id: number) => { frames.delete(id) })
class ResizeObserverStub {
constructor(callback: ResizeObserverCallback) {
notify = () => { callback([], this as unknown as ResizeObserver) }
}
observe = vi.fn()
disconnect = vi.fn()
}
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
.mockReturnValue({ top: 0, bottom: 40 } as DOMRect)
const h = makeHarness({
nodes: [
userInTurn(1, 'first', 1), assistant(2, 'first answer', 1),
userInTurn(4, 'second', 2), assistant(5, 'second answer', 2),
],
turnEnds: new Map([[1, 3], [2, 6]]),
})
const view = render(<h.ChatView {...h.props} />)
const scroller = view.container.querySelector('[class*="scroll"]') as HTMLDivElement
const metrics = installScrollMetrics(scroller, 1_000, 300)
scroller.scrollTop = 700
act(() => {
const pending = [...frames.values()]
frames.clear()
for (const callback of pending) callback(0)
})
rect.mockClear()
metrics.setHeight(1_200)
act(() => { notify?.() })
act(() => {
const pending = [...frames.values()]
frames.clear()
for (const callback of pending) callback(0)
})
expect(scroller.scrollTop).toBe(900)
expect(view.getByRole('button', { name: '跳转到第 2 轮' }).getAttribute('aria-current')).toBe('true')
expect(rect).not.toHaveBeenCalled()
})
it('entering the at-bottom threshold does not snap the remaining scroll distance', () => {
const h = makeHarness({ nodes: [user(1, 'q'), assistant(2, 'a')] })
const view = render(<h.ChatView {...h.props} />)
@@ -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
}
@@ -215,14 +214,16 @@ describe('built-in conversation node Definitions', () => {
expect(streamed).not.toBe(opening)
})
it('bounds each rail preview instead of copying the whole transcript', () => {
it('bounds each rail preview at its card budget instead of copying the whole transcript', () => {
const long = 'x'.repeat(400)
const value = assembler([
at(1, 'turn/start', { turn: 1 }),
at(2, 'user/message', textMessage('user-1', long), { surfaceOp: 'append' }),
])
const items = snapshot(value).navigation.items()
expect(items[0]?.prompt.length).toBe(160)
// One clipped prompt line: 49 characters plus the trailing ellipsis.
expect(items[0]?.prompt.length).toBe(50)
expect(items[0]?.prompt.endsWith('…')).toBe(true)
})
it('classifies reply content separately from reasoning and Tool protocol blocks', () => {
@@ -419,6 +420,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([
@@ -0,0 +1,75 @@
// @vitest-environment jsdom
import { describe, expect, it } from 'vitest'
import { mergeTurnRailItems } from '../src/client/chat/turn-rail-items.ts'
import type { TurnNavigationItem } from '../src/client/contract/snapshot.ts'
function loadedItem(turn: number, prompt = `p${String(turn)}`, response = `r${String(turn)}`): TurnNavigationItem {
return { turn, anchorKey: `anchor-${String(turn)}`, prompt, response }
}
describe('mergeTurnRailItems', () => {
it('returns a stable empty array when both sides are empty', () => {
expect(mergeTurnRailItems([], undefined)).toBe(mergeTurnRailItems([], []))
})
it('maps outline-only turns to unloaded marks with both previews in ascending order', () => {
const items = mergeTurnRailItems([], [
{ turn: 1, seq: 0, prompt: 'first', response: 'first answer' },
{ turn: 2, seq: 9, prompt: '', response: '' },
])
expect(items).toEqual([
{ turn: 1, prompt: 'first', response: 'first answer', anchor: { kind: 'unloaded', seq: 0 } },
{ turn: 2, prompt: '', response: '', anchor: { kind: 'unloaded', seq: 9 } },
])
})
it('prefers the loaded side on overlap but fills empty previews from the outline', () => {
const items = mergeTurnRailItems(
[loadedItem(2, '', ''), loadedItem(3)],
[
{ turn: 1, seq: 0, prompt: 'one', response: 'answer one' },
{ turn: 2, seq: 8, prompt: 'two from outline', response: 'answer two from outline' },
{ turn: 3, seq: 16, prompt: 'three from outline', response: 'answer three from outline' },
],
)
expect(items).toEqual([
{ turn: 1, prompt: 'one', response: 'answer one', anchor: { kind: 'unloaded', seq: 0 } },
{
turn: 2,
prompt: 'two from outline',
response: 'answer two from outline',
anchor: { kind: 'loaded', key: 'anchor-2' },
},
{ turn: 3, prompt: 'p3', response: 'r3', anchor: { kind: 'loaded', key: 'anchor-3' } },
])
})
it('passes loaded turns through when the outline is absent or lagging', () => {
expect(mergeTurnRailItems([loadedItem(7)], undefined)).toEqual([
{ turn: 7, prompt: 'p7', response: 'r7', anchor: { kind: 'loaded', key: 'anchor-7' } },
])
expect(mergeTurnRailItems([loadedItem(4)], [{ turn: 3, seq: 1, prompt: 'older', response: '' }])).toEqual([
{ turn: 3, prompt: 'older', response: '', anchor: { kind: 'unloaded', seq: 1 } },
{ turn: 4, prompt: 'p4', response: 'r4', anchor: { kind: 'loaded', key: 'anchor-4' } },
])
})
it('drops entries with damaged navigation fields but degrades malformed previews to empty', () => {
expect(mergeTurnRailItems([loadedItem(1)], 'not an outline')).toEqual([
{ turn: 1, prompt: 'p1', response: 'r1', anchor: { kind: 'loaded', key: 'anchor-1' } },
])
const items = mergeTurnRailItems([], [
{ turn: -1, seq: 0, prompt: 'negative turn', response: '' },
{ turn: 2, seq: 0.5, prompt: 'fractional seq', response: '' },
{ turn: 3, seq: 4, prompt: 5, response: 6 },
{ turn: 6, seq: 7, prompt: 'kept', response: 8 },
null,
])
// turn/seq are load-bearing (drop); previews are decorative (degrade).
expect(items).toEqual([
{ turn: 3, prompt: '', response: '', anchor: { kind: 'unloaded', seq: 4 } },
{ turn: 6, prompt: 'kept', response: '', anchor: { kind: 'unloaded', seq: 7 } },
])
})
})
+3
View File
@@ -56,6 +56,9 @@
{
"path": "../../session/session-stats"
},
{
"path": "../../session/session-turn-outline"
},
{
"path": "../../settings/settings"
},
@@ -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.
Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff. Show more