From 449c679892c24ed5c0acf785fd4986058529a233 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 18 Sep 2026 11:47:09 +0800 Subject: [PATCH 01/24] fix(session-snapshot): expand source references before writing fixtures --- .../2026-06-19-acp-snapshot-tests.i18n.yaml | 4 ++-- .../testing/2026-06-19-acp-snapshot-tests.md | 2 +- .../2026-06-19-acp-snapshot-tests.zh.md | 2 +- .../session-snapshot/README.i18n.yaml | 4 ++-- .../test-support/session-snapshot/README.md | 2 +- .../session-snapshot/README.zh.md | 2 +- .../session-snapshot/src/normalize.ts | 6 +++++- scripts/session-fixture-layout.spec.ts | 21 ++++++++++++++++++- 8 files changed, 33 insertions(+), 10 deletions(-) diff --git a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.i18n.yaml b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.i18n.yaml index 4376b51c83..42cefa39a0 100644 --- a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.i18n.yaml @@ -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-06-19-acp-snapshot-tests.md -2026-06-19-acp-snapshot-tests.md: d6fd6f74342fda3e1f3c686376f521bf82546e85 -2026-06-19-acp-snapshot-tests.zh.md: dfd09f9d9036763c5fd98393f078bf1772aa0beb +2026-06-19-acp-snapshot-tests.md: 3a21d09609d45b574d7f19c3704a44dde5a3d17c +2026-06-19-acp-snapshot-tests.zh.md: e9f3682289a05e4e54db2de3adcd3bee7042ef1b diff --git a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md index d6fd6f7434..3a21d09609 100644 --- a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md +++ b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md @@ -57,7 +57,7 @@ A snapshot run asserts **two** normalized outputs, because the harness's externa The surfaces are complementary: stdout covers the minimal automation wire, while JSONL covers loop, tool, and boundary structure that the wire intentionally omits. -Normalization replaces session, cwd, protocol-id, timestamp, path, and process volatility; fixture projection omits body sequence/time envelopes without changing payload references. Record and refresh also store a generated workspace and its filesystem-resolved aliases as `{{cwd}}` in the replay fixture, so platform temp roots and random basenames do not affect recordings; authored temp paths and cwd values under an explicit `workspaceParent` remain literal. Scenarios constrain real bash use to stable commands. The stdout expected output remains wire-shaped JSONL and every raw line must parse as JSON. Ordinary Vitest snapshot updates write only the stdout expected output; the explicit `record` and `refresh` modes own replay-fixture writes. +Normalization replaces session, cwd, protocol-id, timestamp, path, and process volatility; fixture projection omits body sequence/time envelopes without changing payload references. The shared snapshot writer expands top-level `sourceEventSeqs` ranges before saving, so record and refresh produce canonical fixture bytes independently of replay normalization. Record and refresh also store a generated workspace and its filesystem-resolved aliases as `{{cwd}}` in the replay fixture, so platform temp roots and random basenames do not affect recordings; authored temp paths and cwd values under an explicit `workspaceParent` remain literal. Scenarios constrain real bash use to stable commands. The stdout expected output remains wire-shaped JSONL and every raw line must parse as JSON. Ordinary Vitest snapshot updates write only the stdout expected output; the explicit `record` and `refresh` modes own replay-fixture writes. ### Isolation: normalization now, sandbox later diff --git a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.zh.md b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.zh.md index dfd09f9d90..e9f3682289 100644 --- a/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.zh.md +++ b/.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.zh.md @@ -57,7 +57,7 @@ Log 从持久 Assistant settlement 与显式标记的 compaction call 推导 chu 两个表面互补:stdout 覆盖精简的自动化协议格式,JSONL 覆盖协议格式有意省略的循环、工具和边界结构。 -规范化会替换会话、cwd、协议 id、时间戳、路径和进程易变值;fixture 投影会省略正文序号/时间 envelope,而不修改 payload 引用。录制与刷新还会在回放 fixture 中将生成的 workspace 及其文件系统解析出的别名存储为 `{{cwd}}`,使平台临时根目录和随机 basename 不影响录制结果;手工编写的临时路径与显式 `workspaceParent` 下的 cwd 值仍保留字面值。场景把真实 bash 使用限制在稳定命令上。stdout 预期输出仍是符合协议格式的 JSONL,每个原始行都必须可解析为 JSON。普通 Vitest 快照更新只写入 stdout 预期输出;回放 fixture 的写入由显式 `record` 和 `refresh` 模式负责。 +规范化会替换会话、cwd、协议 id、时间戳、路径和进程易变值;fixture 投影会省略正文序号/时间 envelope,而不修改 payload 引用。共享快照写入器在保存前展开顶层 `sourceEventSeqs` 区间,使录制与刷新直接产出规范 fixture 字节,无需依赖回放时的规范化。录制与刷新还会在回放 fixture 中将生成的 workspace 及其文件系统解析出的别名存储为 `{{cwd}}`,使平台临时根目录和随机 basename 不影响录制结果;手工编写的临时路径与显式 `workspaceParent` 下的 cwd 值仍保留字面值。场景把真实 bash 使用限制在稳定命令上。stdout 预期输出仍是符合协议格式的 JSONL,每个原始行都必须可解析为 JSON。普通 Vitest 快照更新只写入 stdout 预期输出;回放 fixture 的写入由显式 `record` 和 `refresh` 模式负责。 ### 隔离:当前靠归一化,后续可加沙箱 diff --git a/packages/test-support/session-snapshot/README.i18n.yaml b/packages/test-support/session-snapshot/README.i18n.yaml index 9c31a25c34..6737bcc4cb 100644 --- a/packages/test-support/session-snapshot/README.i18n.yaml +++ b/packages/test-support/session-snapshot/README.i18n.yaml @@ -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/test-support/session-snapshot/README.md -README.md: 51aaff9af7dfce83ed032b42ce0bb471aa384002 -README.zh.md: ad136b19a75170c130bbb872ba02bb88e010bb02 +README.md: 1886c79f7fac505cd515c93be03a6b67d22ffc2e +README.zh.md: 3af39ef8e6b80992a748e4cee85b788ab4ba3852 diff --git a/packages/test-support/session-snapshot/README.md b/packages/test-support/session-snapshot/README.md index 51aaff9af7..1886c79f7f 100644 --- a/packages/test-support/session-snapshot/README.md +++ b/packages/test-support/session-snapshot/README.md @@ -70,7 +70,7 @@ defineAcpSnapshotSuite({ Each recorded-session directory carries a closed `snapshot.yml` manifest plus canonical parent and contiguous child roles. Parent filenames are `session[.vN].jsonl`; children are `session.[.vN].jsonl`; v0 omits `.v0`, positive versions use lowercase `.vN`, and every filename agrees with its header. A role may retain older generations, but the harness selects the numerically highest one. An owning manifest may declare `sessionFormat.version` plus one or more closed `coverage` names to keep that historical generation as an explicit migration fixture; absence tracks the current writer. The manifest also names the scenario, shipped profile, composition/header class, recording source, and only the replay, platform, permission, environment, workspace, or input facts the completed Session cannot reconstruct. Storage guards check tool results and portable paths in every selected parent and child role. Prompt/schema scrubbing, message identity, and prompt-before-request ordering apply to current generations; retained predecessors keep their historical representation. The adapter registers expected-output, Session-log, and optional `workspace.expected/` comparisons; guards reject orphan directories, missing roles, noncanonical names, absolute paths, malformed manifests, and platform-specific separators. -`normalizeSessionSnapshot` retains the complete Session header and event payloads but omits top-level `seq`/`time` envelopes from committed fixtures after normalizing paths and scrubbing system-prompt text and tool schemas; it also normalizes embedded stream clocks and historical packed-row `seq0`/`time0` envelopes, and catalog child-creation clocks. Event order and source-event references are preserved. Replay synthesizes the top-level envelopes in memory, while runtime persistence continues to write complete logs. Multi-session comparison validates expected and harvested logs through the strict build-static Session format catalog before identity redaction and normalization; source filenames cannot alter format validation. A retained historical replay input is not the native current-format writer-output oracle: structural migration preserves request meaning but can produce a different event layout. Normalization preserves unexpected request-header fields, including `system`, so regressions remain visible. Versionless protocol-adapter unit fixtures remain outside the released Session format corpus. Fixtures in the [current writer format](../../../docs/session-format-status.md) use one row per event; retained v0/v1 fixtures may use canonical packed rows. The [temporary repository migrator](../../../scripts/migrate-packed-session-fixtures.ts) (`pnpm run migrate:packed-session-fixtures`) rewrites older historical layouts, and its [removal proposal](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.md) owns its deletion. +`normalizeSessionSnapshot` retains the complete Session header and event payloads but omits top-level `seq`/`time` envelopes from committed fixtures after normalizing paths and scrubbing system-prompt text and tool schemas; it also normalizes embedded stream clocks and historical packed-row `seq0`/`time0` envelopes, and catalog child-creation clocks. Event order and source-event references are preserved. Record and refresh expand top-level `sourceEventSeqs` ranges before writing fixtures. Replay synthesizes the top-level envelopes in memory, while runtime persistence continues to write complete logs. Multi-session comparison validates expected and harvested logs through the strict build-static Session format catalog before identity redaction and normalization; source filenames cannot alter format validation. A retained historical replay input is not the native current-format writer-output oracle: structural migration preserves request meaning but can produce a different event layout. Normalization preserves unexpected request-header fields, including `system`, so regressions remain visible. Versionless protocol-adapter unit fixtures remain outside the released Session format corpus. Fixtures in the [current writer format](../../../docs/session-format-status.md) use one row per event; retained v0/v1 fixtures may use canonical packed rows. The [temporary repository migrator](../../../scripts/migrate-packed-session-fixtures.ts) (`pnpm run migrate:packed-session-fixtures`) rewrites older historical layouts, and its [removal proposal](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.md) owns its deletion. Spill scenarios save through the real local provider under a private temporary root. Their fixture adapter exposes fixed-length logical locators and maps only this run’s saved locators back to real files for retrieval, preserving preview budgets without writing into a shared logical path. Known snapshot spill paths normalize to stable locator tokens, including paths quoted inside JSON omission notices with JSON-escaped Windows separators. Refresh extraction preserves the matched serialized path spelling for literal replacement. Normalization changes only the locator: saved byte lengths and omission counts remain comparison evidence. diff --git a/packages/test-support/session-snapshot/README.zh.md b/packages/test-support/session-snapshot/README.zh.md index ad136b19a7..3af39ef8e6 100644 --- a/packages/test-support/session-snapshot/README.zh.md +++ b/packages/test-support/session-snapshot/README.zh.md @@ -70,7 +70,7 @@ defineAcpSnapshotSuite({ 每个已记录 Session 目录携带封闭的 `snapshot.yml` manifest,以及规范 parent 与连续 child 角色。parent 文件名是 `session[.vN].jsonl`;child 是 `session.[.vN].jsonl`;v0 省略 `.v0`,正版本使用小写 `.vN`,且每个文件名与其 header 一致。一个角色可以保留旧 generation,但 harness 会选择数值最高的一项。拥有 fixture 的 manifest 可以声明 `sessionFormat.version` 与一个或多个封闭 `coverage` 名称,把该历史 generation 保留为显式迁移 fixture;省略此字段时跟随当前 writer。manifest 还会指名场景、随附 profile、组合/header 类别、录制来源,以及已完成 Session 无法重建的 replay、平台、权限、环境、workspace 或输入事实。存储保护检查每个选定 parent 与 child 角色的工具结果和可移植路径。提示词/schema 擦除、消息身份及提示词先于请求的顺序检查适用于当前 generation;保留的前代维持其历史表示。适配器注册预期输出、Session 日志与可选 `workspace.expected/` 比较;保护会拒绝遗留目录、缺失角色、非规范名称、绝对路径、格式错误的 manifest 与平台专用分隔符。 -`normalizeSessionSnapshot` 在规范化路径并擦除系统提示文本与工具 schema 后,会保留完整 Session header 与事件 payload,但从已提交 fixture 中省略顶层 `seq`/`time` envelope;它还会规范化嵌入式 stream clock 与历史 packed-row 的 `seq0`/`time0` envelope 与 catalog child 创建时钟。事件顺序与来源事件引用保持不变。Replay 只在内存中合成顶层 envelope,而运行时持久化仍写入完整日志。多 Session 比较会先通过严格的构建期静态 Session 格式目录校验预期日志与收集日志,再进行身份脱敏与规范化;来源文件名不能改变格式校验。保留的历史 replay 输入不是原生当前格式 writer 输出的比较基准:结构迁移保留请求含义,但可以产生不同的事件布局。归一化保留意外的 request-header 字段(包括 `system`),使回归保持可见。无版本的协议适配器单元测试 fixture 不属于已发布 Session 格式语料。[当前写入器格式](../../../docs/session-format-status.zh.md)的 fixture 每个事件占一行;保留的 v0/v1 fixture 可以使用规范 packed row。[临时仓库迁移器](../../../scripts/migrate-packed-session-fixtures.ts)(`pnpm run migrate:packed-session-fixtures`)会改写更旧的历史布局,由其[移除提案](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.zh.md)负责删除该迁移器。 +`normalizeSessionSnapshot` 在规范化路径并擦除系统提示文本与工具 schema 后,会保留完整 Session header 与事件 payload,但从已提交 fixture 中省略顶层 `seq`/`time` envelope;它还会规范化嵌入式 stream clock 与历史 packed-row 的 `seq0`/`time0` envelope 与 catalog child 创建时钟。事件顺序与来源事件引用保持不变。录制与刷新会在写入 fixture 前展开顶层 `sourceEventSeqs` 区间。Replay 只在内存中合成顶层 envelope,而运行时持久化仍写入完整日志。多 Session 比较会先通过严格的构建期静态 Session 格式目录校验预期日志与收集日志,再进行身份脱敏与规范化;来源文件名不能改变格式校验。保留的历史 replay 输入不是原生当前格式 writer 输出的比较基准:结构迁移保留请求含义,但可以产生不同的事件布局。归一化保留意外的 request-header 字段(包括 `system`),使回归保持可见。无版本的协议适配器单元测试 fixture 不属于已发布 Session 格式语料。[当前写入器格式](../../../docs/session-format-status.zh.md)的 fixture 每个事件占一行;保留的 v0/v1 fixture 可以使用规范 packed row。[临时仓库迁移器](../../../scripts/migrate-packed-session-fixtures.ts)(`pnpm run migrate:packed-session-fixtures`)会改写更旧的历史布局,由其[移除提案](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.zh.md)负责删除该迁移器。 spill 场景通过真实本地提供方保存到私有临时根目录。fixture 适配器提供固定长度的逻辑定位符,并仅将本次运行已保存的定位符映射回实际文件以供检索,在不写入共享逻辑路径的情况下保留预览预算。已知的快照 spill 路径会规范化为稳定的定位符 token,包括 JSON 省略通知中带引号、使用 JSON 转义 Windows 分隔符的路径。刷新提取会保留匹配路径的序列化写法,以便进行字面替换。规范化只改变定位符:保存字节数与省略计数仍作为比较证据。 diff --git a/packages/test-support/session-snapshot/src/normalize.ts b/packages/test-support/session-snapshot/src/normalize.ts index 0201030f6d..fe970077a7 100644 --- a/packages/test-support/session-snapshot/src/normalize.ts +++ b/packages/test-support/session-snapshot/src/normalize.ts @@ -529,7 +529,8 @@ export function scrubModelRequestBulk(rawLog: string): string { /** * Project a persisted session log while tokenizing prompt text and schema * bulk. Each non-empty line is parsed at most once; the session header stays - * byte-identical. Body records omit their persistence-only envelopes. + * byte-identical. Body records omit their persistence-only envelopes and expand + * source-event ranges without changing reference order. * * @param rawLog - persisted or already-projected session JSONL. * @returns committed snapshot JSONL with prompt text and tool schemas tokenized. @@ -545,6 +546,9 @@ export function scrubSessionSnapshot(rawLog: string): string { return line } omitFixtureEnvelope(record) + if (Object.hasOwn(record, 'sourceEventSeqs')) { + record.sourceEventSeqs = decodeSeqRanges(record.sourceEventSeqs) + } normalizeFeedbackClocks(record) return JSON.stringify(record) }).join('\n') diff --git a/scripts/session-fixture-layout.spec.ts b/scripts/session-fixture-layout.spec.ts index 37908f4dda..89d0836ac4 100644 --- a/scripts/session-fixture-layout.spec.ts +++ b/scripts/session-fixture-layout.spec.ts @@ -2,7 +2,8 @@ import { resolve } from 'node:path' import { describe, expect, it } from 'vitest' import { createAssistantMessage } from '@deepseek-ai/dsh-llm' import { SESSION_FORMAT_VERSION, SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session' -import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay' +import { parseSessionLog, prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay' +import { scrubSessionSnapshot } from '@deepseek-ai/dsh-session-snapshot' import { canonicalSessionFixture, inspectSessionFixtureLayouts, @@ -58,6 +59,24 @@ function decodedBody(content: string): SessionEvent[] { } describe('canonicalSessionFixture', () => { + it.each([ + { sources: [0, 1, 2] }, + { sources: [0, 2] }, + { sources: [2, 0, 1] }, + ])('writes canonical snapshots preserving source reference order: $sources', ({ sources }) => { + const event = { + type: 'user/message', seq: 3, time: 15, + data: { id: 'fixture-user', role: 'user', source: { kind: 'plugin', plugin: 'fixture' }, content: [] }, + sourceEventSeqs: sources, surfaceOp: 'append', + } + const raw = [HEADER, ...[...fixtureEvents(), event].map(value => JSON.stringify(value)), ''].join('\n') + const written = scrubSessionSnapshot(prepareSessionSnapshotFixtureForComparison(raw)) + + expect(canonicalSessionFixture(written)).toBe(written) + expect(decodedBody(written).at(-1)?.sourceEventSeqs).toEqual(sources) + expect(scrubSessionSnapshot(written)).toBe(written) + }) + it('preserves the header line and nested compact stream losslessly', () => { const canonical = canonicalSessionFixture(unpackedFixture(), 'fixture.jsonl') expect(canonical).toBeDefined() From 9ee0d1257bc7b6c98bb989c2d8e6d7567c5e0af4 Mon Sep 17 00:00:00 2001 From: _Kerman Date: Fri, 18 Sep 2026 12:44:35 +0800 Subject: [PATCH 02/24] test(session-snapshot): cover source-reference projection directly --- .../test-support/session-snapshot/README.i18n.yaml | 4 ++-- packages/test-support/session-snapshot/README.md | 2 +- packages/test-support/session-snapshot/README.zh.md | 2 +- .../session-snapshot/tests/normalize.spec.ts | 11 +++++++++++ 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/packages/test-support/session-snapshot/README.i18n.yaml b/packages/test-support/session-snapshot/README.i18n.yaml index 6737bcc4cb..c9fd9ccbc2 100644 --- a/packages/test-support/session-snapshot/README.i18n.yaml +++ b/packages/test-support/session-snapshot/README.i18n.yaml @@ -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/test-support/session-snapshot/README.md -README.md: 1886c79f7fac505cd515c93be03a6b67d22ffc2e -README.zh.md: 3af39ef8e6b80992a748e4cee85b788ab4ba3852 +README.md: cd6e63808abb1e6dde2cd95551a8e83d54683f97 +README.zh.md: 7edd0ec71593412e2dada27a3fa4a1aa2fd8a307 diff --git a/packages/test-support/session-snapshot/README.md b/packages/test-support/session-snapshot/README.md index 1886c79f7f..cd6e63808a 100644 --- a/packages/test-support/session-snapshot/README.md +++ b/packages/test-support/session-snapshot/README.md @@ -70,7 +70,7 @@ defineAcpSnapshotSuite({ Each recorded-session directory carries a closed `snapshot.yml` manifest plus canonical parent and contiguous child roles. Parent filenames are `session[.vN].jsonl`; children are `session.[.vN].jsonl`; v0 omits `.v0`, positive versions use lowercase `.vN`, and every filename agrees with its header. A role may retain older generations, but the harness selects the numerically highest one. An owning manifest may declare `sessionFormat.version` plus one or more closed `coverage` names to keep that historical generation as an explicit migration fixture; absence tracks the current writer. The manifest also names the scenario, shipped profile, composition/header class, recording source, and only the replay, platform, permission, environment, workspace, or input facts the completed Session cannot reconstruct. Storage guards check tool results and portable paths in every selected parent and child role. Prompt/schema scrubbing, message identity, and prompt-before-request ordering apply to current generations; retained predecessors keep their historical representation. The adapter registers expected-output, Session-log, and optional `workspace.expected/` comparisons; guards reject orphan directories, missing roles, noncanonical names, absolute paths, malformed manifests, and platform-specific separators. -`normalizeSessionSnapshot` retains the complete Session header and event payloads but omits top-level `seq`/`time` envelopes from committed fixtures after normalizing paths and scrubbing system-prompt text and tool schemas; it also normalizes embedded stream clocks and historical packed-row `seq0`/`time0` envelopes, and catalog child-creation clocks. Event order and source-event references are preserved. Record and refresh expand top-level `sourceEventSeqs` ranges before writing fixtures. Replay synthesizes the top-level envelopes in memory, while runtime persistence continues to write complete logs. Multi-session comparison validates expected and harvested logs through the strict build-static Session format catalog before identity redaction and normalization; source filenames cannot alter format validation. A retained historical replay input is not the native current-format writer-output oracle: structural migration preserves request meaning but can produce a different event layout. Normalization preserves unexpected request-header fields, including `system`, so regressions remain visible. Versionless protocol-adapter unit fixtures remain outside the released Session format corpus. Fixtures in the [current writer format](../../../docs/session-format-status.md) use one row per event; retained v0/v1 fixtures may use canonical packed rows. The [temporary repository migrator](../../../scripts/migrate-packed-session-fixtures.ts) (`pnpm run migrate:packed-session-fixtures`) rewrites older historical layouts, and its [removal proposal](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.md) owns its deletion. +`normalizeSessionSnapshot` retains the complete Session header and event payloads but omits top-level `seq`/`time` envelopes from committed fixtures after normalizing paths and scrubbing system-prompt text and tool schemas; it also normalizes embedded stream clocks and historical packed-row `seq0`/`time0` envelopes, and catalog child-creation clocks. Event order and source-event reference order are preserved. Record and refresh write top-level `sourceEventSeqs` as expanded arrays. Replay synthesizes the top-level envelopes in memory, while runtime persistence continues to write complete logs. Multi-session comparison validates expected and harvested logs through the strict build-static Session format catalog before identity redaction and normalization; source filenames cannot alter format validation. A retained historical replay input is not the native current-format writer-output oracle: structural migration preserves request meaning but can produce a different event layout. Normalization preserves unexpected request-header fields, including `system`, so regressions remain visible. Versionless protocol-adapter unit fixtures remain outside the released Session format corpus. Fixtures in the [current writer format](../../../docs/session-format-status.md) use one row per event; retained v0/v1 fixtures may use canonical packed rows. The [temporary repository migrator](../../../scripts/migrate-packed-session-fixtures.ts) (`pnpm run migrate:packed-session-fixtures`) rewrites older historical layouts, and its [removal proposal](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.md) owns its deletion. Spill scenarios save through the real local provider under a private temporary root. Their fixture adapter exposes fixed-length logical locators and maps only this run’s saved locators back to real files for retrieval, preserving preview budgets without writing into a shared logical path. Known snapshot spill paths normalize to stable locator tokens, including paths quoted inside JSON omission notices with JSON-escaped Windows separators. Refresh extraction preserves the matched serialized path spelling for literal replacement. Normalization changes only the locator: saved byte lengths and omission counts remain comparison evidence. diff --git a/packages/test-support/session-snapshot/README.zh.md b/packages/test-support/session-snapshot/README.zh.md index 3af39ef8e6..7edd0ec715 100644 --- a/packages/test-support/session-snapshot/README.zh.md +++ b/packages/test-support/session-snapshot/README.zh.md @@ -70,7 +70,7 @@ defineAcpSnapshotSuite({ 每个已记录 Session 目录携带封闭的 `snapshot.yml` manifest,以及规范 parent 与连续 child 角色。parent 文件名是 `session[.vN].jsonl`;child 是 `session.[.vN].jsonl`;v0 省略 `.v0`,正版本使用小写 `.vN`,且每个文件名与其 header 一致。一个角色可以保留旧 generation,但 harness 会选择数值最高的一项。拥有 fixture 的 manifest 可以声明 `sessionFormat.version` 与一个或多个封闭 `coverage` 名称,把该历史 generation 保留为显式迁移 fixture;省略此字段时跟随当前 writer。manifest 还会指名场景、随附 profile、组合/header 类别、录制来源,以及已完成 Session 无法重建的 replay、平台、权限、环境、workspace 或输入事实。存储保护检查每个选定 parent 与 child 角色的工具结果和可移植路径。提示词/schema 擦除、消息身份及提示词先于请求的顺序检查适用于当前 generation;保留的前代维持其历史表示。适配器注册预期输出、Session 日志与可选 `workspace.expected/` 比较;保护会拒绝遗留目录、缺失角色、非规范名称、绝对路径、格式错误的 manifest 与平台专用分隔符。 -`normalizeSessionSnapshot` 在规范化路径并擦除系统提示文本与工具 schema 后,会保留完整 Session header 与事件 payload,但从已提交 fixture 中省略顶层 `seq`/`time` envelope;它还会规范化嵌入式 stream clock 与历史 packed-row 的 `seq0`/`time0` envelope 与 catalog child 创建时钟。事件顺序与来源事件引用保持不变。录制与刷新会在写入 fixture 前展开顶层 `sourceEventSeqs` 区间。Replay 只在内存中合成顶层 envelope,而运行时持久化仍写入完整日志。多 Session 比较会先通过严格的构建期静态 Session 格式目录校验预期日志与收集日志,再进行身份脱敏与规范化;来源文件名不能改变格式校验。保留的历史 replay 输入不是原生当前格式 writer 输出的比较基准:结构迁移保留请求含义,但可以产生不同的事件布局。归一化保留意外的 request-header 字段(包括 `system`),使回归保持可见。无版本的协议适配器单元测试 fixture 不属于已发布 Session 格式语料。[当前写入器格式](../../../docs/session-format-status.zh.md)的 fixture 每个事件占一行;保留的 v0/v1 fixture 可以使用规范 packed row。[临时仓库迁移器](../../../scripts/migrate-packed-session-fixtures.ts)(`pnpm run migrate:packed-session-fixtures`)会改写更旧的历史布局,由其[移除提案](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.zh.md)负责删除该迁移器。 +`normalizeSessionSnapshot` 在规范化路径并擦除系统提示文本与工具 schema 后,会保留完整 Session header 与事件 payload,但从已提交 fixture 中省略顶层 `seq`/`time` envelope;它还会规范化嵌入式 stream clock 与历史 packed-row 的 `seq0`/`time0` envelope 与 catalog child 创建时钟。事件顺序与来源事件引用的顺序保持不变。录制与刷新会将顶层 `sourceEventSeqs` 以展开数组的形式写入 fixture。Replay 只在内存中合成顶层 envelope,而运行时持久化仍写入完整日志。多 Session 比较会先通过严格的构建期静态 Session 格式目录校验预期日志与收集日志,再进行身份脱敏与规范化;来源文件名不能改变格式校验。保留的历史 replay 输入不是原生当前格式 writer 输出的比较基准:结构迁移保留请求含义,但可以产生不同的事件布局。归一化保留意外的 request-header 字段(包括 `system`),使回归保持可见。无版本的协议适配器单元测试 fixture 不属于已发布 Session 格式语料。[当前写入器格式](../../../docs/session-format-status.zh.md)的 fixture 每个事件占一行;保留的 v0/v1 fixture 可以使用规范 packed row。[临时仓库迁移器](../../../scripts/migrate-packed-session-fixtures.ts)(`pnpm run migrate:packed-session-fixtures`)会改写更旧的历史布局,由其[移除提案](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.zh.md)负责删除该迁移器。 spill 场景通过真实本地提供方保存到私有临时根目录。fixture 适配器提供固定长度的逻辑定位符,并仅将本次运行已保存的定位符映射回实际文件以供检索,在不写入共享逻辑路径的情况下保留预览预算。已知的快照 spill 路径会规范化为稳定的定位符 token,包括 JSON 省略通知中带引号、使用 JSON 转义 Windows 分隔符的路径。刷新提取会保留匹配路径的序列化写法,以便进行字面替换。规范化只改变定位符:保存字节数与省略计数仍作为比较证据。 diff --git a/packages/test-support/session-snapshot/tests/normalize.spec.ts b/packages/test-support/session-snapshot/tests/normalize.spec.ts index be8bcb7ff4..8afc007cb1 100644 --- a/packages/test-support/session-snapshot/tests/normalize.spec.ts +++ b/packages/test-support/session-snapshot/tests/normalize.spec.ts @@ -1087,6 +1087,17 @@ describe('scrubModelRequestBulk', () => { }) describe('scrubSessionSnapshot', () => { + it('writes expanded source-event references and remains idempotent', () => { + const input = [ + { type: 'session', id: 's' }, + { type: 'assistant/message', sourceEventSeqs: [[1, 3], 5], surfaceOp: 'append', data: { turn: 1, step: 1 } }, + ].map(record => JSON.stringify(record)).join('\n') + + const output = scrubSessionSnapshot(input) + expect(output).toContain('"sourceEventSeqs":[1,2,3,5]') + expect(scrubSessionSnapshot(output)).toBe(output) + }) + it('writes stable feedback clocks while retaining notes and version identity', () => { const input = [ { type: 'session', id: 's' }, From 86ca9de07eb5e5ef431c77eac435bdc448d3425c Mon Sep 17 00:00:00 2001 From: imccyu Date: Sat, 19 Sep 2026 23:47:26 +0800 Subject: [PATCH 03/24] fix(session): read cold seeded rows from the projection cache by header The projection cache read-only face (cachedSnapshot, cachedPredecessorTitle) now matches the lifecycle identity a header witnesses (formatVersion, createdAt, cwd, isSeeded) and serves its rows as a cached block with asOfSeq -1. The fold face (hydratePrepared, write, coldSnapshot) keeps the full identity including the inherited cut. The session list and @ completion drop their isSeeded guards, so forked sessions keep their cached title and list metadata across a Host restart; list-children keeps its body fallback. --- apps/web/tests/subagent-conversation.e2e.ts | 2 +- docs/config-catalog.i18n.yaml | 2 +- docs/config-catalog.md | 2 +- docs/subsystems/session-projection.i18n.yaml | 4 +- docs/subsystems/session-projection.md | 38 ++--- docs/subsystems/session-projection.zh.md | 38 ++--- packages/api/session-controller/src/list.ts | 8 +- .../tests/session-cold.host.spec.ts | 21 ++- .../context/session-reference/src/index.ts | 14 +- .../tests/session-reference.spec.ts | 25 ++- .../extensions/tool-cordis/src/api-catalog.ts | 16 +- .../session-projection-cache/README.i18n.yaml | 4 +- .../session-projection-cache/README.md | 4 +- .../session-projection-cache/README.zh.md | 4 +- .../session-projection-cache/src/index.ts | 133 +++++++++------- .../tests/cache.spec.ts | 146 +++++++++++++----- .../tests/fixtures.spec.ts | 25 ++- .../subagent/subagent/src/list-children.ts | 10 +- 18 files changed, 297 insertions(+), 199 deletions(-) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 3fc4841f43..1b8a432cef 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -86,7 +86,7 @@ async function waitForCacheRow( header: SessionHeader, ): Promise { const deadline = Date.now() + 10_000 - while (scaffold.ctx.sessionProjectionCache.cachedSnapshot(header, SessionLogOffset(0)) === undefined) { + while (scaffold.ctx.sessionProjectionCache.cachedSnapshot(header) === undefined) { if (Date.now() >= deadline) throw new Error(`cache row for "${header.id}" did not land`) await new Promise(resolve => setTimeout(resolve, 10)) } diff --git a/docs/config-catalog.i18n.yaml b/docs/config-catalog.i18n.yaml index 106e1545fb..ecb1a48a7b 100644 --- a/docs/config-catalog.i18n.yaml +++ b/docs/config-catalog.i18n.yaml @@ -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: dad6b57ae0712e04ad16729b4067c541f83c68d6 +config-catalog.md: 92b24a0948883b2974c5cb8ab650bd3db3b50326 config-catalog.zh.md: 4ba0378810f3db4797c0d41fa5230f7069438b3f diff --git a/docs/config-catalog.md b/docs/config-catalog.md index dad6b57ae0..92b24a0948 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2232,7 +2232,7 @@ export interface Config { } ``` -Source: [`packages/session/session-projection-cache/src/index.ts:63`](../packages/session/session-projection-cache/src/index.ts) +Source: [`packages/session/session-projection-cache/src/index.ts:75`](../packages/session/session-projection-cache/src/index.ts) diff --git a/docs/subsystems/session-projection.i18n.yaml b/docs/subsystems/session-projection.i18n.yaml index 808a5bb76f..b0c4faff71 100644 --- a/docs/subsystems/session-projection.i18n.yaml +++ b/docs/subsystems/session-projection.i18n.yaml @@ -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: cb3ac37d593a2b5aae6725854c31a3a39ae3152b -session-projection.zh.md: 5051dab59316840267d16d201a17717742565059 +session-projection.md: b46d8df330de3586691ac7e708e0b5de6c76b33f +session-projection.zh.md: 62fa2ff74ab627cc2a83f76cf4066a3ffc3020f0 diff --git a/docs/subsystems/session-projection.md b/docs/subsystems/session-projection.md index cb3ac37d59..b46d8df330 100644 --- a/docs/subsystems/session-projection.md +++ b/docs/subsystems/session-projection.md @@ -122,20 +122,24 @@ The persisted projection cache service. Opens the `session_projcache` domain at ```ts cordis-catalog /** * The zero-I/O listing read: whole values viewed straight from the stored - * rows (version-matching keys only), each cut carried with its watermark so - * a client value store can seed under its higher-seq-wins rule — as stale - * as the last durable checkpoint but never wrong, and never from an - * unrelated log (the caller's header is the identity witness). Fresher - * paths (the history tail baseline) supersede these values whenever a - * session is actually opened. + * rows (version-matching keys only) of the record bound to the caller's + * lifecycle. The header is the only identity witness a listing holds, so + * this face matches the lifecycle identity (`formatVersion`, `createdAt`, + * `cwd`, `isSeeded`) and not the inherited cut: within one format + * generation the cut is fixed at fork time, so it distinguishes no + * lifecycle the other fields do not, and a viewed value never seeds a fold. + * The view is as stale as the last durable checkpoint but never wrong and + * never from an unrelated log. It is served as a cached block + * (`asOfSeq: -1`): the header cannot vouch that the stored row sequence is + * comparable with the caller's log, so the block claims no watermark and + * any sequenced value (a history baseline, a control baseline, a frame) + * supersedes it once the session is opened. * @param meta - the listed session's header (identity witness; no log read). - * @param inheritedEventCount - exact inherited prefix length that completes - * the checkpoint identity. * @param keys - optional projection keys required by the caller's audience. - * @returns the cut (`asOfSeq` = lowest served-row watermark), or - * `undefined` when no usable row exists for this lifecycle. + * @returns the cached block, or `undefined` when no usable row exists for + * this lifecycle at the current Session format. */ -cachedSnapshot( meta: SessionHeader, inheritedEventCount: SessionLogOffset, keys?: readonly Extract[], ): ProjectionSnapshot | undefined +cachedSnapshot( meta: SessionHeader, keys?: readonly Extract[], ): ProjectionSnapshot | undefined /** * Read only a predecessor checkpoint's title as a zero-I/O listing hint. @@ -146,15 +150,13 @@ cachedSnapshot( meta: SessionHeader, inheritedEventCount: SessionLogOffset, keys * fact from this Session. The registry still requires the current title * projection's row version and schema. No other predecessor projection is * exposed: format normalization can change their current meaning, and the - * strict {@link cachedSnapshot} / hydration paths continue to reject them. + * {@link cachedSnapshot} / hydration paths continue to reject them. * @param meta - authoritative listed Session header. - * @param inheritedEventCount - exact inherited cut completing the lifecycle identity. - * @returns a title-only checkpoint view with `asOfSeq: -1`, or `undefined` - * when the record is current, newer, unrelated, missing, or incompatible - * with the title unit. The sentinel avoids reusing a sequence that a - * cardinality-changing Session migration may have remapped. + * @returns a title-only cached block (`asOfSeq: -1`), or `undefined` when + * the record is current, newer, unrelated, missing, or incompatible with + * the title unit. */ -cachedPredecessorTitle( meta: SessionHeader, inheritedEventCount: SessionLogOffset, ): ProjectionSnapshot | undefined +cachedPredecessorTitle(meta: SessionHeader): ProjectionSnapshot | undefined /** * Hydrate projection cells for an already-prepared Session without another diff --git a/docs/subsystems/session-projection.zh.md b/docs/subsystems/session-projection.zh.md index 5051dab593..62fa2ff74a 100644 --- a/docs/subsystems/session-projection.zh.md +++ b/docs/subsystems/session-projection.zh.md @@ -122,20 +122,24 @@ The persisted projection cache service. Opens the `session_projcache` domain at ```ts cordis-catalog /** * The zero-I/O listing read: whole values viewed straight from the stored - * rows (version-matching keys only), each cut carried with its watermark so - * a client value store can seed under its higher-seq-wins rule — as stale - * as the last durable checkpoint but never wrong, and never from an - * unrelated log (the caller's header is the identity witness). Fresher - * paths (the history tail baseline) supersede these values whenever a - * session is actually opened. + * rows (version-matching keys only) of the record bound to the caller's + * lifecycle. The header is the only identity witness a listing holds, so + * this face matches the lifecycle identity (`formatVersion`, `createdAt`, + * `cwd`, `isSeeded`) and not the inherited cut: within one format + * generation the cut is fixed at fork time, so it distinguishes no + * lifecycle the other fields do not, and a viewed value never seeds a fold. + * The view is as stale as the last durable checkpoint but never wrong and + * never from an unrelated log. It is served as a cached block + * (`asOfSeq: -1`): the header cannot vouch that the stored row sequence is + * comparable with the caller's log, so the block claims no watermark and + * any sequenced value (a history baseline, a control baseline, a frame) + * supersedes it once the session is opened. * @param meta - the listed session's header (identity witness; no log read). - * @param inheritedEventCount - exact inherited prefix length that completes - * the checkpoint identity. * @param keys - optional projection keys required by the caller's audience. - * @returns the cut (`asOfSeq` = lowest served-row watermark), or - * `undefined` when no usable row exists for this lifecycle. + * @returns the cached block, or `undefined` when no usable row exists for + * this lifecycle at the current Session format. */ -cachedSnapshot( meta: SessionHeader, inheritedEventCount: SessionLogOffset, keys?: readonly Extract[], ): ProjectionSnapshot | undefined +cachedSnapshot( meta: SessionHeader, keys?: readonly Extract[], ): ProjectionSnapshot | undefined /** * Read only a predecessor checkpoint's title as a zero-I/O listing hint. @@ -146,15 +150,13 @@ cachedSnapshot( meta: SessionHeader, inheritedEventCount: SessionLogOffset, keys * fact from this Session. The registry still requires the current title * projection's row version and schema. No other predecessor projection is * exposed: format normalization can change their current meaning, and the - * strict {@link cachedSnapshot} / hydration paths continue to reject them. + * {@link cachedSnapshot} / hydration paths continue to reject them. * @param meta - authoritative listed Session header. - * @param inheritedEventCount - exact inherited cut completing the lifecycle identity. - * @returns a title-only checkpoint view with `asOfSeq: -1`, or `undefined` - * when the record is current, newer, unrelated, missing, or incompatible - * with the title unit. The sentinel avoids reusing a sequence that a - * cardinality-changing Session migration may have remapped. + * @returns a title-only cached block (`asOfSeq: -1`), or `undefined` when + * the record is current, newer, unrelated, missing, or incompatible with + * the title unit. */ -cachedPredecessorTitle( meta: SessionHeader, inheritedEventCount: SessionLogOffset, ): ProjectionSnapshot | undefined +cachedPredecessorTitle(meta: SessionHeader): ProjectionSnapshot | undefined /** * Hydrate projection cells for an already-prepared Session without another diff --git a/packages/api/session-controller/src/list.ts b/packages/api/session-controller/src/list.ts index 530414c52d..957d577856 100644 --- a/packages/api/session-controller/src/list.ts +++ b/packages/api/session-controller/src/list.ts @@ -3,7 +3,6 @@ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-agent-presets' import type { ImageAttachmentLimits } from '@deepseek-ai/dsh-attachment' -import { SessionLogOffset } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-session-projection-cache' @@ -273,11 +272,10 @@ export class ApiSessionList { ): SessionProjectionHints | undefined { try { const cache = this.ctx.get('sessionProjectionCache') + // A cold row reads the cache by header alone; the cache serves seeded + // and unseeded lifecycles alike because a listing never seeds a fold. const block = session === undefined - ? header.isSeeded - ? undefined - : cache?.cachedSnapshot(header, SessionLogOffset(0)) - ?? cache?.cachedPredecessorTitle(header, SessionLogOffset(0)) + ? cache?.cachedSnapshot(header) ?? cache?.cachedPredecessorTitle(header) : this.ctx.sessionProjections.cachedSnapshot(session) return block !== undefined && Object.keys(block.values).length > 0 ? { diff --git a/packages/api/session-controller/tests/session-cold.host.spec.ts b/packages/api/session-controller/tests/session-cold.host.spec.ts index c8be6f2252..00988a62fd 100644 --- a/packages/api/session-controller/tests/session-cold.host.spec.ts +++ b/packages/api/session-controller/tests/session-cold.host.spec.ts @@ -152,6 +152,12 @@ describe('sessions.list cold merge', () => { if (meta.id === sid('cached-conversation')) { return { asOfSeq: 1, values: { sessionListMetadata: { blank: false, lastPromptAt: 1000 } } } } + if (meta.id === sid('seeded-cold')) { + return { + asOfSeq: -1, + values: { title: 'Forked title', sessionListMetadata: { blank: false, lastPromptAt: 1200 } }, + } + } return undefined }, cachedPredecessorTitle: () => undefined, @@ -172,10 +178,17 @@ describe('sessions.list cold merge', () => { origin: 'subagent', }) expect(byId['missing-cwd']).toBeUndefined() - // A cold seeded header never consults the cache: its cut is not 0, so a - // cut-0 lookup would alias a different projection identity. - expect(byId['seeded-cold']).toMatchObject({ blank: false, updatedAt: 450 }) - expect(cacheCalls).not.toContain('seeded-cold') + // A cold seeded header reads the cache by header alone, like any other + // cold row: the cache binds the lifecycle, and a listing never seeds a fold. + expect(byId['seeded-cold']).toMatchObject({ + blank: false, + updatedAt: 1200, + projections: { + asOfSeq: -1, + values: { title: 'Forked title', sessionListMetadata: { blank: false, lastPromptAt: 1200 } }, + }, + }) + expect(cacheCalls).toContain('seeded-cold') expect(inspect).not.toHaveBeenCalled() }) diff --git a/packages/context/session-reference/src/index.ts b/packages/context/session-reference/src/index.ts index 848e4ddc15..f2082d85e2 100644 --- a/packages/context/session-reference/src/index.ts +++ b/packages/context/session-reference/src/index.ts @@ -11,7 +11,6 @@ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' import { createUserMessage, freezeMessage, LlmError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, LlmResolvedModelInfo, UserMessage } from '@deepseek-ai/dsh-llm' -import { SessionLogOffset } from '@deepseek-ai/dsh-session' import type { SessionId } from '@deepseek-ai/dsh-session' // Type-only: the `title` projection key plus the live registry and durable // cache Context merges — the two projection faces discovery labels from. @@ -239,9 +238,8 @@ export class SessionReferenceResolver extends TypertRemoteService { * Nothing else is attempted. Folding a title from a log costs the whole * log, and this call sits under every keystroke of `@` completion. A * session that no projection can answer for — one persisted before the - * cache was composed, or seeded straight to disk — is labeled by its id - * and cannot be found by its title until it is opened once, which - * checkpoints it. + * cache was composed — is labeled by its id and cannot be found by its + * title until it is opened once, which checkpoints it. * @param record - the listed session, live or cold. * @returns the title-backed mention label and the subagent-label-first display title. */ @@ -250,13 +248,7 @@ export class SessionReferenceResolver extends TypertRemoteService { const projections = this.ctx.get('sessionProjections') const snapshot = attached !== undefined && projections !== undefined ? projections.snapshot(attached, ['title', 'subagent']) - : record.header.isSeeded - ? undefined - : this.ctx.get('sessionProjectionCache')?.cachedSnapshot( - record.header, - SessionLogOffset(0), - ['title', 'subagent'], - ) + : this.ctx.get('sessionProjectionCache')?.cachedSnapshot(record.header, ['title', 'subagent']) const label = titleOf(snapshot) ?? record.header.id const subagent = snapshot?.values.subagent return { diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index 6ea0ed8cf2..efc8447e90 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -777,27 +777,36 @@ describe('session reference discovery and preparation', () => { })]) }) - it('labels a session no projection answers for by its id, still without a log read', async () => { + it('labels a cold seeded session from its cached title and an uncached one by id, without a log read', async () => { const ctx = await harness() const target = ctx.sessions.create(SessionId('target'), { meta: { cwd: '/same' } }) - const seeded = { + const forked = { version: 0, - id: SessionId('seeded'), + id: SessionId('forked'), createdAt: 10, cwd: '/same', isSeeded: true, } - // Persisted before the cache was composed: the title lives only in its log. - withProjectionCache(ctx, { seeded: 'Unsafe body-free title' }) + const uncached = { ...forked, id: SessionId('uncached'), createdAt: 20 } + // The cache binds the fork's lifecycle by its header alone; the resolver + // needs no cut to read it. A session the cache never checkpointed keeps + // its title in its log only. + withProjectionCache(ctx, { forked: 'Forked title' }) vi.spyOn(ctx.sessionQuery, 'listSessions').mockResolvedValue([ - { header: seeded, live: false, persisted: true }, + { header: forked, live: false, persisted: true }, + { header: uncached, live: false, persisted: true }, ] as never) const readTitles = vi.spyOn(ctx.sessionQuery, 'readTitleSnapshots') await expect(ctx.sessionReferenceResolver.listCandidates(fakeAgent(target))).resolves.toEqual([ - { sessionId: seeded.id, label: seeded.id, displayTitle: seeded.id, cwd: '/same', sameWorkspace: true, createdAt: 10 }, + { sessionId: forked.id, label: 'Forked title', displayTitle: 'Forked title', cwd: '/same', sameWorkspace: true, createdAt: 10 }, + { sessionId: uncached.id, label: uncached.id, displayTitle: uncached.id, cwd: '/same', sameWorkspace: true, createdAt: 20 }, + ]) + // The cached title finds the fork; the uncached session's own title cannot + // find it, and discovery still never opens a log. + await expect(ctx.sessionReferenceResolver.listCandidates(fakeAgent(target), 'forked title')).resolves.toEqual([ + expect.objectContaining({ sessionId: forked.id }), ]) - // Its own title cannot find it, and discovery still never opens the log. await expect(ctx.sessionReferenceResolver.listCandidates(fakeAgent(target), 'anything')).resolves.toEqual([]) expect(readTitles).not.toHaveBeenCalled() vi.restoreAllMocks() diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 78975d4a43..8256b0514d 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1878,16 +1878,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'The persisted projection cache service. Opens the `session_projcache` domain at init, checkpoints live sessions on a throttled write-behind (count/interval triggers from Config) plus three mandatory points — session creation, `turn/end`, and session disposal (the live-to-cold moment) — and serves the cached rows for a session header. Every durable write is fail-soft: failures log a warning and the cache self-heals on the next write.', methods: [ { - signature: 'cachedSnapshot( meta: SessionHeader, inheritedEventCount: SessionLogOffset, keys?: readonly Extract[], ): ProjectionSnapshot | undefined', - description: 'The zero-I/O listing read: whole values viewed straight from the stored rows (version-matching keys only), each cut carried with its watermark so a client value store can seed under its higher-seq-wins rule — as stale as the last durable checkpoint but never wrong, and never from an unrelated log (the caller\'s header is the identity witness). Fresher paths (the history tail baseline) supersede these values whenever a session is actually opened.', - parameters: [{ name: 'meta', description: 'the listed session\'s header (identity witness; no log read).' }, { name: 'inheritedEventCount', description: 'exact inherited prefix length that completes the checkpoint identity.' }, { name: 'keys', description: 'optional projection keys required by the caller\'s audience.' }], - returns: 'the cut (`asOfSeq` = lowest served-row watermark), or `undefined` when no usable row exists for this lifecycle.', + signature: 'cachedSnapshot( meta: SessionHeader, keys?: readonly Extract[], ): ProjectionSnapshot | undefined', + description: 'The zero-I/O listing read: whole values viewed straight from the stored rows (version-matching keys only) of the record bound to the caller\'s lifecycle. The header is the only identity witness a listing holds, so this face matches the lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`) and not the inherited cut: within one format generation the cut is fixed at fork time, so it distinguishes no lifecycle the other fields do not, and a viewed value never seeds a fold. The view is as stale as the last durable checkpoint but never wrong and never from an unrelated log. It is served as a cached block (`asOfSeq: -1`): the header cannot vouch that the stored row sequence is comparable with the caller\'s log, so the block claims no watermark and any sequenced value (a history baseline, a control baseline, a frame) supersedes it once the session is opened.', + parameters: [{ name: 'meta', description: 'the listed session\'s header (identity witness; no log read).' }, { name: 'keys', description: 'optional projection keys required by the caller\'s audience.' }], + returns: 'the cached block, or `undefined` when no usable row exists for this lifecycle at the current Session format.', }, { - signature: 'cachedPredecessorTitle( meta: SessionHeader, inheritedEventCount: SessionLogOffset, ): ProjectionSnapshot | undefined', - description: 'Read only a predecessor checkpoint\'s title as a zero-I/O listing hint.\n\nThe authoritative Session header supplies the lifecycle identity. A cache checkpoint can lag that log but cannot lead it because writes flush the log first, so a matching predecessor title is a genuine (possibly stale) fact from this Session. The registry still requires the current title projection\'s row version and schema. No other predecessor projection is exposed: format normalization can change their current meaning, and the strict cachedSnapshot / hydration paths continue to reject them.', - parameters: [{ name: 'meta', description: 'authoritative listed Session header.' }, { name: 'inheritedEventCount', description: 'exact inherited cut completing the lifecycle identity.' }], - returns: 'a title-only checkpoint view with `asOfSeq: -1`, or `undefined` when the record is current, newer, unrelated, missing, or incompatible with the title unit. The sentinel avoids reusing a sequence that a cardinality-changing Session migration may have remapped.', + signature: 'cachedPredecessorTitle(meta: SessionHeader): ProjectionSnapshot | undefined', + description: 'Read only a predecessor checkpoint\'s title as a zero-I/O listing hint.\n\nThe authoritative Session header supplies the lifecycle identity. A cache checkpoint can lag that log but cannot lead it because writes flush the log first, so a matching predecessor title is a genuine (possibly stale) fact from this Session. The registry still requires the current title projection\'s row version and schema. No other predecessor projection is exposed: format normalization can change their current meaning, and the cachedSnapshot / hydration paths continue to reject them.', + parameters: [{ name: 'meta', description: 'authoritative listed Session header.' }], + returns: 'a title-only cached block (`asOfSeq: -1`), or `undefined` when the record is current, newer, unrelated, missing, or incompatible with the title unit.', }, { signature: 'hydratePrepared( session: Session, events: readonly SessionEvent[], ): ProjectionSnapshot', diff --git a/packages/session/session-projection-cache/README.i18n.yaml b/packages/session/session-projection-cache/README.i18n.yaml index 9945e2d6dd..c921081f57 100644 --- a/packages/session/session-projection-cache/README.i18n.yaml +++ b/packages/session/session-projection-cache/README.i18n.yaml @@ -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/session/session-projection-cache/README.md -README.md: 0417601210b697983993f770688a4e944d518790 -README.zh.md: 32dcbd93c8f18e504ca3a350586860b2e5cbd5b6 +README.md: af319d2606ca7faa7ba88a1da224b703a4a36943 +README.zh.md: 29568b481e61fc359b1f1e970f14d827e8facb50 diff --git a/packages/session/session-projection-cache/README.md b/packages/session/session-projection-cache/README.md index 0417601210..af319d2606 100644 --- a/packages/session/session-projection-cache/README.md +++ b/packages/session/session-projection-cache/README.md @@ -58,11 +58,11 @@ Three mandatory points always write: session creation persists the seed-derived ### Reading cached values -`cachedSnapshot(meta, inheritedEventCount)` synchronously serves client values from the storage domain's in-memory tables with zero I/O. It accepts only an identity-matching record and version- and schema-matching keys, then returns a `{ asOfSeq, values }` cut at the lowest served-row watermark. `cachedPredecessorTitle(meta, inheritedEventCount)` is the narrower listing-only exception: a structurally admitted predecessor record whose lifecycle matches may expose only a current-version-compatible `title` row. The title is a possibly stale fact from a durable prefix, not a fold seed; it carries the sentinel `asOfSeq: -1` because a cardinality-changing Session migration can invalidate the predecessor row's numeric sequence. All other predecessor rows remain unavailable. An unseeded listing knows that its cut is zero; a seeded header-only listing does not know the numeric cut and skips both fast paths until an authoritative body read supplies it. `coldSnapshot(meta, inheritedEventCount, events)` accepts the exact cut with a complete ordered log, skips the checkpointed prefix while folding, and refreshes the record without reading persistence itself. +`cachedSnapshot(meta, keys?)` is the read-only face: it synchronously serves client values from the storage domain's in-memory tables with zero I/O. It accepts a record whose lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`) matches the header and serves its version- and schema-matching keys as a cached block `{ asOfSeq: -1, values }`. A header witnesses no inherited cut and cannot vouch that the stored row sequence is comparable with the log a consumer later opens, so the block claims no watermark and every value the connected Session later produces supersedes it. Within one format generation the cut is fixed at fork time and distinguishes no lifecycle the other fields do not, and a viewed value never seeds a fold, so seeded (forked) sessions are served exactly like unseeded ones. `cachedPredecessorTitle(meta)` is the narrower listing-only exception across a Session-format edge: a structurally admitted predecessor record whose lifecycle matches may expose only a current-version-compatible `title` row, because title text is invariant across the adjacent edges. All other predecessor rows remain unavailable. `coldSnapshot(meta, inheritedEventCount, events)` is a fold face: it accepts the exact cut with a complete ordered log, skips the checkpointed prefix while folding, and refreshes the record without reading persistence itself. ### What the cache guarantees -The log leads and the cache follows: a live checkpoint flushes the session's buffered events durably before the cache row lands, so a crash can leave the cache behind the log but never ahead of it. Reads and writes share the storage domain's coherent in-memory state; the per-unit write chain mutates memory only after durability. Each version-stamped record must match the live unit schema and complete lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`, and `inheritedEventCount`), so a row folded from another Session format generation or fork cut cannot seed the caller. The JSON backend stores each record at `/session_projcache/sessions/.json` in an owner-only directory tree. Domain read validation preserves every own JSON key in checkpoint values, including `__proto__` and `constructor` inside opaque metadata. It rejects values that cannot survive a lossless JSON round trip, using the same rules as checkpoint writes. Each projection then validates its hydration state with its own `stateSchema`; fields carrying opaque JSON need a validator that preserves their keys. +The log leads and the cache follows: a live checkpoint flushes the session's buffered events durably before the cache row lands, so a crash can leave the cache behind the log but never ahead of it. Reads and writes share the storage domain's coherent in-memory state; the per-unit write chain mutates memory only after durability. Each version-stamped record must match the live unit schema and the lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`); the fold faces (`hydratePrepared`, `coldSnapshot`, and checkpoint writes) also require the exact `inheritedEventCount`, so a row folded from another Session format generation or fork cut cannot seed the caller. The JSON backend stores each record at `/session_projcache/sessions/.json` in an owner-only directory tree. Domain read validation preserves every own JSON key in checkpoint values, including `__proto__` and `constructor` inside opaque metadata. It rejects values that cannot survive a lossless JSON round trip, using the same rules as checkpoint writes. Each projection then validates its hydration state with its own `stateSchema`; fields carrying opaque JSON need a validator that preserves their keys. Upgrades never block startup or expose an unproven fold. Records stamped with a version in the spec's `compatibleVersions` remain structurally readable for a current checkpoint rewrite, but a missing or older `formatVersion` never matches a current Session and therefore cannot seed hydration. A lifecycle-matching predecessor title remains available only through the listing hint above because title text is invariant across the adjacent Session-format edges and its row still passes the current projection `stateVersion` and schema. Once the format matches, absent lineage fields decode as the unseeded lineage — exact for unseeded sessions, while a seeded caller fails the identity match and refolds cold. A stored record that still fails schema validation is moved aside as `.json.bak.` under the domain's `invalidRecords: 'backup-and-skip'` policy, logged with its cause, and rebuilt by the next checkpoint. diff --git a/packages/session/session-projection-cache/README.zh.md b/packages/session/session-projection-cache/README.zh.md index 32dcbd93c8..29568b481e 100644 --- a/packages/session/session-projection-cache/README.zh.md +++ b/packages/session/session-projection-cache/README.zh.md @@ -58,11 +58,11 @@ kind: "package-reference" ### 读取缓存值 -`cachedSnapshot(meta, inheritedEventCount)` 以零 I/O 从存储域的内存表同步提供客户端值。它只接受身份匹配的记录以及版本和 schema 均匹配的 key,再按所服务行的最低水位返回 `{ asOfSeq, values }` 切面。`cachedPredecessorTitle(meta, inheritedEventCount)` 是更窄的列表专用例外:生命周期匹配且已通过结构准入的 predecessor record 只能公开与当前版本兼容的 `title` row。该 title 是 durable prefix 中可能过时的事实,而不是 fold seed;它携带 sentinel `asOfSeq: -1`,因为改变事件数量的 Session 迁移会使 predecessor row 的数字序号失效。其他 predecessor row 仍不可用。未 seeded 的列表知道切点为零;仅 header 的 seeded 列表不知道数字切点,因此两条快速路径都要跳过,直到权威正文读取提供它。`coldSnapshot(meta, inheritedEventCount, events)` 接受精确切点与完整有序日志,在折叠时跳过已检查点化的前缀,并在自身不读取持久化层的情况下刷新记录。 +`cachedSnapshot(meta, keys?)` 是只读面:以零 I/O 从存储域的内存表同步提供客户端值。它接受生命周期身份(`formatVersion`、`createdAt`、`cwd`、`isSeeded`)与 header 匹配的记录,把其中版本和 schema 均匹配的 key 作为 cached block `{ asOfSeq: -1, values }` 提供。header 作证不了 inherited cut,也作证不了存储行的序号与消费者稍后打开的日志可比,因此该 block 不声明水位,建连后的 Session 产出的任何值都会覆盖它。在同一格式代内,cut 在 fork 时写死,不能区分其他字段区分不了的生命周期,而只读视图也从不播种 fold,所以 seeded(fork 出来的)会话与 unseeded 会话被同样地提供。`cachedPredecessorTitle(meta)` 是跨 Session 格式 edge 的更窄列表专用例外:生命周期匹配且已通过结构准入的 predecessor record 只能公开与当前版本兼容的 `title` row,因为 title 文本在相邻 edge 之间保持不变。其他 predecessor row 仍不可用。`coldSnapshot(meta, inheritedEventCount, events)` 是 fold 面:接受精确切点与完整有序日志,在折叠时跳过已检查点化的前缀,并在自身不读取持久化层的情况下刷新记录。 ### 缓存保证什么 -日志领先,缓存跟随:活会话检查点先把会话的缓冲事件持久化,然后才保存缓存记录。因此崩溃可能让缓存落后于日志,但绝不会让缓存领先。读取和写入共享存储域内一致的内存状态;逐单元写入链只在持久化成功后修改内存。每个带版本戳的记录必须匹配当前运行单元的 schema 与完整生命周期身份(`formatVersion`、`createdAt`、`cwd`、`isSeeded` 和 `inheritedEventCount`),因此从另一会话格式代或 fork 切点折叠出的行不能播种调用方。JSON 后端把每条记录存于仅所有者可访问的 `/session_projcache/sessions/.json` 目录树中。Domain 读取校验保留检查点值中的所有自有 JSON 键,包括不透明元数据中的 `__proto__` 与 `constructor`。它拒绝无法无损完成 JSON 往返的值,并与检查点写入使用相同规则。随后,每个 projection 用自己的 `stateSchema` 校验 hydration 状态;承载不透明 JSON 的字段需要使用保留其键的校验器。 +日志领先,缓存跟随:活会话检查点先把会话的缓冲事件持久化,然后才保存缓存记录。因此崩溃可能让缓存落后于日志,但绝不会让缓存领先。读取和写入共享存储域内一致的内存状态;逐单元写入链只在持久化成功后修改内存。每个带版本戳的记录必须匹配当前运行单元的 schema 与生命周期身份(`formatVersion`、`createdAt`、`cwd`、`isSeeded`);fold 面(`hydratePrepared`、`coldSnapshot` 与检查点写入)还要求精确的 `inheritedEventCount`,因此从另一会话格式代或 fork 切点折叠出的行不能播种调用方。JSON 后端把每条记录存于仅所有者可访问的 `/session_projcache/sessions/.json` 目录树中。Domain 读取校验保留检查点值中的所有自有 JSON 键,包括不透明元数据中的 `__proto__` 与 `constructor`。它拒绝无法无损完成 JSON 往返的值,并与检查点写入使用相同规则。随后,每个 projection 用自己的 `stateSchema` 校验 hydration 状态;承载不透明 JSON 的字段需要使用保留其键的校验器。 升级绝不拖垮启动,也不会暴露未经证明的折叠结果。版本戳落在 spec `compatibleVersions` 集合内的记录仍可被结构化读取并等待当前检查点重写,但缺失或更旧的 `formatVersion` 绝不匹配当前 Session,因此不能作为 hydrate seed。生命周期匹配的 predecessor title 只能通过上述列表 hint 读取,因为 title 文本在相邻 Session format edge 之间保持不变,并且该 row 仍须通过当前 projection `stateVersion` 与 schema。格式匹配后,缺失的 lineage 字段解码为 unseeded lineage——对非 fork 会话精确无误,seeded 调用方则通不过身份比对、回落冷折叠。仍然通不过 schema 校验的存量记录会按域的 `invalidRecords: 'backup-and-skip'` 策略移出为 `.json.bak.<时间戳>`、连同原因写入日志,并由下一次检查点重建。 diff --git a/packages/session/session-projection-cache/src/index.ts b/packages/session/session-projection-cache/src/index.ts index 639dfcc978..66effbbc49 100644 --- a/packages/session/session-projection-cache/src/index.ts +++ b/packages/session/session-projection-cache/src/index.ts @@ -35,7 +35,19 @@ import type { KvTable } from '@deepseek-ai/dsh-storage-domain' import { projectionCacheDomainSpec } from './spec.ts' import type { CheckpointIdentity, CheckpointRecord } from './spec.ts' -/** Complete identity written by the current cache generation. */ +/** + * The identity a Session header alone witnesses: the format generation the + * fold must have run under and the fields that distinguish one lifecycle + * stored under a session id. The read-only listing face matches exactly this. + */ +type LifecycleIdentity = Omit + +/** + * Complete identity written by the current cache generation: the lifecycle + * identity plus the exact inherited cut, which only a caller holding the + * Session or its body knows. The fold face (hydration, checkpoint writes) + * matches this. + */ type CurrentCheckpointIdentity = CheckpointIdentity & { formatVersion: number isSeeded: boolean @@ -129,26 +141,30 @@ export class SessionProjectionCache extends Service { /** * The zero-I/O listing read: whole values viewed straight from the stored - * rows (version-matching keys only), each cut carried with its watermark so - * a client value store can seed under its higher-seq-wins rule — as stale - * as the last durable checkpoint but never wrong, and never from an - * unrelated log (the caller's header is the identity witness). Fresher - * paths (the history tail baseline) supersede these values whenever a - * session is actually opened. + * rows (version-matching keys only) of the record bound to the caller's + * lifecycle. The header is the only identity witness a listing holds, so + * this face matches the lifecycle identity (`formatVersion`, `createdAt`, + * `cwd`, `isSeeded`) and not the inherited cut: within one format + * generation the cut is fixed at fork time, so it distinguishes no + * lifecycle the other fields do not, and a viewed value never seeds a fold. + * The view is as stale as the last durable checkpoint but never wrong and + * never from an unrelated log. It is served as a cached block + * (`asOfSeq: -1`): the header cannot vouch that the stored row sequence is + * comparable with the caller's log, so the block claims no watermark and + * any sequenced value (a history baseline, a control baseline, a frame) + * supersedes it once the session is opened. * @param meta - the listed session's header (identity witness; no log read). - * @param inheritedEventCount - exact inherited prefix length that completes - * the checkpoint identity. * @param keys - optional projection keys required by the caller's audience. - * @returns the cut (`asOfSeq` = lowest served-row watermark), or - * `undefined` when no usable row exists for this lifecycle. + * @returns the cached block, or `undefined` when no usable row exists for + * this lifecycle at the current Session format. */ cachedSnapshot( meta: SessionHeader, - inheritedEventCount: SessionLogOffset, keys?: readonly Extract[], ): ProjectionSnapshot | undefined { - const record = this.recordFor(meta.id, identityOf(meta, inheritedEventCount)) - if (record === undefined) return undefined + const expected = lifecycleIdentityOf(meta) + const record = this.requireTable().get(meta.id) + if (record === undefined || !currentLifecycleMatches(record.identity, expected)) return undefined return this.viewRecord(record, keys) } @@ -161,43 +177,32 @@ export class SessionProjectionCache extends Service { * fact from this Session. The registry still requires the current title * projection's row version and schema. No other predecessor projection is * exposed: format normalization can change their current meaning, and the - * strict {@link cachedSnapshot} / hydration paths continue to reject them. + * {@link cachedSnapshot} / hydration paths continue to reject them. * @param meta - authoritative listed Session header. - * @param inheritedEventCount - exact inherited cut completing the lifecycle identity. - * @returns a title-only checkpoint view with `asOfSeq: -1`, or `undefined` - * when the record is current, newer, unrelated, missing, or incompatible - * with the title unit. The sentinel avoids reusing a sequence that a - * cardinality-changing Session migration may have remapped. + * @returns a title-only cached block (`asOfSeq: -1`), or `undefined` when + * the record is current, newer, unrelated, missing, or incompatible with + * the title unit. */ - cachedPredecessorTitle( - meta: SessionHeader, - inheritedEventCount: SessionLogOffset, - ): ProjectionSnapshot | undefined { - const expected = identityOf(meta, inheritedEventCount) + cachedPredecessorTitle(meta: SessionHeader): ProjectionSnapshot | undefined { + const expected = lifecycleIdentityOf(meta) const record = this.requireTable().get(meta.id) if (record === undefined || !predecessorIdentityMatches(record.identity, expected)) return undefined - const title = this.viewRecord(record, [PREDECESSOR_TITLE_KEY]) - return title === undefined ? undefined : { ...title, asOfSeq: -1 } + return this.viewRecord(record, [PREDECESSOR_TITLE_KEY]) } - /** View selected wire rows and bind them to their lowest served watermark. */ + /** + * View selected wire rows as a cached block. The block claims no watermark: + * a listing cannot prove the stored row sequence is comparable with the + * log a consumer later opens, and under-claiming is safe where + * over-claiming would let a stale value outrank a sequenced one. + */ private viewRecord( record: CheckpointRecord, keys?: readonly Extract[], ): ProjectionSnapshot | undefined { const values = this.ctx.sessionProjections.viewCheckpoint(record.rows, keys) - const servedKeys = Object.keys(values) - if (servedKeys.length === 0) return undefined - // The block carries ONE cut: the lowest served watermark is the seq every - // value is at least current as of (under-claiming is safe under - // higher-seq-wins; over-claiming would let a stale value outrank pushes). - const firstKey = servedKeys[0] as string - let asOfSeq = (record.rows[firstKey] as ProjectionCheckpoint[string]).seq - for (const key of servedKeys.slice(1)) { - const row = record.rows[key] as ProjectionCheckpoint[string] - if (row.seq < asOfSeq) asOfSeq = row.seq - } - return { asOfSeq, values } + if (Object.keys(values).length === 0) return undefined + return { asOfSeq: -1, values } } /** @@ -391,7 +396,17 @@ export class SessionProjectionCache extends Service { } } -/** Project a header onto the identity fields a record is bound to. */ +/** Project a header onto the identity fields a header alone can witness. */ +function lifecycleIdentityOf(header: SessionHeader): LifecycleIdentity { + return { + formatVersion: header.version, + createdAt: header.createdAt, + ...header.cwd === undefined ? {} : { cwd: header.cwd }, + isSeeded: header.isSeeded, + } +} + +/** Project a header and its exact inherited cut onto the complete fold identity. */ function identityOf( header: SessionHeader, inheritedEventCount: SessionLogOffset, @@ -400,23 +415,30 @@ function identityOf( if (!header.isSeeded && cut !== 0) { throw new Error('unseeded projection-cache identity inherited event count must be 0') } - return { - formatVersion: header.version, - createdAt: header.createdAt, - ...header.cwd === undefined ? {} : { cwd: header.cwd }, - isSeeded: header.isSeeded, - inheritedEventCount: cut, - } + return { ...lifecycleIdentityOf(header), inheritedEventCount: cut } } /** - * Whether a stored record's bound identity names the caller's lifecycle. - * An absent format generation cannot prove the fold semantics and never - * matches. Once the format matches, absent lineage fields (records admitted - * via `compatibleVersions` predate them) read as the unseeded lineage: exact - * for an unseeded caller, while a seeded caller fails the match. + * Whether a stored record may seed the caller's fold: the current format + * generation, the same lifecycle, and the same inherited cut. A record folded + * under another cut encodes that cut in unit states (`schedule`, + * `subagentCatalog`, `permissions`) and would carry it into the continued + * fold and the next checkpoint. Absent lineage fields (records admitted via + * `compatibleVersions` predate them) read as the unseeded lineage: exact for + * an unseeded caller, while a seeded caller fails the match. */ function identityMatches(stored: CheckpointIdentity, expected: CurrentCheckpointIdentity): boolean { + return currentLifecycleMatches(stored, expected) + && (stored.inheritedEventCount ?? 0) === expected.inheritedEventCount +} + +/** + * Whether a stored record was folded from the caller's lifecycle at the + * current Session format. An absent format generation cannot prove the fold + * semantics and never matches. This is the whole identity a header-only + * reader can check, and the whole identity a view needs. + */ +function currentLifecycleMatches(stored: CheckpointIdentity, expected: LifecycleIdentity): boolean { return stored.formatVersion === expected.formatVersion && lifecycleIdentityMatches(stored, expected) } @@ -424,7 +446,7 @@ function identityMatches(stored: CheckpointIdentity, expected: CurrentCheckpoint /** Match one predecessor cache record to the authoritative listed lifecycle. */ function predecessorIdentityMatches( stored: CheckpointIdentity, - expected: CurrentCheckpointIdentity, + expected: LifecycleIdentity, ): boolean { const predecessor = stored.formatVersion === undefined || stored.formatVersion < expected.formatVersion @@ -434,12 +456,11 @@ function predecessorIdentityMatches( /** Match the format-independent fields that distinguish one Session lifecycle. */ function lifecycleIdentityMatches( stored: CheckpointIdentity, - expected: CurrentCheckpointIdentity, + expected: LifecycleIdentity, ): boolean { return stored.createdAt === expected.createdAt && stored.cwd === expected.cwd && (stored.isSeeded ?? false) === expected.isSeeded - && (stored.inheritedEventCount ?? 0) === expected.inheritedEventCount } export default SessionProjectionCache diff --git a/packages/session/session-projection-cache/tests/cache.spec.ts b/packages/session/session-projection-cache/tests/cache.spec.ts index af79b02947..e66f2c2e60 100644 --- a/packages/session/session-projection-cache/tests/cache.spec.ts +++ b/packages/session/session-projection-cache/tests/cache.spec.ts @@ -45,11 +45,13 @@ declare module '@deepseek-ai/dsh-session-projection/types' { 'cache-test/count': number 'cache-test/secret': string 'cache-test/marks3': MarksState + title: string | null } interface SessionProjectionMap { 'cache-test/marks': { marks: string[] } 'cache-test/secondary-marks': { marks: string[] } 'cache-test/marks3': { marks: string[] } + title: string | null } } @@ -108,6 +110,16 @@ const secondaryMarksUnit = { stateVersion: 1, } satisfies ProjectionDefinition<'cache-test/secondary-marks', MarksState> +/** Mirrors the shipped title unit's storage face (stateVersion 1, bare-string state). */ +const titleUnit = { + key: 'title', + stateSchema: z.string().nullable(), + init: () => null, + apply: state => state, + wire: { viewSchema: z.string().nullable(), view: state => state }, + stateVersion: 1, +} satisfies ProjectionDefinition<'title', string | null> + /** One session's record document on the per-record medium. */ const recordPath = (root: string, id: Session['id']): string => join(root, projectionCacheDomainSpec.name, 'sessions', `${String(id)}.json`) @@ -353,16 +365,17 @@ describe('SessionProjectionCache write policy', () => { }) describe('SessionProjectionCache listing read', () => { - it('rejects a nonzero inherited cut for an unseeded header', async () => { + it('rejects a nonzero inherited cut for an unseeded header on the fold face', async () => { const { cache } = await harness() - expect(() => cache.cachedSnapshot( + expect(() => cache.coldSnapshot( headerOf(SessionId('invalid-unseeded-cut')), SessionLogOffset(1), + [], )).toThrow('unseeded projection-cache identity inherited event count must be 0') }) - it('uses the lowest watermark across every served wire row', async () => { + it('serves rows with differing watermarks as one cached block that claims no watermark', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-')) roots.push(root) await seedRecord(root, 'watermark-lower', { @@ -376,13 +389,18 @@ describe('SessionProjectionCache listing read', () => { const { ctx, cache } = await harness({ root }) ctx.sessionProjections.register(secondaryMarksUnit) - expect(cache.cachedSnapshot(headerOf(SessionId('watermark-lower')), SessionLogOffset(0))?.asOfSeq) - .toBe(2) - expect(cache.cachedSnapshot(headerOf(SessionId('watermark-higher')), SessionLogOffset(0))?.asOfSeq) - .toBe(4) + for (const id of ['watermark-lower', 'watermark-higher']) { + expect(cache.cachedSnapshot(headerOf(SessionId(id)))).toEqual({ + asOfSeq: -1, + values: { + 'cache-test/marks': { marks: ['primary'] }, + 'cache-test/secondary-marks': { marks: ['secondary'] }, + }, + }) + } }) - it('refuses a checkpoint created for a different inherited cut', async () => { + it('serves a seeded lifecycle by header alone while the fold face still refuses another cut', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-')) roots.push(root) const id = SessionId('cut-identity') @@ -399,12 +417,54 @@ describe('SessionProjectionCache listing read', () => { ) const { cache } = await harness({ root }) const seededHeader = { ...headerOf(id), isSeeded: true } + const log: SessionEvent[] = [ + { type: 'turn/start', seq: SessionSeq(0), time: 0, data: { turn: 1 } }, + { type: 'cache-test/mark', seq: SessionSeq(1), time: 1, data: { marks: ['logged'] } }, + ] - expect(cache.cachedSnapshot(seededHeader, SessionLogOffset(2))?.values['cache-test/marks']) + // The listing knows only the header: the record's lifecycle matches, so + // its rows are viewed without any cut. + expect(cache.cachedSnapshot(seededHeader)) + .toEqual({ asOfSeq: -1, values: { 'cache-test/marks': { marks: ['seed'] } } }) + // An unseeded header names another lifecycle even though the id matches. + expect(cache.cachedSnapshot(headerOf(id))).toBeUndefined() + // The fold face holds the exact cut: the matching cut seeds from the row, + // another cut refolds the whole log instead of continuing a foreign state. + expect(cache.coldSnapshot(seededHeader, SessionLogOffset(2), log).values['cache-test/marks']) .toEqual({ marks: ['seed'] }) - expect(cache.cachedSnapshot(seededHeader, SessionLogOffset(1))).toBeUndefined() - expect(() => cache.cachedSnapshot(headerOf(id), SessionLogOffset(1))) - .toThrow('unseeded projection-cache identity inherited event count must be 0') + expect(cache.coldSnapshot(seededHeader, SessionLogOffset(1), log).values['cache-test/marks']) + .toEqual({ marks: ['logged'] }) + }) + + it('serves a seeded lifecycle\'s predecessor title by header alone', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-')) + roots.push(root) + const id = SessionId('seeded-predecessor') + await seedRecord( + root, + id, + { + 'cache-test/marks': { ver: 1, seq: SessionSeq(3), val: { marks: ['fork'] } }, + title: { ver: 1, seq: SessionSeq(3), val: 'forked title' }, + }, + { + formatVersion: SESSION_FORMAT_VERSION - 1, + createdAt: 0, + isSeeded: true, + inheritedEventCount: SessionLogOffset(5), + }, + ) + const { ctx, cache } = await harness({ root }) + ctx.sessionProjections.register(titleUnit) + const seededHeader = { ...headerOf(id), isSeeded: true } + + // An older format generation never serves the full block, but its title + // survives the format edge, for a seeded lifecycle as for an unseeded one. + expect(cache.cachedSnapshot(seededHeader)).toBeUndefined() + expect(cache.cachedPredecessorTitle(seededHeader)) + .toEqual({ asOfSeq: -1, values: { title: 'forked title' } }) + // An unseeded header names another lifecycle: no title either. + expect(cache.cachedPredecessorTitle(headerOf(id))).toBeUndefined() }) it('serves a creation-time checkpoint at the before-first-event cursor', async () => { @@ -415,7 +475,7 @@ describe('SessionProjectionCache listing read', () => { }) const { cache } = await harness({ root }) - expect(cache.cachedSnapshot(headerOf(SessionId('before-first-event')), SessionLogOffset(0))) + expect(cache.cachedSnapshot(headerOf(SessionId('before-first-event')))) .toEqual({ asOfSeq: -1, values: { 'cache-test/marks': { marks: [] } } }) }) @@ -436,7 +496,7 @@ describe('SessionProjectionCache listing read', () => { ) const { cache } = await harness({ root }) - expect(cache.cachedSnapshot(headerOf(id), SessionLogOffset(0))).toBeUndefined() + expect(cache.cachedSnapshot(headerOf(id))).toBeUndefined() }) it('keeps host-only checkpoint state out of cached wire snapshots', async () => { @@ -450,15 +510,15 @@ describe('SessionProjectionCache listing read', () => { ctx.sessionProjections.register(secretUnit) const header = headerOf(SessionId('host-state')) - expect(cache.cachedSnapshot(header, SessionLogOffset(0))).toEqual({ - asOfSeq: 4, + expect(cache.cachedSnapshot(header)).toEqual({ + asOfSeq: -1, values: { 'cache-test/marks': { marks: ['wire'] } }, }) - expect(JSON.stringify(cache.cachedSnapshot(header, SessionLogOffset(0)))) + expect(JSON.stringify(cache.cachedSnapshot(header))) .not.toContain('private prompt text') }) - it('serves identity-matching rows with the cut watermark and refuses unrelated ones', async () => { + it('serves lifecycle-matching rows as a cached block and refuses unrelated ones', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-')) roots.push(root) await seedRecord(root, 'listed', { @@ -466,34 +526,31 @@ describe('SessionProjectionCache listing read', () => { }) const { cache } = await harness({ root }) const id = SessionId('listed') - // Matching header: values plus the watermark the client seeds under. - expect(cache.cachedSnapshot(headerOf(id), SessionLogOffset(0))) - .toEqual({ asOfSeq: 4, values: { 'cache-test/marks': { marks: ['t'] } } }) + // Matching header: the values, claiming no watermark the client could compare. + expect(cache.cachedSnapshot(headerOf(id))) + .toEqual({ asOfSeq: -1, values: { 'cache-test/marks': { marks: ['t'] } } }) // A recreated id (different createdAt): the record is unrelated — no block. - expect(cache.cachedSnapshot(headerOf(id, 777), SessionLogOffset(0))).toBeUndefined() + expect(cache.cachedSnapshot(headerOf(id, 777))).toBeUndefined() // Unknown id: no block. - expect(cache.cachedSnapshot(headerOf(SessionId('never-cached')), SessionLogOffset(0))) + expect(cache.cachedSnapshot(headerOf(SessionId('never-cached')))) .toBeUndefined() }) - it('carries ONE cut across multiple served rows: the lowest watermark wins', async () => { + it('views every served wire row of one record in one cached block', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-')) roots.push(root) - // Equal watermarks: whichever row is visited second cannot lower the cut, - // so the one-cut fold sees both a lowering and a non-lowering row in - // every iteration order. await seedRecord(root, 'multi-row', { 'cache-test/marks': { ver: 1, seq: SessionSeq(4), val: { marks: ['a'] } }, 'cache-test/marks3': { ver: 1, seq: SessionSeq(4), val: { marks: ['b'] } }, }) const { ctx, cache } = await harness({ root }) ctx.sessionProjections.register(marks3Unit) - const block = cache.cachedSnapshot(headerOf(SessionId('multi-row')), SessionLogOffset(0)) + const block = cache.cachedSnapshot(headerOf(SessionId('multi-row'))) expect(block?.values).toEqual({ 'cache-test/marks': { marks: ['a'] }, 'cache-test/marks3': { marks: ['b'] }, }) - expect(block?.asOfSeq).toBe(4) + expect(block?.asOfSeq).toBe(-1) }) it('returns undefined when the stored record version is not accepted', async () => { @@ -516,7 +573,7 @@ describe('SessionProjectionCache listing read', () => { }, })) const { cache } = await harness({ root }) - expect(cache.cachedSnapshot(headerOf(SessionId('all-stale')), SessionLogOffset(0))) + expect(cache.cachedSnapshot(headerOf(SessionId('all-stale')))) .toBeUndefined() }) @@ -537,11 +594,20 @@ describe('SessionProjectionCache listing read', () => { const { cache } = await harness({ root }) const id = SessionId('pre-lineage') // Unseeded caller: the absent lineage is exactly its identity — served. - expect(cache.cachedSnapshot(headerOf(id), SessionLogOffset(0))) - .toEqual({ asOfSeq: 4, values: { 'cache-test/marks': { marks: ['kept'] } } }) - // Seeded caller: the lineage-less record cannot vouch for the cut — refused. - expect(cache.cachedSnapshot({ ...headerOf(id), isSeeded: true }, SessionLogOffset(2))) + expect(cache.cachedSnapshot(headerOf(id))) + .toEqual({ asOfSeq: -1, values: { 'cache-test/marks': { marks: ['kept'] } } }) + // Seeded caller: the lineage-less record cannot vouch for a seeded lifecycle — refused. + expect(cache.cachedSnapshot({ ...headerOf(id), isSeeded: true })) .toBeUndefined() + // The fold face reads the absent lineage as the unseeded cut 0: the + // unseeded caller continues from the row, the seeded caller refolds. + const log: SessionEvent[] = [0, 1, 2, 3, 4].map(seq => ({ + type: 'cache-test/mark', seq: SessionSeq(seq), time: seq, data: { marks: [`m${seq}`] }, + })) + expect(cache.coldSnapshot(headerOf(id), SessionLogOffset(0), log).values['cache-test/marks']) + .toEqual({ marks: ['kept'] }) + expect(cache.coldSnapshot({ ...headerOf(id), isSeeded: true }, SessionLogOffset(1), log).values['cache-test/marks']) + .toEqual({ marks: ['m4'] }) }) it('refuses an accepted predecessor record without a Session format generation', async () => { @@ -559,7 +625,7 @@ describe('SessionProjectionCache listing read', () => { })) const { cache } = await harness({ root }) - expect(cache.cachedSnapshot(headerOf(id), SessionLogOffset(0))).toBeUndefined() + expect(cache.cachedSnapshot(headerOf(id))).toBeUndefined() }) it('returns undefined when every stored row is version-mismatched', async () => { @@ -571,7 +637,7 @@ describe('SessionProjectionCache listing read', () => { 'cache-test/marks': { ver: 99, seq: SessionSeq(4), val: { marks: ['old'] } }, }) const { cache } = await harness({ root }) - expect(cache.cachedSnapshot(headerOf(SessionId('row-stale')), SessionLogOffset(0))) + expect(cache.cachedSnapshot(headerOf(SessionId('row-stale')))) .toBeUndefined() }) @@ -589,10 +655,10 @@ describe('SessionProjectionCache listing read', () => { }) const { cache } = await harness({ root }) const id = SessionId('homed') - expect(cache.cachedSnapshot(headerOf(id, 0, '/work'), SessionLogOffset(0))?.values['cache-test/marks']) + expect(cache.cachedSnapshot(headerOf(id, 0, '/work'))?.values['cache-test/marks']) .toEqual({ marks: ['w'] }) - expect(cache.cachedSnapshot(headerOf(id, 0, '/elsewhere'), SessionLogOffset(0))).toBeUndefined() - expect(cache.cachedSnapshot(headerOf(id, 0), SessionLogOffset(0))).toBeUndefined() + expect(cache.cachedSnapshot(headerOf(id, 0, '/elsewhere'))).toBeUndefined() + expect(cache.cachedSnapshot(headerOf(id, 0))).toBeUndefined() }) it('returns undefined for a malformed record document (refold from the log on the caller side)', async () => { @@ -602,7 +668,7 @@ describe('SessionProjectionCache listing read', () => { await mkdir(dirname(path), { recursive: true }) await writeFile(path, 'not json at all') const { cache } = await harness({ root }) - expect(cache.cachedSnapshot(headerOf(SessionId('malformed')), SessionLogOffset(0))) + expect(cache.cachedSnapshot(headerOf(SessionId('malformed')))) .toBeUndefined() }) }) diff --git a/packages/session/session-projection-cache/tests/fixtures.spec.ts b/packages/session/session-projection-cache/tests/fixtures.spec.ts index 3b3de927d6..1116aebb66 100644 --- a/packages/session/session-projection-cache/tests/fixtures.spec.ts +++ b/packages/session/session-projection-cache/tests/fixtures.spec.ts @@ -20,7 +20,7 @@ import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { Context } from '@deepseek-ai/cordis' import { z } from 'zod' -import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' import type { SessionHeader } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' @@ -209,12 +209,10 @@ describe('archived version recovery', () => { const { ctx, cache } = await harness(root) expect(cache.cachedSnapshot( headerFor(SessionId(sid), record.identity), - SessionLogOffset(0), ['title'], )).toBeUndefined() expect(cache.cachedPredecessorTitle( headerFor(SessionId(sid), record.identity), - SessionLogOffset(0), )).toEqual({ asOfSeq: -1, values: { title: record.rows.title?.val }, @@ -243,12 +241,10 @@ describe('archived version recovery', () => { const { ctx, cache } = await harness(root) expect(cache.cachedSnapshot( headerFor(id, doc.record.identity), - SessionLogOffset(0), ['title'], )).toBeUndefined() expect(cache.cachedPredecessorTitle( headerFor(id, doc.record.identity), - SessionLogOffset(0), )).toEqual({ asOfSeq: -1, values: { title: doc.record.rows.title?.val }, @@ -290,25 +286,25 @@ describe('archived version recovery', () => { cwd: '/work', isSeeded: false, }) - expect(cache.cachedPredecessorTitle(listed('older'), SessionLogOffset(0))).toEqual({ + expect(cache.cachedPredecessorTitle(listed('older'))).toEqual({ asOfSeq: -1, values: { title: 'older title' }, }) - expect(cache.cachedPredecessorTitle(listed('current'), SessionLogOffset(0))).toBeUndefined() - expect(cache.cachedPredecessorTitle(listed('newer'), SessionLogOffset(0))).toBeUndefined() - expect(cache.cachedPredecessorTitle(listed('stale-title'), SessionLogOffset(0))).toBeUndefined() - expect(cache.cachedPredecessorTitle(listed('missing'), SessionLogOffset(0))).toBeUndefined() + expect(cache.cachedPredecessorTitle(listed('current'))).toBeUndefined() + expect(cache.cachedPredecessorTitle(listed('newer'))).toBeUndefined() + expect(cache.cachedPredecessorTitle(listed('stale-title'))).toBeUndefined() + expect(cache.cachedPredecessorTitle(listed('missing'))).toBeUndefined() }) - it('refuses a lineage-less archive for a seeded caller (identity mismatch, cold rebuild)', async () => { + it('refuses a lineage-less archive for a seeded caller (lifecycle mismatch, cold rebuild)', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-fx-')) const id = SessionId('fixture-seeded') const doc = await placeDoc(root, id, 'v5-lineageless-doc.json') const { cache } = await harness(root) const seeded = { ...headerFor(id, doc.record.identity), isSeeded: true } - expect(cache.cachedSnapshot(seeded, SessionLogOffset(2), ['title'])).toBeUndefined() - expect(cache.cachedPredecessorTitle(seeded, SessionLogOffset(2))).toBeUndefined() + expect(cache.cachedSnapshot(seeded, ['title'])).toBeUndefined() + expect(cache.cachedPredecessorTitle(seeded)).toBeUndefined() }) it('backs up and skips a record that fails schema validation instead of failing the boot', async () => { @@ -350,11 +346,10 @@ describe('archived version recovery', () => { // The broken record reads as absent; its predecessor-stamped neighbor // remains available for a safe current rewrite. const cache = ctx.sessionProjectionCache - expect(cache.cachedSnapshot(headerFor(SessionId('broken'), { createdAt: 0 }), SessionLogOffset(0))) + expect(cache.cachedSnapshot(headerFor(SessionId('broken'), { createdAt: 0 }))) .toBeUndefined() expect(cache.cachedSnapshot( headerFor(SessionId('survivor'), good.record.identity), - SessionLogOffset(0), ['title'], )).toBeUndefined() await assertRewrite(ctx, root, SessionId('survivor')) diff --git a/packages/subagent/subagent/src/list-children.ts b/packages/subagent/subagent/src/list-children.ts index 9de66e771c..c52d9f3bcc 100644 --- a/packages/subagent/subagent/src/list-children.ts +++ b/packages/subagent/subagent/src/list-children.ts @@ -9,7 +9,7 @@ */ import type { Context } from '@deepseek-ai/cordis' -import { type Session, SessionLogOffset } from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection' import type { SessionProjectionCache } from '@deepseek-ai/dsh-session-projection-cache' @@ -297,13 +297,13 @@ async function resolveColdIdentity( ): Promise { const childId = header.id // A header deliberately exposes only whether a fork cut exists, not its - // integer. An unseeded lifecycle has the exact cut 0 and may use the cache; - // a seeded lifecycle must read the body before an identity seq can be - // classified as inherited or owned. + // integer. An unseeded lifecycle has the exact cut 0, so its cached + // descriptor is owned at every valid seq; a seeded lifecycle must read the + // body before an identity seq can be classified as inherited or owned. if (cache !== undefined && !header.isSeeded) { let cached: SubagentIdentityProjection | null | undefined try { - cached = cache.cachedSnapshot(header, SessionLogOffset(0), ['subagent'])?.values.subagent + cached = cache.cachedSnapshot(header, ['subagent'])?.values.subagent } catch { // Unlike the preparation fold below, a throwing cache read renders no // verdict: the cache is derived data, so its damage (a poisoned stored From 9ff8f264508484a996bb224bcbb25cd820245f4e Mon Sep 17 00:00:00 2001 From: imccyu Date: Sat, 19 Sep 2026 23:47:28 +0800 Subject: [PATCH 04/24] fix(client): keep list-cached projection rows below sequenced writes ProjectionValueStore rows are either cached (viewed from the persisted checkpoint by the session list, no comparable seq) or sequenced (computed by the connected Host, seq comparable within the connection). Cached values fill empty keys only; every baseline discards cached rows before seeding, and every frame replaces them regardless of seq, so a connected Session's values always supersede list hints. The list response and api-session/added blocks write cached rows. --- .../src/client/sessions/manager.ts | 23 +++-- .../src/client/sessions/projection-store.ts | 69 +++++++++++---- .../tests/manager.client.spec.ts | 15 ++-- .../tests/projection-store.client.spec.ts | 87 +++++++++++++++++-- 4 files changed, 152 insertions(+), 42 deletions(-) diff --git a/packages/api/session-controller/src/client/sessions/manager.ts b/packages/api/session-controller/src/client/sessions/manager.ts index f46b6cc8fe..d9cf53d89f 100644 --- a/packages/api/session-controller/src/client/sessions/manager.ts +++ b/packages/api/session-controller/src/client/sessions/manager.ts @@ -376,18 +376,16 @@ export class SessionManager { session.handleBlank(s.blank) session.handleRunning(s.running) } - // Seed each row's projection baseline into the per-session value - // store (cold titles surface without opening the session). Per-key - // apply, not seed(): the list block is a partial baseline — the - // cold cache serves only version-matching keys — so an absent key - // must not clear; higher-seq-wins still keeps a stale list block - // from overwriting a newer push frame or tail baseline. + // Fill each row's cached projection block into the per-session value + // store (cold titles surface without opening the session). Cached, + // not seeded: the list block is a partial view of the persisted + // checkpoint — only version-matching keys, no comparable seq — so an + // absent key must not clear, and any sequenced value (a push frame, + // a tail baseline) outranks it. for (const s of result.value.items) { const block = s.projections if (block === undefined) continue - const store = this.projectionStore(s.sessionId) - const values = block.values as Record - for (const key of Object.keys(values)) store.apply(key, values[key], sessionSeqCursor(block.asOfSeq)) + this.projectionStore(s.sessionId).applyCached(block.values) } } else { this.listState = 'error' @@ -604,12 +602,11 @@ export class SessionManager { handleSessionAdded(summary: SessionSummary): void { this.mergeSummary(summary) this.sessions.get(summary.sessionId)?.handleBlank(summary.blank) + // A list-surface block is cached like the list response itself: the + // Session's own baseline replaces it once the client opens the Session. const projections = summary.projections if (projections !== undefined) { - const store = this.projectionStore(summary.sessionId) - for (const [key, value] of Object.entries(projections.values)) { - store.apply(key, value, sessionSeqCursor(projections.asOfSeq)) - } + this.projectionStore(summary.sessionId).applyCached(projections.values) } } diff --git a/packages/api/session-controller/src/client/sessions/projection-store.ts b/packages/api/session-controller/src/client/sessions/projection-store.ts index a53e4e73ee..24b3b22602 100644 --- a/packages/api/session-controller/src/client/sessions/projection-store.ts +++ b/packages/api/session-controller/src/client/sessions/projection-store.ts @@ -52,11 +52,18 @@ export interface ProjectionsBaseline { values: Readonly> } -/** One key's row: the latest finished value and the seq it is consistent with. */ -interface Row { - value: unknown - seq: SessionSeqCursor -} +/** + * One key's row. A `sequenced` row was computed by the Host for this Session + * within the current connection generation and carries the seq it is + * consistent with; seqs of sequenced rows are comparable with each other. A + * `cached` row was viewed from the persisted projection checkpoint by a + * header-only listing without a Session: its origin cannot vouch that its + * stored seq is comparable with the log the client later opens, so it carries + * none and yields to every sequenced write. + */ +type Row = + | { kind: 'cached'; value: unknown } + | { kind: 'sequenced'; value: unknown; seq: SessionSeqCursor } /** Per-key notification channel: the bare face plus its batching notifier. */ interface Channel { @@ -66,10 +73,14 @@ interface Channel { /** * One session's projection values. Framework semantics, uniform across every - * key: a baseline seeds rows at its cut, a push frame updates one row, and in - * both paths a lower-or-equal seq within the Host generation loses. A replayed - * frame cannot regress a value; a stale baseline cannot overwrite a newer - * frame. A key the store has never seen reads `undefined` (capability absent). Faces are identity-stable + * key. Sequenced writes (a baseline seeds rows at its cut, a push frame + * updates one row) compare seqs among themselves: a lower-or-equal seq within + * the Host generation loses, so a replayed frame cannot regress a value and a + * stale baseline cannot overwrite a newer frame. Cached writes (the session + * list's zero-I/O block) only fill keys no sequenced row holds, and a baseline + * discards every cached row before it seeds, regardless of seq: the connected + * Session is the truth and a cached value never outranks it. A key the store + * has never seen reads `undefined` (capability absent). Faces are identity-stable * per key (create-on-demand, cached) so the React side binds each exactly * once; the store-level channel (`subscribeAny`) serves coarse consumers (the * manager's list projection reads the `title` key). @@ -133,27 +144,51 @@ export class ProjectionValueStore { */ apply(key: string, value: unknown, seq: SessionSeqCursor): void { const row = this.rows.get(key) - if (row !== undefined && seq <= row.seq) return // higher seq wins; replays and stale frames drop - this.rows.set(key, { value, seq }) + // higher seq wins among sequenced rows; replays and stale frames drop. A + // cached row has no comparable seq and always yields. + if (row?.kind === 'sequenced' && seq <= row.seq) return + this.rows.set(key, { kind: 'sequenced', value, seq }) this.changed(key) } /** - * Seed from a history tail page's projections block: every carried key - * lands under the same seq rule as frames; a key the block omits is - * capability-absent as of the cut — its row clears unless a newer frame - * already superseded the cut (a stale baseline can neither overwrite nor - * clear newer values). + * Fill keys from the session list's zero-I/O cached block. A cached value + * lands only where no sequenced row exists: a connected Session has already + * answered for such a key, and the list's view of the persisted checkpoint + * cannot be newer than it. + * @param values - whole values by key viewed from the persisted checkpoint. + */ + applyCached(values: Readonly>): void { + for (const key of Object.keys(values)) { + if (this.rows.get(key)?.kind === 'sequenced') continue + this.rows.set(key, { kind: 'cached', value: values[key] }) + this.changed(key) + } + } + + /** + * Seed from a history tail page's projections block. Every cached row is + * discarded first, regardless of seq: the block comes from the connected + * Session, and a value viewed from the persisted checkpoint never outranks + * it. Then every carried key lands under the same seq rule as frames, and a + * key the block omits is capability-absent as of the cut — its row clears + * unless a newer frame already superseded the cut (a stale baseline can + * neither overwrite nor clear newer sequenced values). * @param baseline - the response's projections block. */ seed(baseline: ProjectionsBaseline): void { + for (const [key, row] of this.rows) { + if (row.kind !== 'cached') continue + this.rows.delete(key) + this.changed(key) + } // Erased walk: the framework crosses the open key space; per-key typing // is re-established at the consumer (useProjection's map lookup). const values = baseline.values as Record for (const key of Object.keys(values)) this.apply(key, values[key], baseline.asOfSeq) for (const [key, row] of this.rows) { if (Object.hasOwn(values, key)) continue - if (row.seq > baseline.asOfSeq) continue + if (row.kind === 'sequenced' && row.seq > baseline.asOfSeq) continue this.rows.delete(key) this.changed(key) } diff --git a/packages/api/session-controller/tests/manager.client.spec.ts b/packages/api/session-controller/tests/manager.client.spec.ts index 7ee5be5397..60e96c30b9 100644 --- a/packages/api/session-controller/tests/manager.client.spec.ts +++ b/packages/api/session-controller/tests/manager.client.spec.ts @@ -203,16 +203,19 @@ describe('list lifecycle', () => { } }) - it('projects cold Session additions and an empty-cut control baseline before history exists', async ({ mock, remote }) => { + it('projects a cold Session addition as cached until an empty-cut control baseline replaces it', async ({ mock, remote }) => { const manager = makeManager(mock, remote) try { manager.handleSessionAdded({ ...summary(S1), projections: { asOfSeq: -1, values: { title: 'before history' } }, }) + expect(manager.getListSnapshot().items[0]?.title).toBe('before history') + // The control baseline is the connected Session's own value: it replaces + // the list-surface title even at the same cursor. manager.handleControlFrame({ type: 'baseline', value: { jobs: { [S1]: [] }, projections: { [S1]: { asOfSeq: -1, values: { title: 'cold baseline' } } } }, }) - expect(manager.getListSnapshot().items[0]?.title).toBe('before history') + expect(manager.getListSnapshot().items[0]?.title).toBe('cold baseline') expect(manager.getListSnapshot().jobsBySession).toEqual({}) } finally { await manager.dispose() @@ -317,23 +320,23 @@ describe('list lifecycle', () => { expect(manager.getListSnapshot().items.find(item => item.sessionId === S1)?.title).toBeUndefined() }) - it('seeds cold titles from the list rows\' projections block under higher-seq-wins', async ({ mock, remote }) => { + it('fills cold titles from the list rows\' projections block as cached values', async ({ mock, remote }) => { const manager = makeManager(mock, remote) - // A push frame landed before the list (S2's title is newer than the block's cut). + // A push frame landed before the list: S2's title is a sequenced value. manager.handleControlFrame({ type: 'projection', sessionId: S2, key: 'title', value: 'Pushed', seq: 9, }) remote.session.list.mockResolvedValue(ok({ items: [ { ...summary(S1), projections: { asOfSeq: 4, values: { title: 'Cold cached' } } }, - { ...summary(S2, { updatedAt: 200 }), projections: { asOfSeq: 5, values: { title: 'List stale' } } }, + { ...summary(S2, { updatedAt: 200 }), projections: { asOfSeq: 50, values: { title: 'List stale' } } }, ] as never[], })) await manager.refreshList() const items = manager.getListSnapshot().items // Cold row: title surfaces straight from the list block — no open, no history. expect(items.find(item => item.sessionId === S1)?.title).toBe('Cold cached') - // The stale list block (seq 5) cannot overwrite the newer push frame (seq 9). + // A list block never displaces a sequenced value, whatever watermark it claims. expect(items.find(item => item.sessionId === S2)?.title).toBe('Pushed') }) diff --git a/packages/api/session-controller/tests/projection-store.client.spec.ts b/packages/api/session-controller/tests/projection-store.client.spec.ts index 2ab2bbaec6..c8af28588e 100644 --- a/packages/api/session-controller/tests/projection-store.client.spec.ts +++ b/packages/api/session-controller/tests/projection-store.client.spec.ts @@ -1,11 +1,12 @@ /** * Projection value store (push model; session-projection subsystem page: - * docs/subsystems/session-projection.md): the single - * higher-seq-wins rule on both paths (a stale baseline cannot overwrite a - * newer push frame; a replayed frame cannot regress), capability absence as - * undefined, generation invalidation, and the Session/manager wiring (tail-page - * seeding, control-stream projection routing pre- and post-instantiation, the - * list rows' title projection). + * docs/subsystems/session-projection.md): the higher-seq-wins rule among + * sequenced writes (a stale baseline cannot overwrite a newer push frame; a + * replayed frame cannot regress), cached list values yielding to every + * sequenced write regardless of seq, capability absence as undefined, + * generation invalidation, and the Session/manager wiring (tail-page seeding, + * control-stream projection routing pre- and post-instantiation, the list + * rows' title projection). */ import { describe, expect } from 'vitest' import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client' @@ -75,6 +76,48 @@ describe('Session projection value semantics', () => { expect(store.get('test/marks')).toBeUndefined() }) + it('cached values fill empty keys only and never displace a sequenced row', () => { + const store = new ProjectionValueStore() + store.applyCached({ 'test/marks': { marks: ['cached'] }, title: 'Cached title' }) + expect(store.values()).toEqual({ 'test/marks': { marks: ['cached'] }, title: 'Cached title' }) + // A later cached view replaces an earlier one: neither carries a seq. + store.applyCached({ title: 'Cached again' }) + expect(store.get('title')).toBe('Cached again') + // Once a sequenced row exists, cached values for that key are ignored. + store.apply('title', 'Pushed', SessionSeq(0)) + store.applyCached({ title: 'Cached late', 'test/marks': { marks: ['cached late'] } }) + expect(store.get('title')).toBe('Pushed') + expect(store.get('test/marks')).toEqual({ marks: ['cached late'] }) + }) + + it('every sequenced write outranks a cached row regardless of seq', () => { + const store = new ProjectionValueStore() + store.applyCached({ 'test/marks': { marks: ['cached'] }, title: 'Cached title', schedule: [] }) + // A frame at the lowest cursor still replaces the cached value. + store.apply('title', 'Frame at -1', -1) + expect(store.get('title')).toBe('Frame at -1') + // A baseline discards every cached row first: the carried key lands at its + // cut, the omitted keys clear even though a cached row has no seq to compare. + store.seed({ asOfSeq: SessionSeq(2), values: { 'test/marks': { marks: ['baseline-2'] } } }) + expect(store.values()).toEqual({ 'test/marks': { marks: ['baseline-2'] } }) + // The same baseline rule keeps protecting newer sequenced rows. + store.apply('title', 'Frame at 9', SessionSeq(9)) + store.applyCached({ title: 'Cached late' }) + store.seed({ asOfSeq: SessionSeq(5), values: { 'test/marks': { marks: ['baseline-5'] } } }) + expect(store.values()).toEqual({ 'test/marks': { marks: ['baseline-5'] }, title: 'Frame at 9' }) + }) + + it('notifies faces for cached fills and for their discard by a baseline', async () => { + const store = new ProjectionValueStore() + const observed: unknown[] = [] + store.faceOf('title').subscribe(() => { observed.push(store.get('title')) }) + store.applyCached({ title: 'Cached title' }) + await Promise.resolve() + store.seed({ asOfSeq: SessionSeq(3), values: {} }) + await Promise.resolve() + expect(observed).toEqual(['Cached title', undefined]) + }) + it('clears all generation watermarks without replacing subscribed faces', async () => { const store = new ProjectionValueStore() const face = store.faceOf('test/marks') @@ -206,6 +249,38 @@ describe('manager frame routing', () => { expect(manager.getListSnapshot().items[0]?.title).toBe('Projected title') }) + it('caches a list block: a Session baseline at any cut replaces it and a list refresh cannot restore it', async ({ mock, remote }) => { + const manager = makeManager(mock, remote) + remote.session.list.mockResolvedValue(ok({ + items: [{ agentAvailable: false, + sessionId: sid('s1'), updatedAt: 1, running: false, blank: false, + // A stale record whose watermark outruns the connected Session's cut. + projections: { asOfSeq: 40, values: { title: 'Cached title', 'test/marks': { marks: ['cached'] } } }, + }], + })) + await manager.refreshList() + expect(manager.getListSnapshot().items[0]?.title).toBe('Cached title') + + // The connected Session answers at a lower cut: it still wins outright, + // and the key it omits clears rather than surviving on its stale seq. + manager.handleControlFrame({ + type: 'baseline', + value: { + jobs: {}, + projections: { [sid('s1')]: { asOfSeq: 2, values: { title: 'Connected title' } } }, + }, + }) + await Promise.resolve() + expect(manager.getListSnapshot().items[0]?.title).toBe('Connected title') + expect(manager.getListSnapshot().items[0]?.projectionValues).toEqual({ title: 'Connected title' }) + + // A later list refresh serving the stale block again cannot displace the + // sequenced value, whatever watermark the block claims. + await manager.refreshList() + expect(manager.getListSnapshot().items[0]?.title).toBe('Connected title') + expect(manager.get(sid('s1')).projections.get('test/marks')).toEqual({ marks: ['cached'] }) + }) + it('projects every retained value into list rows with stable snapshot identity', async ({ mock, remote }) => { const manager = makeManager(mock, remote) remote.session.list.mockResolvedValue(ok({ From 2ef33c7f280989a941d88774ae54d600bae0bfae Mon Sep 17 00:00:00 2001 From: imccyu Date: Sat, 19 Sep 2026 23:47:30 +0800 Subject: [PATCH 05/24] docs(session): record the projection cache listing identity decision Agent Note for the lifecycle identity read-only face and the client store's cached/sequenced row kinds: mechanism, rejected alternatives, and what stays untouched. --- ...listing-identity-and-cached-rows.i18n.yaml | 6 + ...-cache-listing-identity-and-cached-rows.md | 161 ++++++++++++++++++ ...che-listing-identity-and-cached-rows.zh.md | 161 ++++++++++++++++++ 3 files changed, 328 insertions(+) create mode 100644 .agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md create mode 100644 .agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml new file mode 100644 index 0000000000..65576d31cf --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml @@ -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/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md +2026-09-19-projection-cache-listing-identity-and-cached-rows.md: 97495cab8f9bd75791a46065d1c06e4274f7de5e +2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md: f81ccfae2869b9d2b0d3abee020f4a46498cb323 diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md new file mode 100644 index 0000000000..97495cab8f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md @@ -0,0 +1,161 @@ +# Agent Note: Projection cache read-only face matches the lifecycle identity; the client store separates cached and sequenced rows + +Status: implemented + +English | [中文](2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md) + +## Problem + +After a Host process restart, every forked session (`SessionHeader.isSeeded === true`) shows no title in the sidebar session list, `@` reference completion shows only the session id, and list ordering degrades to creation time. Opening the session once restores all of it. On one development machine on 2026-09-19, 44 of 241 projcache records were seeded, all 44 carried a valid `title` row, and the list never read any of them. + +This is neither cache corruption nor a version mismatch. The projcache record's domain version is 7 and its `identity.formatVersion` is 4; those are the cache's own on-disk format generation and the Session log format generation the fold ran under, and both are current. The defect is on the read path. + +### Mechanism + +A cache record is bound to a lifecycle identity: `formatVersion + createdAt + cwd + isSeeded + inheritedEventCount`, matched by `identityMatches` on full equality. Since [#3346](https://github.com/deepseek-harness/deepseek-harness/pull/3346), `inheritedEventCount` (the length of the event prefix a fork inherits, the cut below) no longer appears in the logical header: the header keeps only the `isSeeded` bit and the exact cut follows the body. Since Session format v2 (#3398) the physical header line no longer stores `seedLength` either; the reader derives the cut from the seq of the `session/end-seed {inherited: true}` marker in the body. + +A header-only read therefore cannot obtain the cut: the JSONL backend's `fromHeaderLine` hard-codes `inheritedEventCount: 0` for header-only reads, and `SessionPersistenceSnapshot` carries only the header, the revision, and an optional eventCount. All three header-only cache consumers grew the same guard: + +| Consumer | Guard | Fallback | Consequence | +|---|---|---|---| +| `packages/api/session-controller/src/list.ts` `projectionsFor` | `header.isSeeded ? undefined : cachedSnapshot(header, 0) ?? cachedPredecessorTitle(header, 0)` | none | no title, no `sessionListMetadata`; blank falls back to `false`, ordering falls back to `createdAt` | +| `packages/context/session-reference/src/index.ts` `projectedLabels` | same | none | `@` completion labels by id; the title cannot be searched | +| `packages/subagent/subagent/src/list-children.ts` `resolveColdIdentity` | same | `observeSession` reads the body | correct result, one body read per seeded child | + +When the guard landed (#3346, 2026-09-01), `list.ts` still had `probeSmallCold`: on a cache miss it read the body when the log file was at most `DEFAULT_COLD_BLANK_PROBE_MAX_BYTES = 1024` bytes. Its purpose was blank-session detection; it covered only logs under 1KB and never applied to an ordinary fork. #3400 (2026-09-03) removed it and the list returned to metadata plus cache only. #4320 (2026-09-19) made forking a first-class feature (`packages/core/session/src/fork.ts`, fork at any seq); every fork is `isSeeded: true` with an exact cut, seeded sessions went from a handful to dozens, all of them cold after a restart, and the gap became visible at once. + +### The cache's two uses and where validation lives + +The read and write faces of `SessionProjectionCache` and their callers: + +| Face | What it does with the record | Writes back | Callers | +|---|---|---|---| +| `write(session)` | writes the checkpoint at three mandatory points plus a throttle | yes | the cache's own listeners | +| `hydratePrepared(session, events)` | uses `rows` as the fold starting point and applies events from `row.seq + 1`; the result lands in live cells | the next checkpoint | `session-query/src/observation.ts` | +| `coldSnapshot(meta, cut, events)` | fold starting point plus write-back | yes | no production caller | +| `cachedSnapshot(meta, cut, keys?)` | `viewCheckpoint`: each row passes `ver` and `stateSchema`, is `view`ed, and returned | no | `list.ts`, `session-reference`, `list-children` | +| `cachedPredecessorTitle(meta, cut)` | the same, `title` only, allowing an older `formatVersion` | no | `list.ts` | + +Identity validation lives entirely inside the cache (`recordFor` → `identityMatches`; `viewCheckpoint` checks `ver` and schema per row). `list.ts` validates nothing itself; it merely declines to call when it cannot supply a cut. + +spec.ts and the README describe the purpose of the identity check with one verb: preventing "seed state folded from an unrelated log", "cannot seed the caller". That guards the fold face. The read-only face has never seeded anything. + +### The client store cannot guarantee that connected data replaces hints + +Each session has exactly one `ProjectionValueStore` on the client (`manager.projectionStores`). The block delivered by the list, the history first-page baseline on open, the control baseline, push frames, and rename results all write into that one object, and `useProjection` reads it. All writers are peers under one higher-seq-wins rule: `apply` drops a new value when `seq <= row.seq`, and `seed` clears omitted keys only when `row.seq <= cut`. A list hint whose seq is equal or higher survives untouched after the session is opened. The hint's seq comes from a disk record; after a crash-repair truncation it can be numerically higher than the connected cursor, which is exactly the case where the cache is wrong and the connection is right. Comparing seqs against a hint is the wrong tool. + +## Decision + +### Two read faces; the cut is compared only on the fold face + +| Face | Identity | Who can supply it | Methods | +|---|---|---|---| +| read-only face | lifecycle identity: `formatVersion + createdAt + cwd + isSeeded`, all from the header | any header-only caller | `cachedSnapshot(header, keys?)`, `cachedPredecessorTitle(header)` | +| fold face | lifecycle identity plus `inheritedEventCount` | callers holding the Session or its body | `hydratePrepared`, `write`, `coldSnapshot`, all through `recordFor` | + +The two read-only methods no longer take a cut parameter. `inheritedEventCount` is still written into every record and the fold face still compares it on full equality; the original design expectation, that records folded under different fork cuts never seed each other, is unchanged. + +The read-only face's output is cached: the returned block's `asOfSeq` is always `-1`, the sentinel `cachedPredecessorTitle` already used. A header can vouch neither for the cut nor for the comparability of the record's seq with the current log, so this face declares no seq. The cache stated the principle itself in `viewRecord`: under-claiming is safe under higher-seq-wins, over-claiming would let a stale value outrank pushes. + +### Why the read-only face may skip the cut + +- Within one `formatVersion`, a log's cut is determined by `(id, createdAt, cwd, isSeeded)`: it is fixed at fork creation, and only a cardinality-changing format migration can alter it, which necessarily bumps `formatVersion`. The cut is a derived fact of the lifecycle, not an independent coordinate. +- What the read-only face actually did until now: unseeded callers passed the constant 0 (true by construction) and seeded callers never called. The cut was never compared against any real fact on this face. Removing it changes the rejection set not at all: a record from another lifecycle (any of the four fields differing) is still rejected, unseeded results are identical, and seeded lifecycles go from unaddressable to addressable. +- The read-only face never seeds and never writes back; its output is a pure function of the stored record, the cut plays no part in it, and it flows nowhere. +- The one new exposure: a record whose four fields all match but whose cut differs. The system cannot produce it; only copying a session directory by hand and editing files can. Even then the list shows that record's values until the session is opened, and nothing enters any fold. + +### Consumers + +| Location | Change | +|---|---| +| `list.ts` `projectionsFor` | drop the `isSeeded` branch and `SessionLogOffset(0)`; every cold row reads `cachedSnapshot(header) ?? cachedPredecessorTitle(header)` | +| `session-reference` `projectedLabels` | same symptom, same change | +| `list-children.ts` `resolveColdIdentity` | follows the signature only; the `!header.isSeeded` guard and the body fallback stay, because it needs the cut to classify a seq as inherited or owned, which is fold semantics | + +### The client store separates cached and sequenced rows + +Rows in `ProjectionValueStore` come in two kinds, named for the property the rule depends on: whether the value carries a seq comparable within this connection. + +| Row | Meaning | Carries | +|---|---|---| +| `cached` | viewed from the persisted checkpoint without a Session; its seq is not comparable with this connection | `value` only | +| `sequenced` | computed by the Host for this Session within this connection; seqs share one space | `value` and `seq` | + +Rules: + +| Write | Against a `cached` row | Against a `sequenced` row | +|---|---|---| +| `applyCached(values)` | replaces | ignored | +| `seed(baseline)` | discards every `cached` row first, then writes the block; omitted keys clear under `seq <= cut` | higher-seq-wins | +| `apply(key, value, seq)` | replaces | higher-seq-wins | + +Seq comparison happens only within one Host connection: `handleConnected` clears the whole store, then the list writes cached rows again and opening a session seeds again. From cached to sequenced is an unconditional replacement without any seq comparison. + +Writer classification: + +| Entry | Row kind | +|---|---| +| the `projections` block of each summary in the `session.list` response (`manager.refreshList`) | cached | +| the `projections` block of an `api-session/added` summary (`manager.handleSessionAdded`) | cached | +| the history first page's `projections` (`projections.seed` in `session.ts`) | sequenced | +| the control baseline, live sessions only (`manager.replaceControlBaseline`) | sequenced | +| the `session.projections` result of `refreshProjections` (a body observation) | sequenced | +| push frames (the `projection` frame handled by `manager`) | sequenced | +| the `title` after a successful rename (`session.ts`) | sequenced | + +The `seed` and `apply` signatures are unchanged. The server keeps the `asOfSeq` field on the wire; the client does not read it for cached writes. + +### What stays untouched + +- The Session format, the physical header line, `fromHeaderLine`, persistence, `SessionPersistenceSnapshot`. +- Hydration and the checkpoint write path; `recordFor` keeps full equality on all five fields. +- `coldSnapshot` stays; having no production caller is not a reason to delete it here. +- Old records (domain v4/v5, lacking `isSeeded` and `inheritedEventCount`) keep missing for seeded sessions until the session is opened and rewritten as a v7 record. +- The list still delivers every row with a wire view (`contextBreakdown`, `turnOutline`, and so on); narrowing that is out of scope. + +### Worst case, walked through + +1. The list serves a wrong record; the sidebar shows a wrong title, held in a cached row. +2. The session is opened; for the instant before the first-page baseline arrives the wrong value is still shown. Every pre-population has this window. +3. The first-page baseline `seed`s: every cached row is discarded unconditionally, then the block is written. Nothing of the wrong value survives, whatever its seq. +4. A later list refresh writes cached values that hit sequenced rows and are ignored; the wrong value does not come back. + +## Alternatives considered + +**Write the cut back into the physical header line.** Header-only reads would obtain the cut directly and the read-only face would keep its identity. The cost is another Session format generation right after V4 landed, and reversing #3346's decision that the exact cut does not pose as body-free metadata. Rejected: the header is not changed for this. + +**An index of each session's cut maintained by persistence or session-query.** A new durable index with its own consistency maintenance, serving one display read. Rejected. + +**Restore a bounded body probe.** The `probeSmallCold` idea #3400 removed, or a client-side asynchronous `refreshProjections` for visible seeded sessions. It breaks the list's zero-I/O principle, and the historical 1KB threshold shows it never covered an ordinary fork. Rejected. + +**Only the `asOfSeq: -1` sentinel, without store tiers.** One server-side change makes hints always lose under the seq rule. It rests on a convention: when a hint's seq equals or exceeds the baseline cut (crash-repair truncation), `apply` keeps the old row and the wrong value survives until the next frame. The user requires connected data to replace hints unconditionally, so the rule belongs in the store rather than in a seq convention. The sentinel stays as the read-only face's honest declaration; the replacement guarantee rests on the row kind. + +**Remove the cut from the cache identity entirely.** The fold face needs it: `restore` continues applying from the cached row's state, and `schedule`, `subagentCatalog`, `permissions.seeded`, and owned/inherited classification encode the cut; an error would be written back and persisted. Rejected. + +**Naming the row kinds `hint` / `authoritative`.** Those words speak of trust, while the rule depends on seq comparability. Renamed `cached` / `sequenced` so the names state the property the rule uses. + +## Consequences + +Bought: + +- After a restart, forked sessions immediately show their title, `sessionListMetadata` (blank, lastPromptAt), and every other cached wire value in the sidebar, ordered by the last prompt time. +- `@` completion shows and searches forks by title. +- Connected data replaces list hints unconditionally, independent of seq ordering. +- The two levels of the cache identity have names: the lifecycle identity answers "is this the same log", the fold identity answers "may this continue a fold". + +Paid: + +- `cachedSnapshot` and `cachedPredecessorTitle` change signature; three callers change with them. +- A hand-crafted record with the same four fields and a different cut is displayed in the list until the session is opened. +- Keys the baseline omits clear together with their hints: when a Host does not mount `schedule`, the schedule mark the list hinted disappears after the session opens. Under "connected data is the truth" this is the correct behavior. +- Old records still miss for seeded sessions until an open rewrites them. + +## Testing + +- `session-projection-cache/tests/cache.spec.ts`: a seeded cold header obtains every version-matching row through `cachedSnapshot(header)` with `asOfSeq: -1`; an unseeded header is refused for the same id's seeded record; `coldSnapshot` continues from the row when the cut matches, refolds the whole log when it differs, and throws for an unseeded call with a nonzero cut; `cachedPredecessorTitle(header)` serves only `title` from a seeded record of an older `formatVersion`; rows with differing watermarks form one block that claims no watermark. +- `session-projection-cache/tests/fixtures.spec.ts`: archived v3 to v6 records still expose only the predecessor title; lineage-less archives still miss for seeded callers. +- `api/session-controller/tests/session-cold.host.spec.ts`: a seeded cold summary carries `title` and `sessionListMetadata`, `updatedAt` takes `lastPromptAt`, the cache is queried, and the body is not read. +- `api/session-controller/tests/projection-store.client.spec.ts`: `applyCached` fills empty keys only and never displaces a sequenced row; every sequenced write (including a frame at cursor `-1` and a baseline at a lower cut) replaces cached rows; a baseline discards all cached rows before clearing omitted keys; face subscribers are notified on cached fills and their discard. Manager path: a list block claiming any watermark is replaced by a control baseline at a lower cut, and a later list refresh cannot bring it back. +- `api/session-controller/tests/manager.client.spec.ts`: an `api-session/added` block is written as cached and replaced by a control baseline at the same cursor; a list block does not displace an existing sequenced title. +- `context/session-reference/tests/session-reference.spec.ts`: a seeded cold session is labeled and searchable by its cached title, a session without a cache record is still labeled by id, and neither reads a log. +- `subagent/subagent/tests/list-children.spec.ts`: unchanged; seeded children still go through body observation. diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md new file mode 100644 index 0000000000..f81ccfae28 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md @@ -0,0 +1,161 @@ +# Agent Note: Projection cache 只读面按 lifecycle 身份匹配,客户端 store 区分 cached 与 sequenced 行 + +Status: implemented + +[English](2026-09-19-projection-cache-listing-identity-and-cached-rows.md) | 中文 + +## Problem + +Host 进程重启后,所有 fork 出来的会话(`SessionHeader.isSeeded === true`)在侧边栏列表里没有 title,`@` 引用补全只显示会话 id,列表排序退化到创建时间。打开一次之后恢复。2026-09-19 的一台开发机上,241 条 projcache 记录里有 44 条 seeded,44 条的 `title` 行全部合法,列表一次都没读到。 + +这不是缓存损坏,也不是版本失配。projcache 记录的 domain version 是 7,`identity.formatVersion` 是 4,两者分别是缓存自身的磁盘格式代际和 fold 所依据的 Session 日志格式代际,都是当前值。问题在读取路径。 + +### 机制 + +缓存记录绑定一份 lifecycle identity:`formatVersion + createdAt + cwd + isSeeded + inheritedEventCount`,`identityMatches` 做全等匹配。其中 `inheritedEventCount`(fork 继承的事件前缀长度,下称 cut)从 [#3346](https://github.com/deepseek-harness/deepseek-harness/pull/3346) 起不再出现在逻辑 header 里:header 只保留 `isSeeded` 这一位,精确 cut 跟随正文。Session 格式 v2 起(#3398),物理 header 行也不再存 `seedLength`,reader 从正文里 `session/end-seed {inherited: true}` 标记的 seq 推出 cut。 + +于是 header-only 的读取拿不到 cut:JSONL 后端 `fromHeaderLine` 对 header-only 读取硬编码 `inheritedEventCount: 0`,`SessionPersistenceSnapshot` 只有 header、revision 和可选的 eventCount。三个只读 header 的缓存消费者都因此加了同一个守卫: + +| 消费者 | 守卫 | 兜底 | 后果 | +|---|---|---|---| +| `packages/api/session-controller/src/list.ts` `projectionsFor` | `header.isSeeded ? undefined : cachedSnapshot(header, 0) ?? cachedPredecessorTitle(header, 0)` | 无 | 无 title,无 `sessionListMetadata`,blank 判定退到 `false`,排序退到 `createdAt` | +| `packages/context/session-reference/src/index.ts` `projectedLabels` | 同 | 无 | `@` 补全按 id 显示,搜不到 title | +| `packages/subagent/subagent/src/list-children.ts` `resolveColdIdentity` | 同 | `observeSession` 读正文 | 结果正确,每个 seeded 子代一次正文读 | + +守卫存在时(#3346,2026-09-01),`list.ts` 还有 `probeSmallCold`:缓存 miss 且日志文件不超过 `DEFAULT_COLD_BLANK_PROBE_MAX_BYTES = 1024` 字节时读正文补全。它的目的是识别 blank 会话,只覆盖不到 1KB 的日志,对正常 fork 从未生效。#3400(2026-09-03)删掉它,列表回到纯元数据加缓存。#4320(2026-09-19)把 fork 变成一等功能(`packages/core/session/src/fork.ts`,任意 seq fork),每个 fork 都是 `isSeeded: true` 加精确 cut,seeded 会话数量从个位数变成几十条,重启后全部冷,问题集中显形。 + +### 缓存的两种用途与校验位置 + +`SessionProjectionCache` 的读写面和调用方: + +| 面 | 对记录做什么 | 写回 | 调用方 | +|---|---|---|---| +| `write(session)` | 三个强制点加节流写 checkpoint | 有 | 缓存内部监听 | +| `hydratePrepared(session, events)` | 把 `rows` 当 fold 起点,从 `row.seq + 1` 继续 apply,结果进 live cell | 后续 checkpoint 写回 | `session-query/src/observation.ts` | +| `coldSnapshot(meta, cut, events)` | fold 起点加回写 | 有 | 无生产调用方 | +| `cachedSnapshot(meta, cut, keys?)` | `viewCheckpoint`:每行过 `ver` 和 `stateSchema`,`view` 后返回 | 无 | `list.ts`、`session-reference`、`list-children` | +| `cachedPredecessorTitle(meta, cut)` | 同上,只看 `title`,允许更旧的 `formatVersion` | 无 | `list.ts` | + +身份校验全部在缓存内部(`recordFor` → `identityMatches`;`viewCheckpoint` 逐行校验 `ver` 与 schema)。`list.ts` 自己不校验,只是给不出 cut 时不调。 + +spec.ts 与 README 描述身份检查的目的时用的都是同一个动词:防止 "seed state folded from an unrelated log"、"cannot seed the caller"。它防的是 fold 面。只读面从未做过 seed。 + +### 客户端 store 无法保证建连数据覆盖提示 + +客户端每个会话只有一个 `ProjectionValueStore`(`manager.projectionStores`),列表下发的 block、打开会话的 history 首页基线、control 基线、推送 frame、rename 结果全部写进同一个对象,`useProjection` 读的也是它。所有写入者平等,只有一条 higher-seq-wins 规则:`apply` 在 `seq <= row.seq` 时丢弃新值,`seed` 清理没带的键时只清 `row.seq <= cut` 的行。一个 seq 相等或偏高的列表提示会在会话打开后原样留在格子里。列表提示的 seq 来自磁盘记录,crash-repair 截断日志后它可以数字上高于建连 cursor,而那正是缓存错、建连对的情形。对提示做 seq 比较是用错了工具。 + +## Decision + +### 缓存分成两个读面,cut 只在 fold 面比对 + +| 面 | 身份 | 谁能提供 | 方法 | +|---|---|---|---| +| 只读面 | lifecycle 身份:`formatVersion + createdAt + cwd + isSeeded`,全部来自 header | 任何 header-only 调用方 | `cachedSnapshot(header, keys?)`、`cachedPredecessorTitle(header)` | +| fold 面 | lifecycle 身份加 `inheritedEventCount` | 握有 Session 或正文的调用方 | `recordFor` 所服务的 `hydratePrepared`、`write`、`coldSnapshot` | + +只读面的两个方法不再接受 cut 参数。`inheritedEventCount` 继续写入记录,fold 面继续全等比对它;"不同 fork cut 的记录不能互相当种子"这条原始设计预期不变。 + +只读面的输出定性为 cached:返回的 block `asOfSeq` 恒为 `-1`,沿用 `cachedPredecessorTitle` 已有的哨兵。header 既作证不了 cut,也作证不了记录 seq 与当前日志的可比性,这一面就不声明 seq。缓存自己在 `viewRecord` 里写过这条原则:under-claiming 在 higher-seq-wins 下是安全的,over-claiming 会让陈旧值压过推送。 + +### 只读面为什么可以不比 cut + +- 在同一个 `formatVersion` 下,一条日志的 cut 由 `(id, createdAt, cwd, isSeeded)` 唯一决定:fork 创建时写死,只有改变事件基数的格式迁移能改它,而那种迁移必然改 `formatVersion`。cut 是 lifecycle 的派生事实,不是独立坐标。 +- 只读面今天实际发生的是:unseeded 传常量 0(构造上恒真),seeded 直接不调。cut 在只读面上从未和任何真实事实比过。拿掉它,拒绝集合一个都不变:另一个 lifecycle 的记录(四字段任一不同)照样被拒;unseeded 结果相同;seeded 从不可寻址变成可寻址。 +- 只读面没有 seed、没有写回,输出是存储记录的纯函数,cut 不参与计算,也不流向任何地方。 +- 唯一多出来的暴露面:一份四字段全同、只有 cut 不同的记录。系统自身产生不出它,只有手工复制会话目录再改文件才行。就算出现,后果是列表显示它的值直到会话被打开,仍然不进任何 fold。 + +### 消费者 + +| 位置 | 改法 | +|---|---| +| `list.ts` `projectionsFor` | 删 `isSeeded` 分支和 `SessionLogOffset(0)`,冷会话统一 `cachedSnapshot(header) ?? cachedPredecessorTitle(header)` | +| `session-reference` `projectedLabels` | 同一症状,同一改法 | +| `list-children.ts` `resolveColdIdentity` | 只跟随签名,`!header.isSeeded` 守卫和正文兜底原样保留;它需要 cut 做 inherited/owned 分类,属于 fold 语义 | + +### 客户端 store 区分 cached 与 sequenced 行 + +`ProjectionValueStore` 的行分两类,按"这个值有没有本连接可比的 seq"命名: + +| 行 | 含义 | 携带 | +|---|---|---| +| `cached` | 从持久化 checkpoint 只读看出来的值,没有 Session 参与,seq 与本连接不可比 | 只有 `value` | +| `sequenced` | 本连接内由 Host 对该 Session 算出的值,seq 在同一空间可比 | `value` 加 `seq` | + +规则: + +| 写入 | 遇到 `cached` 行 | 遇到 `sequenced` 行 | +|---|---|---| +| `applyCached(values)` | 覆盖 | 忽略 | +| `seed(baseline)` | 整表丢弃 `cached` 行,再按 block 写入;block 没带的键按 `seq <= cut` 清理 | higher-seq-wins | +| `apply(key, value, seq)` | 覆盖 | higher-seq-wins | + +seq 比较只在同一条 Host 连接内发生:`handleConnected` 先整表 `clear()`,再由列表重新写 cached、打开会话重新 seed。从 cached 到 sequenced 是无条件替换,不看 seq。 + +写入口归类: + +| 入口 | 行类型 | +|---|---| +| `session.list` 响应里每条摘要的 `projections` block(`manager.refreshList`) | cached | +| `api-session/added` 摘要的 `projections` block(`manager.handleSessionAdded`) | cached | +| history 首页 `projections`(`session.ts` 的 `projections.seed`) | sequenced | +| control 基线,仅活会话(`manager.replaceControlBaseline`) | sequenced | +| `refreshProjections` 的 `session.projections` 结果(正文观察) | sequenced | +| 推送 frame(`manager` 处理 `projection` frame) | sequenced | +| rename 成功后的 `title`(`session.ts`) | sequenced | + +`seed` 与 `apply` 签名不变。服务端线上的 `asOfSeq` 字段保留,客户端对 cached 写入不读它。 + +### 不动的部分 + +- Session 格式、物理 header 行、`fromHeaderLine`、persistence、`SessionPersistenceSnapshot`。 +- hydration 与 checkpoint 写路径,`recordFor` 的五字段全等。 +- `coldSnapshot` 保留,不因没有生产调用方而删除。 +- 老记录(domain v4/v5,缺 `isSeeded` 与 `inheritedEventCount`)对 seeded 会话继续 miss,等会话打开后被 v7 记录改写。 +- 列表下发全部带 wire 视图的行(`contextBreakdown`、`turnOutline` 等)这一点不在本次范围。 + +### 最坏情形推演 + +1. 列表用了一份错误记录,侧边栏显示错 title,格子里是 cached 行。 +2. 点进会话,首页基线到达前一瞬仍是错值。这是任何预填充都有的窗口。 +3. 首页基线 `seed`:所有 cached 行先被无条件丢弃,再按 block 写入。错值零残留,与 seq 大小无关。 +4. 之后列表刷新,cached 写入遇到 sequenced 行直接忽略,错值不会被刷回来。 + +## Alternatives considered + +**把 cut 写回物理 header 行。** header-only 读取能直接拿到 cut,只读面无需改身份。代价是 Session 格式再升一版,V4 刚落地;并且要推翻 #3346"精确 cut 不伪装成 body-free metadata"的决定。否决:不为此改 header。 + +**由 persistence 或 session-query 维护每个会话 cut 的索引。** 新增一套 durable 索引及其一致性维护,只为服务一个展示读取。否决。 + +**恢复有界正文探测。** #3400 删掉的 `probeSmallCold` 思路,或由客户端对可见 seeded 会话异步 `refreshProjections`。违背列表零 I/O 原则,且历史阈值 1KB 说明它从未覆盖过正常 fork。否决。 + +**只用 `asOfSeq: -1` 哨兵,不给 store 分层。** 服务端一处改动即可让提示在 seq 规则下永远落败。但它靠约定成立:一旦提示 seq 与基线 cut 相等或偏高(crash-repair 截断),`apply` 保留旧行,错值存活到下一帧。用户要求建连数据无条件覆盖提示,规则要写进 store 而不是靠 seq 约定模拟。哨兵保留为只读面输出的诚实声明,覆盖保证由行类型承担。 + +**把 cut 从缓存身份里彻底删掉。** fold 面需要它:`restore` 从缓存行状态继续 apply,`schedule`、`subagentCatalog`、`permissions.seeded` 与 owned/inherited 归属都编码了 cut,错误会被写回并持久化。否决。 + +**行类型命名 `hint` / `authoritative`。** 说的是可信度,而规则依据的是 seq 可比性。改为 `cached` / `sequenced`,名字直接说明规则用到的性质。 + +## Consequences + +买到的: + +- 重启后 fork 会话在侧边栏立即有 title、`sessionListMetadata`(blank、lastPromptAt)和其余带 wire 的缓存值,排序按最后一次提问时间。 +- `@` 补全对 fork 按 title 显示和搜索。 +- 建连后的数据无条件替换列表提示,不再依赖 seq 大小。 +- 缓存身份的两级含义有了名字:lifecycle 身份回答"是不是同一份日志",fold 身份回答"能不能当续算起点"。 + +付出的: + +- `cachedSnapshot` 与 `cachedPredecessorTitle` 签名变化,三个调用方同步修改。 +- 手工构造的同四字段、不同 cut 的记录会在列表上显示到会话被打开为止。 +- 基线没带的键连提示一起清掉:某个 Host 未挂载 `schedule` 时,打开会话后列表提示过的 schedule 标记消失。按"建连数据是真值"这是正确行为。 +- 老记录对 seeded 会话仍然 miss,直到打开重写。 + +## Testing + +- `session-projection-cache/tests/cache.spec.ts`:seeded 冷 header 通过 `cachedSnapshot(header)` 取到全部版本匹配的行,`asOfSeq` 为 `-1`;unseeded header 对同一 id 的 seeded 记录被拒;`coldSnapshot` 对 cut 一致的记录从行续算、对 cut 不一致的记录整段重新 fold,对 unseeded 且 cut 非 0 的调用抛错;`cachedPredecessorTitle(header)` 对 seeded 的更旧 `formatVersion` 记录只给 `title`;不同 watermark 的多行合成一个不声明 watermark 的 block。 +- `session-projection-cache/tests/fixtures.spec.ts`:归档的 v3 到 v6 记录继续只透出 predecessor title;无 lineage 字段的归档对 seeded 调用方继续 miss。 +- `api/session-controller/tests/session-cold.host.spec.ts`:seeded 冷会话摘要携带 `title` 与 `sessionListMetadata`,`updatedAt` 取 `lastPromptAt`,缓存确实被查询,正文没有被读。 +- `api/session-controller/tests/projection-store.client.spec.ts`:`applyCached` 只填空位、不覆盖 sequenced 行;任何 sequenced 写入(包括 cursor `-1` 的 frame 和 cut 更低的基线)替换 cached 行;基线先丢弃全部 cached 行再清理没带的键;面订阅在 cached 填充与丢弃时都收到通知。manager 路径:列表 block 声明的 watermark 再高,也被 cut 更低的 control 基线替换,之后的列表刷新拿不回来。 +- `api/session-controller/tests/manager.client.spec.ts`:`api-session/added` 的 block 写为 cached,同 cursor 的 control 基线替换它;列表 block 不覆盖已有的 sequenced title。 +- `context/session-reference/tests/session-reference.spec.ts`:seeded 冷会话按缓存 title 标注并可按 title 搜到,没有缓存记录的会话仍按 id 标注,两者都不读日志。 +- `subagent/subagent/tests/list-children.spec.ts`:不变,seeded 子代仍走正文观察。 From 1b51a1ad2da163c5ab92b7ec18a1b758de033787 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 01:04:50 +0800 Subject: [PATCH 06/24] fix(session): label list projection blocks with their sequence space SessionProjectionHints gains a required `kind`: `sequenced` when the Host's live registry computed the block for an attached Session, `cached` when a header-only listing viewed it from the persisted projection cache. `asOfSeq` stays the producer's own watermark in that space, so the cache read faces report the lowest served row seq again instead of the -1 sentinel. The two fields are independent: `kind` names the sequence space, `asOfSeq` the position in it. --- docs/event-producer-consumer.i18n.yaml | 4 +- docs/event-producer-consumer.md | 10 ++--- docs/event-producer-consumer.zh.md | 10 ++--- docs/persistence-catalog.i18n.yaml | 4 +- docs/persistence-catalog.md | 6 +-- docs/persistence-catalog.zh.md | 6 +-- docs/persistence-schema.json | 6 +-- docs/subsystems/session-projection.i18n.yaml | 4 +- docs/subsystems/session-projection.md | 18 ++++----- docs/subsystems/session-projection.zh.md | 18 ++++----- packages/api/session-controller/src/list.ts | 40 ++++++++++++------- packages/api/session-controller/src/types.ts | 18 ++++++++- .../tests/session-cold.host.spec.ts | 9 +++-- .../tests/session-projections.host.spec.ts | 1 + .../extensions/tool-cordis/src/api-catalog.ts | 8 ++-- .../session-projection-cache/README.i18n.yaml | 4 +- .../session-projection-cache/README.md | 2 +- .../session-projection-cache/README.zh.md | 2 +- .../session-projection-cache/src/index.ts | 35 +++++++++------- .../tests/cache.spec.ts | 22 +++++----- .../tests/fixtures.spec.ts | 6 +-- 21 files changed, 134 insertions(+), 99 deletions(-) diff --git a/docs/event-producer-consumer.i18n.yaml b/docs/event-producer-consumer.i18n.yaml index f3dd91b507..f4e736efa4 100644 --- a/docs/event-producer-consumer.i18n.yaml +++ b/docs/event-producer-consumer.i18n.yaml @@ -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/event-producer-consumer.md -event-producer-consumer.md: c26ca2d18995eb4e883815fd4f22ec4773d10728 -event-producer-consumer.zh.md: 588ec67cd55f40b5544b81603d23e65f3ebe1119 +event-producer-consumer.md: 0fa3e7ffaae73a714bcffc6b7f8cd69e24f5e0c4 +event-producer-consumer.zh.md: 9f14a99ad80959be9963821100a6228700eca2b8 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index c26ca2d189..0fa3e7ffaa 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -21,11 +21,11 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:580`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:586`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:593`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:614`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:594`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:621`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:85`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization) | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 588ec67cd5..9f14a99ad8 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -23,11 +23,11 @@ | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`agent`](../packages/core/agent), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`schedule`](../packages/schedule/schedule), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/hooks/hooks-claude-code), [`hooks-codex`](../packages/hooks/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:580`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:586`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:593`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:614`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:594`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:621`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:600`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:607`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:85`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization) | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index ae6c4b51eb..251a673f01 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -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/persistence-catalog.md -persistence-catalog.md: 43b4f86125847625026bd5619216ccdc7be926c1 -persistence-catalog.zh.md: c655d97086fa60630aa5dae1bf3f93be595f179b +persistence-catalog.md: 4e62b69e07daf5809d6070bcc182b71305e70151 +persistence-catalog.zh.md: c001f06e98ac3b7e331044510639b73ec640eb85 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 43b4f86125..4e62b69e07 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -4066,7 +4066,7 @@ Sources: [`packages/llm/llm/src/message.ts:24`](../packages/llm/llm/src/message. SHA-256: `f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b` -Sources: [`packages/api/session-controller/src/types.ts:86`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:100`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5304,7 +5304,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:380`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:20`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:32`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:8`](../packages/experimental/agent-team/src/types.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:10`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/webhook/webhook/src/brand.ts:12`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:6`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:9`](../packages/webhook/webhook/src/brand.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:20`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:32`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:8`](../packages/experimental/agent-team/src/types.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:10`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/webhook/webhook/src/brand.ts:12`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:6`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:9`](../packages/webhook/webhook/src/brand.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7195,7 +7195,7 @@ Sources: [`packages/core/tools/src/index.ts:34`](../packages/core/tools/src/inde SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7` -Sources: [`packages/api/session-controller/src/types.ts:385`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:399`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index c655d97086..c001f06e98 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -4068,7 +4068,7 @@ SHA-256: `719c51f67074f97034a6c94297fe1f4b5d3c8d392c57586dab732aa5398c7a91` SHA-256: `f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b` -来源:[`packages/api/session-controller/src/types.ts:86`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:100`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5306,7 +5306,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:380`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:20`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:32`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:8`](../packages/experimental/agent-team/src/types.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:10`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/webhook/webhook/src/brand.ts:12`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:6`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:9`](../packages/webhook/webhook/src/brand.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:394`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:20`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:32`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:8`](../packages/experimental/agent-team/src/types.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:10`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/webhook/webhook/src/brand.ts:12`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:6`](../packages/webhook/webhook/src/brand.ts) · [`packages/webhook/webhook/src/brand.ts:9`](../packages/webhook/webhook/src/brand.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -7197,7 +7197,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7` -来源:[`packages/api/session-controller/src/types.ts:385`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:399`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 428d512264..db1c54ff38 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -44144,7 +44144,7 @@ "packages/workflow/workflow/src/types.ts#WorkflowRunId" ], "sources": [ - "packages/api/session-controller/src/types.ts:380", + "packages/api/session-controller/src/types.ts:394", "packages/attachment/attachment/src/brand.ts:6", "packages/compaction/compaction/src/brand.ts:4", "packages/core/session/src/types.ts:20", @@ -57727,7 +57727,7 @@ }, "names": [], "sources": [ - "packages/api/session-controller/src/types.ts:385" + "packages/api/session-controller/src/types.ts:399" ] }, { @@ -86253,7 +86253,7 @@ "packages/api/session-controller/src/types.ts#ModelSelection" ], "sources": [ - "packages/api/session-controller/src/types.ts:86" + "packages/api/session-controller/src/types.ts:100" ] }, { diff --git a/docs/subsystems/session-projection.i18n.yaml b/docs/subsystems/session-projection.i18n.yaml index b0c4faff71..cc738c4fcb 100644 --- a/docs/subsystems/session-projection.i18n.yaml +++ b/docs/subsystems/session-projection.i18n.yaml @@ -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: b46d8df330de3586691ac7e708e0b5de6c76b33f -session-projection.zh.md: 62fa2ff74ab627cc2a83f76cf4066a3ffc3020f0 +session-projection.md: 8580b94c4d7dd36f942ff10d77e13d2dc70b7e8b +session-projection.zh.md: b98d348a36c51aab973bc3397ddbf744860245a4 diff --git a/docs/subsystems/session-projection.md b/docs/subsystems/session-projection.md index b46d8df330..8580b94c4d 100644 --- a/docs/subsystems/session-projection.md +++ b/docs/subsystems/session-projection.md @@ -129,14 +129,14 @@ The persisted projection cache service. Opens the `session_projcache` domain at * generation the cut is fixed at fork time, so it distinguishes no * lifecycle the other fields do not, and a viewed value never seeds a fold. * The view is as stale as the last durable checkpoint but never wrong and - * never from an unrelated log. It is served as a cached block - * (`asOfSeq: -1`): the header cannot vouch that the stored row sequence is - * comparable with the caller's log, so the block claims no watermark and - * any sequenced value (a history baseline, a control baseline, a frame) - * supersedes it once the session is opened. + * never from an unrelated log. Its `asOfSeq` is the lowest watermark among + * the served rows: the stored record's own position, which the header + * cannot relate to the log the caller later opens. The Session list + * therefore labels the block as cached, and the client lets every value the + * connected Session produces supersede it whatever this number says. * @param meta - the listed session's header (identity witness; no log read). * @param keys - optional projection keys required by the caller's audience. - * @returns the cached block, or `undefined` when no usable row exists for + * @returns the viewed block, or `undefined` when no usable row exists for * this lifecycle at the current Session format. */ cachedSnapshot( meta: SessionHeader, keys?: readonly Extract[], ): ProjectionSnapshot | undefined @@ -152,9 +152,9 @@ cachedSnapshot( meta: SessionHeader, keys?: readonly Extract[], ): ProjectionSnapshot | undefined @@ -152,9 +152,9 @@ cachedSnapshot( meta: SessionHeader, keys?: readonly Extract 0 - ? { - asOfSeq: block.asOfSeq, - // Listing hints contain every currently cached wire value but remain - // partial: missing cells and cache rows are never materialized here. - values: block.values as SessionProjectionValues, - } - : undefined + return hintsOf('cached', cache?.cachedSnapshot(header) ?? cache?.cachedPredecessorTitle(header)) } catch (error) { this.ctx.logger.warn( `api-session.list: projection column for "${header.id}" failed; serving the row without it: ${String(error)}`, @@ -294,6 +290,22 @@ export class ApiSessionList { } } +/** + * Wrap one projection block as Session-list hints of the named sequence space. + * @param kind - which sequence space the block's watermark belongs to. + * @param block - the block, or `undefined` when no source served one. + * @returns the hints, or `undefined` when the block is absent or carries no value. + */ +function hintsOf( + kind: SessionProjectionHints['kind'], + block: ProjectionSnapshot | undefined, +): SessionProjectionHints | undefined { + if (block === undefined || Object.keys(block.values).length === 0) return undefined + // Listing hints contain every wire value the source currently holds but + // remain partial: missing cells and cache rows are never materialized here. + return { kind, asOfSeq: block.asOfSeq, values: block.values as SessionProjectionValues } +} + function normalizeSearchQuery(query: string): string { const normalized = query.trim() if (normalized.length === 0) { diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index a925e9da83..37294a6dbb 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -49,10 +49,24 @@ export interface SessionListMetadata { readonly lastPromptAt: number | null } -/** Every available cached wire value used as partial, possibly stale Session-list hints. */ +/** + * Every available wire value a Session-list row carries as partial, possibly + * stale hints. `kind` and `asOfSeq` are independent facts: `kind` says which + * sequence space `asOfSeq` belongs to, and therefore how a client may merge + * the block; `asOfSeq` is the producer's watermark in that space. + */ export interface SessionProjectionHints { + /** + * `sequenced`: the Host's live registry produced the block for an attached + * Session, so `asOfSeq` is comparable with baselines and frames of the same + * connection. `cached`: a header-only listing viewed the block from the + * persisted projection cache, so `asOfSeq` is the stored record's own + * watermark and must not be compared with the connected Session's values. + */ + readonly kind: 'cached' | 'sequenced' + /** Watermark of the block in the sequence space named by `kind`. */ readonly asOfSeq: number - /** Provider-validated values present in the cache; omitted keys remain unknown. */ + /** Provider-validated values present in the block; omitted keys remain unknown. */ readonly values: SessionProjectionValues } diff --git a/packages/api/session-controller/tests/session-cold.host.spec.ts b/packages/api/session-controller/tests/session-cold.host.spec.ts index 00988a62fd..c715bbf9ab 100644 --- a/packages/api/session-controller/tests/session-cold.host.spec.ts +++ b/packages/api/session-controller/tests/session-cold.host.spec.ts @@ -97,7 +97,7 @@ describe('sessions.list cold merge', () => { ctx.provide('sessionProjectionCache', { cachedSnapshot: () => undefined, cachedPredecessorTitle: (meta: SessionHeader) => meta.id === sid('legacy-title') - ? { asOfSeq: -1, values: { title: 'Cached predecessor title' } } + ? { asOfSeq: 2, values: { title: 'Cached predecessor title' } } : undefined, } as never) const remote = createSessionTestRemote(ctx, { @@ -119,7 +119,7 @@ describe('sessions.list cold merge', () => { sessionId: sid('legacy-title'), blank: false, updatedAt: 100, - projections: { asOfSeq: -1, values: { title: 'Cached predecessor title' } }, + projections: { kind: 'cached', asOfSeq: 2, values: { title: 'Cached predecessor title' } }, }), ]) expect(stat).not.toHaveBeenCalled() @@ -154,7 +154,7 @@ describe('sessions.list cold merge', () => { } if (meta.id === sid('seeded-cold')) { return { - asOfSeq: -1, + asOfSeq: 5, values: { title: 'Forked title', sessionListMetadata: { blank: false, lastPromptAt: 1200 } }, } } @@ -184,7 +184,8 @@ describe('sessions.list cold merge', () => { blank: false, updatedAt: 1200, projections: { - asOfSeq: -1, + kind: 'cached', + asOfSeq: 5, values: { title: 'Forked title', sessionListMetadata: { blank: false, lastPromptAt: 1200 } }, }, }) diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index 3339a97d14..cc7b1e66b3 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -559,6 +559,7 @@ describe('session.list projections column', () => { const row = response.value.items.find(item => item.sessionId === coldId) expect(row?.running).toBe(false) expect(row?.projections).toEqual({ + kind: 'cached', asOfSeq: 7, values: { 'test/last-user': { text: 'cached' }, diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 8256b0514d..eed58061e6 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1879,15 +1879,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'cachedSnapshot( meta: SessionHeader, keys?: readonly Extract[], ): ProjectionSnapshot | undefined', - description: 'The zero-I/O listing read: whole values viewed straight from the stored rows (version-matching keys only) of the record bound to the caller\'s lifecycle. The header is the only identity witness a listing holds, so this face matches the lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`) and not the inherited cut: within one format generation the cut is fixed at fork time, so it distinguishes no lifecycle the other fields do not, and a viewed value never seeds a fold. The view is as stale as the last durable checkpoint but never wrong and never from an unrelated log. It is served as a cached block (`asOfSeq: -1`): the header cannot vouch that the stored row sequence is comparable with the caller\'s log, so the block claims no watermark and any sequenced value (a history baseline, a control baseline, a frame) supersedes it once the session is opened.', + description: 'The zero-I/O listing read: whole values viewed straight from the stored rows (version-matching keys only) of the record bound to the caller\'s lifecycle. The header is the only identity witness a listing holds, so this face matches the lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`) and not the inherited cut: within one format generation the cut is fixed at fork time, so it distinguishes no lifecycle the other fields do not, and a viewed value never seeds a fold. The view is as stale as the last durable checkpoint but never wrong and never from an unrelated log. Its `asOfSeq` is the lowest watermark among the served rows: the stored record\'s own position, which the header cannot relate to the log the caller later opens. The Session list therefore labels the block as cached, and the client lets every value the connected Session produces supersede it whatever this number says.', parameters: [{ name: 'meta', description: 'the listed session\'s header (identity witness; no log read).' }, { name: 'keys', description: 'optional projection keys required by the caller\'s audience.' }], - returns: 'the cached block, or `undefined` when no usable row exists for this lifecycle at the current Session format.', + returns: 'the viewed block, or `undefined` when no usable row exists for this lifecycle at the current Session format.', }, { signature: 'cachedPredecessorTitle(meta: SessionHeader): ProjectionSnapshot | undefined', description: 'Read only a predecessor checkpoint\'s title as a zero-I/O listing hint.\n\nThe authoritative Session header supplies the lifecycle identity. A cache checkpoint can lag that log but cannot lead it because writes flush the log first, so a matching predecessor title is a genuine (possibly stale) fact from this Session. The registry still requires the current title projection\'s row version and schema. No other predecessor projection is exposed: format normalization can change their current meaning, and the cachedSnapshot / hydration paths continue to reject them.', parameters: [{ name: 'meta', description: 'authoritative listed Session header.' }], - returns: 'a title-only cached block (`asOfSeq: -1`), or `undefined` when the record is current, newer, unrelated, missing, or incompatible with the title unit.', + returns: 'a title-only block at the stored title row\'s watermark, or `undefined` when the record is current, newer, unrelated, missing, or incompatible with the title unit.', }, { signature: 'hydratePrepared( session: Session, events: readonly SessionEvent[], ): ProjectionSnapshot', @@ -6025,7 +6025,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionProjectionHints', - declaration: 'export interface SessionProjectionHints {\n readonly asOfSeq: number;\n readonly values: SessionProjectionValues;\n}', + declaration: 'export interface SessionProjectionHints {\n readonly kind: \'cached\' | \'sequenced\';\n readonly asOfSeq: number;\n readonly values: SessionProjectionValues;\n}', }, { name: 'SessionProjectionMap', diff --git a/packages/session/session-projection-cache/README.i18n.yaml b/packages/session/session-projection-cache/README.i18n.yaml index c921081f57..e935b623ce 100644 --- a/packages/session/session-projection-cache/README.i18n.yaml +++ b/packages/session/session-projection-cache/README.i18n.yaml @@ -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/session/session-projection-cache/README.md -README.md: af319d2606ca7faa7ba88a1da224b703a4a36943 -README.zh.md: 29568b481e61fc359b1f1e970f14d827e8facb50 +README.md: 0ba9c5a47fbf2006be1593cb1805adb5bf9fbc59 +README.zh.md: d697b0520c0edf89572e9994b62e987111481a77 diff --git a/packages/session/session-projection-cache/README.md b/packages/session/session-projection-cache/README.md index af319d2606..0ba9c5a47f 100644 --- a/packages/session/session-projection-cache/README.md +++ b/packages/session/session-projection-cache/README.md @@ -58,7 +58,7 @@ Three mandatory points always write: session creation persists the seed-derived ### Reading cached values -`cachedSnapshot(meta, keys?)` is the read-only face: it synchronously serves client values from the storage domain's in-memory tables with zero I/O. It accepts a record whose lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`) matches the header and serves its version- and schema-matching keys as a cached block `{ asOfSeq: -1, values }`. A header witnesses no inherited cut and cannot vouch that the stored row sequence is comparable with the log a consumer later opens, so the block claims no watermark and every value the connected Session later produces supersedes it. Within one format generation the cut is fixed at fork time and distinguishes no lifecycle the other fields do not, and a viewed value never seeds a fold, so seeded (forked) sessions are served exactly like unseeded ones. `cachedPredecessorTitle(meta)` is the narrower listing-only exception across a Session-format edge: a structurally admitted predecessor record whose lifecycle matches may expose only a current-version-compatible `title` row, because title text is invariant across the adjacent edges. All other predecessor rows remain unavailable. `coldSnapshot(meta, inheritedEventCount, events)` is a fold face: it accepts the exact cut with a complete ordered log, skips the checkpointed prefix while folding, and refreshes the record without reading persistence itself. +`cachedSnapshot(meta, keys?)` is the read-only face: it synchronously serves client values from the storage domain's in-memory tables with zero I/O. It accepts a record whose lifecycle identity (`formatVersion`, `createdAt`, `cwd`, `isSeeded`) matches the header and serves its version- and schema-matching keys as one block whose `asOfSeq` is the lowest watermark among the served rows. That watermark is the stored record's own: a header witnesses no inherited cut and cannot vouch that the row sequence is comparable with the log a consumer later opens, so the Session list labels the block `cached` and the client lets every value the connected Session later produces supersede it. Within one format generation the cut is fixed at fork time and distinguishes no lifecycle the other fields do not, and a viewed value never seeds a fold, so seeded (forked) sessions are served exactly like unseeded ones. `cachedPredecessorTitle(meta)` is the narrower listing-only exception across a Session-format edge: a structurally admitted predecessor record whose lifecycle matches may expose only a current-version-compatible `title` row, because title text is invariant across the adjacent edges. All other predecessor rows remain unavailable. `coldSnapshot(meta, inheritedEventCount, events)` is a fold face: it accepts the exact cut with a complete ordered log, skips the checkpointed prefix while folding, and refreshes the record without reading persistence itself. ### What the cache guarantees diff --git a/packages/session/session-projection-cache/README.zh.md b/packages/session/session-projection-cache/README.zh.md index 29568b481e..d697b0520c 100644 --- a/packages/session/session-projection-cache/README.zh.md +++ b/packages/session/session-projection-cache/README.zh.md @@ -58,7 +58,7 @@ kind: "package-reference" ### 读取缓存值 -`cachedSnapshot(meta, keys?)` 是只读面:以零 I/O 从存储域的内存表同步提供客户端值。它接受生命周期身份(`formatVersion`、`createdAt`、`cwd`、`isSeeded`)与 header 匹配的记录,把其中版本和 schema 均匹配的 key 作为 cached block `{ asOfSeq: -1, values }` 提供。header 作证不了 inherited cut,也作证不了存储行的序号与消费者稍后打开的日志可比,因此该 block 不声明水位,建连后的 Session 产出的任何值都会覆盖它。在同一格式代内,cut 在 fork 时写死,不能区分其他字段区分不了的生命周期,而只读视图也从不播种 fold,所以 seeded(fork 出来的)会话与 unseeded 会话被同样地提供。`cachedPredecessorTitle(meta)` 是跨 Session 格式 edge 的更窄列表专用例外:生命周期匹配且已通过结构准入的 predecessor record 只能公开与当前版本兼容的 `title` row,因为 title 文本在相邻 edge 之间保持不变。其他 predecessor row 仍不可用。`coldSnapshot(meta, inheritedEventCount, events)` 是 fold 面:接受精确切点与完整有序日志,在折叠时跳过已检查点化的前缀,并在自身不读取持久化层的情况下刷新记录。 +`cachedSnapshot(meta, keys?)` 是只读面:以零 I/O 从存储域的内存表同步提供客户端值。它接受生命周期身份(`formatVersion`、`createdAt`、`cwd`、`isSeeded`)与 header 匹配的记录,把其中版本和 schema 均匹配的 key 作为一个 block 提供,其 `asOfSeq` 是所服务各行中最低的水位。这个水位是存储记录自己的:header 作证不了 inherited cut,也作证不了行序号与消费者稍后打开的日志可比,因此 Session list 把该 block 标为 `cached`,客户端让建连后的 Session 产出的任何值覆盖它。在同一格式代内,cut 在 fork 时写死,不能区分其他字段区分不了的生命周期,而只读视图也从不播种 fold,所以 seeded(fork 出来的)会话与 unseeded 会话被同样地提供。`cachedPredecessorTitle(meta)` 是跨 Session 格式 edge 的更窄列表专用例外:生命周期匹配且已通过结构准入的 predecessor record 只能公开与当前版本兼容的 `title` row,因为 title 文本在相邻 edge 之间保持不变。其他 predecessor row 仍不可用。`coldSnapshot(meta, inheritedEventCount, events)` 是 fold 面:接受精确切点与完整有序日志,在折叠时跳过已检查点化的前缀,并在自身不读取持久化层的情况下刷新记录。 ### 缓存保证什么 diff --git a/packages/session/session-projection-cache/src/index.ts b/packages/session/session-projection-cache/src/index.ts index 66effbbc49..34726fc3b8 100644 --- a/packages/session/session-projection-cache/src/index.ts +++ b/packages/session/session-projection-cache/src/index.ts @@ -148,14 +148,14 @@ export class SessionProjectionCache extends Service { * generation the cut is fixed at fork time, so it distinguishes no * lifecycle the other fields do not, and a viewed value never seeds a fold. * The view is as stale as the last durable checkpoint but never wrong and - * never from an unrelated log. It is served as a cached block - * (`asOfSeq: -1`): the header cannot vouch that the stored row sequence is - * comparable with the caller's log, so the block claims no watermark and - * any sequenced value (a history baseline, a control baseline, a frame) - * supersedes it once the session is opened. + * never from an unrelated log. Its `asOfSeq` is the lowest watermark among + * the served rows: the stored record's own position, which the header + * cannot relate to the log the caller later opens. The Session list + * therefore labels the block as cached, and the client lets every value the + * connected Session produces supersede it whatever this number says. * @param meta - the listed session's header (identity witness; no log read). * @param keys - optional projection keys required by the caller's audience. - * @returns the cached block, or `undefined` when no usable row exists for + * @returns the viewed block, or `undefined` when no usable row exists for * this lifecycle at the current Session format. */ cachedSnapshot( @@ -179,9 +179,9 @@ export class SessionProjectionCache extends Service { * exposed: format normalization can change their current meaning, and the * {@link cachedSnapshot} / hydration paths continue to reject them. * @param meta - authoritative listed Session header. - * @returns a title-only cached block (`asOfSeq: -1`), or `undefined` when - * the record is current, newer, unrelated, missing, or incompatible with - * the title unit. + * @returns a title-only block at the stored title row's watermark, or + * `undefined` when the record is current, newer, unrelated, missing, or + * incompatible with the title unit. */ cachedPredecessorTitle(meta: SessionHeader): ProjectionSnapshot | undefined { const expected = lifecycleIdentityOf(meta) @@ -191,18 +191,23 @@ export class SessionProjectionCache extends Service { } /** - * View selected wire rows as a cached block. The block claims no watermark: - * a listing cannot prove the stored row sequence is comparable with the - * log a consumer later opens, and under-claiming is safe where - * over-claiming would let a stale value outrank a sequenced one. + * View selected wire rows as one block bound to the lowest served + * watermark: the seq every served value has folded through at least. The + * number is the record's own; whether a consumer may compare it with a + * live Session's seqs is decided by the face that serves the block, not + * here. */ private viewRecord( record: CheckpointRecord, keys?: readonly Extract[], ): ProjectionSnapshot | undefined { const values = this.ctx.sessionProjections.viewCheckpoint(record.rows, keys) - if (Object.keys(values).length === 0) return undefined - return { asOfSeq: -1, values } + let asOfSeq: ProjectionSnapshot['asOfSeq'] | undefined + for (const [key, row] of Object.entries(record.rows)) { + if (!Object.hasOwn(values, key)) continue + if (asOfSeq === undefined || row.seq < asOfSeq) asOfSeq = row.seq + } + return asOfSeq === undefined ? undefined : { asOfSeq, values } } /** diff --git a/packages/session/session-projection-cache/tests/cache.spec.ts b/packages/session/session-projection-cache/tests/cache.spec.ts index e66f2c2e60..87860844ee 100644 --- a/packages/session/session-projection-cache/tests/cache.spec.ts +++ b/packages/session/session-projection-cache/tests/cache.spec.ts @@ -375,7 +375,7 @@ describe('SessionProjectionCache listing read', () => { )).toThrow('unseeded projection-cache identity inherited event count must be 0') }) - it('serves rows with differing watermarks as one cached block that claims no watermark', async () => { + it('serves rows with differing watermarks as one block at the lowest served watermark', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-projcache-')) roots.push(root) await seedRecord(root, 'watermark-lower', { @@ -389,9 +389,11 @@ describe('SessionProjectionCache listing read', () => { const { ctx, cache } = await harness({ root }) ctx.sessionProjections.register(secondaryMarksUnit) - for (const id of ['watermark-lower', 'watermark-higher']) { + // The block carries one watermark: the seq every served value has folded + // through at least, so the lower of the two rows names the block. + for (const [id, asOfSeq] of [['watermark-lower', 2], ['watermark-higher', 4]] as const) { expect(cache.cachedSnapshot(headerOf(SessionId(id)))).toEqual({ - asOfSeq: -1, + asOfSeq, values: { 'cache-test/marks': { marks: ['primary'] }, 'cache-test/secondary-marks': { marks: ['secondary'] }, @@ -425,7 +427,7 @@ describe('SessionProjectionCache listing read', () => { // The listing knows only the header: the record's lifecycle matches, so // its rows are viewed without any cut. expect(cache.cachedSnapshot(seededHeader)) - .toEqual({ asOfSeq: -1, values: { 'cache-test/marks': { marks: ['seed'] } } }) + .toEqual({ asOfSeq: 1, values: { 'cache-test/marks': { marks: ['seed'] } } }) // An unseeded header names another lifecycle even though the id matches. expect(cache.cachedSnapshot(headerOf(id))).toBeUndefined() // The fold face holds the exact cut: the matching cut seeds from the row, @@ -462,7 +464,7 @@ describe('SessionProjectionCache listing read', () => { // survives the format edge, for a seeded lifecycle as for an unseeded one. expect(cache.cachedSnapshot(seededHeader)).toBeUndefined() expect(cache.cachedPredecessorTitle(seededHeader)) - .toEqual({ asOfSeq: -1, values: { title: 'forked title' } }) + .toEqual({ asOfSeq: 3, values: { title: 'forked title' } }) // An unseeded header names another lifecycle: no title either. expect(cache.cachedPredecessorTitle(headerOf(id))).toBeUndefined() }) @@ -511,7 +513,7 @@ describe('SessionProjectionCache listing read', () => { const header = headerOf(SessionId('host-state')) expect(cache.cachedSnapshot(header)).toEqual({ - asOfSeq: -1, + asOfSeq: 4, values: { 'cache-test/marks': { marks: ['wire'] } }, }) expect(JSON.stringify(cache.cachedSnapshot(header))) @@ -526,9 +528,9 @@ describe('SessionProjectionCache listing read', () => { }) const { cache } = await harness({ root }) const id = SessionId('listed') - // Matching header: the values, claiming no watermark the client could compare. + // Matching header: the values at the stored row's own watermark. expect(cache.cachedSnapshot(headerOf(id))) - .toEqual({ asOfSeq: -1, values: { 'cache-test/marks': { marks: ['t'] } } }) + .toEqual({ asOfSeq: 4, values: { 'cache-test/marks': { marks: ['t'] } } }) // A recreated id (different createdAt): the record is unrelated — no block. expect(cache.cachedSnapshot(headerOf(id, 777))).toBeUndefined() // Unknown id: no block. @@ -550,7 +552,7 @@ describe('SessionProjectionCache listing read', () => { 'cache-test/marks': { marks: ['a'] }, 'cache-test/marks3': { marks: ['b'] }, }) - expect(block?.asOfSeq).toBe(-1) + expect(block?.asOfSeq).toBe(4) }) it('returns undefined when the stored record version is not accepted', async () => { @@ -595,7 +597,7 @@ describe('SessionProjectionCache listing read', () => { const id = SessionId('pre-lineage') // Unseeded caller: the absent lineage is exactly its identity — served. expect(cache.cachedSnapshot(headerOf(id))) - .toEqual({ asOfSeq: -1, values: { 'cache-test/marks': { marks: ['kept'] } } }) + .toEqual({ asOfSeq: 4, values: { 'cache-test/marks': { marks: ['kept'] } } }) // Seeded caller: the lineage-less record cannot vouch for a seeded lifecycle — refused. expect(cache.cachedSnapshot({ ...headerOf(id), isSeeded: true })) .toBeUndefined() diff --git a/packages/session/session-projection-cache/tests/fixtures.spec.ts b/packages/session/session-projection-cache/tests/fixtures.spec.ts index 1116aebb66..0181ed6afc 100644 --- a/packages/session/session-projection-cache/tests/fixtures.spec.ts +++ b/packages/session/session-projection-cache/tests/fixtures.spec.ts @@ -214,7 +214,7 @@ describe('archived version recovery', () => { expect(cache.cachedPredecessorTitle( headerFor(SessionId(sid), record.identity), )).toEqual({ - asOfSeq: -1, + asOfSeq: record.rows.title?.seq, values: { title: record.rows.title?.val }, }) @@ -246,7 +246,7 @@ describe('archived version recovery', () => { expect(cache.cachedPredecessorTitle( headerFor(id, doc.record.identity), )).toEqual({ - asOfSeq: -1, + asOfSeq: doc.record.rows.title?.seq, values: { title: doc.record.rows.title?.val }, }) @@ -287,7 +287,7 @@ describe('archived version recovery', () => { isSeeded: false, }) expect(cache.cachedPredecessorTitle(listed('older'))).toEqual({ - asOfSeq: -1, + asOfSeq: 2, values: { title: 'older title' }, }) expect(cache.cachedPredecessorTitle(listed('current'))).toBeUndefined() From c4d40864fd72e010b235e87280f2048be10935b8 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 01:04:52 +0800 Subject: [PATCH 07/24] fix(client): route list projection blocks by kind A `sequenced` list block merges key by key under higher-seq-wins like any Host-computed value, so a delayed control baseline at a lower cut can neither overwrite nor clear a newer live-session list value. Only a `cached` block goes through applyCached and yields to every sequenced write. The projection store's module docs describe the two row kinds. --- .../src/client/sessions/manager.ts | 45 +++++++++++++------ .../src/client/sessions/projection-store.ts | 23 ++++++---- .../tests/inbox-projection.client.spec.ts | 7 +-- .../tests/manager.client.spec.ts | 14 +++--- .../tests/projection-store.client.spec.ts | 41 +++++++++++++++-- .../tests/sessions-service.client.spec.ts | 2 +- 6 files changed, 96 insertions(+), 36 deletions(-) diff --git a/packages/api/session-controller/src/client/sessions/manager.ts b/packages/api/session-controller/src/client/sessions/manager.ts index d9cf53d89f..d3564d763b 100644 --- a/packages/api/session-controller/src/client/sessions/manager.ts +++ b/packages/api/session-controller/src/client/sessions/manager.ts @@ -7,12 +7,14 @@ import type { WorkspaceId } from '@deepseek-ai/dsh-workspace/types' import type { SessionControlBaseline, SessionControlFrame, + SessionProjectionHints, SessionRenameValue, SessionSummary, SessionJob as JobView, } from '../../types.ts' import { mergeOrderedBaseline } from '../ordered-baseline.ts' import { isRemoteFailure } from '@deepseek-ai/dsh-api-gateway/client' +import { assertNever } from '@deepseek-ai/dsh-util-values' import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import type { SessionListEntry, TitledSessionSummary } from './lineage.ts' import { flattenLineage } from './lineage.ts' @@ -376,16 +378,12 @@ export class SessionManager { session.handleBlank(s.blank) session.handleRunning(s.running) } - // Fill each row's cached projection block into the per-session value - // store (cold titles surface without opening the session). Cached, - // not seeded: the list block is a partial view of the persisted - // checkpoint — only version-matching keys, no comparable seq — so an - // absent key must not clear, and any sequenced value (a push frame, - // a tail baseline) outranks it. + // Land each row's projection block in the per-session value store + // (cold titles surface without opening the session). A list block is + // partial — only the keys its source holds — so an absent key never + // clears; how the present keys merge depends on the block's kind. for (const s of result.value.items) { - const block = s.projections - if (block === undefined) continue - this.projectionStore(s.sessionId).applyCached(block.values) + if (s.projections !== undefined) this.applyListBlock(s.sessionId, s.projections) } } else { this.listState = 'error' @@ -602,11 +600,30 @@ export class SessionManager { handleSessionAdded(summary: SessionSummary): void { this.mergeSummary(summary) this.sessions.get(summary.sessionId)?.handleBlank(summary.blank) - // A list-surface block is cached like the list response itself: the - // Session's own baseline replaces it once the client opens the Session. - const projections = summary.projections - if (projections !== undefined) { - this.projectionStore(summary.sessionId).applyCached(projections.values) + if (summary.projections !== undefined) this.applyListBlock(summary.sessionId, summary.projections) + } + + /** + * Merge one list-surface projection block by the sequence space it declares. + * A `sequenced` block came from the Host's live registry for an attached + * Session, so each key lands under higher-seq-wins against that Session's + * baselines and frames. A `cached` block was viewed from the persisted + * checkpoint by a header-only listing: its watermark is not comparable with + * this connection's seqs, so it only fills keys no sequenced row holds. + */ + private applyListBlock(sessionId: SessionId, block: SessionProjectionHints): void { + const store = this.projectionStore(sessionId) + switch (block.kind) { + case 'sequenced': { + const seq = sessionSeqCursor(block.asOfSeq) + for (const [key, value] of Object.entries(block.values)) store.apply(key, value, seq) + return + } + case 'cached': + store.applyCached(block.values) + return + default: + assertNever(block.kind, 'session list projection block kind') } } diff --git a/packages/api/session-controller/src/client/sessions/projection-store.ts b/packages/api/session-controller/src/client/sessions/projection-store.ts index 24b3b22602..faafa4404f 100644 --- a/packages/api/session-controller/src/client/sessions/projection-store.ts +++ b/packages/api/session-controller/src/client/sessions/projection-store.ts @@ -1,10 +1,14 @@ /** * Generic per-session projection value store (push model; see the * session-projection subsystem page, docs/subsystems/session-projection.md): - * the host is the only computation site; the client holds finished - * whole values per key — `key → { value, seq }` — seeded by a follow opening - * baseline and updated by Session Controller `projection` frames, - * under the single rule **higher seq wins**. No client-side domain folding + * the host is the only computation site; the client holds finished whole + * values per key in one of two row kinds. A `sequenced` row + * (`{ value, seq }`) comes from the connected Host — a follow opening + * baseline, a Session Controller `projection` frame, a list block the Host + * computed for an attached Session — and merges under **higher seq wins** + * against other sequenced rows. A `cached` row (`{ value }`) comes from the + * session list's view of the persisted checkpoint, carries no comparable + * seq, and yields to every sequenced write. No client-side domain folding * exists: a domain ships projection support with zero client code. Per-key * bare observable faces feed `useProjection` (ui-renderer binds them). */ @@ -152,10 +156,11 @@ export class ProjectionValueStore { } /** - * Fill keys from the session list's zero-I/O cached block. A cached value - * lands only where no sequenced row exists: a connected Session has already - * answered for such a key, and the list's view of the persisted checkpoint - * cannot be newer than it. + * Fill keys from a session-list block the Host labeled `cached`: a zero-I/O + * view of the persisted checkpoint. A cached value lands only where no + * sequenced row exists: a connected Session has already answered for such + * a key, and the list's view of the persisted checkpoint cannot be newer + * than it. * @param values - whole values by key viewed from the persisted checkpoint. */ applyCached(values: Readonly>): void { @@ -188,6 +193,8 @@ export class ProjectionValueStore { for (const key of Object.keys(values)) this.apply(key, values[key], baseline.asOfSeq) for (const [key, row] of this.rows) { if (Object.hasOwn(values, key)) continue + // Every cached row was deleted above; the kind test only narrows the + // type so `row.seq` is readable. if (row.kind === 'sequenced' && row.seq > baseline.asOfSeq) continue this.rows.delete(key) this.changed(key) diff --git a/packages/api/session-controller/tests/inbox-projection.client.spec.ts b/packages/api/session-controller/tests/inbox-projection.client.spec.ts index 589aa43d09..9ae17056e6 100644 --- a/packages/api/session-controller/tests/inbox-projection.client.spec.ts +++ b/packages/api/session-controller/tests/inbox-projection.client.spec.ts @@ -64,7 +64,8 @@ describe('Inbox projection intake', () => { const stale = { ...empty, 'next-turn': [message('removed', 'already removed')] } const result = ok({ items: [{ sessionId: SID, updatedAt: 1, running: false, blank: false, agentAvailable: false, - projections: { asOfSeq: 21, values: { inbox: empty } }, + // The Session is attached: the Host's live registry served the block. + projections: { kind: 'sequenced' as const, asOfSeq: 21, values: { inbox: empty } }, }] }) let refreshed: Promise | undefined @@ -109,9 +110,9 @@ describe('Inbox projection intake', () => { const baseline = { type: 'baseline', value: { jobs: {}, projections: {} } } as const const result = ok({ items: [ { sessionId: SID, updatedAt: 1, running: false, blank: false, agentAvailable: false, - projections: { asOfSeq: 1, values: { inbox: empty } } }, + projections: { kind: 'cached' as const, asOfSeq: 1, values: { inbox: empty } } }, { sessionId: hiddenSessionId, updatedAt: 1, running: false, blank: false, agentAvailable: false, - projections: { asOfSeq: 1, values: { inbox: restored } } }, + projections: { kind: 'cached' as const, asOfSeq: 1, values: { inbox: restored } } }, ] }) let refreshed: Promise | undefined diff --git a/packages/api/session-controller/tests/manager.client.spec.ts b/packages/api/session-controller/tests/manager.client.spec.ts index 60e96c30b9..b41ee673c8 100644 --- a/packages/api/session-controller/tests/manager.client.spec.ts +++ b/packages/api/session-controller/tests/manager.client.spec.ts @@ -173,7 +173,7 @@ describe('list lifecycle', () => { it('keeps an opened conversation out of blank-session reuse after a stale list refresh', async ({ mock, remote }) => { const stale = { ...summary(S1, { blank: true, cwd: '/workspace' }), - projections: { asOfSeq: 2, values: { + projections: { kind: 'cached' as const, asOfSeq: 2, values: { sessionListMetadata: { blank: true, lastPromptAt: null }, } }, } @@ -207,7 +207,7 @@ describe('list lifecycle', () => { const manager = makeManager(mock, remote) try { manager.handleSessionAdded({ - ...summary(S1), projections: { asOfSeq: -1, values: { title: 'before history' } }, + ...summary(S1), projections: { kind: 'cached', asOfSeq: -1, values: { title: 'before history' } }, }) expect(manager.getListSnapshot().items[0]?.title).toBe('before history') // The control baseline is the connected Session's own value: it replaces @@ -328,15 +328,15 @@ describe('list lifecycle', () => { }) remote.session.list.mockResolvedValue(ok({ items: [ - { ...summary(S1), projections: { asOfSeq: 4, values: { title: 'Cold cached' } } }, - { ...summary(S2, { updatedAt: 200 }), projections: { asOfSeq: 50, values: { title: 'List stale' } } }, + { ...summary(S1), projections: { kind: 'cached', asOfSeq: 4, values: { title: 'Cold cached' } } }, + { ...summary(S2, { updatedAt: 200 }), projections: { kind: 'cached', asOfSeq: 50, values: { title: 'List stale' } } }, ] as never[], })) await manager.refreshList() const items = manager.getListSnapshot().items // Cold row: title surfaces straight from the list block — no open, no history. expect(items.find(item => item.sessionId === S1)?.title).toBe('Cold cached') - // A list block never displaces a sequenced value, whatever watermark it claims. + // A cached list block never displaces a sequenced value, whatever watermark its record holds. expect(items.find(item => item.sessionId === S2)?.title).toBe('Pushed') }) @@ -885,10 +885,10 @@ describe('connected generation', () => { remote.session.list.mockImplementation(() => calls++ === 0 ? oldList.promise : newList.promise) const manager = makeManager(mock, remote) const oldResult = ok({ items: [{ ...summary(S1), projections: { - asOfSeq: 20, values: { title: 'Unpersisted title' }, + kind: 'cached', asOfSeq: 20, values: { title: 'Unpersisted title' }, } }] as never[] }) const newResult = ok({ items: [{ ...summary(S1), projections: { - asOfSeq: 1, values: { title: 'Durable title' }, + kind: 'cached', asOfSeq: 1, values: { title: 'Durable title' }, } }] as never[] }) const oldPull = manager.refreshList() let newPull: Promise | undefined diff --git a/packages/api/session-controller/tests/projection-store.client.spec.ts b/packages/api/session-controller/tests/projection-store.client.spec.ts index c8af28588e..3ab6ab2de1 100644 --- a/packages/api/session-controller/tests/projection-store.client.spec.ts +++ b/packages/api/session-controller/tests/projection-store.client.spec.ts @@ -249,13 +249,14 @@ describe('manager frame routing', () => { expect(manager.getListSnapshot().items[0]?.title).toBe('Projected title') }) - it('caches a list block: a Session baseline at any cut replaces it and a list refresh cannot restore it', async ({ mock, remote }) => { + it('routes a cached list block below every sequenced write: a Session baseline at any cut replaces it and a list refresh cannot restore it', async ({ mock, remote }) => { const manager = makeManager(mock, remote) remote.session.list.mockResolvedValue(ok({ items: [{ agentAvailable: false, sessionId: sid('s1'), updatedAt: 1, running: false, blank: false, - // A stale record whose watermark outruns the connected Session's cut. - projections: { asOfSeq: 40, values: { title: 'Cached title', 'test/marks': { marks: ['cached'] } } }, + // A cold row viewed from a stale record whose own watermark outruns + // the connected Session's cut. + projections: { kind: 'cached', asOfSeq: 40, values: { title: 'Cached title', 'test/marks': { marks: ['cached'] } } }, }], })) await manager.refreshList() @@ -281,12 +282,46 @@ describe('manager frame routing', () => { expect(manager.get(sid('s1')).projections.get('test/marks')).toEqual({ marks: ['cached'] }) }) + it('merges a sequenced list block under higher-seq-wins: a lower-cut baseline neither overwrites nor clears it', async ({ mock, remote }) => { + const manager = makeManager(mock, remote) + remote.session.list.mockResolvedValue(ok({ + items: [{ agentAvailable: true, + sessionId: sid('s1'), updatedAt: 1, running: false, blank: false, + // The Host's live registry served the block: its watermark shares the connection's seq space. + projections: { kind: 'sequenced', asOfSeq: 40, values: { title: 'Live title', 'test/marks': { marks: ['live'] } } }, + }], + })) + await manager.refreshList() + expect(manager.getListSnapshot().items[0]?.title).toBe('Live title') + + // A delayed baseline at a lower cut is stale against the block: it can + // neither overwrite the carried key nor clear the omitted one. + manager.handleControlFrame({ + type: 'baseline', + value: { + jobs: {}, + projections: { [sid('s1')]: { asOfSeq: 2, values: { title: 'Delayed baseline' } } }, + }, + }) + await Promise.resolve() + expect(manager.getListSnapshot().items[0]?.title).toBe('Live title') + expect(manager.get(sid('s1')).projections.get('test/marks')).toEqual({ marks: ['live'] }) + + // A frame past the block's watermark still advances it. + manager.handleControlFrame({ + type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Frame title', seq: 41, + }) + await Promise.resolve() + expect(manager.getListSnapshot().items[0]?.title).toBe('Frame title') + }) + it('projects every retained value into list rows with stable snapshot identity', async ({ mock, remote }) => { const manager = makeManager(mock, remote) remote.session.list.mockResolvedValue(ok({ items: [{ agentAvailable: true, sessionId: sid('s1'), updatedAt: 1, running: false, blank: false, projections: { + kind: 'sequenced', asOfSeq: 2, values: { 'test/marks': { marks: ['baseline'] } }, }, diff --git a/packages/api/session-controller/tests/sessions-service.client.spec.ts b/packages/api/session-controller/tests/sessions-service.client.spec.ts index e2f87caa29..52da57850d 100644 --- a/packages/api/session-controller/tests/sessions-service.client.spec.ts +++ b/packages/api/session-controller/tests/sessions-service.client.spec.ts @@ -71,7 +71,7 @@ async function feedList(b: Bench, rows: FeedRow[]): Promise { ...(r.origin !== undefined ? { origin: r.origin } : {}), ...(r.projections === undefined ? {} - : { projections: { asOfSeq: 0, values: r.projections } }), + : { projections: { kind: 'sequenced' as const, asOfSeq: 0, values: r.projections } }), })), })) await b.svc.refresh() From f3310dc74644e603b266f43653506c71db5d5450 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 01:04:54 +0800 Subject: [PATCH 08/24] docs(session): record the list block kind decision and cross-link the client merge rules The listing identity note describes the `kind` field, rejects routing on the -1 sentinel, and links the projcache predecessor-recovery and projection-owned client state notes; the latter's client merge rules now distinguish Host-sequenced rows from cached list hints. --- ...nd-projection-owned-client-state.i18n.yaml | 4 +-- ...tions-and-projection-owned-client-state.md | 4 +-- ...ns-and-projection-owned-client-state.zh.md | 4 +-- ...listing-identity-and-cached-rows.i18n.yaml | 4 +-- ...-cache-listing-identity-and-cached-rows.md | 26 +++++++++++-------- ...che-listing-identity-and-cached-rows.zh.md | 26 +++++++++++-------- 6 files changed, 38 insertions(+), 30 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml index 2c2fc1b908..f53d8aec09 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml @@ -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-25-session-observations-and-projection-owned-client-state.md -2026-08-25-session-observations-and-projection-owned-client-state.md: 0ff8cbf50c18285092432850ce5222430f5acf0d -2026-08-25-session-observations-and-projection-owned-client-state.zh.md: f3fca078d089a9ee1e329fdbb661653053053a91 +2026-08-25-session-observations-and-projection-owned-client-state.md: 8573ea89fae6f52a9d28cc75261aea529df4f075 +2026-08-25-session-observations-and-projection-owned-client-state.zh.md: 55c477e994df72ef8f6b6e4bb97b8b35e5783c9b diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md index 0ff8cbf50c..8573ea89fa 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md @@ -108,11 +108,11 @@ These distinctions prevent one overloaded `undefined` from representing cache mi | Follow opening baseline | Complete for the Host composition | Exact opening cursor | Capability absent | | Projection frame | One whole key | Event sequence carried by the frame | Not applicable | -The Client stores one row per key with its sequence number. A newer hint, baseline, or frame replaces a row; an equal or older input is ignored. Reconnect can therefore replace the event window without rolling back a projection frame that was already accepted at a later sequence. +The Client stores one row per key. A row the connected Host computed carries its sequence number: a newer baseline or frame replaces it, an equal or older input is ignored, and reconnect can therefore replace the event window without rolling back a projection frame that was already accepted at a later sequence. A list hint viewed from the persisted cache carries no comparable sequence number and yields to every Host-sequenced write ([projection cache listing identity and cached rows](2026-09-19-projection-cache-listing-identity-and-cached-rows.md)). The list view reads the same per-Session store as the opened Session. Hints can populate title, preset, and other list presentation before follow completes; the opening baseline then converges that state without creating a second summary-only authority. -The per-Session Client projection store accepts list hints, the follow baseline, and later whole-value frames under one higher-sequence-wins rule. It never folds Session events. A baseline or frame may advance a hinted value, while an older cut cannot overwrite a newer row. +The per-Session Client projection store accepts list hints, the follow baseline, and later whole-value frames. Higher-sequence-wins applies among Host-sequenced values; cached list hints sit below all of them. It never folds Session events. A baseline or frame may advance a hinted value, while an older cut cannot overwrite a newer sequenced row. Data that is not derived from one Session remains outside projections. `session/modelCatalog` owns the Host-generation model catalog, and `agentPresets/list` owns the configurable preset roster. A selector combines the relevant catalog with the Session's `modelSelection` or `agentPreset` projection only when both inputs are ready. During refresh it may retain the last complete catalog; before the first complete pair it reports loading instead of rendering a guessed name or availability verdict. diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md index f3fca078d0..55c477e994 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md @@ -108,11 +108,11 @@ Projection 的三种交付状态含义不同: | Follow opening baseline | 对当前 Host composition 完整 | 精确 opening cursor | Capability 不存在 | | Projection frame | 单个完整 key | Frame 携带的 event sequence | 不适用 | -Client 为每个 key 保存带 sequence number 的一行。更新的 hint、baseline 或 frame 会替换 row;相同或更旧的输入被忽略。因此 reconnect 可以替换 event window,而不会回退已经在更晚 sequence 接受的 projection frame。 +Client 为每个 key 保存一行。由建连 Host 算出的行带 sequence number:更新的 baseline 或 frame 会替换它,相同或更旧的输入被忽略,因此 reconnect 可以替换 event window,而不会回退已经在更晚 sequence 接受的 projection frame。从持久化缓存看出来的 list hint 不带可比的 sequence number,让位于所有 Host 排序过的写入([Projection cache 只读面按 lifecycle 身份匹配,客户端 store 区分 cached 与 sequenced 行](2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md))。 List view 与已打开 Session 读取同一个 per-Session store。Hints 可以在 follow 完成前填充 title、preset 和其他 list presentation;opening baseline 随后收敛这份状态,而不会建立第二套 summary-only authority。 -每个 Session 的 Client projection store 按一条 higher-sequence-wins 规则接收 list hints、follow baseline 和后续 whole-value frame。它从不折叠 Session event。Baseline 或 frame 可以推进 hinted value,较旧切面不能覆盖较新的 row。 +每个 Session 的 Client projection store 接收 list hints、follow baseline 和后续 whole-value frame。higher-sequence-wins 只在 Host 排序过的值之间生效;cached list hint 排在它们全部之下。它从不折叠 Session event。Baseline 或 frame 可以推进 hinted value,较旧切面不能覆盖较新的 sequenced row。 不由单个 Session 派生的数据不进入 projection。`session/modelCatalog` 持有当前 Host generation 的 model catalog,`agentPresets/list` 持有可配置 preset roster。Selector 只在相应 catalog 与 Session 的 `modelSelection` 或 `agentPreset` projection 均就绪后组合两者。刷新时可以保留上一份完整 catalog;第一次获得完整输入前显示 loading,而不是展示猜测的名称或可用性结论。 diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml index 65576d31cf..89aa09705c 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml @@ -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-09-19-projection-cache-listing-identity-and-cached-rows.md -2026-09-19-projection-cache-listing-identity-and-cached-rows.md: 97495cab8f9bd75791a46065d1c06e4274f7de5e -2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md: f81ccfae2869b9d2b0d3abee020f4a46498cb323 +2026-09-19-projection-cache-listing-identity-and-cached-rows.md: 170eced69fa6c192b85b50d74b787b8aa9ffb843 +2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md: 58693121cae17f1b0e6411c4bcfebbb4339c2898 diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md index 97495cab8f..170eced69f 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md @@ -12,7 +12,7 @@ This is neither cache corruption nor a version mismatch. The projcache record's ### Mechanism -A cache record is bound to a lifecycle identity: `formatVersion + createdAt + cwd + isSeeded + inheritedEventCount`, matched by `identityMatches` on full equality. Since [#3346](https://github.com/deepseek-harness/deepseek-harness/pull/3346), `inheritedEventCount` (the length of the event prefix a fork inherits, the cut below) no longer appears in the logical header: the header keeps only the `isSeeded` bit and the exact cut follows the body. Since Session format v2 (#3398) the physical header line no longer stores `seedLength` either; the reader derives the cut from the seq of the `session/end-seed {inherited: true}` marker in the body. +A cache record (record format and predecessor recovery: [Projection-cache predecessor recovery and Session-format binding](2026-09-02-projcache-cross-version-read-compat.md)) is bound to a lifecycle identity: `formatVersion + createdAt + cwd + isSeeded + inheritedEventCount`, matched by `identityMatches` on full equality. Since #3346, `inheritedEventCount` (the length of the event prefix a fork inherits, the cut below) no longer appears in the logical header: the header keeps only the `isSeeded` bit and the exact cut follows the body. Since Session format v2 (#3398) the physical header line no longer stores `seedLength` either; the reader derives the cut from the seq of the `session/end-seed {inherited: true}` marker in the body. A header-only read therefore cannot obtain the cut: the JSONL backend's `fromHeaderLine` hard-codes `inheritedEventCount: 0` for header-only reads, and `SessionPersistenceSnapshot` carries only the header, the revision, and an optional eventCount. All three header-only cache consumers grew the same guard: @@ -42,7 +42,7 @@ spec.ts and the README describe the purpose of the identity check with one verb: ### The client store cannot guarantee that connected data replaces hints -Each session has exactly one `ProjectionValueStore` on the client (`manager.projectionStores`). The block delivered by the list, the history first-page baseline on open, the control baseline, push frames, and rename results all write into that one object, and `useProjection` reads it. All writers are peers under one higher-seq-wins rule: `apply` drops a new value when `seq <= row.seq`, and `seed` clears omitted keys only when `row.seq <= cut`. A list hint whose seq is equal or higher survives untouched after the session is opened. The hint's seq comes from a disk record; after a crash-repair truncation it can be numerically higher than the connected cursor, which is exactly the case where the cache is wrong and the connection is right. Comparing seqs against a hint is the wrong tool. +Each session has exactly one `ProjectionValueStore` on the client (`manager.projectionStores`; its merge rules were recorded in [Session observations and projection-owned client state](2026-08-25-session-observations-and-projection-owned-client-state.md)). The block delivered by the list, the history first-page baseline on open, the control baseline, push frames, and rename results all write into that one object, and `useProjection` reads it. All writers are peers under one higher-seq-wins rule: `apply` drops a new value when `seq <= row.seq`, and `seed` clears omitted keys only when `row.seq <= cut`. A list hint whose seq is equal or higher survives untouched after the session is opened. The hint's seq comes from a disk record; after a crash-repair truncation it can be numerically higher than the connected cursor, which is exactly the case where the cache is wrong and the connection is right. Comparing seqs against a hint is the wrong tool. ## Decision @@ -55,7 +55,7 @@ Each session has exactly one `ProjectionValueStore` on the client (`manager.proj The two read-only methods no longer take a cut parameter. `inheritedEventCount` is still written into every record and the fold face still compares it on full equality; the original design expectation, that records folded under different fork cuts never seed each other, is unchanged. -The read-only face's output is cached: the returned block's `asOfSeq` is always `-1`, the sentinel `cachedPredecessorTitle` already used. A header can vouch neither for the cut nor for the comparability of the record's seq with the current log, so this face declares no seq. The cache stated the principle itself in `viewRecord`: under-claiming is safe under higher-seq-wins, over-claiming would let a stale value outrank pushes. +In the block the read-only face returns, `asOfSeq` is the lowest watermark among the served rows, the stored record's own position. A header can vouch neither for the cut nor for the comparability of that watermark with the current log, so comparability is not expressed by this number: the Session list adds an independent field `kind` to each summary's `projections` block (`SessionProjectionHints`). A block a cold session's row viewed from projcache is `cached`; a block the Host's live registry computed for an attached session is `sequenced`. The two fields are independent facts: `kind` names the sequence space `asOfSeq` belongs to, and `asOfSeq` is the watermark within that space. ### Why the read-only face may skip the cut @@ -95,15 +95,15 @@ Writer classification: | Entry | Row kind | |---|---| -| the `projections` block of each summary in the `session.list` response (`manager.refreshList`) | cached | -| the `projections` block of an `api-session/added` summary (`manager.handleSessionAdded`) | cached | +| the `projections` block of each summary in the `session.list` response (`manager.refreshList`) | by the block's `kind`: `cached` for a cold session, `sequenced` for a live one | +| the `projections` block of an `api-session/added` summary (`manager.handleSessionAdded`) | by the block's `kind`; the summary comes from a live session, so in practice `sequenced` | | the history first page's `projections` (`projections.seed` in `session.ts`) | sequenced | | the control baseline, live sessions only (`manager.replaceControlBaseline`) | sequenced | | the `session.projections` result of `refreshProjections` (a body observation) | sequenced | | push frames (the `projection` frame handled by `manager`) | sequenced | | the `title` after a successful rename (`session.ts`) | sequenced | -The `seed` and `apply` signatures are unchanged. The server keeps the `asOfSeq` field on the wire; the client does not read it for cached writes. +The `seed` and `apply` signatures are unchanged. The client routes by `kind`: a `sequenced` block goes through `apply` key by key, a `cached` block through `applyCached`, which does not read its `asOfSeq`. ### What stays untouched @@ -128,7 +128,9 @@ The `seed` and `apply` signatures are unchanged. The server keeps the `asOfSeq` **Restore a bounded body probe.** The `probeSmallCold` idea #3400 removed, or a client-side asynchronous `refreshProjections` for visible seeded sessions. It breaks the list's zero-I/O principle, and the historical 1KB threshold shows it never covered an ordinary fork. Rejected. -**Only the `asOfSeq: -1` sentinel, without store tiers.** One server-side change makes hints always lose under the seq rule. It rests on a convention: when a hint's seq equals or exceeds the baseline cut (crash-repair truncation), `apply` keeps the old row and the wrong value survives until the next frame. The user requires connected data to replace hints unconditionally, so the rule belongs in the store rather than in a seq convention. The sentinel stays as the read-only face's honest declaration; the replacement guarantee rests on the row kind. +**Only the `asOfSeq: -1` sentinel, without store tiers.** One server-side change makes hints always lose under the seq rule. It rests on a convention: when a hint's seq equals or exceeds the baseline cut (crash-repair truncation), `apply` keeps the old row and the wrong value survives until the next frame. The user requires connected data to replace hints unconditionally, so the rule belongs in the store rather than in a seq convention. + +**Express cached through `asOfSeq: -1` and let the client route on the sentinel.** The read-only face always emits `-1` and the client treats every list block as cached. Rejected: one field would carry two meanings, and the second could only be inferred by convention; a live session's list block carries a real seq comparable within the connection, and treating every block as cached demoted those too. The PR review reproduced the regression: a delayed control baseline at a lower cut overwrote a newer list value. The independent field `kind` replaces the sentinel, and `asOfSeq` keeps each source's own watermark. **Remove the cut from the cache identity entirely.** The fold face needs it: `restore` continues applying from the cached row's state, and `schedule`, `subagentCatalog`, `permissions.seeded`, and owned/inherited classification encode the cut; an error would be written back and persisted. Rejected. @@ -146,16 +148,18 @@ Bought: Paid: - `cachedSnapshot` and `cachedPredecessorTitle` change signature; three callers change with them. +- `SessionProjectionHints` gains the required field `kind`; every producer of a list summary and every test fixture that builds one carries it. - A hand-crafted record with the same four fields and a different cut is displayed in the list until the session is opened. - Keys the baseline omits clear together with their hints: when a Host does not mount `schedule`, the schedule mark the list hinted disappears after the session opens. Under "connected data is the truth" this is the correct behavior. - Old records still miss for seeded sessions until an open rewrites them. ## Testing -- `session-projection-cache/tests/cache.spec.ts`: a seeded cold header obtains every version-matching row through `cachedSnapshot(header)` with `asOfSeq: -1`; an unseeded header is refused for the same id's seeded record; `coldSnapshot` continues from the row when the cut matches, refolds the whole log when it differs, and throws for an unseeded call with a nonzero cut; `cachedPredecessorTitle(header)` serves only `title` from a seeded record of an older `formatVersion`; rows with differing watermarks form one block that claims no watermark. +- `session-projection-cache/tests/cache.spec.ts`: a seeded cold header obtains every version-matching row through `cachedSnapshot(header)` at the row's watermark; an unseeded header is refused for the same id's seeded record; `coldSnapshot` continues from the row when the cut matches, refolds the whole log when it differs, and throws for an unseeded call with a nonzero cut; `cachedPredecessorTitle(header)` serves only `title` from a seeded record of an older `formatVersion`; rows with differing watermarks form one block whose `asOfSeq` is the lowest row. - `session-projection-cache/tests/fixtures.spec.ts`: archived v3 to v6 records still expose only the predecessor title; lineage-less archives still miss for seeded callers. -- `api/session-controller/tests/session-cold.host.spec.ts`: a seeded cold summary carries `title` and `sessionListMetadata`, `updatedAt` takes `lastPromptAt`, the cache is queried, and the body is not read. -- `api/session-controller/tests/projection-store.client.spec.ts`: `applyCached` fills empty keys only and never displaces a sequenced row; every sequenced write (including a frame at cursor `-1` and a baseline at a lower cut) replaces cached rows; a baseline discards all cached rows before clearing omitted keys; face subscribers are notified on cached fills and their discard. Manager path: a list block claiming any watermark is replaced by a control baseline at a lower cut, and a later list refresh cannot bring it back. -- `api/session-controller/tests/manager.client.spec.ts`: an `api-session/added` block is written as cached and replaced by a control baseline at the same cursor; a list block does not displace an existing sequenced title. +- `api/session-controller/tests/session-cold.host.spec.ts`: a seeded cold summary carries `kind: 'cached'`, `title`, and `sessionListMetadata`, `updatedAt` takes `lastPromptAt`, the cache is queried, and the body is not read. +- `api/session-controller/tests/projection-store.client.spec.ts`: `applyCached` fills empty keys only and never displaces a sequenced row; every sequenced write (including a frame at cursor `-1` and a baseline at a lower cut) replaces cached rows; a baseline discards all cached rows before clearing omitted keys; face subscribers are notified on cached fills and their discard. Manager path: a `cached` list block at any watermark is replaced by a control baseline at a lower cut, and a later list refresh cannot bring it back; a `sequenced` list block merges under higher-seq-wins, so a delayed baseline at a lower cut neither overwrites nor clears it while a higher-seq frame still advances it. +- `api/session-controller/tests/manager.client.spec.ts`: a `cached` `api-session/added` block is replaced by a control baseline at the same cursor; a `cached` list block does not displace an existing sequenced title. +- `api/session-controller/tests/inbox-projection.client.spec.ts`: unchanged; a live session's `sequenced` list block still outranks a delayed control baseline at a lower cut. - `context/session-reference/tests/session-reference.spec.ts`: a seeded cold session is labeled and searchable by its cached title, a session without a cache record is still labeled by id, and neither reads a log. - `subagent/subagent/tests/list-children.spec.ts`: unchanged; seeded children still go through body observation. diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md index f81ccfae28..58693121ca 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md @@ -12,7 +12,7 @@ Host 进程重启后,所有 fork 出来的会话(`SessionHeader.isSeeded === ### 机制 -缓存记录绑定一份 lifecycle identity:`formatVersion + createdAt + cwd + isSeeded + inheritedEventCount`,`identityMatches` 做全等匹配。其中 `inheritedEventCount`(fork 继承的事件前缀长度,下称 cut)从 [#3346](https://github.com/deepseek-harness/deepseek-harness/pull/3346) 起不再出现在逻辑 header 里:header 只保留 `isSeeded` 这一位,精确 cut 跟随正文。Session 格式 v2 起(#3398),物理 header 行也不再存 `seedLength`,reader 从正文里 `session/end-seed {inherited: true}` 标记的 seq 推出 cut。 +缓存记录(记录格式与前代恢复见 [投影缓存前代恢复与 Session 格式绑定](2026-09-02-projcache-cross-version-read-compat.zh.md))绑定一份 lifecycle identity:`formatVersion + createdAt + cwd + isSeeded + inheritedEventCount`,`identityMatches` 做全等匹配。其中 `inheritedEventCount`(fork 继承的事件前缀长度,下称 cut)从 #3346 起不再出现在逻辑 header 里:header 只保留 `isSeeded` 这一位,精确 cut 跟随正文。Session 格式 v2 起(#3398),物理 header 行也不再存 `seedLength`,reader 从正文里 `session/end-seed {inherited: true}` 标记的 seq 推出 cut。 于是 header-only 的读取拿不到 cut:JSONL 后端 `fromHeaderLine` 对 header-only 读取硬编码 `inheritedEventCount: 0`,`SessionPersistenceSnapshot` 只有 header、revision 和可选的 eventCount。三个只读 header 的缓存消费者都因此加了同一个守卫: @@ -42,7 +42,7 @@ spec.ts 与 README 描述身份检查的目的时用的都是同一个动词: ### 客户端 store 无法保证建连数据覆盖提示 -客户端每个会话只有一个 `ProjectionValueStore`(`manager.projectionStores`),列表下发的 block、打开会话的 history 首页基线、control 基线、推送 frame、rename 结果全部写进同一个对象,`useProjection` 读的也是它。所有写入者平等,只有一条 higher-seq-wins 规则:`apply` 在 `seq <= row.seq` 时丢弃新值,`seed` 清理没带的键时只清 `row.seq <= cut` 的行。一个 seq 相等或偏高的列表提示会在会话打开后原样留在格子里。列表提示的 seq 来自磁盘记录,crash-repair 截断日志后它可以数字上高于建连 cursor,而那正是缓存错、建连对的情形。对提示做 seq 比较是用错了工具。 +客户端每个会话只有一个 `ProjectionValueStore`(`manager.projectionStores`;合并规则原记录于 [Session observation 与 projection 所有的客户端状态](2026-08-25-session-observations-and-projection-owned-client-state.zh.md)),列表下发的 block、打开会话的 history 首页基线、control 基线、推送 frame、rename 结果全部写进同一个对象,`useProjection` 读的也是它。所有写入者平等,只有一条 higher-seq-wins 规则:`apply` 在 `seq <= row.seq` 时丢弃新值,`seed` 清理没带的键时只清 `row.seq <= cut` 的行。一个 seq 相等或偏高的列表提示会在会话打开后原样留在格子里。列表提示的 seq 来自磁盘记录,crash-repair 截断日志后它可以数字上高于建连 cursor,而那正是缓存错、建连对的情形。对提示做 seq 比较是用错了工具。 ## Decision @@ -55,7 +55,7 @@ spec.ts 与 README 描述身份检查的目的时用的都是同一个动词: 只读面的两个方法不再接受 cut 参数。`inheritedEventCount` 继续写入记录,fold 面继续全等比对它;"不同 fork cut 的记录不能互相当种子"这条原始设计预期不变。 -只读面的输出定性为 cached:返回的 block `asOfSeq` 恒为 `-1`,沿用 `cachedPredecessorTitle` 已有的哨兵。header 既作证不了 cut,也作证不了记录 seq 与当前日志的可比性,这一面就不声明 seq。缓存自己在 `viewRecord` 里写过这条原则:under-claiming 在 higher-seq-wins 下是安全的,over-claiming 会让陈旧值压过推送。 +只读面返回的 block 里,`asOfSeq` 是所服务各行中最低的水位,也就是存储记录自己的位置。header 既作证不了 cut,也作证不了这个水位与当前日志的可比性,所以可比性不由这个数字表达:Session list 给每条摘要的 `projections` block(`SessionProjectionHints`)加独立字段 `kind`,冷会话从 projcache 看出来的 block 标 `cached`,活会话由 Host live registry 算出的 block 标 `sequenced`。两个字段各管各的:`kind` 说明 `asOfSeq` 属于哪个序列空间,`asOfSeq` 是那个空间里的水位。 ### 只读面为什么可以不比 cut @@ -95,15 +95,15 @@ seq 比较只在同一条 Host 连接内发生:`handleConnected` 先整表 `cl | 入口 | 行类型 | |---|---| -| `session.list` 响应里每条摘要的 `projections` block(`manager.refreshList`) | cached | -| `api-session/added` 摘要的 `projections` block(`manager.handleSessionAdded`) | cached | +| `session.list` 响应里每条摘要的 `projections` block(`manager.refreshList`) | 按 block 的 `kind`:冷会话 `cached`,活会话 `sequenced` | +| `api-session/added` 摘要的 `projections` block(`manager.handleSessionAdded`) | 按 block 的 `kind`;该摘要来自活会话,实际为 `sequenced` | | history 首页 `projections`(`session.ts` 的 `projections.seed`) | sequenced | | control 基线,仅活会话(`manager.replaceControlBaseline`) | sequenced | | `refreshProjections` 的 `session.projections` 结果(正文观察) | sequenced | | 推送 frame(`manager` 处理 `projection` frame) | sequenced | | rename 成功后的 `title`(`session.ts`) | sequenced | -`seed` 与 `apply` 签名不变。服务端线上的 `asOfSeq` 字段保留,客户端对 cached 写入不读它。 +`seed` 与 `apply` 签名不变。客户端按 `kind` 分流:`sequenced` block 逐键 `apply`,`cached` block 走 `applyCached`,不读它的 `asOfSeq`。 ### 不动的部分 @@ -128,7 +128,9 @@ seq 比较只在同一条 Host 连接内发生:`handleConnected` 先整表 `cl **恢复有界正文探测。** #3400 删掉的 `probeSmallCold` 思路,或由客户端对可见 seeded 会话异步 `refreshProjections`。违背列表零 I/O 原则,且历史阈值 1KB 说明它从未覆盖过正常 fork。否决。 -**只用 `asOfSeq: -1` 哨兵,不给 store 分层。** 服务端一处改动即可让提示在 seq 规则下永远落败。但它靠约定成立:一旦提示 seq 与基线 cut 相等或偏高(crash-repair 截断),`apply` 保留旧行,错值存活到下一帧。用户要求建连数据无条件覆盖提示,规则要写进 store 而不是靠 seq 约定模拟。哨兵保留为只读面输出的诚实声明,覆盖保证由行类型承担。 +**只用 `asOfSeq: -1` 哨兵,不给 store 分层。** 服务端一处改动即可让提示在 seq 规则下永远落败。但它靠约定成立:一旦提示 seq 与基线 cut 相等或偏高(crash-repair 截断),`apply` 保留旧行,错值存活到下一帧。用户要求建连数据无条件覆盖提示,规则要写进 store 而不是靠 seq 约定模拟。 + +**用 `asOfSeq: -1` 表达 cached,客户端按哨兵分流。** 只读面统一输出 `-1`,客户端把所有列表 block 当 cached。否决:一个字段同时承担两个含义,另一个含义只能靠约定推断;活会话的列表 block 带本连接可比的真实 seq,一律当 cached 就把它们也降级了,PR 评审复现了延迟到达、cut 更低的 control 基线覆盖更新列表值的回归。改为独立字段 `kind`,`asOfSeq` 保持各自来源的水位。 **把 cut 从缓存身份里彻底删掉。** fold 面需要它:`restore` 从缓存行状态继续 apply,`schedule`、`subagentCatalog`、`permissions.seeded` 与 owned/inherited 归属都编码了 cut,错误会被写回并持久化。否决。 @@ -146,16 +148,18 @@ seq 比较只在同一条 Host 连接内发生:`handleConnected` 先整表 `cl 付出的: - `cachedSnapshot` 与 `cachedPredecessorTitle` 签名变化,三个调用方同步修改。 +- `SessionProjectionHints` 新增必填字段 `kind`,所有产出列表摘要的地方和构造摘要的测试夹具都要带上。 - 手工构造的同四字段、不同 cut 的记录会在列表上显示到会话被打开为止。 - 基线没带的键连提示一起清掉:某个 Host 未挂载 `schedule` 时,打开会话后列表提示过的 schedule 标记消失。按"建连数据是真值"这是正确行为。 - 老记录对 seeded 会话仍然 miss,直到打开重写。 ## Testing -- `session-projection-cache/tests/cache.spec.ts`:seeded 冷 header 通过 `cachedSnapshot(header)` 取到全部版本匹配的行,`asOfSeq` 为 `-1`;unseeded header 对同一 id 的 seeded 记录被拒;`coldSnapshot` 对 cut 一致的记录从行续算、对 cut 不一致的记录整段重新 fold,对 unseeded 且 cut 非 0 的调用抛错;`cachedPredecessorTitle(header)` 对 seeded 的更旧 `formatVersion` 记录只给 `title`;不同 watermark 的多行合成一个不声明 watermark 的 block。 +- `session-projection-cache/tests/cache.spec.ts`:seeded 冷 header 通过 `cachedSnapshot(header)` 取到全部版本匹配的行,`asOfSeq` 为行水位;unseeded header 对同一 id 的 seeded 记录被拒;`coldSnapshot` 对 cut 一致的记录从行续算、对 cut 不一致的记录整段重新 fold,对 unseeded 且 cut 非 0 的调用抛错;`cachedPredecessorTitle(header)` 对 seeded 的更旧 `formatVersion` 记录只给 `title`;不同 watermark 的多行合成一个 block,`asOfSeq` 取最低行。 - `session-projection-cache/tests/fixtures.spec.ts`:归档的 v3 到 v6 记录继续只透出 predecessor title;无 lineage 字段的归档对 seeded 调用方继续 miss。 -- `api/session-controller/tests/session-cold.host.spec.ts`:seeded 冷会话摘要携带 `title` 与 `sessionListMetadata`,`updatedAt` 取 `lastPromptAt`,缓存确实被查询,正文没有被读。 -- `api/session-controller/tests/projection-store.client.spec.ts`:`applyCached` 只填空位、不覆盖 sequenced 行;任何 sequenced 写入(包括 cursor `-1` 的 frame 和 cut 更低的基线)替换 cached 行;基线先丢弃全部 cached 行再清理没带的键;面订阅在 cached 填充与丢弃时都收到通知。manager 路径:列表 block 声明的 watermark 再高,也被 cut 更低的 control 基线替换,之后的列表刷新拿不回来。 -- `api/session-controller/tests/manager.client.spec.ts`:`api-session/added` 的 block 写为 cached,同 cursor 的 control 基线替换它;列表 block 不覆盖已有的 sequenced title。 +- `api/session-controller/tests/session-cold.host.spec.ts`:seeded 冷会话摘要携带 `kind: 'cached'`、`title` 与 `sessionListMetadata`,`updatedAt` 取 `lastPromptAt`,缓存确实被查询,正文没有被读。 +- `api/session-controller/tests/projection-store.client.spec.ts`:`applyCached` 只填空位、不覆盖 sequenced 行;任何 sequenced 写入(包括 cursor `-1` 的 frame 和 cut 更低的基线)替换 cached 行;基线先丢弃全部 cached 行再清理没带的键;面订阅在 cached 填充与丢弃时都收到通知。manager 路径:`cached` 列表 block 的水位再高,也被 cut 更低的 control 基线替换,之后的列表刷新拿不回来;`sequenced` 列表 block 按 higher-seq-wins,cut 更低的延迟基线既不覆盖也不清掉它,更高 seq 的 frame 仍能推进它。 +- `api/session-controller/tests/manager.client.spec.ts`:`api-session/added` 的 `cached` block 被同 cursor 的 control 基线替换;`cached` 列表 block 不覆盖已有的 sequenced title。 +- `api/session-controller/tests/inbox-projection.client.spec.ts`:不变,活会话的 `sequenced` 列表 block 仍压过延迟到达、cut 更低的 control 基线。 - `context/session-reference/tests/session-reference.spec.ts`:seeded 冷会话按缓存 title 标注并可按 title 搜到,没有缓存记录的会话仍按 id 标注,两者都不读日志。 - `subagent/subagent/tests/list-children.spec.ts`:不变,seeded 子代仍走正文观察。 From 6ab579b6433656788d0f79eefc0fa37bf694a027 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 01:48:33 +0800 Subject: [PATCH 09/24] fix(web): label the assembled-remote fixture's list projection blocks The built-client fixture served newly created Sessions with a control-baseline block as their list projections. Since SessionProjectionHints requires `kind`, the real client's applyListBlock would have hit assertNever on it; the created Session is live on the fixture Host, so its block is sequenced. --- apps/web/tests/assembled-remote.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/web/tests/assembled-remote.ts b/apps/web/tests/assembled-remote.ts index 75852bf6b4..72a3db40db 100644 --- a/apps/web/tests/assembled-remote.ts +++ b/apps/web/tests/assembled-remote.ts @@ -20,6 +20,7 @@ interface SessionSummary { readonly origin?: 'subagent' readonly cwd?: string readonly projections?: { + readonly kind: 'cached' | 'sequenced' readonly asOfSeq: number readonly values: Readonly> } @@ -260,7 +261,9 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass running: false, blank: true, cwd, - projections: structuredClone(blankSessionProjections), + // The created Session is live on this fixture Host: its list block is + // sequenced, like the block the real live registry would serve. + projections: { kind: 'sequenced', ...structuredClone(blankSessionProjections) }, } sessions.push(summary) records.set(sessionId, []) From fd76c9534fb4e3d73704fdd87d37404336391857 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 01:48:34 +0800 Subject: [PATCH 10/24] docs(session): sync the client merge-rule prose with cached and sequenced rows The session-controller README, the per-session store JSDoc, and the projcache predecessor-recovery and durable-web-queue-recovery notes described one higher-seq-wins rule and the asOfSeq -1 title hint. They now state that higher-seq-wins applies among Host-sequenced values, that cached list blocks yield to the connected Session's baseline, and that the predecessor title carries its stored row's watermark under kind: 'cached'. --- .../2026-09-02-projcache-cross-version-read-compat.i18n.yaml | 4 ++-- .../2026-09-02-projcache-cross-version-read-compat.md | 2 +- .../2026-09-02-projcache-cross-version-read-compat.zh.md | 2 +- .../bug-fix/2026-08-17-durable-web-queue-recovery.i18n.yaml | 4 ++-- .../bug-fix/2026-08-17-durable-web-queue-recovery.md | 2 +- .../bug-fix/2026-08-17-durable-web-queue-recovery.zh.md | 2 +- packages/api/session-controller/README.i18n.yaml | 4 ++-- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- .../api/session-controller/src/client/sessions/session.ts | 5 +++-- 10 files changed, 15 insertions(+), 14 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.i18n.yaml index ebe52594b7..87f3b7c351 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.i18n.yaml @@ -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-09-02-projcache-cross-version-read-compat.md -2026-09-02-projcache-cross-version-read-compat.md: 82f7f26d5cd0484f5adcd51db17748f41a298294 -2026-09-02-projcache-cross-version-read-compat.zh.md: 58705ec8f15fbffff6af31872a69f1f19ef5e3c5 +2026-09-02-projcache-cross-version-read-compat.md: 160c5c796bacc6f672b06acc0df4246d7008c52b +2026-09-02-projcache-cross-version-read-compat.zh.md: cff7742f6c1f887b905a2c139e4157782aef677c diff --git a/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.md b/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.md index 82f7f26d5c..160c5c796b 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.md +++ b/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.md @@ -39,7 +39,7 @@ Declared read compatibility — reads tolerate vouched-for older versions, write 5. **Identity matching is stricter than structural admission**: an absent `formatVersion` never matches a current Session, so predecessor rows cannot seed a projection and refold from the authoritative log. Once the format matches, `identityMatches` normalizes absent lineage to unseeded (`?? false` / `?? 0`): exact for an unseeded session, while a seeded expectation fails the match. Poisoned v5 homes therefore boot safely, but their unbound rows are not exposed as current values. 6. **Schema-validation backstop: `invalidRecords: 'backup-and-skip'` (declared by this domain only)**. A stored record that still fails to parse beyond read compatibility no longer refuses the whole domain: the domain layer calls the backend's `KvUnit.backupRecord` (json per-record implementation = rename the document to `.json.bak.`, bytes kept, never read again), prints the concrete failure with `logger.error` (domain, table, key, destination, zod cause), and continues the open with the record absent; the next cold read rebuilds and rewrites that session's cache. **The policy is an explicit per-domain declaration and the default stays fail-loud** — other domains still refuse the whole load on invalid stored data, and a backend without `backupRecord` (single layout, row stores) also falls back to fail-loud. Naming history: quarantine → backup-and-skip (user ruling: the word must carry both "back up" and "skip", sharing its root with the `.bak` suffix; skip-backup was rejected because the CLI `--skip-X` convention reads it as "do not back up"). For this domain it supersedes the reset/destroy recovery path of the [2026-07-28 storage recovery proposal](../../proposed/architecture/2026-07-28-storage-root-and-derived-medium-recovery.md), which stays live for authoritative and whole-medium damage. -7. **A predecessor title is a listing hint, not a fold shortcut**: Session-list startup remains metadata/cache-only and never opens cold log bodies. The log header is authoritative; a lifecycle-matching checkpoint is a durable-prefix witness that may lag but cannot lead the log. `cachedPredecessorTitle` therefore exposes only a predecessor `title` row that still passes the current title unit's `stateVersion` and schema. Both adjacent Session-format edges preserve title text. The hint uses `asOfSeq: -1` rather than the stored row sequence because a cardinality-changing log migration can remap that coordinate. Other predecessor rows remain hidden, and `hydratePrepared`/`coldSnapshot` retain strict format identity, because normalizers can change values such as `blank` or `lastPromptAt` even when storage is physically consistent. +7. **A predecessor title is a listing hint, not a fold shortcut**: Session-list startup remains metadata/cache-only and never opens cold log bodies. The log header is authoritative; a lifecycle-matching checkpoint is a durable-prefix witness that may lag but cannot lead the log. `cachedPredecessorTitle` therefore exposes only a predecessor `title` row that still passes the current title unit's `stateVersion` and schema. Both adjacent Session-format edges preserve title text. The hint carries the stored title row's own watermark as `asOfSeq`; because a cardinality-changing log migration can remap that coordinate, the Session list labels the block `kind: 'cached'` and the client never compares it with the connected Session's seqs ([listing identity and cached rows](2026-09-19-projection-cache-listing-identity-and-cached-rows.md)). Other predecessor rows remain hidden, and `hydratePrepared`/`coldSnapshot` retain strict format identity, because normalizers can change values such as `blank` or `lastPromptAt` even when storage is physically consistent. ### v3-v6 → v7 disposition diff --git a/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.zh.md b/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.zh.md index 58705ec8f1..cff7742f6c 100644 --- a/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-02-projcache-cross-version-read-compat.zh.md @@ -39,7 +39,7 @@ v4→v5 的唯一实质差异是 identity 新增两个 lineage 字段;v6 只 5. **identity 匹配比结构准入更严格**:缺失 `formatVersion` 的记录绝不匹配当前 Session,因此前代行不能播种投影,而会从权威日志重新折叠。格式匹配后,`identityMatches` 才把缺失 lineage 归一化为 unseeded(`?? false` / `?? 0`):对 unseeded 会话精确,对 seeded 期望则匹配失败。v5 投毒 home 因而可以安全启动,但其未绑定行不会作为当前值暴露。 6. **schema 校验兜底:`invalidRecords: 'backup-and-skip'`(仅本域声明)**。读兼容之外仍然解析失败的存量记录不再让整个域拒开:domain 层调用后端的 `KvUnit.backupRecord`(json per-record 实现=把文档改名为 `.json.bak.`,字节留档、不再被读取),用 `logger.error` 打印具体失败信息(域名、表、键、移动去向、zod 失败原因),随后当该记录不存在继续启动;下一次冷读会重建并重写该会话的缓存。**该策略是域级显式声明,缺省仍为 fail-loud**——其他业务域的存量数据校验失败照旧整域拒载;后端没有 `backupRecord` 能力(single 布局、行存储)时也回退 fail-loud。命名沿革:quarantine → backup-and-skip(用户裁决:词要同时含"备份"与"跳过"两义,且与 `.bak` 后缀同源;skip-backup 因 CLI `--skip-X` 惯例存在"不备份"反读而弃用)。对本域而言,该策略取代了 [2026-07-28 存储恢复提案](../../proposed/architecture/2026-07-28-storage-root-and-derived-medium-recovery.zh.md)中 reset/destroy 的恢复途径;该提案对权威介质与整介质损坏仍然有效。 -7. **predecessor title 是列表 hint,而不是 fold shortcut**:Session list 启动保持 metadata/cache-only,绝不打开冷 log body。log header 是权威来源;生命周期匹配的 checkpoint 是 durable prefix witness,可以落后但不能领先日志。因此 `cachedPredecessorTitle` 只公开仍通过当前 title unit `stateVersion` 与 schema 的 predecessor `title` row。两条相邻 Session format edge 都保留 title 文本。该 hint 使用 `asOfSeq: -1`,而不使用存储 row 的序号,因为改变日志事件数量的迁移会重新映射该坐标。其他 predecessor row 继续隐藏,`hydratePrepared`/`coldSnapshot` 仍要求严格格式 identity,因为即使物理存储一致,normalizer 仍可能改变 `blank` 或 `lastPromptAt` 等值。 +7. **predecessor title 是列表 hint,而不是 fold shortcut**:Session list 启动保持 metadata/cache-only,绝不打开冷 log body。log header 是权威来源;生命周期匹配的 checkpoint 是 durable prefix witness,可以落后但不能领先日志。因此 `cachedPredecessorTitle` 只公开仍通过当前 title unit `stateVersion` 与 schema 的 predecessor `title` row。两条相邻 Session format edge 都保留 title 文本。该 hint 的 `asOfSeq` 是存储 title row 自己的水位;因为改变日志事件数量的迁移会重新映射该坐标,Session list 把该 block 标为 `kind: 'cached'`,客户端不会拿它与建连 Session 的 seq 比较([只读面按 lifecycle 身份匹配与 cached 行](2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md))。其他 predecessor row 继续隐藏,`hydratePrepared`/`coldSnapshot` 仍要求严格格式 identity,因为即使物理存储一致,normalizer 仍可能改变 `blank` 或 `lastPromptAt` 等值。 ### v3-v6 → v7 处置 diff --git a/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.i18n.yaml index c18976d463..56aaada1b7 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.i18n.yaml +++ b/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.i18n.yaml @@ -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/bug-fix/2026-08-17-durable-web-queue-recovery.md -2026-08-17-durable-web-queue-recovery.md: c235cc47d5a68623249765753c2757948721ff6e -2026-08-17-durable-web-queue-recovery.zh.md: 2b224b5e1d63905e738dfda0772a3ea578c9aef3 +2026-08-17-durable-web-queue-recovery.md: 5fbfdf0e62c1034fbea138016cc2979489de474f +2026-08-17-durable-web-queue-recovery.zh.md: 2aaffd6bc571aab449d9429758fdf45bb4dd8d4c diff --git a/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.md b/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.md index c235cc47d5..5fbfdf0e62 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.md +++ b/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.md @@ -18,7 +18,7 @@ The registry folds committed splices before `Session.append()` returns; each Age The generic session-projection carrier is the only Web transport. It sends higher-seq `session/projection` values, includes the complete values block in each `session.follow` opening snapshot, folds detached cold logs, and uses the projection cache when valid. There is no Host-owned `queue` projection, placement vocabulary, handoff list, dedicated queue frame, or live-Agent reconnect enumeration. -A synchronous subscription to ready Host generations discards every retained projection value and watermark before refreshing queries and restarting the control stream, including cold Sessions absent from the process-local control baseline. The first control stream waits for generation readiness; a baseline cannot arrive before invalidation and then be erased by a later Cordis `connection/reset` notification. Observable faces retain their identities and subscriptions. A list request from an earlier generation cannot publish values or settle the current request; history and list values from the new generation may therefore establish a lower durable seq without losing to unpersisted state. Within a generation, all incoming baselines obey higher-seq-wins, so a delayed control baseline cannot remove or overwrite newer list or history values. +A synchronous subscription to ready Host generations discards every retained projection value and watermark before refreshing queries and restarting the control stream, including cold Sessions absent from the process-local control baseline. The first control stream waits for generation readiness; a baseline cannot arrive before invalidation and then be erased by a later Cordis `connection/reset` notification. Observable faces retain their identities and subscriptions. A list request from an earlier generation cannot publish values or settle the current request; history and list values from the new generation may therefore establish a lower durable seq without losing to unpersisted state. Within a generation, all Host-sequenced values obey higher-seq-wins, so a delayed control baseline cannot remove or overwrite newer history values or a live Session's list values; a cached list block viewed from the projection cache yields to the baseline instead ([listing identity and cached rows](../architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md)). The client Session binding retains `inbox` in its generic per-session projection store and does not copy it into `SessionSnapshot`. QueueDock reads `next-turn` directly. ChatView reads user-origin `next-step` messages directly and ignores injected context. Claiming removes a pending value through the durable splice; a later `user/message` is rendered through the ordinary conversation projection. diff --git a/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.zh.md b/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.zh.md index 2b224b5e1d..2aaffd6bc5 100644 --- a/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.zh.md +++ b/.agents/notes/implemented/bug-fix/2026-08-17-durable-web-queue-recovery.zh.md @@ -18,7 +18,7 @@ Inbox 接受消息时会记录规范化的 `agent/inbox/spliced` 事件,但 We 通用会话投影传输层是唯一 Web 传输。它发送 seq 更高的 `session/projection` 值,在每次 `session.follow` 的起始快照中包含完整 values 块,折叠已分离的冷日志,并在缓存有效时使用投影缓存。系统不存在 Host 拥有的 `queue` 投影、placement 词汇、handoff 列表、专用 queue 帧或枚举 live Agent 的重连逻辑。 -对已就绪 Host generation 的同步订阅会先丢弃所有保留的投影值及其水位,再刷新查询并重新打开 control stream,其中也包括进程本地 control baseline 中没有列出的冷 Session。首次 control stream 会等待 generation 就绪;baseline 不会先于旧状态清理到达,再被较晚的 Cordis `connection/reset` 通知清除。Observable face 保留自身标识及订阅。较早 generation 的 list 请求不能发布值或使当前请求结束,因此新 generation 的历史与 list 值可以建立较低的持久 seq,而不会被尚未持久化的状态挡住。同一 generation 内,所有收到的 baseline 都遵循较高 seq 优先,因此延迟到达的 control baseline 不能删除或覆盖较新的 list 或 history 值。 +对已就绪 Host generation 的同步订阅会先丢弃所有保留的投影值及其水位,再刷新查询并重新打开 control stream,其中也包括进程本地 control baseline 中没有列出的冷 Session。首次 control stream 会等待 generation 就绪;baseline 不会先于旧状态清理到达,再被较晚的 Cordis `connection/reset` 通知清除。Observable face 保留自身标识及订阅。较早 generation 的 list 请求不能发布值或使当前请求结束,因此新 generation 的历史与 list 值可以建立较低的持久 seq,而不会被尚未持久化的状态挡住。同一 generation 内,所有 Host 排序过的值都遵循较高 seq 优先,因此延迟到达的 control baseline 不能删除或覆盖较新的 history 值或活 Session 的 list 值;从 projection cache 看出来的 cached list block 则让位于该 baseline([只读面按 lifecycle 身份匹配与 cached 行](../architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md))。 客户端 Session binding 在通用逐会话投影存储中保留 `inbox`,不会把它复制进 `SessionSnapshot`。QueueDock 直接读取 `next-turn`。ChatView 直接读取用户来源的 `next-step` 消息,并忽略注入上下文。认领操作通过持久 splice 移除待处理值;后续 `user/message` 由普通会话投影渲染。 diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index d04576c269..f0c39d8dbb 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -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: a0e18910d14f879171a1415476a7e05a0d261a8a -README.zh.md: 58466e387fd604137a2358e8b9a7de3320691034 +README.md: c9f63d462c6e291abda7312c66c8fffcd7109c57 +README.zh.md: f6d03b45b6bf9d3e809e70154adacd59ce341721 diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index a0e18910d1..c9f63d462c 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -39,7 +39,7 @@ Client list refreshes retain unchanged row objects and reuse the items array whe Projection reads retain loading and failure state independently of their values. Reconnect cancels reads from the previous connection and reloads previously requested projections; live membership updates arrive through the control stream. Parent availability comes from Host summaries and remains unknown until a summary or a successful list baseline establishes it. Address lookup resolves projected children without selecting them or creating scopes. -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`, `append`, and `settle-assistant` 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. The Web adapter explicitly opts into cursorless Assistant frames: each opening carries the active attempt's `startedAfterSeq`, `nextIndex`, and compact stream, and every stream member becomes a Client-only `assistant/live-chunk` entry ordered between durable cursors. The Host captures a follower-local arrival ordinal with that baseline and suppresses buffered frames at or before the cut; a replacement Agent may restart frame revision at one. A durable `assistant/message` or `assistant/attempt` arriving after an active opening stays staged only when its seq follows `startedAfterSeq` and its Turn and Step match; the matching end type, seq, and index publishes one named settlement delta that retires the attempt's transient rows and adds the durable entry while earlier same-step retries remain visible. Revision, dense-index, or settlement gaps for a known attempt reopen follow, while a controller that missed the start ignores unknown-attempt frames and publishes their durable settlement normally. An abandoned end publishes a settlement delta without a durable entry so its transient rows retire immediately. A durable gap-repair page has no Assistant baseline, so its held notification reopens follow once for a paired page and baseline. Every history record covers exactly its event seq. 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 jobs and projection state instead of treating transient values as durable events. At each ready Host generation, a synchronous Client subscription clears retained projection values and watermarks before refreshing queries and restarting the control stream, including Sessions absent from the control baseline. The first control stream waits for generation readiness, so its opening values cannot precede invalidation. Outstanding list responses from the previous generation cannot republish those values. Within a generation, a delayed control baseline cannot overwrite or clear newer list, history, or live values. The durable `inbox` projection carries both pending lists through the same cold-read and reconnect path as other projections. Client Agent contexts provide the identity used by the independent [`fileUpload`](../../client/file-upload/README.md) service; Session objects expose lifecycle, prompt, queue, and history operations rather than file transfer. +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`, `append`, and `settle-assistant` 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. The Web adapter explicitly opts into cursorless Assistant frames: each opening carries the active attempt's `startedAfterSeq`, `nextIndex`, and compact stream, and every stream member becomes a Client-only `assistant/live-chunk` entry ordered between durable cursors. The Host captures a follower-local arrival ordinal with that baseline and suppresses buffered frames at or before the cut; a replacement Agent may restart frame revision at one. A durable `assistant/message` or `assistant/attempt` arriving after an active opening stays staged only when its seq follows `startedAfterSeq` and its Turn and Step match; the matching end type, seq, and index publishes one named settlement delta that retires the attempt's transient rows and adds the durable entry while earlier same-step retries remain visible. Revision, dense-index, or settlement gaps for a known attempt reopen follow, while a controller that missed the start ignores unknown-attempt frames and publishes their durable settlement normally. An abandoned end publishes a settlement delta without a durable entry so its transient rows retire immediately. A durable gap-repair page has no Assistant baseline, so its held notification reopens follow once for a paired page and baseline. Every history record covers exactly its event seq. 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 jobs and projection state instead of treating transient values as durable events. At each ready Host generation, a synchronous Client subscription clears retained projection values and watermarks before refreshing queries and restarting the control stream, including Sessions absent from the control baseline. The first control stream waits for generation readiness, so its opening values cannot precede invalidation. Outstanding list responses from the previous generation cannot republish those values. Within a generation, a delayed control baseline cannot overwrite or clear newer sequenced values, whether they arrived through a live Session's list block, a history page, or a frame; a cached list block, viewed from the projection cache for a cold Session, yields to the connected Session's baseline whatever watermark it carries. The durable `inbox` projection carries both pending lists through the same cold-read and reconnect path as other projections. Client Agent contexts provide the identity used by the independent [`fileUpload`](../../client/file-upload/README.md) service; Session objects expose lifecycle, prompt, queue, and history operations rather than file transfer. 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. The echo stores ordered image previews and durable file references. Session derives its `transcript`, `queued`, or `steering` placement from the current running state and 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`, including pending messages in the `inbox` projection. An echo retires one animation frame after its durable event or queue occurrence is observed, immediately when its identified prompt fails or is abandoned, and as failed on disposal. Each retirement fires `onRetire` exactly once; an observed retirement includes the ordered durable attachment references so the composer can release successful cards while preserving failed drafts. Echoes are Client memory only; reload and reconnect rebuild the conversation from durable events alone. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 58466e387f..f6d03b45b6 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -39,7 +39,7 @@ Client 列表刷新保留未变化的行对象,并在顺序和值均相同时 投影读取独立于其值保留加载与失败状态。重连会取消上一连接的读取,并重新加载已请求的投影;实时成员更新通过 control stream 到达。父 Agent 可用性来自 Host 摘要,在收到对应摘要或成功的列表 baseline 前保持未知。地址查找直接解析投影中的子项,不会选择它们或创建 scope。 -Client 适配器提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend`、`append` 与 `settle-assistant` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页 50 条消息,而 `loadThrough(seq)`——轮次跳转加载器——按每页 200 条消息循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。Web 适配器显式选择接收无 cursor 的 Assistant frame:每个 opening 携带活跃 attempt 的 `startedAfterSeq`、`nextIndex` 与紧凑 stream,每个 stream member 都成为排在持久 cursor 之间的 Client-only `assistant/live-chunk` 条目。Host 会随该 baseline 捕获 follower 本地到达序号,并抑制该 cut 及之前的 buffered frame;replacement Agent 可以从 revision 一重新开始。活跃 opening 之后到达的持久 `assistant/message` 或 `assistant/attempt` 只有在其 seq 晚于 `startedAfterSeq` 且轮次与步骤匹配时才会保持暂存;匹配的 end type、seq 与 index 会发布一个具名 settlement delta,删除该 attempt 的瞬态 row、加入持久条目,并保留同一步骤中更早的 retry。已知 attempt 的 revision、密集 index 或 settlement 缺口会重新打开 follow;若 controller 错过 start,则忽略 unknown-attempt frame,并正常发布其持久 settlement。Abandoned end 会发布不含持久条目的 settlement delta,使瞬态 row 立即退出。持久缺口修复 page 不携带 Assistant baseline,因此 held notification 会重新打开 follow 一次,以取得配对的 page 与 baseline。每条历史 record 只覆盖自身的事件 seq。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 jobs 和 projection 状态,而不会把瞬态值当作 durable event。每次 Host generation 就绪时,同步的 Client 订阅会先清除保留的投影值及其水位,再刷新查询并重新打开 control stream,其中也包括 control baseline 中没有列出的 Session。首次 control stream 会等待 generation 就绪,确保其 opening 值不会先于旧状态清理到达。上一代尚未完成的 list 响应无法重新发布这些值。同一 generation 内,延迟到达的 control baseline 不能覆盖或清除较新的 list、history 或 live 值。持久 `inbox` 投影通过与其他投影相同的冷读取和重连路径传输两份待处理列表。Client Agent 上下文提供独立 [`fileUpload`](../../client/file-upload/README.zh.md) 服务使用的身份;Session 对象提供生命周期、prompt、queue 与历史操作,不提供文件传输。 +Client 适配器提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend`、`append` 与 `settle-assistant` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页 50 条消息,而 `loadThrough(seq)`——轮次跳转加载器——按每页 200 条消息循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。Web 适配器显式选择接收无 cursor 的 Assistant frame:每个 opening 携带活跃 attempt 的 `startedAfterSeq`、`nextIndex` 与紧凑 stream,每个 stream member 都成为排在持久 cursor 之间的 Client-only `assistant/live-chunk` 条目。Host 会随该 baseline 捕获 follower 本地到达序号,并抑制该 cut 及之前的 buffered frame;replacement Agent 可以从 revision 一重新开始。活跃 opening 之后到达的持久 `assistant/message` 或 `assistant/attempt` 只有在其 seq 晚于 `startedAfterSeq` 且轮次与步骤匹配时才会保持暂存;匹配的 end type、seq 与 index 会发布一个具名 settlement delta,删除该 attempt 的瞬态 row、加入持久条目,并保留同一步骤中更早的 retry。已知 attempt 的 revision、密集 index 或 settlement 缺口会重新打开 follow;若 controller 错过 start,则忽略 unknown-attempt frame,并正常发布其持久 settlement。Abandoned end 会发布不含持久条目的 settlement delta,使瞬态 row 立即退出。持久缺口修复 page 不携带 Assistant baseline,因此 held notification 会重新打开 follow 一次,以取得配对的 page 与 baseline。每条历史 record 只覆盖自身的事件 seq。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 jobs 和 projection 状态,而不会把瞬态值当作 durable event。每次 Host generation 就绪时,同步的 Client 订阅会先清除保留的投影值及其水位,再刷新查询并重新打开 control stream,其中也包括 control baseline 中没有列出的 Session。首次 control stream 会等待 generation 就绪,确保其 opening 值不会先于旧状态清理到达。上一代尚未完成的 list 响应无法重新发布这些值。同一 generation 内,延迟到达的 control baseline 不能覆盖或清除较新的 sequenced 值,无论它们来自活 Session 的 list block、history page 还是 frame;冷 Session 从 projection cache 看出来的 cached list block 则不论水位都让位于建连 Session 的 baseline。持久 `inbox` 投影通过与其他投影相同的冷读取和重连路径传输两份待处理列表。Client Agent 上下文提供独立 [`fileUpload`](../../client/file-upload/README.zh.md) 服务使用的身份;Session 对象提供生命周期、prompt、queue 与历史操作,不提供文件传输。 Session 对象还承载本地提交回显:`session.beginSubmission` 在调用方序列化与提示词之前,同步把一条回显写入 `SessionSnapshot.pendingSubmissions`,会话 UI 因此能在点击提交的当帧显示消息。回显按顺序存放图片预览与持久文件引用。Session 根据当前运行状态与请求的投递模式推导其 `transcript`、`queued` 或 `steering` 位置,并在序列化期间保留该位置。提示词的 `requestId` 是关联标识:Host 把它回显为 durable user source 的 `rpcId`,`inbox` 投影中的待处理消息也保留同一 source。回显在观察到其 durable event 或 queue occurrence 后延迟一个动画帧退休,带标识的提示词失败或被放弃时立即退休,销毁时按 failed 退休。每次退休恰好触发一次 `onRetire`;observed 退休还会携带有序的持久附件引用,让 composer 释放成功卡片并保留失败草稿。回显只存在于 Client 内存;刷新与重连只从持久事件重建会话。 diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index cd38a26fcf..fb1eb7a01d 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -137,8 +137,9 @@ export class Session implements SessionFace { * Per-session projection value store (push model; see the session-projection * subsystem page, docs/subsystems/session-projection.md): finished whole * values computed on the Host, seeded by the tail page's - * projections block and updated by Session Controller control frames under the - * one higher-seq-wins rule. Keys are read via `projections.faceOf(key)` + * projections block and updated by Session Controller control frames; + * Host-sequenced writes merge under higher-seq-wins and cached list blocks + * yield to them (projection-store.ts). Keys are read via `projections.faceOf(key)` * (the useProjection resolution face); the conversation snapshot never * carries projection values, and no client-side domain folding exists. * Manager-owned when constructed through SessionManager (frames route and From de055efa9a27a3156c0a34b817ae70407f9c24c8 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 02:04:37 +0800 Subject: [PATCH 11/24] test(session): list a forked Session's cached title after a Host restart A real fork made through sessions.fork is checkpointed into the projection cache, the Context is disposed, and a Host booted over the same storage root serves the fork's title and list metadata from the header alone, as a kind: 'cached' block, without inspecting or opening the log. --- ...listing-identity-and-cached-rows.i18n.yaml | 4 +- ...-cache-listing-identity-and-cached-rows.md | 1 + ...che-listing-identity-and-cached-rows.zh.md | 1 + .../tests/session-projections.host.spec.ts | 81 +++++++++++++++++++ 4 files changed, 85 insertions(+), 2 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml index 89aa09705c..ea121beb8c 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.i18n.yaml @@ -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-09-19-projection-cache-listing-identity-and-cached-rows.md -2026-09-19-projection-cache-listing-identity-and-cached-rows.md: 170eced69fa6c192b85b50d74b787b8aa9ffb843 -2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md: 58693121cae17f1b0e6411c4bcfebbb4339c2898 +2026-09-19-projection-cache-listing-identity-and-cached-rows.md: 61b82e5003ba4b634230941f5d3df65e65491e25 +2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md: ef49d90bc68ca501f7496adbac1d1aa8a5d706a7 diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md index 170eced69f..61b82e5003 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.md @@ -158,6 +158,7 @@ Paid: - `session-projection-cache/tests/cache.spec.ts`: a seeded cold header obtains every version-matching row through `cachedSnapshot(header)` at the row's watermark; an unseeded header is refused for the same id's seeded record; `coldSnapshot` continues from the row when the cut matches, refolds the whole log when it differs, and throws for an unseeded call with a nonzero cut; `cachedPredecessorTitle(header)` serves only `title` from a seeded record of an older `formatVersion`; rows with differing watermarks form one block whose `asOfSeq` is the lowest row. - `session-projection-cache/tests/fixtures.spec.ts`: archived v3 to v6 records still expose only the predecessor title; lineage-less archives still miss for seeded callers. - `api/session-controller/tests/session-cold.host.spec.ts`: a seeded cold summary carries `kind: 'cached'`, `title`, and `sessionListMetadata`, `updatedAt` takes `lastPromptAt`, the cache is queried, and the body is not read. +- `api/session-controller/tests/session-projections.host.spec.ts`: a real fork made through `sessions.fork` is checkpointed into projcache, the whole Context is disposed, and a Host restarted over the same storage root reads the `kind: 'cached'` `title` and `sessionListMetadata` through `session.list` from the header alone; `inspect` and `open` are never called. - `api/session-controller/tests/projection-store.client.spec.ts`: `applyCached` fills empty keys only and never displaces a sequenced row; every sequenced write (including a frame at cursor `-1` and a baseline at a lower cut) replaces cached rows; a baseline discards all cached rows before clearing omitted keys; face subscribers are notified on cached fills and their discard. Manager path: a `cached` list block at any watermark is replaced by a control baseline at a lower cut, and a later list refresh cannot bring it back; a `sequenced` list block merges under higher-seq-wins, so a delayed baseline at a lower cut neither overwrites nor clears it while a higher-seq frame still advances it. - `api/session-controller/tests/manager.client.spec.ts`: a `cached` `api-session/added` block is replaced by a control baseline at the same cursor; a `cached` list block does not displace an existing sequenced title. - `api/session-controller/tests/inbox-projection.client.spec.ts`: unchanged; a live session's `sequenced` list block still outranks a delayed control baseline at a lower cut. diff --git a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md index 58693121ca..ef49d90bc6 100644 --- a/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md @@ -158,6 +158,7 @@ seq 比较只在同一条 Host 连接内发生:`handleConnected` 先整表 `cl - `session-projection-cache/tests/cache.spec.ts`:seeded 冷 header 通过 `cachedSnapshot(header)` 取到全部版本匹配的行,`asOfSeq` 为行水位;unseeded header 对同一 id 的 seeded 记录被拒;`coldSnapshot` 对 cut 一致的记录从行续算、对 cut 不一致的记录整段重新 fold,对 unseeded 且 cut 非 0 的调用抛错;`cachedPredecessorTitle(header)` 对 seeded 的更旧 `formatVersion` 记录只给 `title`;不同 watermark 的多行合成一个 block,`asOfSeq` 取最低行。 - `session-projection-cache/tests/fixtures.spec.ts`:归档的 v3 到 v6 记录继续只透出 predecessor title;无 lineage 字段的归档对 seeded 调用方继续 miss。 - `api/session-controller/tests/session-cold.host.spec.ts`:seeded 冷会话摘要携带 `kind: 'cached'`、`title` 与 `sessionListMetadata`,`updatedAt` 取 `lastPromptAt`,缓存确实被查询,正文没有被读。 +- `api/session-controller/tests/session-projections.host.spec.ts`:用 `sessions.fork` 造一个真实 fork 并写入 projcache,销毁整个 Context 后在同一存储根上重启 Host,只凭 header 通过 `session.list` 读到 `kind: 'cached'` 的 `title` 与 `sessionListMetadata`,`inspect` / `open` 一次都没被调用。 - `api/session-controller/tests/projection-store.client.spec.ts`:`applyCached` 只填空位、不覆盖 sequenced 行;任何 sequenced 写入(包括 cursor `-1` 的 frame 和 cut 更低的基线)替换 cached 行;基线先丢弃全部 cached 行再清理没带的键;面订阅在 cached 填充与丢弃时都收到通知。manager 路径:`cached` 列表 block 的水位再高,也被 cut 更低的 control 基线替换,之后的列表刷新拿不回来;`sequenced` 列表 block 按 higher-seq-wins,cut 更低的延迟基线既不覆盖也不清掉它,更高 seq 的 frame 仍能推进它。 - `api/session-controller/tests/manager.client.spec.ts`:`api-session/added` 的 `cached` block 被同 cursor 的 control 基线替换;`cached` 列表 block 不覆盖已有的 sequenced title。 - `api/session-controller/tests/inbox-projection.client.spec.ts`:不变,活会话的 `sequenced` 列表 block 仍压过延迟到达、cut 更低的 control 基线。 diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index cc7b1e66b3..c7657ac815 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -22,6 +22,7 @@ import type { Session, SessionEvent, SessionHeader, UserMessage } from '@deepsee import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import type { ProjectionDefinition } from '@deepseek-ai/dsh-session-projection' import SessionProjectionCache, { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' +import { titleProjectionDefinition } from '@deepseek-ai/dsh-session-title' import Storage from '@deepseek-ai/dsh-storage' import * as StorageDomain from '@deepseek-ai/dsh-storage-domain' import * as StorageJson from '@deepseek-ai/dsh-storage-json' @@ -622,6 +623,86 @@ describe('session.list projections column', () => { } }) + it('lists a forked Session\'s cached title after a Host restart without opening its body', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-api-projcache-')) + const id = SessionId('session-cold-fork') + /** One Host process over `root`: storage stack, registry with the title unit, and the cache. */ + const boot = async (): Promise => { + const ctx = new Context() + await ctx.plugin(Storage) + await ctx.plugin(StorageJson, { root }) + await ctx.plugin(StorageDomain, { backend: 'json' }) + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + await ctx.plugin(SessionProjectionRegistry) + ctx.sessionProjections.register(titleProjectionDefinition) + await ctx.plugin(SessionProjectionCache, { writeEveryEvents: 100, writeIntervalMs: 60_000 }) + return ctx + } + + // First process: a fork inherits its ancestor's prompt and title, the + // cache checkpoints the fold, and the process ends without ever listing. + const first = await boot() + let header: SessionHeader | undefined + let lastSeq: number | undefined + let promptTime: number | undefined + try { + remote(first) + await new Promise(resolve => setTimeout(resolve, 0)) + let child: Session | undefined + const owner = await first.plugin(Object.assign((sessionCtx: Context) => { + const parent = sessionCtx.sessions.create(SessionId('session-cold-fork-parent'), { + meta: { createdAt: 5, cwd: '/workspace' }, + }) + parent.append('turn/start', { turn: 1 }) + promptTime = parent.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'ancestor prompt' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }).time + parent.append('session/title', { title: 'Forked title', messageSeqs: [], source: { kind: 'user' } }) + parent.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + child = sessionCtx.sessions.fork(parent, undefined, id) + }, { inject: ['sessions'] })) + if (child === undefined) throw new Error('child was not forked') + expect(child.header.isSeeded).toBe(true) + expect(child.inheritedEventCount).toBe(4) + await first.sessionProjectionCache.write(child) + header = child.header + lastSeq = child.seq - 1 + await owner.dispose() + } finally { + await first.fiber.dispose() + } + if (header === undefined || lastSeq === undefined || promptTime === undefined) throw new Error('unreachable') + + // Second process: persistence knows the header, the cache holds the + // record, and nothing opens the log. + const second = await boot() + try { + const gateway = remote(second) + await new Promise(resolve => setTimeout(resolve, 0)) + const load = () => { throw new Error('a cold fork listing must not load the event log') } + second.provide('sessionPersistence', testSessionPersistence(second, { + list: async () => [header], + inspect: load, + open: load, + }) as never) + + const response = await gateway.list(request({})) + if (!response.ok) throw new Error('unreachable') + const row = response.value.items.find(item => item.sessionId === id) + expect(row).toMatchObject({ blank: false, updatedAt: promptTime }) + expect(row?.projections).toMatchObject({ + kind: 'cached', + asOfSeq: lastSeq, + values: { title: 'Forked title', sessionListMetadata: { blank: false, lastPromptAt: promptTime } }, + }) + } finally { + await second.fiber.dispose() + await rm(root, { recursive: true, force: true }) + } + }) + it('cold rows without a cache plugin (or without a stored row) just lack the column', async () => { const { ctx } = await harness(true) const coldId = SessionId('session-cold-uncached') From 4b02d03ed58bcf0c848bc9be86db366df7e92287 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 10:54:20 +0800 Subject: [PATCH 12/24] test(session): compare the forked cold row's recency with the list formula The cold row's updatedAt is the later of the header's creation time and the cached last prompt; the fork's creation time is wall-clock and can trail the inherited prompt by a millisecond, so the restart test asserts the same maximum instead of the prompt time alone. --- .../tests/session-projections.host.spec.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index c7657ac815..5b3dd18b42 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -691,7 +691,10 @@ describe('session.list projections column', () => { const response = await gateway.list(request({})) if (!response.ok) throw new Error('unreachable') const row = response.value.items.find(item => item.sessionId === id) - expect(row).toMatchObject({ blank: false, updatedAt: promptTime }) + // Cold recency is the later of the header's creation time and the cached + // last prompt; the fork's creation time is wall-clock and may trail the + // inherited prompt by a tick. + expect(row).toMatchObject({ blank: false, updatedAt: Math.max(header.createdAt, promptTime) }) expect(row?.projections).toMatchObject({ kind: 'cached', asOfSeq: lastSeq, From e5a72d73dfc1541bd24c3d960e12737669d832cc Mon Sep 17 00:00:00 2001 From: Magolor Date: Thu, 17 Sep 2026 15:15:24 +0800 Subject: [PATCH 13/24] feat(client): add extensible session menu actions --- ...17-session-row-menu-actions-slot.i18n.yaml | 6 ++ ...026-09-17-session-row-menu-actions-slot.md | 35 ++++++++ ...-09-17-session-row-menu-actions-slot.zh.md | 35 ++++++++ docs/subsystems/slots.i18n.yaml | 4 +- docs/subsystems/slots.md | 3 +- docs/subsystems/slots.zh.md | 3 +- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../client/ui-primitives/src/Menu.module.css | 11 +++ packages/client/ui-primitives/src/Menu.tsx | 81 ++++++++++++++++++- packages/client/ui-primitives/src/index.ts | 4 +- .../ui-primitives/tests/atoms.client.spec.tsx | 36 ++++++++- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 25 +++++- packages/client/ui-workspace/README.zh.md | 25 +++++- .../ui-workspace/src/client/contract/slots.ts | 34 +++++++- .../client/ui-workspace/src/client/index.ts | 15 ++-- .../ui-workspace/src/client/rows/Rows.tsx | 31 +++++-- .../src/client/rows/WorkspaceBrowser.tsx | 14 +++- .../ui-workspace/tests/apply.client.spec.ts | 3 +- .../tests/rename-assembly.client.spec.tsx | 59 +++++++++++++- .../ui-workspace/tests/rows.client.spec.tsx | 29 +++++++ .../src/client/slot-catalog.ts | 54 ++++++++++++- 24 files changed, 477 insertions(+), 42 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md create mode 100644 .agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml new file mode 100644 index 0000000000..6d120db585 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml @@ -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/architecture/2026-09-17-session-row-menu-actions-slot.md +2026-09-17-session-row-menu-actions-slot.md: 63a5c467cf79fa1d5d6d542d36fd4881215017a5 +2026-09-17-session-row-menu-actions-slot.zh.md: d17715d4253b28439a980dddf36f7fa4c0e324b4 diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md new file mode 100644 index 0000000000..63a5c467cf --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md @@ -0,0 +1,35 @@ +# Agent Note: Session row menu action slot + +Status: implemented + +English | [中文](2026-09-17-session-row-menu-actions-slot.zh.md) + +## Problem + +The Session row menu was a closed list of actions owned by `ui-workspace`. A third-party client plugin could add a separate sidebar control, but it could not place an action beside Rename, Fork, and Archive without changing the owning package or copying the menu interaction. + +## Decision + +`ui-workspace` declares the root-scoped ordered-list slot `sidebar.workspaces.session.menu.action` under its `sidebar.workspaces` registration. Each contribution receives the target `sessionId`, the row `displayTitle` (persisted title, project basename, then Session id), and a `dismiss()` callback; the contributing plugin keeps its services and mutations in its own registration closure. + +The shared `MenuAction` primitive renders contributed rows inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Dynamic client packages cannot import the primitive, so their own `role="menuitem"` control calls the owner `dismiss()` after acting. + +### Ordering and disclosure + +Rename, Fork, and Archive remain a fixed owner-defined group at the top. Contributions form a semantically separated group below them and sort by slot priority, then `order`, then registration order. The group is visually and accessibly hidden when empty. The existing ellipsis menu remains the only disclosure layer; nested “More…” grouping is not part of the contract. + +## Verification + +Primitive tests cover selection, dismissal, focus restoration, submenu reset, the semantic separator, and keyboard order. Row tests cover owner props and built-in-before-plugin placement. The assembled Slot runtime test registers packaged and dynamic-style contributions in reverse order and verifies ordering, display-title identity, dismissal, and trigger-focus restoration. + +## Alternatives considered + +**Pass menu descriptors through the slot owner props.** This makes a render slot behave like a second data registry, exposes presentation policy through callbacks, and prevents ordinary slot components from owning their injected services. + +**Expose only raw menu markup.** That would let packaged plugins drift from the menu's accessibility, focus, and visual behavior. `MenuAction` remains their stable path, while `dismiss()` gives import-free dynamic packages the minimum lifecycle capability they need. + +**Add primary and “More…” slots immediately.** Session actions are already behind the row's ellipsis, and no current action set needs another disclosure level. A second hierarchy would add labeling and keyboard policy before a demonstrated density problem exists. + +## Consequences + +Plugins can add Session actions without editing `ui-workspace`, while core actions keep a stable position and external conflicts use the slot registry's existing id and priority rules. Packaged contributions use `MenuAction`; dynamic contributions own their markup and must call `dismiss()` after acting. All plugin actions remain in the secondary row menu until observed scale justifies a new hierarchy. diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md new file mode 100644 index 0000000000..d17715d425 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md @@ -0,0 +1,35 @@ +# Agent Note: Session 行菜单 action slot + +Status: implemented + +[English](2026-09-17-session-row-menu-actions-slot.md) | 中文 + +## 问题 + +Session 行菜单原本是由 `ui-workspace` 持有的封闭 action 列表。第三方客户端插件可以添加独立的侧边栏控件,却无法在不修改 owner 包或复制菜单交互的情况下,把 action 放到 Rename、Fork 与 Archive 旁边。 + +## 决策 + +`ui-workspace` 在其 `sidebar.workspaces` 注册项下声明 root-scoped 有序列表 slot `sidebar.workspaces.session.menu.action`。每个贡献项接收目标 `sessionId`、行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id)与 `dismiss()` 回调;贡献插件将自身服务与 mutation 保留在自己的注册闭包中。 + +共享 `MenuAction` primitive 在 `Menu` 内渲染贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。动态客户端包无法导入该 primitive,因此其自有 `role="menuitem"` 控件需在执行操作后调用 owner 的 `dismiss()`。 + +### 排序与渐进披露 + +Rename、Fork 与 Archive 作为固定的 owner-defined 分组保持在顶部。贡献项在下方形成带语义分隔的分组,依次按 slot priority、`order` 与注册顺序排列。空分组在视觉与无障碍 API 中均隐藏。现有省略号菜单仍是唯一的渐进披露层;嵌套「More…」分组不属于此约定。 + +## 验证 + +Primitive 测试覆盖选择、关闭、焦点恢复、子菜单重置、语义分隔线与键盘顺序。行测试覆盖 owner props 与内置 action 优先于插件 action 的位置。组装后的 Slot 运行时测试以相反顺序注册打包贡献项与动态风格贡献项,并验证顺序、显示标题身份、关闭与触发按钮焦点恢复。 + +## 考虑过的替代方案 + +**通过 slot owner props 传递菜单 descriptor。** 这会使渲染 slot 变成第二套数据注册表,通过回调暴露展示策略,并阻止普通 slot 组件持有自身注入服务。 + +**只暴露原始菜单 markup。** 这会让打包插件偏离菜单的无障碍、焦点与视觉行为。`MenuAction` 仍是它们的稳定路径,而 `dismiss()` 为无法导入组件的动态包提供所需的最小生命周期能力。 + +**立即添加主要 slot 与「More…」slot。** Session action 已位于行省略号之后,而且当前 action 集合不需要另一层渐进披露。在出现已证实的密度问题前,第二层级只会提前增加标签与键盘策略。 + +## 后果 + +插件无需编辑 `ui-workspace` 即可添加 Session action,同时 core action 保持稳定位置,外部冲突沿用 slot 注册表已有的 id 与 priority 规则。打包贡献项使用 `MenuAction`;动态贡献项自有其 markup,并须在执行操作后调用 `dismiss()`。所有插件 action 都保留在次级行菜单内,直到观察到的规模证明需要新层级。 diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index cd5d7d24e1..6aeb3cb01f 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -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/slots.md -slots.md: c441557092d0273c7beebd222ed7ca329b02c0df -slots.zh.md: 48aafad0042e06f7a6945be4768249dfa4b5aab1 +slots.md: 0143fd713c856d17cb3d2e77188155c46983e106 +slots.zh.md: 18a52f954a7b065504de990e34fc42f536868e4d diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index c441557092..0143fd713c 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -116,7 +116,8 @@ root │ ├─ sidebar.panellist │ ├─ sidebar.footer.action │ ├─ sidebar.workspaces -│ │ └─ sidebar.workspaces.directoryFlow +│ │ ├─ sidebar.workspaces.directoryFlow +│ │ └─ sidebar.workspaces.session.menu.action │ └─ sidebar.settings │ ├─ settings.trigger │ ├─ settings.header diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 48aafad004..18a52f954a 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -116,7 +116,8 @@ root │ ├─ sidebar.panellist │ ├─ sidebar.footer.action │ ├─ sidebar.workspaces -│ │ └─ sidebar.workspaces.directoryFlow +│ │ ├─ sidebar.workspaces.directoryFlow +│ │ └─ sidebar.workspaces.session.menu.action │ └─ sidebar.settings │ ├─ settings.trigger │ ├─ settings.header diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 8d8279ffea..e8e71de00d 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -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-primitives/README.md -README.md: 4bc5d53f1fde5ac65015ef023134b163b351797f -README.zh.md: 481a84150f480c87568a91af0311a3d4fcf2c637 +README.md: 5f45c6ffdc530a0ea7a64a7161c35f992c88ed02 +README.zh.md: 052c1c583c62e4dd06c0366eeadc5b41de86d9ec diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 4bc5d53f1f..5f45c6ffdc 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -40,7 +40,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `Switch` | Two-state toggle, 36×20. `label` is required, so the control cannot ship unnamed. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. | | `Input` | Single-line text entry for search boxes and inline forms. | -| `Menu` | Dropdown of items, separators, and group labels, with nested submenus. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. | +| `Menu`, `MenuAction` | Dropdown of owner-defined items, separators, and group labels, with nested submenus plus optional child actions rendered through `MenuAction`. Injected actions share the same styling, dismissal, focus restoration, submenu reset, and keyboard order. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. | | `Pill` | Selectable capsule button for view switchers and filters; takes `active` and `onClick`. | | `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. | | `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader. `aria-hidden`, so the render site owns the name. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 481a84150f..052c1c583c 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -40,7 +40,7 @@ kind: "package-library" | `Switch` | 36×20 的双态开关。`label` 必填,控件不可能在没有名称的情况下发布。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。 | | `Input` | 单行文本输入,用于搜索框与行内表单。 | -| `Menu` | 由条目、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 | +| `Menu`, `MenuAction` | 由 owner 定义条目、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单,也可通过 `MenuAction` 渲染可选子 action。注入的 action 共享相同样式、关闭行为、焦点恢复、子菜单重置和键盘顺序。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 | | `Pill` | 可选中的胶囊按钮,用于视图切换与筛选器;接受 `active` 与 `onClick`。 | | `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 | | `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading。它是 `aria-hidden` 的,名称由渲染点提供。 | diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index fe769b2d05..8c0b9c280d 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -75,6 +75,17 @@ min-height: 0; } +/* Extension actions are the secondary group after owner-defined rows. */ +.extensionActions:not(:has([role='menuitem'], [role='menuitemcheckbox'], [role='menuitemradio'])) { + display: none; +} + +.extensionSeparator { + margin-top: 4px; + margin-bottom: 4px; + border-top: 0.5px solid var(--dsw-alias-border-l2); +} + .scrollable .viewport { overflow-y: auto; } diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index b165c2da54..7b12caadef 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -1,4 +1,4 @@ -import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode } from 'react' import { createPortal } from 'react-dom' import clsx from 'clsx' @@ -36,6 +36,60 @@ export interface MenuLabel { /** One primary-menu entry: a row, a separator, or a heading label. */ export type MenuEntry = MenuItem | MenuSeparator | MenuLabel +interface MenuActionContextValue { + clearSubmenu: () => void + select: (action: () => void) => void +} + +const MenuActionContext = createContext(null) + +/** Props for an action contributed as a child of {@link Menu}. */ +export interface MenuActionProps { + /** Visible action label. */ + children: ReactNode + /** Leading icon. */ + icon?: ReactNode + /** Whether the action cannot be selected. */ + disabled?: boolean + /** Use the destructive action colors. */ + danger?: boolean + /** Run the action, then close the containing menu and restore focus. */ + onSelect: () => void +} + +/** + * Render one action supplied through a menu extension point. + * + * The action must be a descendant of {@link Menu}. It shares the menu's + * keyboard navigation, selection dismissal, focus restoration, and styling. + * @param props - action presentation and behavior. + * @param props.children - visible action label. + * @param props.icon - optional leading icon. + * @param props.disabled - whether the action cannot be selected. + * @param props.danger - whether to use destructive action colors. + * @param props.onSelect - action to run before the menu closes. + * @returns one menu-item row. + */ +export function MenuAction({ children, icon, disabled = false, danger = false, onSelect }: MenuActionProps) { + const menu = useContext(MenuActionContext) + if (menu === null) throw new Error('MenuAction must be rendered inside Menu') + return ( +
+ +
+ ) +} + function isSeparator(entry: MenuEntry): entry is MenuSeparator { return 'type' in entry && entry.type === 'separator' } @@ -84,6 +138,8 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 } * scroll/resize; return null to skip placement for that frame. * @param props.footer - rows pinned below the scrolling items area, separated * by a hairline; they stay visible while the items above scroll. + * @param props.children - extension actions appended after `items` in a + * separated group. Render each action with {@link MenuAction}. * @param props.selection - how a selected row is marked: a trailing check * (`'check'`, default — figma .Menu_cell) or the hover fill held on the row * with no check (`'fill'`, for icon-labelled rows where a trailing glyph @@ -94,11 +150,12 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 } * document.body outside the owner's DOM subtree. * @returns anchor wrapper with the conditional list. */ -export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, onClose, align = 'start', side = 'bottom', portal = false, closeOnPointerLeave = false, dense = false, compact = false, autoFocus = false, selection = 'check', getAnchorRect, footer, className, listClassName }: { +export function Menu({ open, anchor, items, children, selectedId, selectedIds, onSelect, onClose, align = 'start', side = 'bottom', portal = false, closeOnPointerLeave = false, dense = false, compact = false, autoFocus = false, selection = 'check', getAnchorRect, footer, className, listClassName }: { open: boolean autoFocus?: boolean anchor: ReactNode items: readonly MenuEntry[] + children?: ReactNode footer?: readonly MenuEntry[] selectedId?: string | undefined selectedIds?: readonly string[] | undefined @@ -343,6 +400,15 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o // scroll clip would crop it, so only submenu-free menus get the height cap. const scrollable = !items.some(entry => !isSeparator(entry) && !isLabel(entry) && entry.submenu !== undefined && entry.submenu.length > 0) + const selectExtensionAction = (action: () => void): void => { + try { + action() + } finally { + onClose() + refocusAfterSelection() + } + } + const renderEntry = (entry: MenuEntry) => { if (isSeparator(entry)) { return
@@ -420,6 +486,17 @@ export function Menu({ open, anchor, items, selectedId, selectedIds, onSelect, o >
{items.map(renderEntry)} + {children !== undefined && ( + { setOpenSubmenuId(null) }, + select: selectExtensionAction, + }}> +
+
+ {children} +
+ + )}
{footer !== undefined && footer.length > 0 && (
diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index ba649aeb20..735a2ce33f 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -14,8 +14,8 @@ export type { TagTone } from './Tag.tsx' export { Switch } from './Switch.tsx' export { Checkbox } from './Checkbox.tsx' export { Input } from './Input.tsx' -export { Menu } from './Menu.tsx' -export type { MenuEntry, MenuItem, MenuSeparator, MenuLabel } from './Menu.tsx' +export { Menu, MenuAction } from './Menu.tsx' +export type { MenuActionProps, MenuEntry, MenuItem, MenuSeparator, MenuLabel } from './Menu.tsx' export { useAnchoredMaxHeight } from './useAnchoredMaxHeight.ts' export { useAnchoredPosition } from './useAnchoredPosition.ts' export type { AnchoredPositionOptions } from './useAnchoredPosition.ts' diff --git a/packages/client/ui-primitives/tests/atoms.client.spec.tsx b/packages/client/ui-primitives/tests/atoms.client.spec.tsx index a61ff443b7..c9b3ebf30c 100644 --- a/packages/client/ui-primitives/tests/atoms.client.spec.tsx +++ b/packages/client/ui-primitives/tests/atoms.client.spec.tsx @@ -1,7 +1,8 @@ // @vitest-environment jsdom +import { useState } from 'react' import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' -import { Button, ConnectionIndicator, Input, Menu, Modal, Pill } from '@deepseek-ai/dsh-client-ui-primitives' +import { Button, ConnectionIndicator, Input, Menu, MenuAction, Modal, Pill } from '@deepseek-ai/dsh-client-ui-primitives' import { POINTER_GRACE_MS } from '../src/pointer-grace.ts' afterEach(cleanup) @@ -76,6 +77,39 @@ describe('Menu', () => { expect(onSelect).toHaveBeenCalledWith('a') }) + it('appends extension actions to keyboard order and restores trigger focus after selection', async () => { + const onAction = vi.fn() + function Harness() { + const [open, setOpen] = useState(true) + return ( + trigger} + items={[{ id: 'a', label: 'Alpha', submenu: [{ id: 'a1', label: 'Alpha one' }] }]} + onSelect={() => {}} + onClose={() => { setOpen(false) }} + > + Publish + + ) + } + render() + const trigger = screen.getByRole('button', { name: 'trigger' }) + fireEvent.mouseEnter(screen.getByRole('menuitem', { name: 'Alpha' })) + expect(screen.getByRole('menuitem', { name: 'Alpha one' })).toBeDefined() + expect(screen.getByRole('separator')).toBeDefined() + const publish = screen.getByRole('menuitem', { name: 'Publish' }) + trigger.focus() + fireEvent.keyDown(trigger, { key: 'End' }) + expect(document.activeElement).toBe(publish) + expect(screen.queryByRole('menuitem', { name: 'Alpha one' })).toBeNull() + fireEvent.click(publish) + expect(onAction).toHaveBeenCalledOnce() + expect(screen.queryByRole('menu')).toBeNull() + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(trigger) + }) + it('disabled item does not select; Escape and outside pointerdown close', () => { const onSelect = vi.fn() const onClose = vi.fn() diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 5f4245e471..78b7b9e956 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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-workspace/README.md -README.md: 0125f563e7d0f062dd37f58a218d76dd85b0fa51 -README.zh.md: 9db3ea3a39f7c314ebb7d874d858457f00501bd7 +README.md: 94cd7f6707a88d8c31b7c3987674d5a14b62e21b +README.zh.md: 4a28f0d29744d358163246ad5d523dc25c780b55 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 0125f563e7..94cd7f6707 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -1,5 +1,5 @@ --- -description: "Shared Workspace browser and picker plugin for the dsh web client: grouped or flat session rows, add/rename/reorder, search, fork, archive, and the directory-flow picking hole." +description: "Shared Workspace browser and picker plugin for the dsh web client: grouped or flat session rows, management actions, extensible Session menus, and directory picking." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package lets users browse grouped or flat Session lists, choose a Workspace for a new Session, and manage Workspaces and Sessions through add, rename, reorder, search, fork, archive, and Workspace deletion. Pending interactions appear as warning dots, active scheduled tasks as alarm markers, and subagent-origin Sessions remain hidden. Canonically distinct folder paths remain separate Workspaces. Adding a Workspace requires a composed directory picker; without one, the add action is unavailable. +This package lets users browse grouped or flat Session lists, choose a Workspace for a new Session, and manage Workspaces and Sessions through add, rename, reorder, search, fork, archive, extensible row-menu actions, and Workspace deletion. Pending interactions appear as warning dots, active scheduled tasks as alarm markers, and subagent-origin Sessions remain hidden. Canonically distinct folder paths remain separate Workspaces. Adding a Workspace requires a composed directory picker; without one, the add action is unavailable. ## Table of Contents @@ -47,7 +47,7 @@ Collapsed search is one header action beside the view and add actions: activatin ### Managing sessions -The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action forks at the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. +The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action forks at the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Client plugins can append Session-specific actions to this menu through the ordered `sidebar.workspaces.session.menu.action` slot. Archive commits without a confirmation dialog and retains the Session's account position. View options control visibility: the default hides archived Sessions, Show archived includes them, and Archived only hides ordinary Sessions. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a toast with undo and filter-menu actions. Unarchive removes the archive mark without restoring a pin or changing the saved position. @@ -81,6 +81,25 @@ The package is one composition: both target slots are declared by other plugins, Each registration declares a **directory-flow child hole** (`single` kind: `conversation.hero.workspace.directoryFlow` / `sidebar.workspaces.directoryFlow`) that the composed picker package's client half fills with its picking interaction — the `-native` backend's renderless OS-chooser driver, an in-app browsing dialog under a `-browse` composition. The flat **Add workspace...** action renders only while the surface's hole is occupied; an empty hole means the composition has no picking affordance. This package owns the trigger and the adoption: the occupant reports one picked path per open through the hole's owner conversation (`open`/`busy`/`onPicked`/`onCancel`/`onError`), and the owner adopts it through the object layer, selecting the committed Workspace only after its list projection has refreshed. +### Session menu actions + +An external client plugin injects `sidebar.workspaces.session.menu.action`, registers a fresh `id` and `order`, and renders the shared `MenuAction` primitive. Each action receives the target's `sessionId`, its row `displayTitle` (persisted title, project basename, then Session id), and `dismiss()`. Plugin services remain in the registration's inject closure, and action text comes from the plugin's locale dictionary. Built-in actions stay first in their fixed order. Slot priority sorts before `order`; equal priority and order retain registration order. The secondary group has a semantic separator and is hidden from both presentation and accessibility APIs when empty. + +```tsx +import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' + +ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register( + { name: 'sidebar.workspaces.session.menu.action', id: 'export-session', order: 100 }, + ({ sessionId, displayTitle }) => ( + { exportSession(sessionId) }}> + {t('session.export', { title: displayTitle })} + + ), +)) +``` + +Dynamic client packages cannot import `MenuAction`; they render a `role="menuitem"` control with `React.createElement` and call the supplied `dismiss()` after acting. `dismiss()` closes the menu and restores trigger focus unless the action moved focus elsewhere. + ### View state Once the Workspace baseline is ready, browser-persisted expansion and Session-order records retain only current Workspace ids plus Ungrouped and the flat-list account. `WorkspaceView.sessionIds` supplies real-Workspace membership, not Session display order. View actions receive complete account orders, never filtered rows. A new member without a Session summary waits for that summary, while a saved position survives a temporarily missing summary. Archive visibility is applied only when deriving rows. Pin and drag writes save complete orders; ordinary derivation does not write them. The selected blank Session remains an explicit position write, including during Workspace reconnection, when other saved members are retained until the baseline establishes membership. Ordering remains mounted while the sidebar is a rail or search replaces its body. Last updated derives from current summaries without reading saved positions; equal timestamps use Session ids as a stable tie-break. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 9db3ea3a39..4a28f0d297 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -1,5 +1,5 @@ --- -description: "dsh Web 客户端的共享 Workspace 浏览器与选择器插件:分组或扁平的会话行、添加、重命名、重排序、搜索、fork、归档,以及目录流选取子 slot。" +description: "dsh Web 客户端的共享 Workspace 浏览器与选择器插件:分组或扁平的会话行、管理操作、可扩展 Session 菜单与目录选择。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -本包让用户浏览分组或扁平的 Session 列表、为新 Session 选择 Workspace,并通过添加、重命名、重排序、搜索、fork、归档和删除 Workspace 来管理 Workspace 与 Session。待处理交互显示为警告点,活动定时任务显示为闹钟标识,subagent 来源的 Session 则保持隐藏。规范化后仍有差异的文件夹路径会保留为独立 Workspace。添加 Workspace 需要组合目录选择器;没有目录选择器时,添加操作不可用。 +本包让用户浏览分组或扁平的 Session 列表、为新 Session 选择 Workspace,并通过添加、重命名、重排序、搜索、fork、归档、可扩展行菜单操作和删除 Workspace 来管理 Workspace 与 Session。待处理交互显示为警告点,活动定时任务显示为闹钟标识,subagent 来源的 Session 则保持隐藏。规范化后仍有差异的文件夹路径会保留为独立 Workspace。添加 Workspace 需要组合目录选择器;没有目录选择器时,添加操作不可用。 ## 目录 @@ -47,7 +47,7 @@ kind: "package-reference" ### 管理会话 -Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 在源会话最后一个已完成轮次处 fork,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。 +Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 在源会话最后一个已完成轮次处 fork,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。客户端插件可通过有序 `sidebar.workspaces.session.menu.action` slot 向此菜单追加 Session 专属 action。 Archive 不经确认对话框直接提交,并保留 Session 的记账位置。视图选项控制显隐:默认隐藏已归档 Session,显示已归档会将其纳入列表,仅显示已归档则隐藏普通 Session。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后,toast 提供撤销与打开筛选菜单的操作。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。 @@ -81,6 +81,25 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 每个注册各自声明一个**目录流子 slot**(`single` kind:`conversation.hero.workspace.directoryFlow`/`sidebar.workspaces.directoryFlow`),由组合的选择器包 client half 填入其选取交互——`-native` 后端的无渲染 OS 选择器驱动,`-browse` 组合下则是应用内浏览对话框。平铺显示的**添加工作区…** 操作仅在当前界面的 slot 被占用时渲染;slot 为空意味着该组合没有目录选择能力。本包持有触发与接纳:占用方通过 slot 的属主交互约定(`open`/`busy`/`onPicked`/`onCancel`/`onError`)每次打开上报一个所选路径,owner 通过对象层接纳它,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace。 +### Session 菜单 action + +外部客户端插件注入 `sidebar.workspaces.session.menu.action`,注册新的 `id` 与 `order`,并渲染共享 `MenuAction` primitive。每个 action 接收目标的 `sessionId`、行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id)与 `dismiss()`;插件服务仍留在注册项的 inject 闭包中,action 文案来自插件自己的 locale 字典。内置 action 按固定顺序保持在前。Slot priority 先于 `order` 排序;priority 与 order 都相同时保留注册顺序。次级分组带有语义分隔线;没有 action 时,它在视觉与无障碍 API 中都隐藏。 + +```tsx +import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' + +ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register( + { name: 'sidebar.workspaces.session.menu.action', id: 'export-session', order: 100 }, + ({ sessionId, displayTitle }) => ( + { exportSession(sessionId) }}> + {t('session.export', { title: displayTitle })} + + ), +)) +``` + +动态客户端包无法导入 `MenuAction`;它们通过 `React.createElement` 渲染 `role="menuitem"` 控件,并在执行操作后调用传入的 `dismiss()`。`dismiss()` 会关闭菜单,并在 action 未自行移动焦点时把焦点还给触发按钮。 + ### 视图状态 Workspace 基线就绪后,浏览器持久化的展开状态和 Session 顺序记录只保留当前 Workspace id、Ungrouped 和单列表记账。`WorkspaceView.sessionIds` 提供真实 Workspace 的成员关系,而不提供 Session 显示顺序。视图操作接收完整记账顺序,而不是筛选后的行。尚无 Session 摘要的新成员会等待摘要,已保存的位置则在摘要暂时缺失时保留。归档显隐仅在派生行时应用。置顶和拖拽写入完整顺序,普通派生不执行写入。当前选中的空白 Session 仍是一次显式位置写入;Workspace 重连时同样如此,此时保留其他已保存成员,直到基线确定成员关系。侧边栏收成窄栏或搜索替代列表主体时,排序仍保持挂载。最近更新从当前摘要派生,不读取已保存位置;时间相同时按 Session id 稳定排序。 diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index f8d50e58d5..b991b08a93 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -8,8 +8,8 @@ * - WorkspacePicker fills the conversation empty-state hole (menu + error * dialog shared with the browser). * - * Each registration also declares one **directory-flow hole** (`single` - * kind): the slot a composed picker package's client half fills with its + * Both registrations declare a **directory-flow hole** (`single` kind): the + * slot a composed picker package's client half fills with its * picking interaction — a renderless native-chooser driver or an in-app * browsing dialog. ui-workspace owns the trigger (the "Add workspace…" * entry, present only while the hole is occupied) and the adoption @@ -20,7 +20,8 @@ * leaves the surface with no add affordance at all. * Two holes exist because the two menu surfaces are independent slot entries * and a hole has exactly one declaring entry — they carry the same owner - * contract and the same occupant. + * contract and the same occupant. WorkspaceBrowser also declares the ordered + * Session-menu action list that client plugins can extend. */ import type { HostObservable, PropsHooks, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pull the owner SlotMap merges into programs that resolve the @@ -51,12 +52,35 @@ export interface DirectoryFlowOwnerProps { onError: (message: string) => void } +/** Point-in-time Session row information supplied to each menu action. */ +export interface SessionMenuActionOwnerProps { + /** Session targeted by the open row menu. */ + sessionId: SessionId + /** Row display title: persisted title, project basename, or Session id. */ + displayTitle: string + /** + * Close the menu and restore trigger focus when the action leaves focus behind. + * + * An acting item not rendered with `MenuAction` MUST call this after its + * operation. `MenuAction` performs the same close-and-refocus behavior. + */ + dismiss: () => void +} + declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Directory-flow hole under the conversation empty-state picker (declared by the WorkspacePicker entry). */ 'conversation.hero.workspace.directoryFlow': { kind: 'single'; scope: 'root'; owner: DirectoryFlowOwnerProps } /** Directory-flow hole under the sidebar browsing region (declared by the WorkspaceBrowser entry). */ 'sidebar.workspaces.directoryFlow': { kind: 'single'; scope: 'root'; owner: DirectoryFlowOwnerProps } + /** + * Ordered third-party actions below the built-in Session row-menu actions. + * Registrations use a fresh id; priority precedes order, with registration + * order breaking ties. Packaged plugins render `MenuAction`; dynamic markup + * calls the owner `dismiss()` after acting. An empty list has no visible or + * accessible secondary group. + */ + 'sidebar.workspaces.session.menu.action': { kind: 'list'; scope: 'root'; owner: SessionMenuActionOwnerProps } } } @@ -147,7 +171,9 @@ export type WorkspaceBrowserInjected = { /** Full browser props: shell owner share + viewing store + injected actions + the locale seat. */ export type WorkspaceBrowserProps = PropsRuntime<'sidebar.workspaces'> - & PropsRenderSlots<'sidebar.workspaces.directoryFlow'> + & PropsRenderSlots< + 'sidebar.workspaces.directoryFlow' | 'sidebar.workspaces.session.menu.action' + > & PropsStore> & Omit & PropsHooks diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 44d65efb20..f4e23df96f 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -5,7 +5,8 @@ * (`conversation.hero.workspace` — both hero forms). Both read real Host * Workspaces through the global useWorkspaces hook, and each declares its * own `single` directory-flow child hole for the composed picker package's - * client half (see the contract module doc). Export discipline: + * client half. WorkspaceBrowser additionally declares the ordered Session + * menu-action list (see the contract module doc). Export discipline: * packages/client/AGENTS.md. */ import type { Context } from '@deepseek-ai/cordis' @@ -33,7 +34,8 @@ import { en, zh, type WorkspaceKey } from './locales.ts' export type { UiWorkspace } from './navigation.ts' export type { DirectoryFlowOwnerProps, DirectoryFlowSlotName, DirectoryPickingHooks, DirectoryPickingInjected, - WorkspaceBrowserInjected, WorkspaceBrowserProps, WorkspacePickerInjected, WorkspacePickerProps, + SessionMenuActionOwnerProps, WorkspaceBrowserInjected, WorkspaceBrowserProps, + WorkspacePickerInjected, WorkspacePickerProps, } from './contract/slots.ts' export type { WorkspaceKey } from './locales.ts' @@ -142,12 +144,15 @@ export function apply(ctx: Context): void { createWorkspace: input => workspaces.create(input), hooks: { directoryFlow: pickerFlowSource }, }) - // Each registration declares its directory-flow child in the same call; - // slot injection follows both the owner and declaration HMR lifetimes. + // Each registration declares its owned children in the same call; slot + // injection follows both the owner and declaration HMR lifetimes. ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register( { name: 'sidebar.workspaces', - children: { 'sidebar.workspaces.directoryFlow': { kind: 'single', scope: 'root' } }, + children: { + 'sidebar.workspaces.directoryFlow': { kind: 'single', scope: 'root' }, + 'sidebar.workspaces.session.menu.action': { kind: 'list', scope: 'root' }, + }, store: createWorkspaceViewStore(), inject: browserInjected, locale: NS, diff --git a/packages/client/ui-workspace/src/client/rows/Rows.tsx b/packages/client/ui-workspace/src/client/rows/Rows.tsx index 6a19c0c9eb..019efede50 100644 --- a/packages/client/ui-workspace/src/client/rows/Rows.tsx +++ b/packages/client/ui-workspace/src/client/rows/Rows.tsx @@ -2,10 +2,13 @@ * Workspace browser tree row components (figma Cell set 14:3080): pure presentational — * all data and callbacks arrive via props. Hover swaps (folder->chevron, * time->ellipsis, action buttons) are CSS-only, and a session row's clipped - * title is scrolled programmatically while the row is hovered. Session and - * Workspace hover cards are suppressed while a menu is open. + * title is scrolled programmatically while the row is hovered. Row ... menus are + * visual-only except workspace Rename/Delete and the Session built-ins plus + * ordered plugin actions; the session and workspace hover cards are suppressed + * while a menu is open. */ import { useEffect, useRef, useState } from 'react' +import type { ReactNode } from 'react' import clsx from 'clsx' import { HoverCard, IconAlarmClockOutlineRegular, IconArchiveOutlineRegular, IconBranchOutlineRegular, @@ -15,7 +18,7 @@ import { } from '@deepseek-ai/dsh-client-ui-primitives' import type { StateDotState } from '@deepseek-ai/dsh-client-ui-primitives' import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path' -import type { WorkspaceBrowserProps } from '../contract/slots.ts' +import type { SessionMenuActionOwnerProps, WorkspaceBrowserProps } from '../contract/slots.ts' import type { GroupNode, SearchResultNode, SessionNode } from '../tree.ts' import css from './Rows.module.css' @@ -461,6 +464,7 @@ export function SearchResultItem({ result, currentId, onOpen, onUnarchive, t }: * @param props.onRename - open the session rename dialog (id + current title). * @param props.onFork - fork a session at its last completed turn. * @param props.onArchive - archive a session by id. + * @param props.renderSessionMenuActions - render ordered plugin actions after the built-in actions. * @param props.onReveal - scroll this row into view after search navigation, then acknowledge it. * @param props.drag - optional row-drag target wiring; blank rows cannot start a drag. * @param props.flat - omit the empty status slot in the hierarchy-free flat list. @@ -468,7 +472,7 @@ export function SearchResultItem({ result, currentId, onOpen, onUnarchive, t }: * @returns the session row. */ export function SessionNodeItem({ - node, currentId, now, onOpen, onRename, onFork, onArchive, onUnarchive, onPin, onReveal, drag, flat = false, t, + node, currentId, now, onOpen, onRename, onFork, onArchive, onUnarchive, onPin, renderSessionMenuActions, onReveal, drag, flat = false, t, }: { node: SessionNode currentId: string | undefined @@ -484,6 +488,8 @@ export function SessionNodeItem({ onUnarchive: (id: SessionNode['id']) => void /** Pin or unpin this session (row menu action; `pin` false unpins). */ onPin: (id: SessionNode['id'], pin: boolean) => void + /** Render ordered plugin actions after the built-in row-menu actions. */ + renderSessionMenuActions?: ((owner: SessionMenuActionOwnerProps) => ReactNode) | undefined /** Scroll this row into view after search navigation, then acknowledge it. */ onReveal?: (() => void) | undefined /** Present on reorderable-list rows so every row can remain a drop target. */ @@ -505,6 +511,7 @@ export function SessionNodeItem({ const [menuOpen, setMenuOpen] = useState(false) const rowRef = useRef(null) const titleRef = useRef(null) + const menuTriggerRef = useRef(null) useEffect(() => { if (onReveal === undefined) return rowRef.current?.scrollIntoView({ block: 'nearest' }) @@ -529,6 +536,13 @@ export function SessionNodeItem({ { id: 'fork', label: t('menu.fork'), icon: }, { id: 'archive', label: t('menu.archiveSession'), icon: }, ] + const dismissSessionMenu = (): void => { + setMenuOpen(false) + queueMicrotask(() => { + const active = document.activeElement + if (active === null || active === document.body) menuTriggerRef.current?.focus() + }) + } // Figma session cell: pad 8, status slot 16, then a 4px title gap. const ownRow = (
)} - /> + > + {renderSessionMenuActions?.({ + sessionId: node.id, + displayTitle: row.title, + dismiss: dismissSessionMenu, + })} + + ) + : ( + { selected(id, sessionId, displayTitle) }}>{label} + ), + ) + } + registerAction('later', 20, 'Later action') + registerAction('earlier', 10, 'Earlier action', true) + const view = runtime.renderRoot() + + const row = (await view.findByText('Session title')).closest('[role="treeitem"]')! + fireEvent.click(within(row as HTMLElement).getByLabelText('会话“Session title”的操作')) + expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ + '重命名', '分叉会话', '归档会话', 'Earlier action', 'Later action', + ]) + fireEvent.click(view.getByRole('menuitem', { name: 'Earlier action' })) + expect(selected).toHaveBeenCalledWith('earlier', SID, 'Session title') + expect(view.queryByRole('menu')).toBeNull() + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(within(row as HTMLElement).getByLabelText('会话“Session title”的操作')) + await runtime.dispose() + }) + it('renames via the row menu: binding.session.rename fires, the dialog closes, the row re-labels from the list', async () => { const runtime = await createRuntime() const rename = vi.fn(async title => ({ diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index 680a9dcd74..ba510da94f 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -5,6 +5,8 @@ import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/clie import type { SessionId } from '@deepseek-ai/dsh-session/types' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' +import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' +import type { SessionMenuActionOwnerProps } from '../src/client/contract/slots.ts' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { RowDragProps } from '../src/client/rows/Rows.tsx' import { ProjectRowItem, SearchResultItem, SessionNodeItem } from '../src/client/rows/Rows.tsx' @@ -550,6 +552,33 @@ describe('workspace browser rows', () => { expect(screen.queryByRole('menu')).toBeNull() }) + it('appends plugin actions after built-ins with the Session owner props', () => { + const onOpen = vi.fn() + const onPluginAction = vi.fn() + const renderSessionMenuActions = vi.fn(({ sessionId, displayTitle }: SessionMenuActionOwnerProps) => ( + { onPluginAction(sessionId, displayTitle) }}>Export + )) + const node: SessionNode = { + id: sid('s1'), title: 'One', blank: false, running: false, + runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, + } + render() + + fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) + const actions = screen.getAllByRole('menuitem') + expect(actions.map(action => action.textContent)).toEqual(['重命名', '分叉会话', '归档会话', 'Export']) + fireEvent.click(screen.getByRole('menuitem', { name: 'Export' })) + expect(renderSessionMenuActions).toHaveBeenCalled() + const owner = renderSessionMenuActions.mock.calls.at(-1)?.[0] + expect(owner?.sessionId).toBe(node.id) + expect(owner?.displayTitle).toBe('One') + expect(typeof owner?.dismiss).toBe('function') + expect(onPluginAction).toHaveBeenCalledWith(node.id, 'One') + expect(screen.queryByRole('menu')).toBeNull() + expect(onOpen).not.toHaveBeenCalled() + }) it('shows the hover card after the dwell and suppresses it while the row menu is open', () => { vi.useFakeTimers() diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 9d8b9b731d..9fda33bda9 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -696,7 +696,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace.directoryFlow\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:57', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:73', }, { key: 'conversation.input.attachments', @@ -3236,7 +3236,57 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.directoryFlow\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:59', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:75', + }, + { + key: 'sidebar.workspaces.session.menu.action', + kind: 'list', + scope: 'root', + summary: 'Ordered third-party actions below the built-in Session row-menu actions.', + doc: 'Ordered third-party actions below the built-in Session row-menu actions.\nRegistrations use a fresh id; priority precedes order, with registration\norder breaking ties. Packaged plugins render `MenuAction`; dynamic markup\ncalls the owner `dismiss()` after acting. An empty list has no visible or\naccessible secondary group.', + registerOptions: [ + { + name: 'id', + requirement: 'required', + type: 'string', + doc: 'Your cell key. Use an id of your own: a fresh id is added beside the shipped entries, while reusing a shipped id puts you in THAT cell and replaces it. Owners that filter by id address you by it.', + }, + { + name: 'order', + requirement: 'optional', + type: 'number', + doc: 'Position among the entries, ascending (default 0).', + }, + { + name: 'label', + requirement: 'optional', + type: 'string | (() => string)', + doc: 'Display text where the owner projects one (nav rows, tabs). A thunk is re-read on every projection, so localized text follows the active locale without re-registering.', + }, + ], + ownerProps: [ + '/** Point-in-time Session row information supplied to each menu action. */\nexport interface SessionMenuActionOwnerProps {\n /** Session targeted by the open row menu. */\n sessionId: SessionId\n /** Row display title: persisted title, project basename, or Session id. */\n displayTitle: string\n /**\n * Close the menu and restore trigger focus when the action leaves focus behind.\n *\n * An acting item not rendered with `MenuAction` MUST call this after its\n * operation. `MenuAction` performs the same close-and-refocus behavior.\n */\n dismiss: () => void\n}', + ], + ownerPropsReferences: [ + 'SessionId', + ], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'sidebar.workspaces\' (client-ui-workspace), so it exists while that entry is mounted', + occupants: [], + replaceRisk: 'none', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.session.menu.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.action\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:83', }, { key: 'tool.call.images', From cfcd3f3b0ed3b4749c12e1c0b6d3e44d6b351858 Mon Sep 17 00:00:00 2001 From: Magolor Date: Thu, 17 Sep 2026 18:17:06 +0800 Subject: [PATCH 14/24] test(client): cover session action focus handoff --- .../ui-workspace/tests/rows.client.spec.tsx | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index ba510da94f..07f6a315dd 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -552,24 +552,36 @@ describe('workspace browser rows', () => { expect(screen.queryByRole('menu')).toBeNull() }) - it('appends plugin actions after built-ins with the Session owner props', () => { + it('appends plugin actions after built-ins with the Session owner props', async () => { const onOpen = vi.fn() const onPluginAction = vi.fn() - const renderSessionMenuActions = vi.fn(({ sessionId, displayTitle }: SessionMenuActionOwnerProps) => ( - { onPluginAction(sessionId, displayTitle) }}>Export + const renderSessionMenuActions = vi.fn(({ + sessionId, displayTitle, dismiss, + }: SessionMenuActionOwnerProps) => ( + )) const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, } - render() + render(<> + + + ) fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) const actions = screen.getAllByRole('menuitem') expect(actions.map(action => action.textContent)).toEqual(['重命名', '分叉会话', '归档会话', 'Export']) fireEvent.click(screen.getByRole('menuitem', { name: 'Export' })) + await act(async () => { await Promise.resolve() }) expect(renderSessionMenuActions).toHaveBeenCalled() const owner = renderSessionMenuActions.mock.calls.at(-1)?.[0] expect(owner?.sessionId).toBe(node.id) @@ -577,6 +589,7 @@ describe('workspace browser rows', () => { expect(typeof owner?.dismiss).toBe('function') expect(onPluginAction).toHaveBeenCalledWith(node.id, 'One') expect(screen.queryByRole('menu')).toBeNull() + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Destination' })) expect(onOpen).not.toHaveBeenCalled() }) From fec5c888c4fc35b0c872193af8d8d93e39217319 Mon Sep 17 00:00:00 2001 From: Magolor Date: Thu, 17 Sep 2026 22:08:15 +0800 Subject: [PATCH 15/24] fix(client): preserve session action slot contract --- ...17-session-row-menu-actions-slot.i18n.yaml | 4 +-- ...026-09-17-session-row-menu-actions-slot.md | 4 +-- ...-09-17-session-row-menu-actions-slot.zh.md | 4 +-- .../client/ui-primitives/src/Menu.module.css | 2 +- packages/client/ui-workspace/README.i18n.yaml | 4 +-- packages/client/ui-workspace/README.md | 4 +-- packages/client/ui-workspace/README.zh.md | 4 +-- .../ui-workspace/src/client/contract/slots.ts | 29 +++++++++++++--- .../ui-workspace/src/client/rows/Rows.tsx | 12 +++---- .../src/client/rows/WorkspaceBrowser.tsx | 19 ++++++----- .../tests/rename-assembly.client.spec.tsx | 14 ++++++-- .../ui-workspace/tests/rows.client.spec.tsx | 34 +++++++++++-------- .../src/client/slot-catalog.ts | 6 ++-- scripts/gen-client-catalog.spec.ts | 7 ++++ scripts/gen-client-catalog.ts | 17 ++++++++++ 15 files changed, 112 insertions(+), 52 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml index 6d120db585..39eecfb4a1 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml @@ -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-09-17-session-row-menu-actions-slot.md -2026-09-17-session-row-menu-actions-slot.md: 63a5c467cf79fa1d5d6d542d36fd4881215017a5 -2026-09-17-session-row-menu-actions-slot.zh.md: d17715d4253b28439a980dddf36f7fa4c0e324b4 +2026-09-17-session-row-menu-actions-slot.md: a7524c71caa2ba34b836cb1c82eaa0a6c610799e +2026-09-17-session-row-menu-actions-slot.zh.md: 197bbe012e197efa40c1049f80056f5f64fb20ab diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md index 63a5c467cf..a7524c71ca 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md @@ -12,11 +12,11 @@ The Session row menu was a closed list of actions owned by `ui-workspace`. A thi `ui-workspace` declares the root-scoped ordered-list slot `sidebar.workspaces.session.menu.action` under its `sidebar.workspaces` registration. Each contribution receives the target `sessionId`, the row `displayTitle` (persisted title, project basename, then Session id), and a `dismiss()` callback; the contributing plugin keeps its services and mutations in its own registration closure. -The shared `MenuAction` primitive renders contributed rows inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Dynamic client packages cannot import the primitive, so their own `role="menuitem"` control calls the owner `dismiss()` after acting. +The shared `MenuAction` primitive renders contributed rows inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Import-free dynamic client packages instead render a native `button[role="menuitem"]` and call the owner `dismiss()` after acting. ### Ordering and disclosure -Rename, Fork, and Archive remain a fixed owner-defined group at the top. Contributions form a semantically separated group below them and sort by slot priority, then `order`, then registration order. The group is visually and accessibly hidden when empty. The existing ellipsis menu remains the only disclosure layer; nested “More…” grouping is not part of the contract. +Rename, Fork, and Archive remain a fixed owner-defined group at the top. Contributions form a semantically separated group below them and sort by lower slot priority, lower `order`, then registration sequence. The dynamic browser-half facade gives each registration a distinct decreasing priority, so newer dynamic registrations precede older ones regardless of `order`; packaged registrations at equal priority use `order`. The group is visually and accessibly hidden when empty. The existing ellipsis menu remains the only disclosure layer; nested “More…” grouping is not part of the contract. ## Verification diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md index d17715d425..197bbe012e 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md @@ -12,11 +12,11 @@ Session 行菜单原本是由 `ui-workspace` 持有的封闭 action 列表。第 `ui-workspace` 在其 `sidebar.workspaces` 注册项下声明 root-scoped 有序列表 slot `sidebar.workspaces.session.menu.action`。每个贡献项接收目标 `sessionId`、行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id)与 `dismiss()` 回调;贡献插件将自身服务与 mutation 保留在自己的注册闭包中。 -共享 `MenuAction` primitive 在 `Menu` 内渲染贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。动态客户端包无法导入该 primitive,因此其自有 `role="menuitem"` 控件需在执行操作后调用 owner 的 `dismiss()`。 +共享 `MenuAction` primitive 在 `Menu` 内渲染贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。无法导入该 primitive 的动态客户端包改为渲染原生 `button[role="menuitem"]`,并在执行操作后调用 owner 的 `dismiss()`。 ### 排序与渐进披露 -Rename、Fork 与 Archive 作为固定的 owner-defined 分组保持在顶部。贡献项在下方形成带语义分隔的分组,依次按 slot priority、`order` 与注册顺序排列。空分组在视觉与无障碍 API 中均隐藏。现有省略号菜单仍是唯一的渐进披露层;嵌套「More…」分组不属于此约定。 +Rename、Fork 与 Archive 作为固定的 owner-defined 分组保持在顶部。贡献项在下方形成带语义分隔的分组,依次按较低的 slot priority、较低的 `order` 与注册顺序排列。动态 browser-half facade 为每次注册分配不同且递减的 priority,因此较新的动态注册无视 `order` 排在较旧注册之前;相同 priority 的打包注册才使用 `order`。空分组在视觉与无障碍 API 中均隐藏。现有省略号菜单仍是唯一的渐进披露层;嵌套「More…」分组不属于此约定。 ## 验证 diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index 8c0b9c280d..19e48b7509 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -76,7 +76,7 @@ } /* Extension actions are the secondary group after owner-defined rows. */ -.extensionActions:not(:has([role='menuitem'], [role='menuitemcheckbox'], [role='menuitemradio'])) { +.extensionActions:not(:has(button[role='menuitem'])) { display: none; } diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 78b7b9e956..bf32710936 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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-workspace/README.md -README.md: 94cd7f6707a88d8c31b7c3987674d5a14b62e21b -README.zh.md: 4a28f0d29744d358163246ad5d523dc25c780b55 +README.md: 5bc338740668d4d927ca10bc02969334710eaf0e +README.zh.md: 8acaff5eca129a4398aa38c6d2576c327ae79e64 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 94cd7f6707..5bc3387406 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -83,7 +83,7 @@ Each registration declares a **directory-flow child hole** (`single` kind: `conv ### Session menu actions -An external client plugin injects `sidebar.workspaces.session.menu.action`, registers a fresh `id` and `order`, and renders the shared `MenuAction` primitive. Each action receives the target's `sessionId`, its row `displayTitle` (persisted title, project basename, then Session id), and `dismiss()`. Plugin services remain in the registration's inject closure, and action text comes from the plugin's locale dictionary. Built-in actions stay first in their fixed order. Slot priority sorts before `order`; equal priority and order retain registration order. The secondary group has a semantic separator and is hidden from both presentation and accessibility APIs when empty. +An external client plugin injects `sidebar.workspaces.session.menu.action`, registers a fresh `id` and `order`, and renders the shared `MenuAction` primitive. Each action receives the target's `sessionId`, its row `displayTitle` (persisted title, project basename, then Session id), and `dismiss()`. Plugin services remain in the registration's inject closure, and action text comes from the plugin's locale dictionary. Built-in actions stay first in their fixed order. Plugin actions sort by lower priority, lower `order`, then registration sequence. The dynamic browser-half facade assigns every registration a distinct decreasing priority, so newer dynamic registrations precede older ones regardless of `order`; packaged registrations at the same priority use `order`. The secondary group has a semantic separator and is hidden from both presentation and accessibility APIs when empty. ```tsx import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' @@ -98,7 +98,7 @@ ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.regis )) ``` -Dynamic client packages cannot import `MenuAction`; they render a `role="menuitem"` control with `React.createElement` and call the supplied `dismiss()` after acting. `dismiss()` closes the menu and restores trigger focus unless the action moved focus elsewhere. +Import-free dynamic client packages render a native ` )} > - {renderSessionMenuActions?.({ + {renderSlot?.('sidebar.workspaces.session.menu.action', { sessionId: node.id, displayTitle: row.title, dismiss: dismissSessionMenu, diff --git a/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx index dd9ce3577d..26c581191a 100644 --- a/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx @@ -24,7 +24,8 @@ import type { } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type { SessionMenuActionOwnerProps, WorkspaceBrowserProps } from '../contract/slots.ts' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { WorkspaceBrowserProps } from '../contract/slots.ts' import type { ArchivedFilter, GroupNode, SessionNode, SessionOrderBy, SessionRowState } from '../tree.ts' import { deriveFlat, deriveGroups, deriveSearchResults, orderByRecency, owningGroupKey, owningParentFolder, @@ -268,7 +269,7 @@ type SessionTreeProps = Pick< /** Pin or unpin a session (row menu action; `pin` false unpins). */ onSessionPin: (sessionId: SessionNode['id'], pin: boolean) => void /** Render ordered plugin actions in each Session row menu. */ - renderSessionMenuActions: (owner: SessionMenuActionOwnerProps) => ReactNode + renderSlot: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] /** One Session chosen from search that must be exposed and scrolled into view. */ revealSessionId?: SessionId | undefined /** Acknowledge that the chosen Session row has been revealed. */ @@ -281,7 +282,7 @@ function SessionTree({ rowState, workspaceReady, animationResetKey, usePanelInfo, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onSessionUnarchive, onSessionPin, - renderSessionMenuActions, + renderSlot, insertWorkspaceBefore, nestWorkspaces, groupExpansion, setGroupExpanded, setSessionOrder, home, t, @@ -566,7 +567,7 @@ function SessionTree({ onArchive={onSessionArchive} onUnarchive={onSessionUnarchive} onPin={onSessionPin} - renderSessionMenuActions={renderSessionMenuActions} + renderSlot={renderSlot} onReveal={node.id === revealSessionId && group.key === revealGroup ? () => { onSessionRevealed(node.id) } : undefined} @@ -617,7 +618,7 @@ function SessionTree({ function FlatList({ list, sessionIds, rowState, useSessionStatus, open, forkSession, onSessionRename, onSessionArchive, onSessionUnarchive, onSessionPin, - renderSessionMenuActions, + renderSlot, usePanelInfo, setSessionOrder, workspaceReady, animationResetKey, revealSessionId, onSessionRevealed, t, }: Pick< @@ -629,7 +630,7 @@ function FlatList({ | 'onSessionArchive' | 'onSessionUnarchive' | 'onSessionPin' - | 'renderSessionMenuActions' + | 'renderSlot' | 'usePanelInfo' | 'setSessionOrder' | 'workspaceReady' @@ -690,7 +691,7 @@ function FlatList({ onArchive={onSessionArchive} onUnarchive={onSessionUnarchive} onPin={onSessionPin} - renderSessionMenuActions={renderSessionMenuActions} + renderSlot={renderSlot} onReveal={node.id === revealSessionId ? () => { onSessionRevealed(node.id) } : undefined} @@ -1425,7 +1426,7 @@ export function WorkspaceBrowser({ open={guardedOpen} forkSession={forkSession} onSessionRename={onSessionRename} onSessionArchive={onSessionArchive} onSessionUnarchive={onSessionUnarchive} onSessionPin={onSessionPin} - renderSessionMenuActions={owner => renderSlot('sidebar.workspaces.session.menu.action', owner)} + renderSlot={renderSlot} setSessionOrder={saveSessionOrder} revealSessionId={revealSessionId} onSessionRevealed={acknowledgeSessionReveal} @@ -1441,7 +1442,7 @@ export function WorkspaceBrowser({ onSessionArchive={onSessionArchive} onSessionUnarchive={onSessionUnarchive} onSessionPin={onSessionPin} - renderSessionMenuActions={owner => renderSlot('sidebar.workspaces.session.menu.action', owner)} + renderSlot={renderSlot} forkSession={forkSession} workspaces={orderedWorkspaces} ungroupedSessionIds={orderedUngroupedSessionIds} diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index e3b109b0dd..c878b15d20 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -95,15 +95,23 @@ describe('session rename through the assembled browser', () => { const view = runtime.renderRoot() const row = (await view.findByText('Session title')).closest('[role="treeitem"]')! - fireEvent.click(within(row as HTMLElement).getByLabelText('会话“Session title”的操作')) + const trigger = within(row as HTMLElement).getByLabelText('会话“Session title”的操作') + fireEvent.click(trigger) expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ '重命名', '分叉会话', '归档会话', 'Earlier action', 'Later action', ]) - fireEvent.click(view.getByRole('menuitem', { name: 'Earlier action' })) + const later = view.getByRole('menuitem', { name: 'Later action' }) + const earlier = view.getByRole('menuitem', { name: 'Earlier action' }) + trigger.focus() + fireEvent.keyDown(trigger, { key: 'End' }) + expect(document.activeElement).toBe(later) + fireEvent.keyDown(later, { key: 'ArrowUp' }) + expect(document.activeElement).toBe(earlier) + fireEvent.click(earlier) expect(selected).toHaveBeenCalledWith('earlier', SID, 'Session title') expect(view.queryByRole('menu')).toBeNull() await act(async () => { await Promise.resolve() }) - expect(document.activeElement).toBe(within(row as HTMLElement).getByLabelText('会话“Session title”的操作')) + expect(document.activeElement).toBe(trigger) await runtime.dispose() }) diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index 07f6a315dd..fdf5dfe9ef 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -6,6 +6,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionMenuActionOwnerProps } from '../src/client/contract/slots.ts' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { RowDragProps } from '../src/client/rows/Rows.tsx' @@ -555,17 +556,22 @@ describe('workspace browser rows', () => { it('appends plugin actions after built-ins with the Session owner props', async () => { const onOpen = vi.fn() const onPluginAction = vi.fn() - const renderSessionMenuActions = vi.fn(({ - sessionId, displayTitle, dismiss, - }: SessionMenuActionOwnerProps) => ( - - )) + const rendered = vi.fn() + const renderSlot: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] = (name, value) => { + // The generic framework signature cannot narrow its owner from a runtime key in a test stub. + const owner = value as unknown as SessionMenuActionOwnerProps + const { sessionId, displayTitle, dismiss } = owner + rendered(name, value) + return ( + + ) + } const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, @@ -574,7 +580,7 @@ describe('workspace browser rows', () => { + renderSlot={renderSlot} t={t} /> ) fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) @@ -582,8 +588,8 @@ describe('workspace browser rows', () => { expect(actions.map(action => action.textContent)).toEqual(['重命名', '分叉会话', '归档会话', 'Export']) fireEvent.click(screen.getByRole('menuitem', { name: 'Export' })) await act(async () => { await Promise.resolve() }) - expect(renderSessionMenuActions).toHaveBeenCalled() - const owner = renderSessionMenuActions.mock.calls.at(-1)?.[0] + expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.menu.action', expect.any(Object)) + const owner = rendered.mock.calls.at(-1)?.[1] as SessionMenuActionOwnerProps | undefined expect(owner?.sessionId).toBe(node.id) expect(owner?.displayTitle).toBe('One') expect(typeof owner?.dismiss).toBe('function') diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index 9fda33bda9..c178adb2ff 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -3243,7 +3243,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ kind: 'list', scope: 'root', summary: 'Ordered third-party actions below the built-in Session row-menu actions.', - doc: 'Ordered third-party actions below the built-in Session row-menu actions.\nRegistrations use a fresh id; priority precedes order, with registration\norder breaking ties. Packaged plugins render `MenuAction`; dynamic markup\ncalls the owner `dismiss()` after acting. An empty list has no visible or\naccessible secondary group.', + doc: 'Ordered third-party actions below the built-in Session row-menu actions.\nRegistrations use a fresh id and sort by lower priority, lower order, then\nregistration sequence. Dynamic browser halves receive distinct decreasing\npriorities, so newer dynamic registrations precede older ones regardless\nof order. Packaged plugins render `MenuAction`; import-free dynamic markup\nrenders a `button[role="menuitem"]` and calls the owner `dismiss()` after\nacting. An empty list has no visible or accessible secondary group.', registerOptions: [ { name: 'id', @@ -3285,8 +3285,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ declaredBy: 'an entry in \'sidebar.workspaces\' (client-ui-workspace), so it exists while that entry is mounted', occupants: [], replaceRisk: 'none', - example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.session.menu.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.action\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:83', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n const copyLabel = \'Copy Session ID\' // Localize in the contributing package.\n ctx.slots.inject(\'sidebar.workspaces.session.menu.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.action\', id: \'copy-session-id\', order: 100 },\n ({ sessionId, dismiss }) => React.createElement(\n \'button\',\n {\n type: \'button\',\n role: \'menuitem\',\n onClick: () => { navigator.clipboard.writeText(sessionId).then(dismiss, dismiss) },\n },\n copyLabel,\n ),\n ))\n },\n}', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:104', }, { key: 'tool.call.images', diff --git a/scripts/gen-client-catalog.spec.ts b/scripts/gen-client-catalog.spec.ts index 6d1c81c019..be02a03f9f 100644 --- a/scripts/gen-client-catalog.spec.ts +++ b/scripts/gen-client-catalog.spec.ts @@ -183,6 +183,13 @@ describe('client slot projection', () => { expect(entry?.example).toContain("ctx.slots.inject('demo.seat'") expect(entry?.example).toContain("id: 'my-entry'") }) + + it('uses an authored example when a slot interaction needs more than generic markup', () => { + const [entry] = resolveSlotEntries([ + declaration({ jsDoc: '/** A seat.\n * @example\n * return { custom: true }\n */' }), + ], [], OWNER_TYPES, kits) + expect(entry?.example).toBe('return { custom: true }') + }) }) describe('the per-slot report budget', () => { diff --git a/scripts/gen-client-catalog.ts b/scripts/gen-client-catalog.ts index 0443aa2e9d..e4bb3f0933 100644 --- a/scripts/gen-client-catalog.ts +++ b/scripts/gen-client-catalog.ts @@ -336,6 +336,8 @@ function keyDomainOf(declaration: SlotDeclaration, occupants: readonly SlotRegis /** A runnable minimal registration for one slot, per cardinality. */ function exampleOf(declaration: SlotDeclaration): string { + const authored = blockTag(declaration.jsDoc, 'example') + if (authored !== undefined) return authored const options = [`name: '${declaration.key}'`, ...KIND_EXAMPLE[declaration.kind] ?? []].join(', ') return [ 'return {', @@ -350,6 +352,21 @@ function exampleOf(declaration: SlotDeclaration): string { ].join('\n') } +/** One multiline JSDoc block tag, without comment decoration. */ +function blockTag(jsDoc: string, name: string): string | undefined { + const lines = jsDoc.replace(/^\/\*\*/, '').replace(/\*\/$/, '').split('\n') + .map(line => line.replace(/^\s*\*?\s?/, '').replace(/\s+$/, '')) + const start = lines.findIndex(line => line === `@${name}` || line.startsWith(`@${name} `)) + if (start < 0) return undefined + const body = [lines[start]?.slice(name.length + 1).trimStart() ?? ''] + for (const line of lines.slice(start + 1)) { + if (line.startsWith('@')) break + body.push(line) + } + const value = body.join('\n').trim() + return value === '' ? undefined : value +} + /** Extra example options per cardinality. */ const KIND_EXAMPLE: Readonly> = { single: [], From 4db234b408cde803e9e602003a25ee6c21f9a81e Mon Sep 17 00:00:00 2001 From: Magolor Date: Fri, 18 Sep 2026 11:03:41 +0800 Subject: [PATCH 16/24] fix(client): align session action slot contract --- ...17-session-row-menu-actions-slot.i18n.yaml | 4 +- ...026-09-17-session-row-menu-actions-slot.md | 12 ++-- ...-09-17-session-row-menu-actions-slot.zh.md | 12 ++-- apps/web/tests/client-plugin-live.e2e.ts | 71 ++++++++++++++++++- .../session-actions.expected.md | 7 ++ .../plugins/fixture-live-client/client.js | 35 ++++++++- .../plugins/fixture-live-client/package.json | 3 + packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 68 +++++++++++++++--- packages/client/ui-workspace/README.zh.md | 68 +++++++++++++++--- .../ui-workspace/src/client/contract/slots.ts | 33 ++++----- .../ui-workspace/src/client/rows/Rows.tsx | 16 +---- .../src/client/rows/WorkspaceBrowser.tsx | 4 +- .../tests/rename-assembly.client.spec.tsx | 23 +++--- .../ui-workspace/tests/rows.client.spec.tsx | 30 +++++--- .../src/client/slot-catalog.ts | 12 ++-- 16 files changed, 299 insertions(+), 103 deletions(-) create mode 100644 apps/web/tests/expected/client-plugin-live/session-actions.expected.md diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml index 39eecfb4a1..96fcdb2142 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml @@ -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-09-17-session-row-menu-actions-slot.md -2026-09-17-session-row-menu-actions-slot.md: a7524c71caa2ba34b836cb1c82eaa0a6c610799e -2026-09-17-session-row-menu-actions-slot.zh.md: 197bbe012e197efa40c1049f80056f5f64fb20ab +2026-09-17-session-row-menu-actions-slot.md: 081013c410671439f387a363cc86dc4e5fbf2fb3 +2026-09-17-session-row-menu-actions-slot.zh.md: f9bdb848ac0f6908ac086c3e7d9ea44a076d8052 diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md index a7524c71ca..081013c410 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md @@ -10,26 +10,26 @@ The Session row menu was a closed list of actions owned by `ui-workspace`. A thi ## Decision -`ui-workspace` declares the root-scoped ordered-list slot `sidebar.workspaces.session.menu.action` under its `sidebar.workspaces` registration. Each contribution receives the target `sessionId`, the row `displayTitle` (persisted title, project basename, then Session id), and a `dismiss()` callback; the contributing plugin keeps its services and mutations in its own registration closure. +`ui-workspace` declares the root-scoped ordered-list slot `sidebar.workspaces.session.menu.action` under its `sidebar.workspaces` registration. Each contribution receives the target `sessionId` and row `displayTitle` (persisted title, project basename, then Session id); the contributing plugin keeps its services and mutations in its own registration closure. -The shared `MenuAction` primitive renders contributed rows inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Import-free dynamic client packages instead render a native `button[role="menuitem"]` and call the owner `dismiss()` after acting. +The shared `MenuAction` primitive renders every contributed row inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Dynamic client packages declare `ui-primitives` as a runtime dependency and resolve the host's shared export through their loader `require`, avoiding a second component protocol. ### Ordering and disclosure -Rename, Fork, and Archive remain a fixed owner-defined group at the top. Contributions form a semantically separated group below them and sort by lower slot priority, lower `order`, then registration sequence. The dynamic browser-half facade gives each registration a distinct decreasing priority, so newer dynamic registrations precede older ones regardless of `order`; packaged registrations at equal priority use `order`. The group is visually and accessibly hidden when empty. The existing ellipsis menu remains the only disclosure layer; nested “More…” grouping is not part of the contract. +Rename, Fork, and Archive remain a fixed owner-defined group at the top. Contributions form a semantically separated group below them and follow list-slot ordering: lower `order` first, then the live ledger order. Equal-order packaged registrations keep registration sequence; equal-order dynamic registrations use the facade's decreasing shadowing priority, so the newer entry comes first. Priority otherwise selects the active registration inside one reused-id cell and does not override order across distinct ids. The group is visually and accessibly hidden when empty. The existing ellipsis menu remains the only disclosure layer; nested “More…” grouping is not part of the contract. ## Verification -Primitive tests cover selection, dismissal, focus restoration, submenu reset, the semantic separator, and keyboard order. Row tests cover owner props and built-in-before-plugin placement. The assembled Slot runtime test registers packaged and dynamic-style contributions in reverse order and verifies ordering, display-title identity, dismissal, and trigger-focus restoration. +Primitive tests cover selection, dismissal, focus restoration, submenu reset, the semantic separator, and keyboard order. Row tests cover owner props and built-in-before-plugin placement. The assembled Slot runtime test verifies that order remains primary across different priorities. A real Loader/Web scenario installs a dynamic package, opens a seeded Session menu in Chromium, snapshots the assembled menu, selects an action, and verifies dismissal, owner data, and fiber-lifetime cleanup. ## Alternatives considered **Pass menu descriptors through the slot owner props.** This makes a render slot behave like a second data registry, exposes presentation policy through callbacks, and prevents ordinary slot components from owning their injected services. -**Expose only raw menu markup.** That would let packaged plugins drift from the menu's accessibility, focus, and visual behavior. `MenuAction` remains their stable path, while `dismiss()` gives import-free dynamic packages the minimum lifecycle capability they need. +**Expose raw menu markup.** That would let plugins drift from the menu's accessibility, focus, and visual behavior. Requiring the shared `MenuAction` keeps one interaction contract for packaged and dynamically loaded contributions. **Add primary and “More…” slots immediately.** Session actions are already behind the row's ellipsis, and no current action set needs another disclosure level. A second hierarchy would add labeling and keyboard policy before a demonstrated density problem exists. ## Consequences -Plugins can add Session actions without editing `ui-workspace`, while core actions keep a stable position and external conflicts use the slot registry's existing id and priority rules. Packaged contributions use `MenuAction`; dynamic contributions own their markup and must call `dismiss()` after acting. All plugin actions remain in the secondary row menu until observed scale justifies a new hierarchy. +Plugins can add Session actions without editing `ui-workspace`, while core actions keep a stable position and external conflicts use the slot registry's existing id and priority rules. Every contribution uses the shared `MenuAction`. All plugin actions remain in the secondary row menu until observed scale justifies a new hierarchy. diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md index 197bbe012e..f9bdb848ac 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md @@ -10,26 +10,26 @@ Session 行菜单原本是由 `ui-workspace` 持有的封闭 action 列表。第 ## 决策 -`ui-workspace` 在其 `sidebar.workspaces` 注册项下声明 root-scoped 有序列表 slot `sidebar.workspaces.session.menu.action`。每个贡献项接收目标 `sessionId`、行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id)与 `dismiss()` 回调;贡献插件将自身服务与 mutation 保留在自己的注册闭包中。 +`ui-workspace` 在其 `sidebar.workspaces` 注册项下声明 root-scoped 有序列表 slot `sidebar.workspaces.session.menu.action`。每个贡献项接收目标 `sessionId` 与行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id);贡献插件将自身服务与 mutation 保留在自己的注册闭包中。 -共享 `MenuAction` primitive 在 `Menu` 内渲染贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。无法导入该 primitive 的动态客户端包改为渲染原生 `button[role="menuitem"]`,并在执行操作后调用 owner 的 `dismiss()`。 +共享 `MenuAction` primitive 在 `Menu` 内渲染所有贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。动态客户端包将 `ui-primitives` 声明为运行时依赖,再通过 loader 的 `require` 解析宿主共享 export,避免引入第二套组件协议。 ### 排序与渐进披露 -Rename、Fork 与 Archive 作为固定的 owner-defined 分组保持在顶部。贡献项在下方形成带语义分隔的分组,依次按较低的 slot priority、较低的 `order` 与注册顺序排列。动态 browser-half facade 为每次注册分配不同且递减的 priority,因此较新的动态注册无视 `order` 排在较旧注册之前;相同 priority 的打包注册才使用 `order`。空分组在视觉与无障碍 API 中均隐藏。现有省略号菜单仍是唯一的渐进披露层;嵌套「More…」分组不属于此约定。 +Rename、Fork 与 Archive 作为固定的 owner-defined 分组保持在顶部。贡献项在下方形成带语义分隔的分组,并遵循 list slot 排序:先按较小的 `order`,再按 live ledger 顺序。`order` 相同的打包注册保持注册顺序;动态注册使用 facade 分配的递减 shadowing priority,因此较新的注册在前。除此之外,priority 只在一个复用 id 的 cell 内选择活动注册,不会让不同 id 跨越 order。空分组在视觉与无障碍 API 中均隐藏。现有省略号菜单仍是唯一的渐进披露层;嵌套「More…」分组不属于此约定。 ## 验证 -Primitive 测试覆盖选择、关闭、焦点恢复、子菜单重置、语义分隔线与键盘顺序。行测试覆盖 owner props 与内置 action 优先于插件 action 的位置。组装后的 Slot 运行时测试以相反顺序注册打包贡献项与动态风格贡献项,并验证顺序、显示标题身份、关闭与触发按钮焦点恢复。 +Primitive 测试覆盖选择、关闭、焦点恢复、子菜单重置、语义分隔线与键盘顺序。行测试覆盖 owner props 与内置 action 优先于插件 action 的位置。组装后的 Slot 运行时测试验证不同 priority 下仍以 order 为主。真实 Loader/Web 场景安装动态包,在 Chromium 中打开已播种 Session 的菜单,对组装结果取快照,选择 action,并验证关闭、owner 数据与 fiber 生命周期清理。 ## 考虑过的替代方案 **通过 slot owner props 传递菜单 descriptor。** 这会使渲染 slot 变成第二套数据注册表,通过回调暴露展示策略,并阻止普通 slot 组件持有自身注入服务。 -**只暴露原始菜单 markup。** 这会让打包插件偏离菜单的无障碍、焦点与视觉行为。`MenuAction` 仍是它们的稳定路径,而 `dismiss()` 为无法导入组件的动态包提供所需的最小生命周期能力。 +**暴露原始菜单 markup。** 这会让插件偏离菜单的无障碍、焦点与视觉行为。要求使用共享 `MenuAction`,可让打包与动态加载的贡献项遵守同一套交互协议。 **立即添加主要 slot 与「More…」slot。** Session action 已位于行省略号之后,而且当前 action 集合不需要另一层渐进披露。在出现已证实的密度问题前,第二层级只会提前增加标签与键盘策略。 ## 后果 -插件无需编辑 `ui-workspace` 即可添加 Session action,同时 core action 保持稳定位置,外部冲突沿用 slot 注册表已有的 id 与 priority 规则。打包贡献项使用 `MenuAction`;动态贡献项自有其 markup,并须在执行操作后调用 `dismiss()`。所有插件 action 都保留在次级行菜单内,直到观察到的规模证明需要新层级。 +插件无需编辑 `ui-workspace` 即可添加 Session action,同时 core action 保持稳定位置,外部冲突沿用 slot 注册表已有的 id 与 priority 规则。所有贡献项都使用共享 `MenuAction`。所有插件 action 都保留在次级行菜单内,直到观察到的规模证明需要新层级。 diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index 3b321032de..f116b56f36 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -5,11 +5,17 @@ import { tmpdir } from 'node:os' import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { chromium, type Page } from 'playwright' import { expect, it, onTestFailed, onTestFinished } from 'vitest' -import { launchWebScaffold, watchConsole, captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './scaffold.ts' -import { saveFailureShot, ZH_BROWSER_LOCALE } from './support.ts' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, launchWebScaffold, + seedSession, watchConsole, webSnapshotMode, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot, ZH_BROWSER_LOCALE } from './support.ts' const FIXTURE = fileURLToPath(new URL('./fixtures/plugins/fixture-live-client', import.meta.url)) const EXPECTED = fileURLToPath(new URL('./expected/client-plugin-live', import.meta.url)) +const SESSION_ACTION_EXPECTED = join(EXPECTED, 'session-actions.expected.md') +const SESSION_SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) +const SESSION_TITLE = 'Session action extension' async function openInventory(page: Page, url: string) { await page.goto(url, { waitUntil: 'load' }) @@ -20,6 +26,67 @@ async function openInventory(page: Page, url: string) { return dialog } +it('loads ordered Session actions through the real plugin graph and removes them with their fiber', async () => { + const scaffold = await launchWebScaffold({ extraInstallAnchors: [join(FIXTURE, 'package.json')] }) + const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd) + const sessionId = await seedSession(scaffold, await readFile(SESSION_SEED, 'utf8'), 'session-menu-actions-web-e2e') + await workspace.attachSession(sessionId) + await scaffold.ctx.sessionController.rename({ sessionId, title: SESSION_TITLE }) + const entryId = await scaffold.ctx.loader.create({ name: '@fixture/live-client' }) + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const console = watchConsole(page) + onTestFailed(() => saveFailureShot(page, 'web-e2e-session-menu-actions')) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const row = page.getByRole('treeitem').filter({ has: page.getByText(SESSION_TITLE, { exact: true }) }) + await row.waitFor({ timeout: 20_000 }) + const trigger = row.getByRole('button', { name: `Session actions for ${SESSION_TITLE}` }) + + await row.hover() + await trigger.focus() + await trigger.click() + const menu = page.getByRole('menu') + await menu.waitFor() + expect(await menu.getByRole('menuitem').allTextContents()).toEqual([ + 'Rename', 'Fork session', 'Archive session', 'Export session', 'Copy session ID', + ]) + await compareOrRefreshGolden( + SESSION_ACTION_EXPECTED, + await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd), + webSnapshotMode(), + ) + + await menu.getByRole('menuitem', { name: 'Export session' }).click() + await expect.poll(() => menu.count()).toBe(0) + expect(await page.evaluate(() => ({ + action: document.documentElement.dataset.sessionAction, + id: document.documentElement.dataset.sessionActionId, + title: document.documentElement.dataset.sessionActionTitle, + }))).toEqual({ action: 'fixture.export-session', id: sessionId, title: SESSION_TITLE }) + + scaffold.ctx.loader.remove(entryId) + await expect.poll(() => page.evaluate( + () => document.documentElement.dataset.liveDisposals, + )).toBe('1') + await row.hover() + await trigger.click() + await menu.waitFor() + expect(await menu.getByRole('menuitem').allTextContents()).toEqual([ + 'Rename', 'Fork session', 'Archive session', + ]) + expect(await menu.getByRole('separator').count()).toBe(0) + expect(console.pageErrors).toEqual([]) + await assertFixtureInventory(EXPECTED, [ + 'bootstrap-rebuild.expected.md', 'enabled.expected.md', 'recovered.expected.md', + 'session-actions.expected.md', + ]) + } finally { + await browser.close() + await scaffold.close() + } +}, 120_000) + it('synchronizes two pages, disposes effects and restores an offline page from the latest graph without navigation', async () => { const scaffold = await launchWebScaffold({ extraInstallAnchors: [join(FIXTURE, 'package.json')], diff --git a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md new file mode 100644 index 0000000000..20ea2bfade --- /dev/null +++ b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md @@ -0,0 +1,7 @@ +- menu: + - menuitem "Rename" + - menuitem "Fork session" + - menuitem "Archive session" + - separator + - menuitem "Export session" + - menuitem "Copy session ID" diff --git a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js index d870a5e52a..1373f8b637 100644 --- a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js +++ b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js @@ -3,6 +3,7 @@ window.__ModuleLoader__.load({ id: '@fixture/live-client', factory(require) { const React = require('react') + const { MenuAction } = require('@deepseek-ai/dsh-client-ui-primitives') const style = document.createElement('style') style.dataset.plugin = '@fixture/live-client' style.textContent = '[data-live-client] { color: rgb(12, 34, 56); position: absolute; bottom: 20px; right: 20px; }' @@ -13,8 +14,14 @@ window.__ModuleLoader__.load({ const counters = document.documentElement.dataset counters.liveMounts = String(Number(counters.liveMounts ?? 0) + 1) ctx.effect(() => ctx.locale.register('fixtureLive', { - zh: { active: '动态插件已启用', configSummary: '示例配置项', configForm: '动态插件配置', configField: '问候语', configSave: '保存' }, - en: { active: 'Live plugin enabled', configSummary: 'An example setting', configForm: 'Live plugin configuration', configField: 'Greeting', configSave: 'Save' }, + zh: { + active: '动态插件已启用', configSummary: '示例配置项', configForm: '动态插件配置', configField: '问候语', configSave: '保存', + exportSession: '导出会话', copySessionId: '复制会话 ID', + }, + en: { + active: 'Live plugin enabled', configSummary: 'An example setting', configForm: 'Live plugin configuration', configField: 'Greeting', configSave: 'Save', + exportSession: 'Export session', copySessionId: 'Copy session ID', + }, })) ctx.slots.inject('shell.overlay', () => ctx.slots.register({ name: 'shell.overlay', id: 'fixture-live-client', locale: 'fixtureLive', @@ -34,6 +41,30 @@ window.__ModuleLoader__.load({ }, React.createElement('label', null, t('configField'), React.createElement('input', { name: 'greeting', defaultValue: 'hello' })), React.createElement('button', { type: 'submit' }, t('configSave'))))) + const actionInjected = () => ({ + selectAction(action, sessionId, displayTitle) { + counters.sessionAction = action + counters.sessionActionId = sessionId + counters.sessionActionTitle = displayTitle + }, + }) + const registerSessionAction = (id, order, label) => ctx.slots.register({ + name: 'sidebar.workspaces.session.menu.action', id, order, locale: 'fixtureLive', inject: actionInjected, + }, ({ sessionId, displayTitle, selectAction, t }) => React.createElement( + MenuAction, + { + onSelect: () => { + selectAction(id, sessionId, displayTitle) + }, + }, + t(label), + )) + ctx.slots.inject('sidebar.workspaces.session.menu.action', function* () { + // The later registration receives the lower dynamic priority, but + // list order remains the primary cross-id display policy. + yield registerSessionAction('fixture.export-session', 100, 'exportSession') + yield registerSessionAction('fixture.copy-session-id', 200, 'copySessionId') + }) ctx.effect(() => { const ping = () => { counters.liveHits = String(Number(counters.liveHits ?? 0) + 1) } window.addEventListener('dsh-fixture-ping', ping) diff --git a/apps/web/tests/fixtures/plugins/fixture-live-client/package.json b/apps/web/tests/fixtures/plugins/fixture-live-client/package.json index f0dc6ea35f..a1ea61f660 100644 --- a/apps/web/tests/fixtures/plugins/fixture-live-client/package.json +++ b/apps/web/tests/fixtures/plugins/fixture-live-client/package.json @@ -8,5 +8,8 @@ "dsh": { "bundle": { "patch": "./cordis.patch.yml" }, "client": { "platform": "web" } + }, + "dependencies": { + "@deepseek-ai/dsh-client-ui-primitives": "workspace:*" } } diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index bf32710936..bd9e85f29a 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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-workspace/README.md -README.md: 5bc338740668d4d927ca10bc02969334710eaf0e -README.zh.md: 8acaff5eca129a4398aa38c6d2576c327ae79e64 +README.md: 6abb08afe05bd5fe55d60905ab3d7c8c0b25d63a +README.zh.md: 0e7867f861a9736841e6c07ab5eefd977cbb0d0c diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 5bc3387406..6abb08afe0 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -83,22 +83,74 @@ Each registration declares a **directory-flow child hole** (`single` kind: `conv ### Session menu actions -An external client plugin injects `sidebar.workspaces.session.menu.action`, registers a fresh `id` and `order`, and renders the shared `MenuAction` primitive. Each action receives the target's `sessionId`, its row `displayTitle` (persisted title, project basename, then Session id), and `dismiss()`. Plugin services remain in the registration's inject closure, and action text comes from the plugin's locale dictionary. Built-in actions stay first in their fixed order. Plugin actions sort by lower priority, lower `order`, then registration sequence. The dynamic browser-half facade assigns every registration a distinct decreasing priority, so newer dynamic registrations precede older ones regardless of `order`; packaged registrations at the same priority use `order`. The secondary group has a semantic separator and is hidden from both presentation and accessibility APIs when empty. +An external client plugin contributes to `sidebar.workspaces.session.menu.action`. Built-in actions stay first in their fixed order; contributed actions form a secondary group after a semantic separator. The group is absent from presentation and accessibility APIs when it has no rendered menu-item button. + +Each contribution receives the target `sessionId` and row `displayTitle` (persisted title, project basename, then Session id). Render the contribution with the shared `MenuAction` primitive; it owns the menu's styling, keyboard behavior, dismissal, and focus restoration. Use a fresh, package-namespaced `id`. Lower `order` values render first. Equal-order packaged registrations keep registration sequence; equal-order dynamic registrations use the facade's decreasing shadowing priority, so the newer entry comes first. `priority` otherwise selects the active registration when two entries deliberately reuse one `id`; it does not move a distinct id across `order` groups. + +#### Packaged client plugin + +Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot key. Keep the Component at module scope, project business operations through the registration's `inject` face, and own visible copy in the contributing package's locale namespace. ```tsx +import type { Context } from '@deepseek-ai/cordis' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' +import type { + InjectFace, LocaleDictOf, PropsLocale, PropsRuntime, +} from '@deepseek-ai/dsh-client-ui-slots' +import { exportSession } from './export-session.ts' -ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register( - { name: 'sidebar.workspaces.session.menu.action', id: 'export-session', order: 100 }, - ({ sessionId, displayTitle }) => ( +const NS = 'acme.sessionActions' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + 'acme.sessionActions': 'export' + } +} + +const en: LocaleDictOf = { export: 'Export {title}' } +const zh: LocaleDictOf = { export: '导出 {title}' } + +interface ExportActionInjected { + exportSession: (sessionId: SessionId) => void +} + +type ExportActionProps = + PropsRuntime<'sidebar.workspaces.session.menu.action'> + & PropsLocale + & InjectFace + +function ExportAction({ sessionId, displayTitle, exportSession, t }: ExportActionProps) { + return ( { exportSession(sessionId) }}> - {t('session.export', { title: displayTitle })} + {t('export', { title: displayTitle })} - ), -)) + ) +} + +export const inject = ['slots', 'locale'] + +export function apply(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'acme-session-actions: dictionaries') + + ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register({ + name: 'sidebar.workspaces.session.menu.action', + id: 'acme.export-session', + order: 100, + locale: NS, + inject: (): ExportActionInjected => ({ exportSession }), + }, ExportAction)) +} ``` -Import-free dynamic client packages render a native ` - ) - : ( - { selected(id, sessionId, displayTitle) }}>{label} - ), + { name: 'sidebar.workspaces.session.menu.action', id, order, priority }, + ({ sessionId, displayTitle }: SessionMenuActionOwnerProps) => ( + { selected(id, sessionId, displayTitle) }}>{label} + ), ) } - registerAction('later', 20, 'Later action') - registerAction('earlier', 10, 'Earlier action', true) + // List display order stays primary even when the later registration has + // the lower shadowing priority assigned to dynamic browser packages. + registerAction('earlier', 10, -1, 'Earlier action') + registerAction('later', 20, -2, 'Later action') const view = runtime.renderRoot() const row = (await view.findByText('Session title')).closest('[role="treeitem"]')! diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index fdf5dfe9ef..e7428003b9 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -1,6 +1,7 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, createEvent, fireEvent, render, screen } from '@testing-library/react' +import type { ComponentProps } from 'react' import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' @@ -10,7 +11,9 @@ import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionMenuActionOwnerProps } from '../src/client/contract/slots.ts' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { RowDragProps } from '../src/client/rows/Rows.tsx' -import { ProjectRowItem, SearchResultItem, SessionNodeItem } from '../src/client/rows/Rows.tsx' +import { + ProjectRowItem, SearchResultItem, SessionNodeItem as SessionNodeItemComponent, +} from '../src/client/rows/Rows.tsx' import type { GroupNode, SearchResultNode, SessionNode } from '../src/client/tree.ts' import { en, zh } from '../src/client/locales.ts' @@ -22,6 +25,15 @@ const tEn = makeTranslate(en, commonEn) as never const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId +const renderNoSessionActions: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] = () => null + +// Direct row specs use the real required Slot share, empty unless the case supplies an occupant. +function SessionNodeItem({ renderSlot = renderNoSessionActions, ...props }: Omit< + ComponentProps, 'renderSlot' +> & Partial, 'renderSlot'>>) { + return +} + /** Half detection reads the row rect; jsdom rects are all-zero by default. */ function stubRect(row: HTMLElement): void { row.getBoundingClientRect = () => ({ @@ -560,16 +572,14 @@ describe('workspace browser rows', () => { const renderSlot: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] = (name, value) => { // The generic framework signature cannot narrow its owner from a runtime key in a test stub. const owner = value as unknown as SessionMenuActionOwnerProps - const { sessionId, displayTitle, dismiss } = owner + const { sessionId, displayTitle } = owner rendered(name, value) return ( - + ) } const node: SessionNode = { @@ -577,13 +587,14 @@ describe('workspace browser rows', () => { runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, } render(<> - ) - fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) + const trigger = screen.getByRole('button', { name: '会话“One”的操作' }) + trigger.focus() + fireEvent.click(trigger) const actions = screen.getAllByRole('menuitem') expect(actions.map(action => action.textContent)).toEqual(['重命名', '分叉会话', '归档会话', 'Export']) fireEvent.click(screen.getByRole('menuitem', { name: 'Export' })) @@ -592,10 +603,9 @@ describe('workspace browser rows', () => { const owner = rendered.mock.calls.at(-1)?.[1] as SessionMenuActionOwnerProps | undefined expect(owner?.sessionId).toBe(node.id) expect(owner?.displayTitle).toBe('One') - expect(typeof owner?.dismiss).toBe('function') expect(onPluginAction).toHaveBeenCalledWith(node.id, 'One') expect(screen.queryByRole('menu')).toBeNull() - expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Destination' })) + expect(document.activeElement).toBe(trigger) expect(onOpen).not.toHaveBeenCalled() }) diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index c178adb2ff..0a36d6207c 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -696,7 +696,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace.directoryFlow\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:73', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:66', }, { key: 'conversation.input.attachments', @@ -3236,14 +3236,14 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.directoryFlow\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:75', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:68', }, { key: 'sidebar.workspaces.session.menu.action', kind: 'list', scope: 'root', summary: 'Ordered third-party actions below the built-in Session row-menu actions.', - doc: 'Ordered third-party actions below the built-in Session row-menu actions.\nRegistrations use a fresh id and sort by lower priority, lower order, then\nregistration sequence. Dynamic browser halves receive distinct decreasing\npriorities, so newer dynamic registrations precede older ones regardless\nof order. Packaged plugins render `MenuAction`; import-free dynamic markup\nrenders a `button[role="menuitem"]` and calls the owner `dismiss()` after\nacting. An empty list has no visible or accessible secondary group.', + doc: 'Ordered third-party actions below the built-in Session row-menu actions.\nRegistrations use a fresh id and sort by lower order. Equal-order packaged\nregistrations keep registration sequence; equal-order dynamic registrations\nuse the facade\'s decreasing shadowing priority, so the newer entry comes\nfirst. Priority selects the active registration for one reused id; it does\nnot override order across distinct ids. Contributions render `MenuAction`\nso the shared primitive owns styling, keyboard behavior, dismissal, and\nfocus restoration. An empty list has no visible or accessible secondary group.', registerOptions: [ { name: 'id', @@ -3265,7 +3265,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Point-in-time Session row information supplied to each menu action. */\nexport interface SessionMenuActionOwnerProps {\n /** Session targeted by the open row menu. */\n sessionId: SessionId\n /** Row display title: persisted title, project basename, or Session id. */\n displayTitle: string\n /**\n * Close the menu and restore trigger focus when the action leaves focus behind.\n *\n * An acting item not rendered with `MenuAction` MUST call this after its\n * operation. `MenuAction` performs the same close-and-refocus behavior.\n */\n dismiss: () => void\n}', + '/** Point-in-time Session row information supplied to each menu action. */\nexport interface SessionMenuActionOwnerProps {\n /** Session targeted by the open row menu. */\n sessionId: SessionId\n /** Row display title: persisted title, project basename, or Session id. */\n displayTitle: string\n}', ], ownerPropsReferences: [ 'SessionId', @@ -3285,8 +3285,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ declaredBy: 'an entry in \'sidebar.workspaces\' (client-ui-workspace), so it exists while that entry is mounted', occupants: [], replaceRisk: 'none', - example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n const copyLabel = \'Copy Session ID\' // Localize in the contributing package.\n ctx.slots.inject(\'sidebar.workspaces.session.menu.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.action\', id: \'copy-session-id\', order: 100 },\n ({ sessionId, dismiss }) => React.createElement(\n \'button\',\n {\n type: \'button\',\n role: \'menuitem\',\n onClick: () => { navigator.clipboard.writeText(sessionId).then(dismiss, dismiss) },\n },\n copyLabel,\n ),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:104', + example: 'const React = require(\'react\')\nconst { MenuAction } = require(\'@deepseek-ai/dsh-client-ui-primitives\')\n\nreturn {\n inject: [\'slots\'],\n apply(ctx) {\n const copyLabel = \'Copy Session ID\' // Localize in the contributing package.\n ctx.slots.inject(\'sidebar.workspaces.session.menu.action\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.session.menu.action\', id: \'copy-session-id\', order: 100 },\n ({ sessionId }) => React.createElement(\n MenuAction,\n { onSelect: () => { void navigator.clipboard.writeText(sessionId) } },\n copyLabel,\n ),\n ))\n },\n}', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:97', }, { key: 'tool.call.images', From d849d656a577b0fb7f08aa0f5ebae97e3367210c Mon Sep 17 00:00:00 2001 From: Magolor Date: Fri, 18 Sep 2026 16:59:58 +0800 Subject: [PATCH 17/24] fix(client): use baseline menu primitive --- .../2026-09-17-session-row-menu-actions-slot.i18n.yaml | 4 ++-- .../architecture/2026-09-17-session-row-menu-actions-slot.md | 2 +- .../2026-09-17-session-row-menu-actions-slot.zh.md | 2 +- .../tests/fixtures/plugins/fixture-live-client/package.json | 3 --- packages/client/ui-workspace/README.i18n.yaml | 4 ++-- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- 7 files changed, 8 insertions(+), 11 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml index 96fcdb2142..1bced81aa7 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml @@ -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-09-17-session-row-menu-actions-slot.md -2026-09-17-session-row-menu-actions-slot.md: 081013c410671439f387a363cc86dc4e5fbf2fb3 -2026-09-17-session-row-menu-actions-slot.zh.md: f9bdb848ac0f6908ac086c3e7d9ea44a076d8052 +2026-09-17-session-row-menu-actions-slot.md: 21f17505a5e24c68b6b96a1eee34dbf76d9aa40f +2026-09-17-session-row-menu-actions-slot.zh.md: ae30d88dc8c2fb2b34ca2dc06fdb1eb5bb6c9f43 diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md index 081013c410..21f17505a5 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md @@ -12,7 +12,7 @@ The Session row menu was a closed list of actions owned by `ui-workspace`. A thi `ui-workspace` declares the root-scoped ordered-list slot `sidebar.workspaces.session.menu.action` under its `sidebar.workspaces` registration. Each contribution receives the target `sessionId` and row `displayTitle` (persisted title, project basename, then Session id); the contributing plugin keeps its services and mutations in its own registration closure. -The shared `MenuAction` primitive renders every contributed row inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Dynamic client packages declare `ui-primitives` as a runtime dependency and resolve the host's shared export through their loader `require`, avoiding a second component protocol. +The shared `MenuAction` primitive renders every contributed row inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Dynamic client bundles resolve `ui-primitives` directly from the host's implicit baseline through their loader `require`; they do not declare a runtime dependency or carry a second component protocol. ### Ordering and disclosure diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md index f9bdb848ac..ae30d88dc8 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md @@ -12,7 +12,7 @@ Session 行菜单原本是由 `ui-workspace` 持有的封闭 action 列表。第 `ui-workspace` 在其 `sidebar.workspaces` 注册项下声明 root-scoped 有序列表 slot `sidebar.workspaces.session.menu.action`。每个贡献项接收目标 `sessionId` 与行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id);贡献插件将自身服务与 mutation 保留在自己的注册闭包中。 -共享 `MenuAction` primitive 在 `Menu` 内渲染所有贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。动态客户端包将 `ui-primitives` 声明为运行时依赖,再通过 loader 的 `require` 解析宿主共享 export,避免引入第二套组件协议。 +共享 `MenuAction` primitive 在 `Menu` 内渲染所有贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。动态客户端 bundle 直接通过 loader 的 `require` 从宿主隐式 baseline 解析 `ui-primitives`;它们不声明运行时依赖,也不携带第二套组件协议。 ### 排序与渐进披露 diff --git a/apps/web/tests/fixtures/plugins/fixture-live-client/package.json b/apps/web/tests/fixtures/plugins/fixture-live-client/package.json index a1ea61f660..f0dc6ea35f 100644 --- a/apps/web/tests/fixtures/plugins/fixture-live-client/package.json +++ b/apps/web/tests/fixtures/plugins/fixture-live-client/package.json @@ -8,8 +8,5 @@ "dsh": { "bundle": { "patch": "./cordis.patch.yml" }, "client": { "platform": "web" } - }, - "dependencies": { - "@deepseek-ai/dsh-client-ui-primitives": "workspace:*" } } diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index bd9e85f29a..8fee12f4a5 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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-workspace/README.md -README.md: 6abb08afe05bd5fe55d60905ab3d7c8c0b25d63a -README.zh.md: 0e7867f861a9736841e6c07ab5eefd977cbb0d0c +README.md: 98bc6c7843c6d76c236f6bce83bf70a823d3394e +README.zh.md: 678568ad19e9b20ab9ad989a6d5505af7bc295f3 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 6abb08afe0..98bc6c7843 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -150,7 +150,7 @@ export function apply(ctx: Context): void { #### Dynamic client package -A dynamically loaded browser half follows the same component contract. Declare `@deepseek-ai/dsh-client-ui-primitives` as a runtime dependency, resolve its shared `MenuAction` export through the loader's `require`, and render it with `React.createElement`. Do not bundle a second copy of React or the primitive: `MenuAction` must share the host menu context. The real Loader/Web fixture and generated Client Slot catalog contain runnable examples. +A dynamically loaded browser half follows the same component contract. `@deepseek-ai/dsh-client-ui-primitives` is an implicit baseline external: resolve its shared `MenuAction` export directly through the loader's `require`, and render it with `React.createElement`. Do not list the primitive as a runtime dependency or bundle another copy; declare a development dependency only when source compilation needs its types. `MenuAction` must share the host menu context. The real Loader/Web fixture and generated Client Slot catalog contain runnable examples. ### View state diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 0e7867f861..678568ad19 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -150,7 +150,7 @@ export function apply(ctx: Context): void { #### 动态客户端包 -动态加载的 browser half 采用同一套组件协议。将 `@deepseek-ai/dsh-client-ui-primitives` 声明为运行时依赖,通过 loader 的 `require` 解析共享的 `MenuAction` export,再用 `React.createElement` 渲染。不要打包第二份 React 或 primitive:`MenuAction` 必须与宿主菜单共享 context。真实 Loader/Web fixture 与生成的 Client Slot catalog 都包含可运行示例。 +动态加载的 browser half 采用同一套组件协议。`@deepseek-ai/dsh-client-ui-primitives` 是隐式 baseline external:直接通过 loader 的 `require` 解析共享的 `MenuAction` export,再用 `React.createElement` 渲染。不要把 primitive 列为运行时依赖或打包另一份副本;仅在源码编译需要其类型时声明开发依赖。`MenuAction` 必须与宿主菜单共享 context。真实 Loader/Web fixture 与生成的 Client Slot catalog 都包含可运行示例。 ### 视图状态 From 5ca9b77c4462e850defc0b4f291e580a682109bc Mon Sep 17 00:00:00 2001 From: imccyu Date: Sat, 19 Sep 2026 19:17:55 +0800 Subject: [PATCH 18/24] test(client): expect the pin row ahead of the session menu actions master's session row menu now leads with Pin session and SessionNode carries pinned/archived, so the slot-action specs and the Web golden take the row as it is after the rebase. --- apps/web/tests/client-plugin-live.e2e.ts | 4 ++-- .../expected/client-plugin-live/session-actions.expected.md | 1 + .../ui-workspace/tests/rename-assembly.client.spec.tsx | 2 +- packages/client/ui-workspace/tests/rows.client.spec.tsx | 6 +++--- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index f116b56f36..96445ae04f 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -49,7 +49,7 @@ it('loads ordered Session actions through the real plugin graph and removes them const menu = page.getByRole('menu') await menu.waitFor() expect(await menu.getByRole('menuitem').allTextContents()).toEqual([ - 'Rename', 'Fork session', 'Archive session', 'Export session', 'Copy session ID', + 'Pin session', 'Rename', 'Fork session', 'Archive session', 'Export session', 'Copy session ID', ]) await compareOrRefreshGolden( SESSION_ACTION_EXPECTED, @@ -73,7 +73,7 @@ it('loads ordered Session actions through the real plugin graph and removes them await trigger.click() await menu.waitFor() expect(await menu.getByRole('menuitem').allTextContents()).toEqual([ - 'Rename', 'Fork session', 'Archive session', + 'Pin session', 'Rename', 'Fork session', 'Archive session', ]) expect(await menu.getByRole('separator').count()).toBe(0) expect(console.pageErrors).toEqual([]) diff --git a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md index 20ea2bfade..f3c45cace9 100644 --- a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md +++ b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md @@ -1,4 +1,5 @@ - menu: + - menuitem "Pin session" - menuitem "Rename" - menuitem "Fork session" - menuitem "Archive session" diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index aa2621c914..9e137d99b9 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -93,7 +93,7 @@ describe('session rename through the assembled browser', () => { const trigger = within(row as HTMLElement).getByLabelText('会话“Session title”的操作') fireEvent.click(trigger) expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - '重命名', '分叉会话', '归档会话', 'Earlier action', 'Later action', + '置顶会话', '重命名', '分叉会话', '归档会话', 'Earlier action', 'Later action', ]) const later = view.getByRole('menuitem', { name: 'Later action' }) const earlier = view.getByRole('menuitem', { name: 'Earlier action' }) diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index e7428003b9..950abad4e1 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -584,11 +584,11 @@ describe('workspace browser rows', () => { } const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, - runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, + runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } render(<> ) @@ -596,7 +596,7 @@ describe('workspace browser rows', () => { trigger.focus() fireEvent.click(trigger) const actions = screen.getAllByRole('menuitem') - expect(actions.map(action => action.textContent)).toEqual(['重命名', '分叉会话', '归档会话', 'Export']) + expect(actions.map(action => action.textContent)).toEqual(['置顶会话', '重命名', '分叉会话', '归档会话', 'Export']) fireEvent.click(screen.getByRole('menuitem', { name: 'Export' })) await act(async () => { await Promise.resolve() }) expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.menu.action', expect.any(Object)) From 21586fe28c9cfdbcceefd0656a1bfd65795a4f04 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 12:11:29 +0800 Subject: [PATCH 19/24] feat(client): compose session row actions from slot lists A Session row's "..." menu and its hover buttons become two list slots the WorkspaceBrowser entry declares, `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. The shipped actions register from apply the way a client plugin does: pin (menu 100, button 200), rename (200), fork (300), archive (menu 400, button 100). An entry receives only the row identity, reads the pin and archive sets through Set hooks its own face injects, decides its own visibility, renders `MenuItemButton` or one icon button, and dismisses the menu through the slot-level `useMenuOpenState` hook bound from the row's render occurrence. Each action's behavior lives in its injected callbacks. `UiWorkspace` gains `pinSession` and `unpinSession`; the pin write into the saved orders happens there, through the viewing-store instance the apply creates and hands the browser's registration as its handle (the ui-layout pattern), reading the memberships current at completion. The rename dialog and the row-action notice are `shell.overlay` entries fed by apply-closure observables through the faces' `hooks`; the archived notice switches the archived filter directly. WorkspaceBrowser threads no action callbacks, renders no toast, and hosts no rename dialog; its title double-click raises the same rename request. In ui-primitives, `MenuItemButton` is the plain `role="menuitem"` row for menus whose rows are components: it shares a data row's markup and styling and needs no shared state, because `Menu` decides the keyboard walk from the DOM and now runs the post-selection focus return once on the list's click bubble for every row kind. `Menu` accepts such rows as `children` beside `items`, which becomes optional together with `onSelect`; `separatorBefore` lets a row start a group with the same hairline a separator entry draws. The context-based `MenuAction` goes away with its extension group. --- ...17-session-row-menu-actions-slot.i18n.yaml | 4 +- ...026-09-17-session-row-menu-actions-slot.md | 28 +- ...-09-17-session-row-menu-actions-slot.zh.md | 28 +- docs/subsystems/slots.i18n.yaml | 4 +- docs/subsystems/slots.md | 3 +- docs/subsystems/slots.zh.md | 3 +- .../client/ui-primitives/README.i18n.yaml | 4 +- packages/client/ui-primitives/README.md | 2 +- packages/client/ui-primitives/README.zh.md | 2 +- .../client/ui-primitives/src/Menu.module.css | 18 +- packages/client/ui-primitives/src/Menu.tsx | 113 ++--- packages/client/ui-primitives/src/index.ts | 4 +- .../ui-primitives/tests/atoms.client.spec.tsx | 19 +- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 48 +- packages/client/ui-workspace/README.zh.md | 48 +- .../ui-workspace/src/client/contract/slots.ts | 244 ++++++++-- .../client/ui-workspace/src/client/index.ts | 155 +++++- .../ui-workspace/src/client/navigation.ts | 31 ++ .../ui-workspace/src/client/pin-order.ts | 51 ++ .../ui-workspace/src/client/rows/Rows.tsx | 113 ++--- .../src/client/rows/WorkspaceBrowser.tsx | 226 ++------- .../client/session-actions/ArchiveSession.tsx | 61 +++ .../client/session-actions/ForkSession.tsx | 24 + .../src/client/session-actions/PinSession.tsx | 72 +++ .../client/session-actions/RenameSession.tsx | 122 +++++ .../client/session-actions/RowActionToast.tsx | 47 ++ .../src/client/session-actions/derived.ts | 26 + .../client/ui-workspace/src/client/stores.ts | 3 + .../ui-workspace/tests/apply.client.spec.ts | 402 ++++++++++++++-- .../tests/rename-assembly.client.spec.tsx | 142 +++--- .../ui-workspace/tests/rows.client.spec.tsx | 303 +++++------- .../tests/session-actions.client.spec.tsx | 443 ++++++++++++++++++ .../tests/workspace-browser.client.spec.tsx | 283 +++-------- .../tests/workspaces-service.client.spec.ts | 50 +- .../src/client/slot-catalog.ts | 81 +++- 36 files changed, 2178 insertions(+), 1033 deletions(-) create mode 100644 packages/client/ui-workspace/src/client/pin-order.ts create mode 100644 packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx create mode 100644 packages/client/ui-workspace/src/client/session-actions/ForkSession.tsx create mode 100644 packages/client/ui-workspace/src/client/session-actions/PinSession.tsx create mode 100644 packages/client/ui-workspace/src/client/session-actions/RenameSession.tsx create mode 100644 packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx create mode 100644 packages/client/ui-workspace/src/client/session-actions/derived.ts create mode 100644 packages/client/ui-workspace/tests/session-actions.client.spec.tsx diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml index 1bced81aa7..d48130328d 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.i18n.yaml @@ -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-09-17-session-row-menu-actions-slot.md -2026-09-17-session-row-menu-actions-slot.md: 21f17505a5e24c68b6b96a1eee34dbf76d9aa40f -2026-09-17-session-row-menu-actions-slot.zh.md: ae30d88dc8c2fb2b34ca2dc06fdb1eb5bb6c9f43 +2026-09-17-session-row-menu-actions-slot.md: 936e0f2163d888102fdb6c083c57e6ba6e549714 +2026-09-17-session-row-menu-actions-slot.zh.md: 906395fa9d5850260c042202c787cd9a4bc8b55b diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md index 21f17505a5..936e0f2163 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.md @@ -1,4 +1,4 @@ -# Agent Note: Session row menu action slot +# Agent Note: Session row actions as slot lists Status: implemented @@ -6,30 +6,30 @@ English | [中文](2026-09-17-session-row-menu-actions-slot.zh.md) ## Problem -The Session row menu was a closed list of actions owned by `ui-workspace`. A third-party client plugin could add a separate sidebar control, but it could not place an action beside Rename, Fork, and Archive without changing the owning package or copying the menu interaction. +The Session row's "..." menu and its hover buttons were closed lists owned by `ui-workspace`: the browser built the menu `items` by row state, rendered the pin and archive buttons itself, and dispatched every verb through callbacks it threaded down the tree, together with the toast and rename dialog those verbs needed. A client plugin could add a sidebar control of its own, but not an action beside the shipped ones without editing the owning package or copying the menu interaction. ## Decision -`ui-workspace` declares the root-scoped ordered-list slot `sidebar.workspaces.session.menu.action` under its `sidebar.workspaces` registration. Each contribution receives the target `sessionId` and row `displayTitle` (persisted title, project basename, then Session id); the contributing plugin keeps its services and mutations in its own registration closure. +`ui-workspace` declares two root-scoped `list` slots under its `sidebar.workspaces` registration — `sidebar.workspaces.session.menu.item` for the menu rows and `sidebar.workspaces.session.row.action` for the hover buttons — and registers its own actions into them from `apply` exactly as a client plugin would: `pin` (menu 100, button 200), `rename` (200), `fork` (300), `archive` (menu 400, button 100). The lists are the menu and the button strip: entries render in ascending `order`, a plugin action lands wherever its order says, and reusing a shipped id at another `priority` shadows that action through the registry's ordinary cell rules. There is no separate "extension group" and no separator. -The shared `MenuAction` primitive renders every contributed row inside `Menu`. It owns the same menu-item semantics, keyboard walk, submenu reset, dismissal, focus restoration, disabled state, icon position, and danger styling as owner-defined rows. Dynamic client bundles resolve `ui-primitives` directly from the host's implicit baseline through their loader `require`; they do not declare a runtime dependency or carry a second component protocol. +An entry receives only the row identity, `{ sessionId, displayTitle }`, and owns everything else. It reads the Host state it cares about through the standard hooks (`useWorkspaces` for the pin and archive sets) and decides its own visibility from it: pin renders nothing on an archived row because the Host keeps the two sets exclusive; archive never consults pin. Its whole behavior lives in its registration's `inject` face, so a component only calls one callback: `pinSession` delegates to `uiWorkspace.pinSession`, which performs the Host pin and then fronts the Session in its accounts' saved orders with `pinSessionOrder`, reading the memberships current at completion from the object-layer snapshots (`pin-order.ts`), beside `archiveSession`, which the same service already owned; the archive action's callback adds the notice. The service writes view order through the viewing-store instance the apply creates and hands the browser's registration as its handle, the pattern `ui-layout` uses for its layout store. The registry-global pin and archive sets reach the entries as Sets through the faces' `hooks`, derived once per Workspace snapshot, so a row reads its own membership with one lookup. -### Ordering and disclosure +The surfaces an action raises outlive the row menu, so they are this package's `shell.overlay` entries: the rename dialog and the row-action notice. An action reaches its surface through the plugin's own apply-closure observable, injected as a callback on the action side (`requestSessionRename`, `notify`) and as a `hooks` source on the surface side (`useRenameRequest`, `useToast`). The browser raises the same rename request from a title double-click and the same notice when an archived row is clicked; the archived notice's second action switches the archived filter to "show" through the same store instance, since the browser's view-options menu is no longer in the loop. -Rename, Fork, and Archive remain a fixed owner-defined group at the top. Contributions form a semantically separated group below them and follow list-slot ordering: lower `order` first, then the live ledger order. Equal-order packaged registrations keep registration sequence; equal-order dynamic registrations use the facade's decreasing shadowing priority, so the newer entry comes first. Priority otherwise selects the active registration inside one reused-id cell and does not override order across distinct ids. The group is visually and accessibly hidden when empty. The existing ellipsis menu remains the only disclosure layer; nested “More…” grouping is not part of the contract. - -## Verification - -Primitive tests cover selection, dismissal, focus restoration, submenu reset, the semantic separator, and keyboard order. Row tests cover owner props and built-in-before-plugin placement. The assembled Slot runtime test verifies that order remains primary across different priorities. A real Loader/Web scenario installs a dynamic package, opens a seeded Session menu in Chromium, snapshots the assembled menu, selects an action, and verifies dismissal, owner data, and fiber-lifetime cleanup. +Menu entries render `MenuItemButton`, the `ui-primitives` row component for menus whose rows are components: a plain row, markup and styling only. It joins the menu's keyboard walk and the focus return because `Menu` decides both from the DOM (the arrow walk queries the rows; the post-selection focus return runs once on the list's click bubble, for data rows and component rows alike). Closing is the owner's state for both kinds of row: data rows through the owner's `onSelect`, component rows through the slot-level `useMenuOpenState` hook — the declaration carries `inject: { hooks: { menuOpenState } }`, `SessionNodeItem` passes its `[open, setOpen]` pair as the occurrence's `hookContext`, and the factory hands the pair back. That is the channel `sidebar.right.pane.tab` already uses for `useTabInfo`. ## Alternatives considered -**Pass menu descriptors through the slot owner props.** This makes a render slot behave like a second data registry, exposes presentation policy through callbacks, and prevents ordinary slot components from owning their injected services. +**A React context between `Menu` and the row component.** Rejected: business components see zero React contexts ([client rules](../../../../packages/client/AGENTS.md)); the Menu-to-row relationship is parent-to-child through the slot system, so its control travels through the slot channels. -**Expose raw menu markup.** That would let plugins drift from the menu's accessibility, focus, and visual behavior. Requiring the shared `MenuAction` keeps one interaction contract for packaged and dynamically loaded contributions. +**Owner-supplied row capabilities.** Passing `pinned`/`archived` and `pin`/`archive`/`rename`/`fork` callbacks to entries, through owner props or a slot-level hook, keeps the browser the owner of every verb and makes the shipped actions thin wrappers over it. Rejected: these are not capabilities of a menu; each action's behavior is that action's own, and an entry can read the Host state it needs directly. -**Add primary and “More…” slots immediately.** Session actions are already behind the row's ellipsis, and no current action set needs another disclosure level. A second hierarchy would add labeling and keyboard policy before a demonstrated density problem exists. +**A dedicated slot appended below the shipped rows.** Rejected: it makes the shipped rows a privileged group a plugin can only follow, and it needs a second rendering path in the primitive for what is one ordered list. + +**Entries that compute their own view-order writes.** A pin entry subscribing to the whole Session list and Workspace snapshot to assemble `pinSessionOrder`'s inputs re-renders every visible row on every list change and puts ordering detail into a menu row. Rejected: the injected callback owns the write and reads the snapshots once, at completion. + +**Declared shared stores for the rename request and the notice.** The request and the notice are one plugin's transient facts, so they travel as apply-closure observables through the entries' own inject faces. ## Consequences -Plugins can add Session actions without editing `ui-workspace`, while core actions keep a stable position and external conflicts use the slot registry's existing id and priority rules. Every contribution uses the shared `MenuAction`. All plugin actions remain in the secondary row menu until observed scale justifies a new hierarchy. +Plugins add, reorder, or shadow Session row actions in the menu and in the hover strip without editing `ui-workspace`, and the shipped actions follow the same rules and the same registration path. `WorkspaceBrowser` no longer threads action callbacks, renders a toast, or hosts the rename dialog; `Menu` grew `children` and made `items`/`onSelect` optional; `shell.overlay` gained two `ui-workspace` entries. The archived notice applies the "show archived" filter directly instead of opening the view-options menu. diff --git a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md index ae30d88dc8..906395fa9d 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-session-row-menu-actions-slot.zh.md @@ -1,4 +1,4 @@ -# Agent Note: Session 行菜单 action slot +# Agent Note: Session 行 action 即 slot 列表 Status: implemented @@ -6,30 +6,30 @@ Status: implemented ## 问题 -Session 行菜单原本是由 `ui-workspace` 持有的封闭 action 列表。第三方客户端插件可以添加独立的侧边栏控件,却无法在不修改 owner 包或复制菜单交互的情况下,把 action 放到 Rename、Fork 与 Archive 旁边。 +Session 行的 "..." 菜单和行尾悬停按钮原本是 `ui-workspace` 持有的封闭列表:browser 按行状态拼菜单 `items`、自己渲染置顶和归档按钮、把每个动作的回调一路传下去,连这些动作需要的 toast 和重命名对话框也由它持有。客户端插件可以自己添加侧边栏控件,却无法在不修改 owner 包或复制菜单交互的情况下把 action 放到内置项旁边。 ## 决策 -`ui-workspace` 在其 `sidebar.workspaces` 注册项下声明 root-scoped 有序列表 slot `sidebar.workspaces.session.menu.action`。每个贡献项接收目标 `sessionId` 与行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id);贡献插件将自身服务与 mutation 保留在自己的注册闭包中。 +`ui-workspace` 在其 `sidebar.workspaces` 注册项下声明两个 root-scoped `list` slot——菜单行用 `sidebar.workspaces.session.menu.item`,悬停按钮用 `sidebar.workspaces.session.row.action`——并在 `apply` 里以客户端插件的同一方式注册自己的 action:`pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100)。列表就是菜单和按钮条:条目按 `order` 升序渲染,插件 action 落在其 order 所指的位置,以另一个 `priority` 复用内置 id 则按注册表的普通 cell 规则遮蔽。没有单独的"扩展分组",也没有分隔线。 -共享 `MenuAction` primitive 在 `Menu` 内渲染所有贡献行。它让贡献行拥有与 owner 定义行相同的菜单项语义、键盘走位、子菜单重置、关闭行为、焦点恢复、禁用状态、图标位置与 danger 样式。动态客户端 bundle 直接通过 loader 的 `require` 从宿主隐式 baseline 解析 `ui-primitives`;它们不声明运行时依赖,也不携带第二套组件协议。 +条目只接收行身份 `{ sessionId, displayTitle }`,其余一切自己负责。它用标准 hook 读自己关心的 Host 状态(置顶与归档集合来自 `useWorkspaces`),并据此决定是否显示:Host 规定两个集合互斥,所以 pin 在归档行上不渲染;archive 从不参考 pin。整套行为放在注册项自己的 `inject` face 里,组件只调一个回调:`pinSession` 委托给 `uiWorkspace.pinSession`——先做 Host 置顶,成功后用 `pinSessionOrder` 把会话推到其记账保存顺序的最前,成员关系在完成时刻从对象层快照读取(`pin-order.ts`)——和这个服务原本就持有的 `archiveSession` 并列;归档 action 的回调在此之上加上提示。服务经 apply 自己创建、并作为 handle 交给 browser 注册项的那个 viewing store 实例写入视图顺序,与 `ui-layout` 处理 layout store 的方式相同。置顶与归档集合以 Set 形式经 face 的 `hooks` 到达条目,每次 Workspace 快照变化只重建一次,行读自己那一位只需一次查找。 -### 排序与渐进披露 +action 发起的浮层必须活得比行菜单久,所以它们是本包注册在 `shell.overlay` 的条目:重命名对话框和行 action 提示。action 经本插件 apply 闭包里的观察源到达自己的浮层:action 一侧注入为回调(`requestSessionRename`、`notify`),浮层一侧注入为 `hooks` 源(`useRenameRequest`、`useToast`)。browser 在标题双击时发出同一个重命名请求,在点击归档行时发出同一种提示;归档提示的第二个动作经同一个 store 实例把归档筛选切到"显示",因为 browser 的视图选项菜单已不在链路上。 -Rename、Fork 与 Archive 作为固定的 owner-defined 分组保持在顶部。贡献项在下方形成带语义分隔的分组,并遵循 list slot 排序:先按较小的 `order`,再按 live ledger 顺序。`order` 相同的打包注册保持注册顺序;动态注册使用 facade 分配的递减 shadowing priority,因此较新的注册在前。除此之外,priority 只在一个复用 id 的 cell 内选择活动注册,不会让不同 id 跨越 order。空分组在视觉与无障碍 API 中均隐藏。现有省略号菜单仍是唯一的渐进披露层;嵌套「More…」分组不属于此约定。 - -## 验证 - -Primitive 测试覆盖选择、关闭、焦点恢复、子菜单重置、语义分隔线与键盘顺序。行测试覆盖 owner props 与内置 action 优先于插件 action 的位置。组装后的 Slot 运行时测试验证不同 priority 下仍以 order 为主。真实 Loader/Web 场景安装动态包,在 Chromium 中打开已播种 Session 的菜单,对组装结果取快照,选择 action,并验证关闭、owner 数据与 fiber 生命周期清理。 +菜单条目渲染 `MenuItemButton`——`ui-primitives` 为"行是组件"的菜单提供的行组件,只是一行普通 markup 与样式。它能加入菜单的键盘走位与焦点归还,是因为 `Menu` 从 DOM 上统一决定这两件事(方向键走位查询行元素;选中后的焦点归还在列表的 click 冒泡上执行一次,数据行与组件行一视同仁)。两类行的关闭都是 owner 的状态:数据行通过 owner 的 `onSelect`,组件行通过 slot 级 `useMenuOpenState` hook——声明带 `inject: { hooks: { menuOpenState } }`,`SessionNodeItem` 把自己的 `[open, setOpen]` 作为该次渲染的 `hookContext` 传入,factory 把这一对原样交回。这正是 `sidebar.right.pane.tab` 用于 `useTabInfo` 的通道。 ## 考虑过的替代方案 -**通过 slot owner props 传递菜单 descriptor。** 这会使渲染 slot 变成第二套数据注册表,通过回调暴露展示策略,并阻止普通 slot 组件持有自身注入服务。 +**在 `Menu` 与行组件之间放一个 React context。** 否决:业务组件不接触任何 React context([client 规则](../../../../packages/client/AGENTS.md));Menu 与行是经 slot 系统建立的父子关系,控制权就该走 slot 的通道。 -**暴露原始菜单 markup。** 这会让插件偏离菜单的无障碍、焦点与视觉行为。要求使用共享 `MenuAction`,可让打包与动态加载的贡献项遵守同一套交互协议。 +**由 owner 提供行能力。** 把 `pinned`/`archived` 和 `pin`/`archive`/`rename`/`fork` 回调经 owner props 或 slot 级 hook 交给条目,会让 browser 继续拥有每个动作,内置 action 沦为薄封装。否决:这些不是菜单的能力,每个 action 的行为属于它自己,需要的 Host 状态条目可以直接读。 -**立即添加主要 slot 与「More…」slot。** Session action 已位于行省略号之后,而且当前 action 集合不需要另一层渐进披露。在出现已证实的密度问题前,第二层级只会提前增加标签与键盘策略。 +**在内置行下方追加一个专用 slot。** 否决:它把内置行变成插件只能跟在后面的特权分组,还要在 primitive 里为本来只是一个有序列表的东西开第二条渲染路径。 + +**让条目自己算置顶顺序写入。** pin 条目为了拼 `pinSessionOrder` 的输入订阅整个 Session 列表和 Workspace 快照,列表一变所有可见行都重渲染,排序细节还进了菜单行。否决:写入归注入的回调,在完成时刻读一次快照。 + +**用声明式共享 store 传重命名请求与提示。** 请求与提示是本插件自己的瞬时事实,所以经条目自己的 inject face 以 apply 闭包观察源传递。 ## 后果 -插件无需编辑 `ui-workspace` 即可添加 Session action,同时 core action 保持稳定位置,外部冲突沿用 slot 注册表已有的 id 与 priority 规则。所有贡献项都使用共享 `MenuAction`。所有插件 action 都保留在次级行菜单内,直到观察到的规模证明需要新层级。 +插件无需修改 `ui-workspace` 即可在菜单和悬停条里添加、重排或遮蔽 Session 行 action,内置 action 遵循相同规则、走相同注册路径。`WorkspaceBrowser` 不再传递 action 回调、渲染 toast 或承载重命名对话框;`Menu` 新增 `children`,`items`/`onSelect` 变为可选;`shell.overlay` 多了两个 `ui-workspace` 条目。归档提示直接应用"显示已归档"筛选,不再打开视图选项菜单。 diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index 6aeb3cb01f..50d7a12706 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -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/slots.md -slots.md: 0143fd713c856d17cb3d2e77188155c46983e106 -slots.zh.md: 18a52f954a7b065504de990e34fc42f536868e4d +slots.md: 1e820fd880163d565a72733372fa4f2cc70a62b5 +slots.zh.md: c5bec8e752b9d9e1922f608449ca3249d0477062 diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index 0143fd713c..1e820fd880 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -117,7 +117,8 @@ root │ ├─ sidebar.footer.action │ ├─ sidebar.workspaces │ │ ├─ sidebar.workspaces.directoryFlow -│ │ └─ sidebar.workspaces.session.menu.action +│ │ ├─ sidebar.workspaces.session.menu.item +│ │ └─ sidebar.workspaces.session.row.action │ └─ sidebar.settings │ ├─ settings.trigger │ ├─ settings.header diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 18a52f954a..c5bec8e752 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -117,7 +117,8 @@ root │ ├─ sidebar.footer.action │ ├─ sidebar.workspaces │ │ ├─ sidebar.workspaces.directoryFlow -│ │ └─ sidebar.workspaces.session.menu.action +│ │ ├─ sidebar.workspaces.session.menu.item +│ │ └─ sidebar.workspaces.session.row.action │ └─ sidebar.settings │ ├─ settings.trigger │ ├─ settings.header diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index e8e71de00d..d8df0b30d6 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -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-primitives/README.md -README.md: 5f45c6ffdc530a0ea7a64a7161c35f992c88ed02 -README.zh.md: 052c1c583c62e4dd06c0366eeadc5b41de86d9ec +README.md: 51ad53a79a676f013b61213764479a1247de522c +README.zh.md: c41d19af1855c8ab1582fa92b956ef283d3466cf diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 5f45c6ffdc..51ad53a79a 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -40,7 +40,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `Switch` | Two-state toggle, 36×20. `label` is required, so the control cannot ship unnamed. | | `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. | | `Input` | Single-line text entry for search boxes and inline forms. | -| `Menu`, `MenuAction` | Dropdown of owner-defined items, separators, and group labels, with nested submenus plus optional child actions rendered through `MenuAction`. Injected actions share the same styling, dismissal, focus restoration, submenu reset, and keyboard order. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. | +| `Menu`, `MenuItemButton` | Dropdown of `items` data rows, separators, and group labels, with nested submenus; `children` adds component rows, each a `MenuItemButton` (`separatorBefore` starts a new group), in the same list. Every row shares the styling, the keyboard walk, and the focus return; closing stays the owner's state change for both kinds. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. | | `Pill` | Selectable capsule button for view switchers and filters; takes `active` and `onClick`. | | `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. | | `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader. `aria-hidden`, so the render site owns the name. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 052c1c583c..c41d19af18 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -40,7 +40,7 @@ kind: "package-library" | `Switch` | 36×20 的双态开关。`label` 必填,控件不可能在没有名称的情况下发布。 | | `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。 | | `Input` | 单行文本输入,用于搜索框与行内表单。 | -| `Menu`, `MenuAction` | 由 owner 定义条目、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单,也可通过 `MenuAction` 渲染可选子 action。注入的 action 共享相同样式、关闭行为、焦点恢复、子菜单重置和键盘顺序。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 | +| `Menu`, `MenuItemButton` | 由 `items` 数据行、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单;`children` 在同一列表中加入组件行,每行一个 `MenuItemButton`(`separatorBefore` 开启新分组)。所有行共享样式、键盘走位与焦点归还;两类行的关闭都是 owner 状态的改变。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 | | `Pill` | 可选中的胶囊按钮,用于视图切换与筛选器;接受 `active` 与 `onClick`。 | | `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 | | `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading。它是 `aria-hidden` 的,名称由渲染点提供。 | diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index 19e48b7509..79650a1cb1 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -75,17 +75,6 @@ min-height: 0; } -/* Extension actions are the secondary group after owner-defined rows. */ -.extensionActions:not(:has(button[role='menuitem'])) { - display: none; -} - -.extensionSeparator { - margin-top: 4px; - margin-bottom: 4px; - border-top: 0.5px solid var(--dsw-alias-border-l2); -} - .scrollable .viewport { overflow-y: auto; } @@ -260,6 +249,13 @@ background: var(--dsw-alias-border-l2); } +/* Two group starts in a row (a data separator followed by a row that also + * starts a group, or two such rows) draw one line, not two. */ +.separator + .separator, +.separator + .itemWrap > .separator:first-child { + display: none; +} + /* Nested card to the right of the parent row. * Bottom-aligned with the parent menu card (grows upward): itemWrap sits in * .list's 3px pad, so bottom: -3px matches the list's outer bottom edge. diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index 7b12caadef..9b5c927d1b 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -1,4 +1,4 @@ -import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useEffect, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode } from 'react' import { createPortal } from 'react-dom' import clsx from 'clsx' @@ -36,52 +36,53 @@ export interface MenuLabel { /** One primary-menu entry: a row, a separator, or a heading label. */ export type MenuEntry = MenuItem | MenuSeparator | MenuLabel -interface MenuActionContextValue { - clearSubmenu: () => void - select: (action: () => void) => void -} - -const MenuActionContext = createContext(null) - -/** Props for an action contributed as a child of {@link Menu}. */ -export interface MenuActionProps { - /** Visible action label. */ +/** Props for one component-rendered menu row. */ +export interface MenuItemButtonProps { + /** Visible row label. */ children: ReactNode - /** Leading icon. */ + /** Leading icon (figma .Menu_cell gap 8). */ icon?: ReactNode - /** Whether the action cannot be selected. */ + /** Whether the row cannot be activated. */ disabled?: boolean - /** Use the destructive action colors. */ + /** Destructive row: error-colored text/icon and danger hover fill. */ danger?: boolean - /** Run the action, then close the containing menu and restore focus. */ + /** + * Start a new group: a hairline above this row, the same one a + * `{ type: 'separator' }` data entry draws. It comes and goes with the row, + * so a row that renders nothing leaves no stray line, and two adjacent + * group starts collapse into one line. + */ + separatorBefore?: boolean + /** Row activation (click, Enter, or Tab on the focused row). */ onSelect: () => void } /** - * Render one action supplied through a menu extension point. - * - * The action must be a descendant of {@link Menu}. It shares the menu's - * keyboard navigation, selection dismissal, focus restoration, and styling. - * @param props - action presentation and behavior. - * @param props.children - visible action label. + * Render one `role="menuitem"` row for a {@link Menu} whose rows are + * components rather than `items` data: the same markup and styling as a data + * row, so it joins the list's keyboard walk and post-selection focus return + * without any shared state. Closing the menu stays the owner's decision, as + * it is for data rows. + * @param props.children - visible row label. * @param props.icon - optional leading icon. - * @param props.disabled - whether the action cannot be selected. - * @param props.danger - whether to use destructive action colors. - * @param props.onSelect - action to run before the menu closes. + * @param props.disabled - whether the row cannot be activated. + * @param props.danger - whether to use the destructive row colors. + * @param props.separatorBefore - whether this row starts a new group (hairline above it). + * @param props.onSelect - row activation callback. * @returns one menu-item row. */ -export function MenuAction({ children, icon, disabled = false, danger = false, onSelect }: MenuActionProps) { - const menu = useContext(MenuActionContext) - if (menu === null) throw new Error('MenuAction must be rendered inside Menu') +export function MenuItemButton({ + children, icon, disabled = false, danger = false, separatorBefore = false, onSelect, +}: MenuItemButtonProps) { return ( -
+
+ {separatorBefore &&
} } - items={[{ id: 'a', label: 'Alpha', submenu: [{ id: 'a1', label: 'Alpha one' }] }]} + items={[{ id: 'a', label: 'Alpha' }]} onSelect={() => {}} onClose={() => { setOpen(false) }} > - Publish + { onAction(); setOpen(false) }}>Publish ) } render() const trigger = screen.getByRole('button', { name: 'trigger' }) - fireEvent.mouseEnter(screen.getByRole('menuitem', { name: 'Alpha' })) - expect(screen.getByRole('menuitem', { name: 'Alpha one' })).toBeDefined() - expect(screen.getByRole('separator')).toBeDefined() + expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual(['Alpha', 'Publish']) + // The component row starts a group: one hairline, between the data row and it. + const publishWrap = screen.getByRole('menuitem', { name: 'Publish' }).parentElement + expect(screen.getByRole('separator').nextElementSibling).toBe(screen.getByRole('menuitem', { name: 'Publish' })) + expect(publishWrap?.contains(screen.getByRole('separator'))).toBe(true) const publish = screen.getByRole('menuitem', { name: 'Publish' }) trigger.focus() fireEvent.keyDown(trigger, { key: 'End' }) expect(document.activeElement).toBe(publish) - expect(screen.queryByRole('menuitem', { name: 'Alpha one' })).toBeNull() + fireEvent.keyDown(publish, { key: 'ArrowUp' }) + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Alpha' })) fireEvent.click(publish) expect(onAction).toHaveBeenCalledOnce() expect(screen.queryByRole('menu')).toBeNull() diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 8fee12f4a5..7ffc1dfcf9 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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-workspace/README.md -README.md: 98bc6c7843c6d76c236f6bce83bf70a823d3394e -README.zh.md: 678568ad19e9b20ab9ad989a6d5505af7bc295f3 +README.md: 65b0bd300b9e13bea18fc0c49b0594e38b649728 +README.zh.md: 170a1a3e2bd71b400aa9e2c0e318f5e9100b3526 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 98bc6c7843..65b0bd300b 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -1,5 +1,5 @@ --- -description: "Shared Workspace browser and picker plugin for the dsh web client: grouped or flat session rows, management actions, extensible Session menus, and directory picking." +description: "Shared Workspace browser and picker plugin for the dsh web client: grouped or flat session rows, management actions, the slot-composed Session row actions, and directory picking." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -This package lets users browse grouped or flat Session lists, choose a Workspace for a new Session, and manage Workspaces and Sessions through add, rename, reorder, search, fork, archive, extensible row-menu actions, and Workspace deletion. Pending interactions appear as warning dots, active scheduled tasks as alarm markers, and subagent-origin Sessions remain hidden. Canonically distinct folder paths remain separate Workspaces. Adding a Workspace requires a composed directory picker; without one, the add action is unavailable. +This package lets users browse grouped or flat Session lists, choose a Workspace for a new Session, and manage Workspaces and Sessions through add, rename, reorder, search, fork, archive, and Workspace deletion; the Session row menu and its hover buttons are slot lists that client plugins extend. Pending interactions appear as warning dots, active scheduled tasks as alarm markers, and subagent-origin Sessions remain hidden. Canonically distinct folder paths remain separate Workspaces. Adding a Workspace requires a composed directory picker; without one, the add action is unavailable. ## Table of Contents @@ -47,9 +47,9 @@ Collapsed search is one header action beside the view and add actions: activatin ### Managing sessions -The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action forks at the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Client plugins can append Session-specific actions to this menu through the ordered `sidebar.workspaces.session.menu.action` slot. +The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action forks at the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, and Archive are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it. -Archive commits without a confirmation dialog and retains the Session's account position. View options control visibility: the default hides archived Sessions, Show archived includes them, and Archived only hides ordinary Sessions. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a toast with undo and filter-menu actions. Unarchive removes the archive mark without restoring a pin or changing the saved position. +Archive commits without a confirmation dialog and retains the Session's account position. View options control visibility: the default hides archived Sessions, Show archived includes them, and Archived only hides ordinary Sessions. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a notice with an undo action and a "show archived" action that switches the filter directly. Unarchive removes the archive mark without restoring a pin or changing the saved position. A Session title wider than its row is clipped with an ellipsis at rest. Hovering the row scrolls the title to its far edge — the incremented title of a fork, for example — and reveals it without the ellipsis; leaving the row returns the title to its start. @@ -81,15 +81,15 @@ The package is one composition: both target slots are declared by other plugins, Each registration declares a **directory-flow child hole** (`single` kind: `conversation.hero.workspace.directoryFlow` / `sidebar.workspaces.directoryFlow`) that the composed picker package's client half fills with its picking interaction — the `-native` backend's renderless OS-chooser driver, an in-app browsing dialog under a `-browse` composition. The flat **Add workspace...** action renders only while the surface's hole is occupied; an empty hole means the composition has no picking affordance. This package owns the trigger and the adoption: the occupant reports one picked path per open through the hole's owner conversation (`open`/`busy`/`onPicked`/`onCancel`/`onError`), and the owner adopts it through the object layer, selecting the committed Workspace only after its list projection has refreshed. -### Session menu actions +### Session row actions -An external client plugin contributes to `sidebar.workspaces.session.menu.action`. Built-in actions stay first in their fixed order; contributed actions form a secondary group after a semantic separator. The group is absent from presentation and accessibility APIs when it has no rendered menu-item button. +The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), and `archive` (menu 400, button 100) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action. -Each contribution receives the target `sessionId` and row `displayTitle` (persisted title, project basename, then Session id). Render the contribution with the shared `MenuAction` primitive; it owns the menu's styling, keyboard behavior, dismissal, and focus restoration. Use a fresh, package-namespaced `id`. Lower `order` values render first. Equal-order packaged registrations keep registration sequence; equal-order dynamic registrations use the facade's decreasing shadowing priority, so the newer entry comes first. `priority` otherwise selects the active registration when two entries deliberately reuse one `id`; it does not move a distinct id across `order` groups. +An entry receives only the row identity (`sessionId`, `displayTitle`) and owns everything else. It reads the Host state it cares about through its own injected hooks (the pin and archive sets, as Sets derived once per Workspace snapshot), decides its own visibility (pin renders nothing on an archived row, because the Host keeps the two sets exclusive), carries its whole behavior in its registration's `inject` face (a pin also fronts the Session in its saved orders; an archive raises the notice), and raises its own surfaces: the rename dialog and the row-action notice are this package's `shell.overlay` entries, fed by the requests the actions inject. A menu entry renders one `MenuItemButton` (with `separatorBefore` when it starts a new group; the hairline comes and goes with the row) and dismisses the menu through the slot-level `useMenuOpenState` hook, the menu's own open state bound from the row's render occurrence; a hover button entry renders one icon button. The browser passes no action callbacks to its rows; its remaining verbs are the search results' restore button and the title double-click, which raises the same rename request. #### Packaged client plugin -Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot key. Keep the Component at module scope, project business operations through the registration's `inject` face, and own visible copy in the contributing package's locale namespace. +Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot keys. Keep the Component at module scope and own visible copy in the contributing package's locale namespace. ```tsx import type { Context } from '@deepseek-ai/cordis' @@ -97,7 +97,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' -import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' +import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, LocaleDictOf, PropsLocale, PropsRuntime, } from '@deepseek-ai/dsh-client-ui-slots' @@ -114,20 +114,21 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { const en: LocaleDictOf = { export: 'Export {title}' } const zh: LocaleDictOf = { export: '导出 {title}' } -interface ExportActionInjected { +interface ExportRowInjected { exportSession: (sessionId: SessionId) => void } -type ExportActionProps = - PropsRuntime<'sidebar.workspaces.session.menu.action'> +type ExportRowProps = + PropsRuntime<'sidebar.workspaces.session.menu.item'> & PropsLocale - & InjectFace + & InjectFace -function ExportAction({ sessionId, displayTitle, exportSession, t }: ExportActionProps) { +function ExportRow({ sessionId, displayTitle, useMenuOpenState, exportSession, t }: ExportRowProps) { + const [, setMenuOpen] = useMenuOpenState() return ( - { exportSession(sessionId) }}> + { setMenuOpen(false); exportSession(sessionId) }}> {t('export', { title: displayTitle })} - + ) } @@ -136,21 +137,22 @@ export const inject = ['slots', 'locale'] export function apply(ctx: Context): void { ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'acme-session-actions: dictionaries') - ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register({ - name: 'sidebar.workspaces.session.menu.action', + // Order 500 places the row after the shipped Archive (400); `separatorBefore` opens the plugin group. + ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register({ + name: 'sidebar.workspaces.session.menu.item', id: 'acme.export-session', - order: 100, + order: 500, locale: NS, - inject: (): ExportActionInjected => ({ exportSession }), - }, ExportAction)) + inject: (): ExportRowInjected => ({ exportSession }), + }, ExportRow)) } ``` -`ctx.slots.inject()` is required even if the owner is normally present: it waits for the declaration, removes the contribution when that declaration collapses, and registers it again after restoration. The registration's `inject` factory may close over the plugin's declared Cordis services; the Component receives only the projected data and callbacks. +`ctx.slots.inject()` is required even if the owner is normally present: it waits for the declaration, removes the contribution when that declaration collapses, and registers it again after restoration. The registration's `inject` factory may close over the plugin's declared Cordis services; the Component receives only the projected data and callbacks. A hover button registers into `sidebar.workspaces.session.row.action` the same way and renders one icon button. #### Dynamic client package -A dynamically loaded browser half follows the same component contract. `@deepseek-ai/dsh-client-ui-primitives` is an implicit baseline external: resolve its shared `MenuAction` export directly through the loader's `require`, and render it with `React.createElement`. Do not list the primitive as a runtime dependency or bundle another copy; declare a development dependency only when source compilation needs its types. `MenuAction` must share the host menu context. The real Loader/Web fixture and generated Client Slot catalog contain runnable examples. +A dynamically loaded browser half follows the same component contract. `@deepseek-ai/dsh-client-ui-primitives` is an implicit baseline external: resolve `MenuItemButton` through the loader's `require` and render it with `React.createElement`. Do not list the primitive as a runtime dependency or bundle another copy; declare a development dependency only when source compilation needs its types. The real Loader/Web fixture and the generated Client Slot catalog contain runnable examples. ### View state diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 678568ad19..170a1a3e2b 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -1,5 +1,5 @@ --- -description: "dsh Web 客户端的共享 Workspace 浏览器与选择器插件:分组或扁平的会话行、管理操作、可扩展 Session 菜单与目录选择。" +description: "dsh Web 客户端的共享 Workspace 浏览器与选择器插件:分组或扁平的会话行、管理操作、由 slot 组合的 Session 行 action 与目录选择。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -本包让用户浏览分组或扁平的 Session 列表、为新 Session 选择 Workspace,并通过添加、重命名、重排序、搜索、fork、归档、可扩展行菜单操作和删除 Workspace 来管理 Workspace 与 Session。待处理交互显示为警告点,活动定时任务显示为闹钟标识,subagent 来源的 Session 则保持隐藏。规范化后仍有差异的文件夹路径会保留为独立 Workspace。添加 Workspace 需要组合目录选择器;没有目录选择器时,添加操作不可用。 +本包让用户浏览分组或扁平的 Session 列表、为新 Session 选择 Workspace,并通过添加、重命名、重排序、搜索、fork、归档和删除 Workspace 来管理 Workspace 与 Session;Session 行菜单及其悬停按钮是可由客户端插件扩展的 slot 列表。待处理交互显示为警告点,活动定时任务显示为闹钟标识,subagent 来源的 Session 则保持隐藏。规范化后仍有差异的文件夹路径会保留为独立 Workspace。添加 Workspace 需要组合目录选择器;没有目录选择器时,添加操作不可用。 ## 目录 @@ -47,9 +47,9 @@ kind: "package-reference" ### 管理会话 -Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 在源会话最后一个已完成轮次处 fork,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。客户端插件可通过有序 `sidebar.workspaces.session.menu.action` slot 向此菜单追加 Session 专属 action。 +Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 在源会话最后一个已完成轮次处 fork,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。 -Archive 不经确认对话框直接提交,并保留 Session 的记账位置。视图选项控制显隐:默认隐藏已归档 Session,显示已归档会将其纳入列表,仅显示已归档则隐藏普通 Session。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后,toast 提供撤销与打开筛选菜单的操作。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。 +Archive 不经确认对话框直接提交,并保留 Session 的记账位置。视图选项控制显隐:默认隐藏已归档 Session,显示已归档会将其纳入列表,仅显示已归档则隐藏普通 Session。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后的提示提供"撤销"和"筛选已归档会话"两个动作,后者直接把筛选切到显示已归档。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。 标题宽于所在行时,静止状态以省略号裁切。把指针停在行上,标题会滚动到远端——例如 fork 递增后的标题——并在揭示时不显示省略号;指针离开后标题回到开头。 @@ -81,15 +81,15 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** 每个注册各自声明一个**目录流子 slot**(`single` kind:`conversation.hero.workspace.directoryFlow`/`sidebar.workspaces.directoryFlow`),由组合的选择器包 client half 填入其选取交互——`-native` 后端的无渲染 OS 选择器驱动,`-browse` 组合下则是应用内浏览对话框。平铺显示的**添加工作区…** 操作仅在当前界面的 slot 被占用时渲染;slot 为空意味着该组合没有目录选择能力。本包持有触发与接纳:占用方通过 slot 的属主交互约定(`open`/`busy`/`onPicked`/`onCancel`/`onError`)每次打开上报一个所选路径,owner 通过对象层接纳它,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace。 -### Session 菜单 action +### Session 行 action -外部客户端插件向 `sidebar.workspaces.session.menu.action` 贡献 action。内置 action 以固定顺序保持在前;贡献 action 位于语义分隔线后的次级分组中。没有渲染菜单按钮时,该分组不会出现在视觉与无障碍 API 中。 +Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。 -每个贡献项接收目标 `sessionId` 与行 `displayTitle`(依次回退到持久化标题、项目目录名、Session id)。贡献项必须使用共享的 `MenuAction` primitive 渲染;菜单样式、键盘行为、关闭与焦点恢复均由它统一负责。请使用带包命名空间的新 `id`。较小的 `order` 先渲染;`order` 相同的打包注册保持注册顺序,动态注册则使用 facade 分配的递减 shadowing priority,因此较新的注册在前。除此之外,`priority` 只在两个注册有意复用同一 `id` 时选择活动项,不会让不同 id 跨越 `order` 分组。 +条目只接收行身份(`sessionId`、`displayTitle`),其余一切自己负责:用自己注入的 hook 读自己关心的 Host 状态(置顶与归档集合,以每次 Workspace 快照只派生一次的 Set 形式),自己决定是否显示(Host 规定归档与置顶互斥,所以 pin 在归档行上不渲染),整套行为放在注册项自己的 `inject` face 里(置顶成功后顺带把会话推到保存顺序最前,归档成功后发提示),浮层也自己带——重命名对话框和行 action 的提示是本包注册在 `shell.overlay` 的条目,由 action 注入的请求驱动。菜单条目渲染一个 `MenuItemButton`(开启新分组的行加 `separatorBefore`,分隔线随行一起出现和消失),并通过 slot 级 `useMenuOpenState` hook(菜单自身的打开状态,从该行的渲染出现处绑定)关闭菜单;悬停按钮条目渲染一个图标按钮。browser 不再向行传任何 action 回调,它剩下的动作只有搜索结果里的恢复按钮和标题双击,后者发出的是同一个重命名请求。 #### 打包客户端插件 -按照 Client 依赖规则,将 `ui-workspace`、`ui-slots`、`ui-renderer`、`client-locale` 与 `ui-primitives` 声明为浏览器/类型开发依赖。纯类型的 `ui-workspace/client` import 会加载本包的 `SlotMap` 声明;缺少该 import 时,独立编译的插件不会知道这个 slot key。Component 保持模块级稳定身份;业务操作通过注册项的 `inject` face 投影;用户可见文案由贡献包自己的 locale namespace 持有。 +按照 Client 依赖规则,将 `ui-workspace`、`ui-slots`、`ui-renderer`、`client-locale` 与 `ui-primitives` 声明为浏览器/类型开发依赖。纯类型的 `ui-workspace/client` import 会加载本包的 `SlotMap` 声明;缺少该 import 时,独立编译的插件不会知道这些 slot key。Component 保持模块级稳定身份;用户可见文案由贡献包自己的 locale namespace 持有。 ```tsx import type { Context } from '@deepseek-ai/cordis' @@ -97,7 +97,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' -import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' +import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, LocaleDictOf, PropsLocale, PropsRuntime, } from '@deepseek-ai/dsh-client-ui-slots' @@ -114,20 +114,21 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { const en: LocaleDictOf = { export: 'Export {title}' } const zh: LocaleDictOf = { export: '导出 {title}' } -interface ExportActionInjected { +interface ExportRowInjected { exportSession: (sessionId: SessionId) => void } -type ExportActionProps = - PropsRuntime<'sidebar.workspaces.session.menu.action'> +type ExportRowProps = + PropsRuntime<'sidebar.workspaces.session.menu.item'> & PropsLocale - & InjectFace + & InjectFace -function ExportAction({ sessionId, displayTitle, exportSession, t }: ExportActionProps) { +function ExportRow({ sessionId, displayTitle, useMenuOpenState, exportSession, t }: ExportRowProps) { + const [, setMenuOpen] = useMenuOpenState() return ( - { exportSession(sessionId) }}> + { setMenuOpen(false); exportSession(sessionId) }}> {t('export', { title: displayTitle })} - + ) } @@ -136,21 +137,22 @@ export const inject = ['slots', 'locale'] export function apply(ctx: Context): void { ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'acme-session-actions: dictionaries') - ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register({ - name: 'sidebar.workspaces.session.menu.action', + // Order 500 places the row after the shipped Archive (400); `separatorBefore` opens the plugin group. + ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register({ + name: 'sidebar.workspaces.session.menu.item', id: 'acme.export-session', - order: 100, + order: 500, locale: NS, - inject: (): ExportActionInjected => ({ exportSession }), - }, ExportAction)) + inject: (): ExportRowInjected => ({ exportSession }), + }, ExportRow)) } ``` -即使 owner 通常已经存在,也必须使用 `ctx.slots.inject()`:它等待声明,在声明折叠时移除贡献项,并在声明恢复后重新注册。注册项的 `inject` factory 可以闭包使用插件已声明的 Cordis service;Component 只接收投影后的数据和 callback。 +即使 owner 通常已经存在,也必须使用 `ctx.slots.inject()`:它等待声明,在声明折叠时移除贡献项,并在声明恢复后重新注册。注册项的 `inject` factory 可以闭包使用插件已声明的 Cordis service;Component 只接收投影后的数据和 callback。悬停按钮以同样方式注册到 `sidebar.workspaces.session.row.action`,渲染一个图标按钮。 #### 动态客户端包 -动态加载的 browser half 采用同一套组件协议。`@deepseek-ai/dsh-client-ui-primitives` 是隐式 baseline external:直接通过 loader 的 `require` 解析共享的 `MenuAction` export,再用 `React.createElement` 渲染。不要把 primitive 列为运行时依赖或打包另一份副本;仅在源码编译需要其类型时声明开发依赖。`MenuAction` 必须与宿主菜单共享 context。真实 Loader/Web fixture 与生成的 Client Slot catalog 都包含可运行示例。 +动态加载的 browser half 采用同一套组件协议。`@deepseek-ai/dsh-client-ui-primitives` 是隐式 baseline external:通过 loader 的 `require` 解析 `MenuItemButton`,再用 `React.createElement` 渲染。不要把 primitive 列为运行时依赖或打包另一份副本;仅在源码编译需要其类型时声明开发依赖。真实 Loader/Web fixture 与生成的 Client Slot catalog 都包含可运行示例。 ### 视图状态 diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 0e6d57a33a..2e9dad88c6 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -20,14 +20,26 @@ * leaves the surface with no add affordance at all. * Two holes exist because the two menu surfaces are independent slot entries * and a hole has exactly one declaring entry — they carry the same owner - * contract and the same occupant. WorkspaceBrowser also declares the ordered - * Session-menu action list that client plugins can extend. + * contract and the same occupant. + * + * WorkspaceBrowser also declares the two **Session row action lists**: every + * row of a Session's "..." menu is an entry of + * `sidebar.workspaces.session.menu.item`, and every hover button at the row's + * end is an entry of `sidebar.workspaces.session.row.action`. The shipped + * actions — pin, rename, fork, archive — are ordinary entries this package + * registers from `apply`, each carrying its own behavior in its own inject + * face and reading its own Host state through the standard hooks, so a client + * plugin's action lands beside them by `order` and needs nothing from the + * browser beyond the row identity. */ -import type { HostObservable, PropsHooks, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type { + HostObservable, InjectFace, PropsHooks, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore, SlotHookFactory, +} from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pull the owner SlotMap merges into programs that resolve the // runtime shares below. import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client' import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' @@ -52,14 +64,35 @@ export interface DirectoryFlowOwnerProps { onError: (message: string) => void } -/** Point-in-time Session row information supplied to each menu action. */ -export interface SessionMenuActionOwnerProps { - /** Session targeted by the open row menu. */ +/** Owner share of one Session row action occurrence: the row the action belongs to. */ +export interface SessionRowOwnerProps { + /** Session the row shows. */ sessionId: SessionId /** Row display title: persisted title, project basename, or Session id. */ displayTitle: string } +/** The row menu's open state as its owner holds it: the `useState` pair. */ +export type MenuOpenState = readonly [open: boolean, setOpen: (open: boolean) => void] + +/** + * Hook every row-menu entry receives. Rows only render while the menu is + * open, so an entry reads it for the setter: `setOpen(false)` dismisses the + * menu the entry sits in — the same state the owner's `onClose` sets. + */ +export type UseMenuOpenState = () => MenuOpenState + +/** + * Bind the row's render occurrence into the entries' `useMenuOpenState` hook: + * the owner supplies its open-state pair as the occurrence's `hookContext`, + * and the hook hands that pair back. + * @param _standard - framework standard props (unused). + * @param state - the menu's open-state pair from the render occurrence. + * @returns the hook the entry calls. + */ +export const menuOpenStateFactory: SlotHookFactory<'sidebar.workspaces.session.menu.item', UseMenuOpenState> = + (_standard, state) => () => state + declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Directory-flow hole under the conversation empty-state picker (declared by the WorkspacePicker entry). */ @@ -67,34 +100,51 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { /** Directory-flow hole under the sidebar browsing region (declared by the WorkspaceBrowser entry). */ 'sidebar.workspaces.directoryFlow': { kind: 'single'; scope: 'root'; owner: DirectoryFlowOwnerProps } /** - * Ordered third-party actions below the built-in Session row-menu actions. - * Registrations use a fresh id and sort by lower order. Equal-order packaged - * registrations keep registration sequence; equal-order dynamic registrations - * use the facade's decreasing shadowing priority, so the newer entry comes - * first. Priority selects the active registration for one reused id; it does - * not override order across distinct ids. Contributions render `MenuAction` - * so the shared primitive owns styling, keyboard behavior, dismissal, and - * focus restoration. An empty list has no visible or accessible secondary group. + * The rows of one Session's "..." menu, in ascending `order`. ui-workspace + * registers the shipped rows here — `pin` (100), `rename` (200), `fork` + * (300), `archive` (400) — so a plugin row is placed by its own `order` + * among them. Use a package-namespaced `id`; reusing a shipped id at + * another `priority` shadows that row. Each entry renders one + * `MenuItemButton` (`separatorBefore` when it starts a new group), decides + * its own visibility from its own state, and dismisses the menu through the + * injected `useMenuOpenState` hook after acting. Labels come from the + * contributing package's locale namespace. * @example * const React = require('react') - * const { MenuAction } = require('@deepseek-ai/dsh-client-ui-primitives') + * const { MenuItemButton } = require('@deepseek-ai/dsh-client-ui-primitives') * * return { * inject: ['slots'], * apply(ctx) { * const copyLabel = 'Copy Session ID' // Localize in the contributing package. - * ctx.slots.inject('sidebar.workspaces.session.menu.action', () => ctx.slots.register( - * { name: 'sidebar.workspaces.session.menu.action', id: 'copy-session-id', order: 100 }, - * ({ sessionId }) => React.createElement( - * MenuAction, - * { onSelect: () => { void navigator.clipboard.writeText(sessionId) } }, - * copyLabel, - * ), + * ctx.slots.inject('sidebar.workspaces.session.menu.item', () => ctx.slots.register( + * { name: 'sidebar.workspaces.session.menu.item', id: 'copy-session-id', order: 500 }, + * ({ sessionId, useMenuOpenState }) => { + * const [, setMenuOpen] = useMenuOpenState() + * return React.createElement( + * MenuItemButton, + * { onSelect: () => { setMenuOpen(false); void navigator.clipboard.writeText(sessionId) } }, + * copyLabel, + * ) + * }, * )) * }, * } */ - 'sidebar.workspaces.session.menu.action': { kind: 'list'; scope: 'root'; owner: SessionMenuActionOwnerProps } + 'sidebar.workspaces.session.menu.item': { + kind: 'list' + scope: 'root' + owner: SessionRowOwnerProps + hookContext: MenuOpenState + inject: { hooks: { menuOpenState: SlotHookFactory<'sidebar.workspaces.session.menu.item', UseMenuOpenState> } } + } + /** + * The hover buttons at the end of one Session row, in ascending `order`, + * after the "..." menu trigger. ui-workspace registers `archive` (100) and + * `pin` (200) here. An entry renders one icon button (or nothing, when its + * action does not apply to the row) and owns the action it performs. + */ + 'sidebar.workspaces.session.row.action': { kind: 'list'; scope: 'root'; owner: SessionRowOwnerProps } } } @@ -153,10 +203,10 @@ export type WorkspaceBrowserInjected = { ) => Promise<{ items: readonly SessionSearchResultItem[]; hasMore: boolean }> /** Maximum number of merged rows rendered for one search. */ searchResultLimit: number - /** Rename a Session (explicit user title; resolves on host acceptance). */ - renameSession: (sessionId: SessionId, title: string) => Promise - /** Fork a Session at its last completed turn and open the child. */ - forkSession: (sessionId: SessionId) => void + /** Open the Session rename dialog (a row title double-click); the rename action entry raises the same request. */ + requestSessionRename: (sessionId: SessionId, currentTitle: string) => void + /** Tell the user an archived row cannot be opened (a click on it). */ + notifyArchivedNotOpenable: () => void /** Rename a Host Workspace (rejects on name conflict; resolves on durability). */ renameWorkspace: (workspaceId: WorkspaceId, title: string) => Promise /** Delete only a Host Workspace registration; directory and Session logs remain. */ @@ -166,29 +216,143 @@ export type WorkspaceBrowserInjected = { * Omitted anchor appends to the end. */ insertWorkspaceBefore: (workspaceId: WorkspaceId, beforeWorkspaceId?: WorkspaceId) => Promise - /** - * Archive a Session into the registry-global set: hidden from grouping - * surfaces, log and accounting slot retained. Archiving the current - * session clears the selection into the New Session view state. - */ - archiveSession: (sessionId: SessionId) => Promise - /** Remove a Session from the registry-global archived set. */ + /** Remove a Session from the registry-global archived set (the search results' restore button). */ unarchiveSession: (sessionId: SessionId) => Promise - /** Add a Session to the registry-global pinned set (newest pin first). */ - pinSession: (sessionId: SessionId) => Promise - /** Remove a Session from the registry-global pinned set. */ - unpinSession: (sessionId: SessionId) => Promise /** Adopt a picked host directory as a real Workspace before targeting a Session. */ createWorkspace: (input: { path: string }) => Promise } +/** The browser's declared viewing store handle, shared with the row actions that write view state. */ +export type WorkspaceViewStoreHandle = ReturnType + +/** Props of one shipped row-menu entry: owner share + locale seat + the entry's own injected share. */ +export type SessionMenuItemProps = + PropsRuntime<'sidebar.workspaces.session.menu.item'> + & PropsLocale<'workspace'> + & InjectFace + +/** Props of one shipped row hover button: owner share + locale seat + the entry's own injected share. */ +export type SessionRowActionProps = + PropsRuntime<'sidebar.workspaces.session.row.action'> + & PropsLocale<'workspace'> + & InjectFace + +/** One transient notice a row action raises; the overlay toast entry renders it. */ +export type RowToast = + | { kind: 'archived'; sessionId: SessionId } + | { kind: 'pinFailed' } + | { kind: 'unpinFailed' } + | { kind: 'archivedNotOpenable' } + +/** The notice on display; `seq` keys remounts so a repeated notice restarts its hold. */ +export type RowToastState = RowToast & { seq: number } + +/** + * Pin action share (menu row and hover button). The callbacks carry the whole + * behavior: the Host call, fronting the Session in its saved orders after a + * pin, and the failure notice. The hooks are the registry-global sets as + * Sets, so a row reads its own membership with one lookup. + */ +export interface PinSessionInjected { + hooks: { + /** Pinned Session ids. */ + pinned: HostObservable> + /** Archived Session ids (pin does not apply to an archived row). */ + archived: HostObservable> + } + /** Pin a Session; on success it leads its accounts' saved orders, on failure the notice says so. */ + pinSession: (sessionId: SessionId) => void + /** Unpin a Session; saved positions stay as they are. */ + unpinSession: (sessionId: SessionId) => void +} + +/** + * Archive action share (menu row and hover button). The callbacks carry the + * whole behavior: the Host call, the notice a success raises, and the + * diagnostics for a rejection. + */ +export interface ArchiveSessionInjected { + hooks: { + /** Archived Session ids. */ + archived: HostObservable> + } + /** + * Archive a Session into the registry-global set: the row keeps its + * account position and shows per the archived filter; archiving the + * current session clears the selection into the New Session view state. + */ + archiveSession: (sessionId: SessionId) => void + /** Remove a Session from the registry-global archived set. */ + unarchiveSession: (sessionId: SessionId) => void +} + +/** Fork action share. */ +export interface ForkSessionInjected { + /** Fork a Session at its last completed turn; the child arrives through the Host list. */ + forkSession: (sessionId: SessionId) => void +} + +/** Rename action share: the row only raises the request; the dialog entry answers it. */ +export interface RenameSessionInjected { + /** Ask for the rename dialog, seeded with the row's current title. */ + requestSessionRename: (sessionId: SessionId, currentTitle: string) => void +} + +/** A Session rename the rename action asked for; the dialog entry opens on it. */ +export interface SessionRenameRequest { + /** Session to rename. */ + sessionId: SessionId + /** Title the dialog seeds its draft from. */ + currentTitle: string +} + +/** Rename dialog share: the pending request, its settlement, and the rename hop the dialog confirms with. */ +export interface SessionRenameDialogInjected { + hooks: { + /** The rename asked for, until the dialog consumes or cancels it. */ + renameRequest: HostObservable + } + /** Consume or cancel the pending request. */ + settleSessionRename: () => void + /** Rename a Session (explicit user title; resolves on host acceptance). */ + renameSession: (sessionId: SessionId, title: string) => Promise +} + +/** Row toast share: the notice on display, its dismissal, and the two actions the archived notice offers. */ +export interface RowToastInjected { + hooks: { + /** The notice on display, or none. */ + toast: HostObservable + } + /** Take the notice down. */ + dismissToast: () => void + /** Undo an archive from its notice. */ + undoArchive: (sessionId: SessionId) => void + /** Switch the archived filter to "show" so the archived row is back in view. */ + showArchived: () => void +} + +/** Props of the rename dialog entry in `shell.overlay`. */ +export type SessionRenameDialogProps = + PropsRuntime<'shell.overlay'> + & PropsLocale<'workspace'> + & Omit + & PropsHooks + +/** Props of the row toast entry in `shell.overlay`. */ +export type RowToastProps = + PropsRuntime<'shell.overlay'> + & PropsLocale<'workspace'> + & Omit + & PropsHooks + /** Full browser props: shell owner share + viewing store + injected actions + the locale seat. */ export type WorkspaceBrowserProps = PropsRuntime<'sidebar.workspaces'> & PropsRenderSlots< - 'sidebar.workspaces.directoryFlow' | 'sidebar.workspaces.session.menu.action' + 'sidebar.workspaces.directoryFlow' | 'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action' > - & PropsStore> + & PropsStore & Omit & PropsHooks & PropsLocale<'workspace'> diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index f4e23df96f..b66277a782 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -5,15 +5,20 @@ * (`conversation.hero.workspace` — both hero forms). Both read real Host * Workspaces through the global useWorkspaces hook, and each declares its * own `single` directory-flow child hole for the composed picker package's - * client half. WorkspaceBrowser additionally declares the ordered Session - * menu-action list (see the contract module doc). Export discipline: + * client half. WorkspaceBrowser additionally declares the two Session row + * action lists, and this apply registers the shipped actions — pin, rename, + * fork, archive — into them the way any client plugin would, each with its + * own behavior, plus the rename dialog and the row-action notice into + * `shell.overlay` (see the contract module doc). Export discipline: * packages/client/AGENTS.md. */ import type { Context } from '@deepseek-ai/cordis' import type { RemoteHostFacts } from '@deepseek-ai/dsh-api-remotes/client' import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client' import type { IWorkspaces, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { HostObservable, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots' +import type { SessionId } from '@deepseek-ai/dsh-session/types' // Type-only: pulls the Controller service merges. import type {} from '@deepseek-ai/dsh-api-session-controller/client' import type {} from '@deepseek-ai/dsh-api-workspace-controller/client' @@ -24,17 +29,28 @@ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' // Type-only: pulls the Session root standard-hook merge. import type {} from '@deepseek-ai/dsh-client-ui-session/client' -import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from './contract/slots.ts' +import { + type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected, + type RenameSessionInjected, type RowToast, type RowToastInjected, type RowToastState, type SessionRenameDialogInjected, + type SessionRenameRequest, type WorkspaceBrowserInjected, type WorkspacePickerInjected, +} from './contract/slots.ts' import { UiWorkspaceService } from './navigation.ts' import { createWorkspaceViewStore } from './stores.ts' import { WorkspaceBrowser } from './rows/WorkspaceBrowser.tsx' +import { ArchiveSessionMenuItem, ArchiveSessionRowButton } from './session-actions/ArchiveSession.tsx' +import { derive } from './session-actions/derived.ts' +import { ForkSessionMenuItem } from './session-actions/ForkSession.tsx' +import { PinSessionMenuItem, PinSessionRowButton } from './session-actions/PinSession.tsx' +import { RenameSessionMenuItem, SessionRenameDialog } from './session-actions/RenameSession.tsx' +import { RowActionToast } from './session-actions/RowActionToast.tsx' import { WorkspacePicker } from './WorkspacePicker.tsx' import { en, zh, type WorkspaceKey } from './locales.ts' export type { UiWorkspace } from './navigation.ts' export type { DirectoryFlowOwnerProps, DirectoryFlowSlotName, DirectoryPickingHooks, DirectoryPickingInjected, - SessionMenuActionOwnerProps, WorkspaceBrowserInjected, WorkspaceBrowserProps, + MenuOpenState, RowToast, SessionRenameRequest, SessionRowOwnerProps, UseMenuOpenState, WorkspaceBrowserInjected, + WorkspaceBrowserProps, WorkspacePickerInjected, WorkspacePickerProps, } from './contract/slots.ts' export type { WorkspaceKey } from './locales.ts' @@ -81,8 +97,14 @@ export const inject = [ export function apply(ctx: Context): void { const sessions = ctx.get('sessions') as ISessions const workspaces = ctx.get('workspaces') as IWorkspaces + // One viewing-store instance, created here as ui-layout does for its layout + // store: the browser declares the handle, and the UiWorkspace service writes + // view order through the same instance the renderer hands the browser. + const viewHandle = createWorkspaceViewStore() + const viewInstance = viewHandle.create() + const viewStore: typeof viewHandle = { ...viewHandle, create: () => viewInstance } const uiWorkspace = new UiWorkspaceService( - ctx, ctx.remote.directoryPicker, workspaces, sessions) + ctx, ctx.remote.directoryPicker, workspaces, sessions, viewInstance.actions) ctx.slots.provideRoot({ hooks: { workspaces: workspaces.list } }) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-workspace: dictionaries') @@ -107,6 +129,76 @@ export function apply(ctx: Context): void { const openSession: WorkspaceBrowserInjected['open'] = (sessionId) => { uiWorkspace.openSession(sessionId) } + // Registry-global sets as Sets, rebuilt only when the Workspace snapshot changes. + const pinnedSet = derive(workspaces.list, snapshot => new Set(snapshot.pinnedSessionIds)) + const archivedSet = derive(workspaces.list, snapshot => new Set(snapshot.archivedSessionIds)) + // Plugin-private facts the row actions and their overlay surfaces share: + // the pending rename request and the notice on display. Each business + // writes through its own injected callback and the surface reads through + // its bound hook. + const renameRequest = createSnapshotStore(null) + const rowToast = createSnapshotStore(null) + let toastSeq = 0 + const notify = (toast: RowToast): void => { rowToast.set({ ...toast, seq: ++toastSeq }) } + const requestSessionRename = (sessionId: SessionId, currentTitle: string): void => { + renameRequest.set({ sessionId, currentTitle }) + } + const unarchiveSession = (sessionId: SessionId): void => { + uiWorkspace.unarchiveSession(sessionId).catch((reason: unknown) => { + console.warn('session unarchive rejected:', reason) + }) + } + const renameSession: SessionRenameDialogInjected['renameSession'] = async (sessionId, title) => { + const result = await sessions.using( + sessionId, + { source: 'workspaceOperation' }, + reference => reference.binding.session.rename(title), + ) + if (!result.ok) throw new Error(result.error.message) + } + const pinInjected = (): PinSessionInjected => ({ + hooks: { pinned: pinnedSet, archived: archivedSet }, + // Pin failures surface as a notice: nothing else on the surface moves, so + // a silent failure would read as a dead action. + pinSession: (sessionId) => { + uiWorkspace.pinSession(sessionId).catch(() => { notify({ kind: 'pinFailed' }) }) + }, + unpinSession: (sessionId) => { + uiWorkspace.unpinSession(sessionId).catch(() => { notify({ kind: 'unpinFailed' }) }) + }, + }) + const archiveInjected = (): ArchiveSessionInjected => ({ + hooks: { archived: archivedSet }, + // Archive preserves the log and the account position, so it needs no + // confirmation; the notice offers undo and the archived filter. + archiveSession: (sessionId) => { + uiWorkspace.archiveSession(sessionId).then(() => { + notify({ kind: 'archived', sessionId }) + }).catch((reason: unknown) => { + console.warn('session archive rejected:', reason) + }) + }, + unarchiveSession, + }) + const forkInjected = (): ForkSessionInjected => ({ + forkSession: (sessionId) => { + uiWorkspace.forkSession(sessionId).catch(() => { + // Fork or child-title failure leaves the list as it was. + }) + }, + }) + const renameInjected = (): RenameSessionInjected => ({ requestSessionRename }) + const renameDialogInjected = (): SessionRenameDialogInjected => ({ + hooks: { renameRequest }, + settleSessionRename: () => { renameRequest.set(null) }, + renameSession, + }) + const rowToastInjected = (): RowToastInjected => ({ + hooks: { toast: rowToast }, + dismissToast: () => { rowToast.set(null) }, + undoArchive: unarchiveSession, + showArchived: () => { viewInstance.actions.setArchivedFilter('show') }, + }) const browserInjected = (): WorkspaceBrowserInjected => ({ // Explicit group actions keep their target; unscoped New Session inherits // the current Session Workspace before the recent-Workspace fallback. @@ -114,29 +206,14 @@ export function apply(ctx: Context): void { open: openSession, searchSessions, searchResultLimit: sessions.searchResultLimit, - renameSession: async (sessionId, title) => { - const result = await sessions.using( - sessionId, - { source: 'workspaceOperation' }, - reference => reference.binding.session.rename(title), - ) - if (!result.ok) throw new Error(result.error.message) - }, - forkSession: (sessionId) => { - uiWorkspace.forkSession(sessionId) - .catch(() => { - // Fork or child-rename failure keeps the current selection. - }) - }, + requestSessionRename, + notifyArchivedNotOpenable: () => { notify({ kind: 'archivedNotOpenable' }) }, renameWorkspace: async (workspaceId, title) => { await workspaces.rename(workspaceId, title) }, deleteWorkspace: async (workspaceId) => { await workspaces.delete(workspaceId) }, insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => { await workspaces.insertBefore(workspaceId, beforeWorkspaceId) }, - archiveSession: async (sessionId) => { await uiWorkspace.archiveSession(sessionId) }, unarchiveSession: async (sessionId) => { await uiWorkspace.unarchiveSession(sessionId) }, - pinSession: async (sessionId) => { await workspaces.pinSession(sessionId) }, - unpinSession: async (sessionId) => { await workspaces.unpinSession(sessionId) }, createWorkspace: input => workspaces.create(input), hooks: { directoryFlow: browserFlowSource, hostInfo }, }) @@ -151,14 +228,44 @@ export function apply(ctx: Context): void { name: 'sidebar.workspaces', children: { 'sidebar.workspaces.directoryFlow': { kind: 'single', scope: 'root' }, - 'sidebar.workspaces.session.menu.action': { kind: 'list', scope: 'root' }, + // Every row entry reads the menu's open state through a hook bound + // from the row's render occurrence (the owner passes the state pair + // as hookContext). + 'sidebar.workspaces.session.menu.item': { + kind: 'list', scope: 'root', inject: { hooks: { menuOpenState: menuOpenStateFactory } }, + }, + 'sidebar.workspaces.session.row.action': { kind: 'list', scope: 'root' }, }, - store: createWorkspaceViewStore(), + store: viewStore, inject: browserInjected, locale: NS, }, WorkspaceBrowser, )) + // The shipped row actions take the same route as a plugin's: `slots.inject` + // waits for the browser registration above to declare each list, and the + // entries leave with it. Orders step by 100 so a plugin entry can land + // between them. + ctx.slots.inject('sidebar.workspaces.session.menu.item', function* () { + yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'pin', order: 100, locale: NS, inject: pinInjected }, PinSessionMenuItem) + yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'rename', order: 200, locale: NS, inject: renameInjected }, RenameSessionMenuItem) + yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'fork', order: 300, locale: NS, inject: forkInjected }, ForkSessionMenuItem) + yield ctx.slots.register({ name: 'sidebar.workspaces.session.menu.item', id: 'archive', order: 400, locale: NS, inject: archiveInjected }, ArchiveSessionMenuItem) + }) + ctx.slots.inject('sidebar.workspaces.session.row.action', function* () { + yield ctx.slots.register({ name: 'sidebar.workspaces.session.row.action', id: 'archive', order: 100, locale: NS, inject: archiveInjected }, ArchiveSessionRowButton) + yield ctx.slots.register({ name: 'sidebar.workspaces.session.row.action', id: 'pin', order: 200, locale: NS, inject: pinInjected }, PinSessionRowButton) + }) + // The surfaces the actions raise live in the frame-wide layer: they must + // outlive the row menu the action sat in. + ctx.slots.inject('shell.overlay', function* () { + yield ctx.slots.register({ + name: 'shell.overlay', id: 'workspace.session-rename', locale: NS, inject: renameDialogInjected, + }, SessionRenameDialog) + yield ctx.slots.register({ + name: 'shell.overlay', id: 'workspace.row-toast', locale: NS, inject: rowToastInjected, + }, RowActionToast) + }) ctx.slots.inject('conversation.hero.workspace', () => ctx.slots.register( { name: 'conversation.hero.workspace', diff --git a/packages/client/ui-workspace/src/client/navigation.ts b/packages/client/ui-workspace/src/client/navigation.ts index 22138ec707..d08bf2da00 100644 --- a/packages/client/ui-workspace/src/client/navigation.ts +++ b/packages/client/ui-workspace/src/client/navigation.ts @@ -16,6 +16,8 @@ import type { } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import { pinOrderAccounts, pinOrderSource } from './pin-order.ts' +import type { WorkspaceViewStoreActions } from './stores.ts' interface MainSelection { readonly sessionId?: SessionId @@ -63,6 +65,19 @@ export interface UiWorkspace { * @param sessionId - Session to unarchive. */ unarchiveSession(sessionId: SessionId): Promise + /** + * Pin a Session on the Host, then lead it in its accounts' saved orders + * (its Workspace group or Ungrouped, and the flat list). The order write + * reads the memberships current at completion, so reorders that landed + * while the Host call was pending keep their positions. + * @param sessionId - Session to pin. + */ + pinSession(sessionId: SessionId): Promise + /** + * Unpin a Session on the Host; saved positions stay as they are. + * @param sessionId - Session to unpin. + */ + unpinSession(sessionId: SessionId): Promise /** * Open the Host-native directory picker. * @returns the selected directory, or null when cancelled. @@ -115,12 +130,14 @@ class UiWorkspaceService extends Service implements UiWorkspace { * @param directoryPicker - the directory-picking Remote namespace. * @param workspaces - pure Workspace Controller. * @param sessions - pure Session Controller. + * @param view - the browser's viewing-store write set (one instance shared with its registration). */ constructor( ctx: Context, private readonly directoryPicker: ClientRemote['directoryPicker'], private readonly workspaces: IWorkspaces, private readonly sessions: ISessions, + private readonly view: Pick, ) { super(ctx, 'uiWorkspace') ctx.effect(() => { @@ -217,6 +234,20 @@ class UiWorkspaceService extends Service implements UiWorkspace { await this.workspaces.unarchiveSession(sessionId) } + async pinSession(sessionId: SessionId): Promise { + await this.workspaces.pinSession(sessionId) + const { items, pinnedSessionIds, archivedSessionIds } = this.workspaces.list.getSnapshot() + this.view.pinSessionOrder( + sessionId, + pinOrderAccounts(items, sessionId), + pinOrderSource(items, this.sessions.list.getSnapshot(), { pinnedSessionIds, archivedSessionIds }), + ) + } + + async unpinSession(sessionId: SessionId): Promise { + await this.workspaces.unpinSession(sessionId) + } + async pickDirectory(): Promise { const result = await this.directoryPicker.pick() if (!result.ok) throw new Error(`directory picker failed: ${result.error.message}`) diff --git a/packages/client/ui-workspace/src/client/pin-order.ts b/packages/client/ui-workspace/src/client/pin-order.ts new file mode 100644 index 0000000000..fd80c53027 --- /dev/null +++ b/packages/client/ui-workspace/src/client/pin-order.ts @@ -0,0 +1,51 @@ +/** + * The complete account memberships a Pin order write reconciles against, + * derived from the same Host snapshots the browser orders by, so the + * UiWorkspace service can complete the write without the browser in the loop. + */ +import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client' +import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { FLAT_SESSION_ORDER_KEY } from './stores.ts' +import { owningGroupKey, sessionMemberIds, type SessionRowState, UNGROUPED_KEY } from './tree.ts' + +/** What `pinSessionOrder` reconciles a pinned Session's accounts against. */ +export interface PinOrderSource { + members: Readonly> + summaries: SessionListState['byId'] + rowState: Pick +} + +/** + * Every account's complete membership: each Workspace, Ungrouped, and the flat list. + * @param workspaces - current Host Workspaces. + * @param list - current Session list snapshot. + * @param rowState - registry-global pin and archive sets. + * @returns the order source for one pin write. + */ +export function pinOrderSource( + workspaces: readonly WorkspaceView[], + list: SessionListState, + rowState: PinOrderSource['rowState'], +): PinOrderSource { + const accounted = new Set(workspaces.flatMap(workspace => workspace.sessionIds)) + return { + members: Object.fromEntries([ + ...workspaces.map(workspace => [workspace.workspaceId, workspace.sessionIds] as const), + [UNGROUPED_KEY, list.ids.filter(id => list.byId[id] !== undefined && !accounted.has(id))], + [FLAT_SESSION_ORDER_KEY, sessionMemberIds(list)], + ]), + summaries: list.byId, + rowState, + } +} + +/** + * The accounts a pinned Session leads: its group (or Ungrouped) and the flat list. + * @param workspaces - current Host Workspaces. + * @param sessionId - the Session being pinned. + * @returns the account keys `pinSessionOrder` fronts. + */ +export function pinOrderAccounts(workspaces: readonly WorkspaceView[], sessionId: SessionId): readonly string[] { + return [owningGroupKey(workspaces, sessionId), FLAT_SESSION_ORDER_KEY] +} diff --git a/packages/client/ui-workspace/src/client/rows/Rows.tsx b/packages/client/ui-workspace/src/client/rows/Rows.tsx index d902f52808..e4e75ce9cd 100644 --- a/packages/client/ui-workspace/src/client/rows/Rows.tsx +++ b/packages/client/ui-workspace/src/client/rows/Rows.tsx @@ -2,23 +2,26 @@ * Workspace browser tree row components (figma Cell set 14:3080): pure presentational — * all data and callbacks arrive via props. Hover swaps (folder->chevron, * time->ellipsis, action buttons) are CSS-only, and a session row's clipped - * title is scrolled programmatically while the row is hovered. Row ... menus are - * visual-only except workspace Rename/Delete and the Session built-ins plus - * ordered plugin actions; the session and workspace hover cards are suppressed - * while a menu is open. + * title is scrolled programmatically while the row is hovered. Workspace row + * menus are visual-only except Rename/Delete. A Session row's "..." menu and + * its hover buttons are the `sidebar.workspaces.session.menu.item` and + * `sidebar.workspaces.session.row.action` lists, rendered through the + * browser's `renderSlot` with the menu's open state as the occurrence's hook + * context; this package's own actions are entries like any plugin's. The + * session and workspace hover cards are suppressed while a menu is open. */ -import { useEffect, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import clsx from 'clsx' import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { - HoverCard, IconAlarmClockOutlineRegular, IconArchiveOutlineRegular, IconBranchOutlineRegular, - IconEditOutlineRegular, IconEllipsisOutlineRegular, IconFolderCloseRegular, IconFolderOpenRegular, - IconNewChatOutlineRegular, IconPinFillRegular, IconPinOutlineRegular, IconTrashOutlineRegular, + HoverCard, IconAlarmClockOutlineRegular, IconArchiveOutlineRegular, IconEditOutlineRegular, + IconEllipsisOutlineRegular, IconFolderCloseRegular, IconFolderOpenRegular, + IconNewChatOutlineRegular, IconPinFillRegular, IconTrashOutlineRegular, IconTriangleRightFillRegular, IconUnarchiveOutlineRegular, Menu, relativeTime, StateDot, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { StateDotState } from '@deepseek-ai/dsh-client-ui-primitives' import { abbreviateHomePath } from '@deepseek-ai/dsh-util-workspace-path' -import type { WorkspaceBrowserProps } from '../contract/slots.ts' +import type { MenuOpenState, WorkspaceBrowserProps } from '../contract/slots.ts' import type { GroupNode, SearchResultNode, SessionNode } from '../tree.ts' import css from './Rows.module.css' @@ -461,10 +464,8 @@ export function SearchResultItem({ result, currentId, onOpen, onUnarchive, t }: * @param props.currentId - selected session id (row highlight). * @param props.now - epoch ms for relative-time formatting. * @param props.onOpen - open a session by id. - * @param props.onRename - open the session rename dialog (id + current title). - * @param props.onFork - fork a session at its last completed turn. - * @param props.onArchive - archive a session by id. - * @param props.renderSlot - render ordered plugin actions after the built-in actions. + * @param props.onRenameRequest - open the rename dialog from a title double-click (id + current title). + * @param props.renderSlot - render the row's `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action` lists. * @param props.onReveal - scroll this row into view after search navigation, then acknowledge it. * @param props.drag - optional row-drag target wiring; blank rows cannot start a drag. * @param props.flat - omit the empty status slot in the hierarchy-free flat list. @@ -472,22 +473,14 @@ export function SearchResultItem({ result, currentId, onOpen, onUnarchive, t }: * @returns the session row. */ export function SessionNodeItem({ - node, currentId, now, onOpen, onRename, onFork, onArchive, onUnarchive, onPin, renderSlot, onReveal, drag, flat = false, t, + node, currentId, now, onOpen, onRenameRequest, renderSlot, onReveal, drag, flat = false, t, }: { node: SessionNode currentId: string | undefined now: number onOpen: (id: SessionNode['id']) => void - /** Open the browser-owned session rename dialog (row menu action). */ - onRename: (id: SessionNode['id'], currentTitle: string) => void - /** Fork a session at its last completed turn (row menu action). */ - onFork: (id: SessionNode['id']) => void - /** Archive this session (row menu action; commits without a dialog). */ - onArchive: (id: SessionNode['id']) => void - /** Unarchive this session (row menu action on archived rows). */ - onUnarchive: (id: SessionNode['id']) => void - /** Pin or unpin this session (row menu action; `pin` false unpins). */ - onPin: (id: SessionNode['id'], pin: boolean) => void + /** Open the rename dialog from a title double-click (id + current title). */ + onRenameRequest: (id: SessionNode['id'], currentTitle: string) => void /** Scroll this row into view after search navigation, then acknowledge it. */ onReveal?: (() => void) | undefined /** Present on reorderable-list rows so every row can remain a drop target. */ @@ -495,7 +488,7 @@ export function SessionNodeItem({ /** The row is rendered without a parent Workspace header. */ flat?: boolean | undefined t: RowTranslate -} & PropsRenderSlots<'sidebar.workspaces.session.menu.action'>) { +} & PropsRenderSlots<'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action'>) { const row = node const title = displayTitle(node, t) const selected = node.id === currentId @@ -507,6 +500,8 @@ export function SessionNodeItem({ // their drop targets to fellow pinned rows. const draggable = drag !== undefined && !row.blank && !row.archived const [menuOpen, setMenuOpen] = useState(false) + // The menu's open state, bound into the row entries' `useMenuOpenState` hook. + const menuOpenState = useMemo((): MenuOpenState => [menuOpen, setMenuOpen], [menuOpen]) const rowRef = useRef(null) const titleRef = useRef(null) useEffect(() => { @@ -514,25 +509,6 @@ export function SessionNodeItem({ rowRef.current?.scrollIntoView({ block: 'nearest' }) onReveal() }, [onReveal]) - // Archive hides the row through the registry-global archive set and never - // touches the session log, so it is not styled as destructive and needs no - // confirmation dialog. Archived rows swap pin/archive for unarchive. - const sessionMenuItems = row.archived - ? [ - { id: 'rename', label: t('rename'), icon: }, - { id: 'fork', label: t('menu.fork'), icon: }, - { id: 'unarchive', label: t('menu.unarchiveSession'), icon: }, - ] - : [ - { - id: row.pinned ? 'unpin' : 'pin', - label: t(row.pinned ? 'menu.unpinSession' : 'menu.pinSession'), - icon: row.pinned ? : , - }, - { id: 'rename', label: t('rename'), icon: }, - { id: 'fork', label: t('menu.fork'), icon: }, - { id: 'archive', label: t('menu.archiveSession'), icon: }, - ] // Figma session cell: pad 8, status slot 16, then a 4px title gap. const ownRow = (
{ e.stopPropagation(); onRename(node.id, row.title) }} + : (e) => { e.stopPropagation(); onRenameRequest(node.id, row.title) }} > {title} @@ -615,16 +591,6 @@ export function SessionNodeItem({ { setMenuOpen(false) }} - items={sessionMenuItems} - onSelect={(id) => { - setMenuOpen(false) - if (id === 'rename') onRename(node.id, row.title) - if (id === 'fork') onFork(node.id) - if (id === 'archive') onArchive(node.id) - if (id === 'unarchive') onUnarchive(node.id) - if (id === 'pin') onPin(node.id, true) - if (id === 'unpin') onPin(node.id, false) - }} portal closeOnPointerLeave anchor={( @@ -638,38 +604,13 @@ export function SessionNodeItem({ )} > - {renderSlot('sidebar.workspaces.session.menu.action', { - sessionId: node.id, - displayTitle: row.title, - })} + {renderSlot( + 'sidebar.workspaces.session.menu.item', + { sessionId: node.id, displayTitle: row.title }, + { hookContext: menuOpenState }, + )} - - - - {/* Rightmost so it lands where the rest-state pin marker sits. */} - {!row.archived && ( - - - - )} + {renderSlot('sidebar.workspaces.session.row.action', { sessionId: node.id, displayTitle: row.title })} )}
diff --git a/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx index 6a42c16777..7d5fc2e79e 100644 --- a/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx @@ -7,8 +7,12 @@ * rail entry path, each requesting expansion through the owner share. Adding * is the header button's one action, so it raises the directory flow with no * menu in between; the flow and its error dialog live in WorkspacePicker - * (same package — direct composition, no slot between them). Session row - * menus render the browser-owned action list after their built-in actions. + * (same package — direct composition, no slot between them). A Session row's + * "..." menu and hover buttons are the `sidebar.workspaces.session.menu.item` + * and `sidebar.workspaces.session.row.action` lists rendered through this + * entry's `renderSlot`; the actions in them, this package's own included, + * are slot entries with their own behavior, so this component threads no + * action callbacks and hosts no action surface. */ import { type CSSProperties, type ReactNode, useEffect, useMemo, useRef, useState } from 'react' import clsx from 'clsx' @@ -16,8 +20,8 @@ import { Button, IconArchiveCheckOutlineRegular, IconArchiveOutlineRegular, IconChevronsUpDownOutlineRegular, IconClockOutlineRegular, IconCloseFillRegular, IconFlatListOutlineRegular, IconFolderCloseRegular, IconProjectAddOutlineRegular, - IconSearchOutlineRegular, IconSlidersTwoOutlineRegular, IconWarningOutlineRegular, - IconWorkspaceTreeOutlineRegular, Menu, Modal, Toast, Tooltip, + IconSearchOutlineRegular, IconSlidersTwoOutlineRegular, + IconWorkspaceTreeOutlineRegular, Menu, Modal, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { SessionListState, SessionSearchResultItem, @@ -103,27 +107,16 @@ function useNativeDragAcceptance(active: boolean): void { } /** Grouping, ordering, and archived-filter menu; own open state so it resets with the wide chrome. */ -function ViewOptionsMenu({ groupBy, orderBy, archivedFilter, onGroupPick, onOrderPick, onArchivedFilterPick, openSeq, t }: { +function ViewOptionsMenu({ groupBy, orderBy, archivedFilter, onGroupPick, onOrderPick, onArchivedFilterPick, t }: { groupBy: SessionGroupBy orderBy: SessionOrderBy archivedFilter: ArchivedFilter onGroupPick: (mode: SessionGroupBy) => void onOrderPick: (mode: SessionOrderBy) => void onArchivedFilterPick: (filter: ArchivedFilter) => void - /** Each bump above zero opens the menu (the archive toast's filter action). */ - openSeq?: number t: WorkspaceBrowserProps['t'] }) { const [open, setOpen] = useState(false) - // Seeded with the mount-time value: a chrome remount (e.g. window resize - // through the rail breakpoint) must not replay an old toast-action bump. - const seenOpenSeq = useRef(openSeq ?? 0) - useEffect(() => { - if (openSeq !== undefined && openSeq > seenOpenSeq.current) { - seenOpenSeq.current = openSeq - setOpen(true) - } - }, [openSeq]) return ( & PropsRenderSlots<'sidebar.workspaces.session.menu.action'> & { +> & PropsRenderSlots<'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action'> & { /** Always-mounted Session list snapshot. */ list: SessionListState /** Host account home for POSIX hover-path abbreviation. */ @@ -260,14 +250,8 @@ type SessionTreeProps = Pick< onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void /** Open the browser-owned delete-confirmation dialog for a real Workspace group. */ onDeleteRequest: (workspaceId: WorkspaceId, currentTitle: string) => void - /** Open the browser-owned session rename dialog. */ - onSessionRename: (sessionId: SessionNode['id'], currentTitle: string) => void - /** Archive a Session; the selected filter determines its visibility. */ - onSessionArchive: (sessionId: SessionNode['id']) => void - /** Unarchive a session (row menu action on archived rows). */ - onSessionUnarchive: (sessionId: SessionNode['id']) => void - /** Pin or unpin a session (row menu action; `pin` false unpins). */ - onSessionPin: (sessionId: SessionNode['id'], pin: boolean) => void + /** Open the rename dialog from a row title double-click. */ + onSessionRenameRequest: (sessionId: SessionNode['id'], currentTitle: string) => void /** One Session chosen from search that must be exposed and scrolled into view. */ revealSessionId?: SessionId | undefined /** Acknowledge that the chosen Session row has been revealed. */ @@ -276,10 +260,10 @@ type SessionTreeProps = Pick< /** The scrolling session tree; unmounting drops the sessions subscription and expand-all state. */ function SessionTree({ - list, useSessionStatus, startSession, open, forkSession, workspaces, ungroupedSessionIds, + list, useSessionStatus, startSession, open, workspaces, ungroupedSessionIds, rowState, workspaceReady, animationResetKey, usePanelInfo, - onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onSessionUnarchive, onSessionPin, + onRenameRequest, onDeleteRequest, onSessionRenameRequest, renderSlot, insertWorkspaceBefore, nestWorkspaces, groupExpansion, setGroupExpanded, @@ -560,11 +544,7 @@ function SessionTree({ currentId={current} now={now} onOpen={open} - onRename={onSessionRename} - onFork={forkSession} - onArchive={onSessionArchive} - onUnarchive={onSessionUnarchive} - onPin={onSessionPin} + onRenameRequest={onSessionRenameRequest} renderSlot={renderSlot} onReveal={node.id === revealSessionId && group.key === revealGroup ? () => { onSessionRevealed(node.id) } @@ -614,8 +594,7 @@ function SessionTree({ /** The flat "In one list" body: every session is one draggable top-level row. */ function FlatList({ - list, sessionIds, rowState, useSessionStatus, open, forkSession, onSessionRename, onSessionArchive, - onSessionUnarchive, onSessionPin, + list, sessionIds, rowState, useSessionStatus, open, onSessionRenameRequest, renderSlot, usePanelInfo, setSessionOrder, workspaceReady, animationResetKey, revealSessionId, onSessionRevealed, t, @@ -623,11 +602,7 @@ function FlatList({ SessionTreeProps, | 'useSessionStatus' | 'open' - | 'forkSession' - | 'onSessionRename' - | 'onSessionArchive' - | 'onSessionUnarchive' - | 'onSessionPin' + | 'onSessionRenameRequest' | 'renderSlot' | 'usePanelInfo' | 'setSessionOrder' @@ -684,11 +659,7 @@ function FlatList({ currentId={currentId} now={now} onOpen={open} - onRename={onSessionRename} - onFork={forkSession} - onArchive={onSessionArchive} - onUnarchive={onSessionUnarchive} - onPin={onSessionPin} + onRenameRequest={onSessionRenameRequest} renderSlot={renderSlot} onReveal={node.id === revealSessionId ? () => { onSessionRevealed(node.id) } @@ -841,15 +812,12 @@ export function WorkspaceBrowser({ actions, startSession, open, - renameSession, - forkSession, + requestSessionRename, + notifyArchivedNotOpenable, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, - archiveSession, unarchiveSession, - pinSession, - unpinSession, createWorkspace, searchSessions, searchResultLimit, @@ -876,23 +844,11 @@ export function WorkspaceBrowser({ const archivedFilter = useStore(s => s.archivedFilter ?? 'default') const groupExpansion = useStore(s => s.groupExpansion) const sessionOrderByAccount = useStore(s => s.sessionOrderByAccount) - // Each bump opens the view-options menu (the archive toast's filter action). - const [viewOptionsOpenSeq, setViewOptionsOpenSeq] = useState(0) - // One transient banner at a time; the seq keys remounts so a repeat message restarts its hold. - const [toast, setToast] = useState<{ - text: string - seq: number - tone: 'warning' | 'success' - actions?: readonly { label: string; onClick: () => void }[] - } | null>(null) - const showToast = (text: string): void => { - setToast(current => ({ text, seq: (current?.seq ?? 0) + 1, tone: 'warning' })) - } // Archived sessions are not openable: the row stays visible under the // filter but a click explains instead of navigating. const guardedOpen = (sessionId: SessionId): void => { if (archivedSessionIds.includes(sessionId)) { - showToast(t('toast.archivedNotOpenable')) + notifyArchivedNotOpenable() return } open(sessionId) @@ -952,9 +908,6 @@ export function WorkspaceBrowser({ [UNGROUPED_KEY, orderedUngroupedSessionIds] as const, [FLAT_SESSION_ORDER_KEY, orderedFlatSessionIds] as const, ]), [orderedFlatSessionIds, orderedUngroupedSessionIds, orderedWorkspaces]) - const pinOrderSource = { workspaces, ungroupedMemberIds, flatMemberIds, summaries: list.byId, rowState: orderState } - const latestPinOrder = useRef(pinOrderSource) - latestPinOrder.current = pinOrderSource useEffect(() => { if (workspacePhase !== 'ready') return actions.retainAccountKeys([ @@ -1024,7 +977,7 @@ export function WorkspaceBrowser({ const openSearchResult = (sessionId: SessionId): void => { if (archivedSessionIds.includes(sessionId)) { - showToast(t('toast.archivedNotOpenable')) + notifyArchivedNotOpenable() return } setRevealSessionId(sessionId) @@ -1139,88 +1092,13 @@ export function WorkspaceBrowser({ }) } - // Session rename dialog (same browser-owned pattern as workspace rename; - // sessions have no client-side name-conflict rule — the host normalizes). - // Unlike workspace rename, an unchanged title is NOT blocked: confirming - // the current automatic title is the gesture that pins it. - const [sessionRenameTarget, setSessionRenameTarget] = useState<{ sessionId: SessionNode['id']; currentTitle: string } | null>(null) - const [sessionRenameDraft, setSessionRenameDraft] = useState('') - const [sessionRenaming, setSessionRenaming] = useState(false) - const [sessionRenameError, setSessionRenameError] = useState(null) - const sessionRenameTrimmed = sessionRenameDraft.trim() - const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === '' || sessionRenameTarget === null - const closeSessionRename = () => { - if (sessionRenaming) return - setSessionRenameTarget(null) - setSessionRenameError(null) - } - const confirmSessionRename = () => { - if (sessionRenameBlocked) return - setSessionRenaming(true) - setSessionRenameError(null) - renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => { - setSessionRenaming(false) - setSessionRenameTarget(null) - }).catch((reason: unknown) => { - setSessionRenaming(false) - setSessionRenameError(reason instanceof Error ? reason.message : String(reason)) - }) - } - const onSessionRename = (sessionId: SessionNode['id'], currentTitle: string) => { - setSessionRenameTarget({ sessionId, currentTitle }) - setSessionRenameDraft(currentTitle) - setSessionRenameError(null) - } - - // Archive preserves the log and account position, so it needs no confirmation. - // The selected filter determines visibility after the archive-set echo. - const onSessionArchive = (sessionId: SessionNode['id']) => { - archiveSession(sessionId).then(() => { - setToast(current => ({ - text: t('toast.archived'), - seq: (current?.seq ?? 0) + 1, - tone: 'success', - actions: [ - { label: t('toast.archivedUndo'), onClick: () => { setToast(null); onSessionUnarchive(sessionId) } }, - { - prefix: t('toast.archivedOr'), - label: t('toast.archivedFilter'), - onClick: () => { setToast(null); setViewOptionsOpenSeq(seq => seq + 1) }, - }, - ], - })) - }).catch((reason: unknown) => { - console.warn('session archive rejected:', reason) - }) - } + // The search results' restore button; the row actions own the rest of the + // Session verbs as slot entries. const onSessionUnarchive = (sessionId: SessionNode['id']) => { unarchiveSession(sessionId).catch((reason: unknown) => { console.warn('session unarchive rejected:', reason) }) } - // Pin failures surface as a toast: unlike archive, nothing else on the - // surface moves, so a silent failure would read as a dead menu action. - const onSessionPin = (sessionId: SessionNode['id'], pin: boolean) => { - (pin ? pinSession(sessionId) : unpinSession(sessionId)).then(() => { - if (!pin) return - const source = latestPinOrder.current - actions.pinSessionOrder( - sessionId, - [owningGroupKey(source.workspaces, sessionId), FLAT_SESSION_ORDER_KEY], - { - members: Object.fromEntries([ - ...source.workspaces.map(workspace => [workspace.workspaceId, workspace.sessionIds] as const), - [UNGROUPED_KEY, source.ungroupedMemberIds], - [FLAT_SESSION_ORDER_KEY, source.flatMemberIds], - ]), - summaries: source.summaries, - rowState: source.rowState, - }, - ) - }).catch(() => { - showToast(t(pin ? 'toast.pinFailed' : 'toast.unpinFailed')) - }) - } // Delete dialog is separate from the row so a successful removal can // unmount that row without tearing down the in-flight confirmation state. @@ -1331,7 +1209,6 @@ export function WorkspaceBrowser({ onGroupPick={actions.setGroupBy} onOrderPick={(mode) => { actions.setOrderBy(mode, activeSessionOrders) }} onArchivedFilterPick={actions.setArchivedFilter} - openSeq={viewOptionsOpenSeq} t={t} /> )} @@ -1421,9 +1298,8 @@ export function WorkspaceBrowser({ workspaceReady={workspaceReady} animationResetKey={`${groupBy}/${orderBy}/${archivedFilter}`} useSessionStatus={useSessionStatus} - open={guardedOpen} forkSession={forkSession} - onSessionRename={onSessionRename} onSessionArchive={onSessionArchive} - onSessionUnarchive={onSessionUnarchive} onSessionPin={onSessionPin} + open={guardedOpen} + onSessionRenameRequest={requestSessionRename} renderSlot={renderSlot} setSessionOrder={saveSessionOrder} revealSessionId={revealSessionId} @@ -1436,12 +1312,8 @@ export function WorkspaceBrowser({ usePanelInfo={usePanelInfo} list={list} useSessionStatus={useSessionStatus} - onSessionRename={onSessionRename} - onSessionArchive={onSessionArchive} - onSessionUnarchive={onSessionUnarchive} - onSessionPin={onSessionPin} + onSessionRenameRequest={requestSessionRename} renderSlot={renderSlot} - forkSession={forkSession} workspaces={orderedWorkspaces} ungroupedSessionIds={orderedUngroupedSessionIds} workspaceReady={workspaceReady} @@ -1506,37 +1378,6 @@ export function WorkspaceBrowser({ {renameError !== null &&
{renameError}
} - - - - - )} - > - { e.target.select() }} - onChange={(e) => { setSessionRenameDraft(e.target.value); setSessionRenameError(null) }} - onCompositionStart={() => { composingRef.current = true }} - onCompositionEnd={() => { composingRef.current = false }} - onKeyDown={(e) => { - if (e.key === 'Enter' && !composingRef.current) { - e.preventDefault() - confirmSessionRename() - } - }} - /> - {sessionRenameError !== null &&
{sessionRenameError}
} -
{t('delete.pending')}
} {deleteError !== null &&
{deleteError}
} - {toast !== null && ( - }} - {...toast.actions === undefined ? {} : { actions: toast.actions, holdMs: ARCHIVE_TOAST_HOLD_MS }} - onDone={() => { setToast(null) }} - /> - )}
) } diff --git a/packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx b/packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx new file mode 100644 index 0000000000..43e4a7365b --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx @@ -0,0 +1,61 @@ +/** + * The archive action: a `sidebar.workspaces.session.menu.item` row and a + * `sidebar.workspaces.session.row.action` button over one injected behavior. + * The same entries restore an archived row; the notice a successful archive + * raises and the diagnostics for Host rejections live in the injected + * callbacks, not here. + */ +import { + IconArchiveOutlineRegular, IconUnarchiveOutlineRegular, MenuItemButton, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { ArchiveSessionInjected, SessionMenuItemProps, SessionRowActionProps } from '../contract/slots.ts' +import css from '../rows/Rows.module.css' + +/** + * Menu row (order 400): archive, or restore an archived row. + * @param props - owner share, the archive share, and the menu open state. + * @returns the row. + */ +export function ArchiveSessionMenuItem({ + sessionId, useArchived, useMenuOpenState, archiveSession, unarchiveSession, t, +}: SessionMenuItemProps) { + const [, setMenuOpen] = useMenuOpenState() + const archived = useArchived(set => set.has(sessionId)) + return ( + : } + onSelect={() => { + setMenuOpen(false) + ;(archived ? unarchiveSession : archiveSession)(sessionId) + }} + > + {t(archived ? 'menu.unarchiveSession' : 'menu.archiveSession')} + + ) +} + +/** + * Hover button (order 100): archive, or restore an archived row. + * @param props - owner share and the archive share. + * @returns the button. + */ +export function ArchiveSessionRowButton({ + sessionId, useArchived, archiveSession, unarchiveSession, t, +}: SessionRowActionProps) { + const archived = useArchived(set => set.has(sessionId)) + return ( + + + + ) +} diff --git a/packages/client/ui-workspace/src/client/session-actions/ForkSession.tsx b/packages/client/ui-workspace/src/client/session-actions/ForkSession.tsx new file mode 100644 index 0000000000..1b979b29de --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/ForkSession.tsx @@ -0,0 +1,24 @@ +/** The fork action: one `sidebar.workspaces.session.menu.item` row. */ +import { IconBranchOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' +import type { ForkSessionInjected, SessionMenuItemProps } from '../contract/slots.ts' + +/** + * Menu row (order 300): fork at the Session's last completed turn; the child + * arrives through the Host list beside its source. + * @param props - owner share, menu open state, and the fork share. + * @returns the row. + */ +export function ForkSessionMenuItem({ sessionId, useMenuOpenState, forkSession, t }: SessionMenuItemProps) { + const [, setMenuOpen] = useMenuOpenState() + return ( + } + onSelect={() => { + setMenuOpen(false) + forkSession(sessionId) + }} + > + {t('menu.fork')} + + ) +} diff --git a/packages/client/ui-workspace/src/client/session-actions/PinSession.tsx b/packages/client/ui-workspace/src/client/session-actions/PinSession.tsx new file mode 100644 index 0000000000..efbe4263ba --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/PinSession.tsx @@ -0,0 +1,72 @@ +/** + * The pin action: a `sidebar.workspaces.session.menu.item` row and a + * `sidebar.workspaces.session.row.action` button over one injected behavior. + * Pin and archive are mutually exclusive on the Host, so the action reads both + * sets and does not offer itself on an archived row; what a pin does beyond + * the Host call (fronting the Session in its saved orders, the failure + * notice) lives in the injected callbacks, not here. + */ +import { + IconPinFillRegular, IconPinOutlineRegular, MenuItemButton, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PinSessionInjected, SessionMenuItemProps, SessionRowActionProps } from '../contract/slots.ts' +import css from '../rows/Rows.module.css' + +type PinState = Pick, 'sessionId' | 'usePinned' | 'useArchived'> + +/** The row's pin and archive membership, one Set lookup each. */ +function usePinState({ sessionId, usePinned, useArchived }: PinState) { + return { + pinned: usePinned(pinned => pinned.has(sessionId)), + archived: useArchived(archived => archived.has(sessionId)), + } +} + +/** + * Menu row (order 100): pin or unpin by the row's current state; absent on archived rows. + * @param props - owner share, the pin share, and the menu open state. + * @returns the row, or null for an archived Session. + */ +export function PinSessionMenuItem(props: SessionMenuItemProps) { + const { sessionId, useMenuOpenState, pinSession, unpinSession, t } = props + const [, setMenuOpen] = useMenuOpenState() + const { pinned, archived } = usePinState(props) + if (archived) return null + return ( + : } + onSelect={() => { + setMenuOpen(false) + ;(pinned ? unpinSession : pinSession)(sessionId) + }} + > + {t(pinned ? 'menu.unpinSession' : 'menu.pinSession')} + + ) +} + +/** + * Hover button (order 200, rightmost: it lands where the rest-state pin marker sits); absent on archived rows. + * @param props - owner share and the pin share. + * @returns the button, or null for an archived Session. + */ +export function PinSessionRowButton(props: SessionRowActionProps) { + const { sessionId, pinSession, unpinSession, t } = props + const { pinned, archived } = usePinState(props) + if (archived) return null + return ( + + + + ) +} diff --git a/packages/client/ui-workspace/src/client/session-actions/RenameSession.tsx b/packages/client/ui-workspace/src/client/session-actions/RenameSession.tsx new file mode 100644 index 0000000000..b481dac886 --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/RenameSession.tsx @@ -0,0 +1,122 @@ +/** + * The rename action: a `sidebar.workspaces.session.menu.item` row that raises + * the rename request, and the `shell.overlay` dialog entry that answers it. + * The dialog lives outside the row menu because the row unmounts with the + * menu; the browser raises the same request from a title double-click. + */ +import { useRef, useState } from 'react' +import { Button, IconEditOutlineRegular, MenuItemButton, Modal } from '@deepseek-ai/dsh-client-ui-primitives' +import type { + RenameSessionInjected, SessionMenuItemProps, SessionRenameDialogInjected, SessionRenameDialogProps, SessionRenameRequest, +} from '../contract/slots.ts' +import css from '../rows/WorkspaceBrowser.module.css' + +/** + * Menu row (order 200): ask for the rename dialog, seeded with the row's current title. + * @param props - owner share, menu open state, and the rename share. + * @returns the row. + */ +export function RenameSessionMenuItem({ + sessionId, displayTitle, useMenuOpenState, requestSessionRename, t, +}: SessionMenuItemProps) { + const [, setMenuOpen] = useMenuOpenState() + return ( + } + onSelect={() => { + setMenuOpen(false) + requestSessionRename(sessionId, displayTitle) + }} + > + {t('rename')} + + ) +} + +/** + * The `shell.overlay` entry: nothing while no rename is requested, otherwise + * one dialog per request (keyed by the Session, so a new request starts a + * fresh draft). Sessions have no client-side name-conflict rule (the host + * normalizes), and unlike Workspace rename an unchanged title is NOT + * blocked: confirming the current automatic title is the gesture that pins it. + * @param props - the request hook, its settlement, the rename hop, and the locale seat. + * @returns the open dialog, or null. + */ +export function SessionRenameDialog({ useRenameRequest, settleSessionRename, renameSession, t }: SessionRenameDialogProps) { + const request = useRenameRequest(pending => pending) + if (request === null) return null + return ( + + ) +} + +/** One request's dialog: the draft seeds from the request on mount; in-flight and error state die with it. */ +function RenameForm({ request, renameSession, onSettle, t }: { + request: SessionRenameRequest + renameSession: SessionRenameDialogInjected['renameSession'] + onSettle: () => void + t: SessionRenameDialogProps['t'] +}) { + const [draft, setDraft] = useState(request.currentTitle) + const [renaming, setRenaming] = useState(false) + const [error, setError] = useState(null) + // IME composition: Enter that commits a composition must not submit. + const composingRef = useRef(false) + const trimmed = draft.trim() + const blocked = renaming || trimmed === '' + const close = () => { + if (renaming) return + onSettle() + } + const confirm = () => { + if (blocked) return + setRenaming(true) + setError(null) + renameSession(request.sessionId, trimmed).then(() => { + setRenaming(false) + onSettle() + }).catch((reason: unknown) => { + setRenaming(false) + setError(reason instanceof Error ? reason.message : String(reason)) + }) + } + return ( + + + + + )} + > + { e.target.select() }} + onChange={(e) => { setDraft(e.target.value); setError(null) }} + onCompositionStart={() => { composingRef.current = true }} + onCompositionEnd={() => { composingRef.current = false }} + onKeyDown={(e) => { + if (e.key === 'Enter' && !composingRef.current) { + e.preventDefault() + confirm() + } + }} + /> + {error !== null &&
{error}
} +
+ ) +} diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx new file mode 100644 index 0000000000..a30763c67e --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -0,0 +1,47 @@ +/** + * The `shell.overlay` entry that shows the row actions' notices: the archived + * notice with its undo and "show archived" actions, pin failures, and the + * browser's "archived rows cannot be opened" notice. One notice at a time; + * a parent rerender does not extend its hold. + */ +import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' +import type { RowToastProps } from '../contract/slots.ts' + +/** Hold for the actionable archived notice: two buttons need a longer read-and-react window than a plain notice. */ +const ARCHIVED_TOAST_HOLD_MS = 6000 + +/** + * @param props - the notice hook, its dismissal, the two archived-notice actions, and the locale seat. + * @returns the notice on display, or null. + */ +export function RowActionToast({ useToast, dismissToast, undoArchive, showArchived, t }: RowToastProps) { + const toast = useToast(current => current) + if (toast === null) return null + if (toast.kind === 'archived') { + const { sessionId } = toast + return ( + { dismissToast(); undoArchive(sessionId) } }, + { prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), onClick: () => { dismissToast(); showArchived() } }, + ]} + onDone={dismissToast} + /> + ) + } + const text = toast.kind === 'pinFailed' + ? t('toast.pinFailed') + : toast.kind === 'unpinFailed' ? t('toast.unpinFailed') : t('toast.archivedNotOpenable') + return ( + } + onDone={dismissToast} + /> + ) +} diff --git a/packages/client/ui-workspace/src/client/session-actions/derived.ts b/packages/client/ui-workspace/src/client/session-actions/derived.ts new file mode 100644 index 0000000000..900fc8f053 --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/derived.ts @@ -0,0 +1,26 @@ +/** Derived observable sources for the row actions' injected hooks. */ +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' + +/** + * Project one observable into another, recomputing only when the source + * snapshot changes identity, so consumers that select from the projection + * (a Set lookup per row) never rebuild it per read. + * @param source - the observable to project. + * @param project - pure projection of one source snapshot. + * @returns the projected observable, subscribing through the source. + */ +export function derive(source: HostObservable, project: (snapshot: S) => T): HostObservable { + let seen: S | undefined + let value: T | undefined + return { + getSnapshot: () => { + const snapshot = source.getSnapshot() + if (value === undefined || snapshot !== seen) { + seen = snapshot + value = project(snapshot) + } + return value + }, + subscribe: listener => source.subscribe(listener), + } +} diff --git a/packages/client/ui-workspace/src/client/stores.ts b/packages/client/ui-workspace/src/client/stores.ts index 3ccc377e77..bf32225b88 100644 --- a/packages/client/ui-workspace/src/client/stores.ts +++ b/packages/client/ui-workspace/src/client/stores.ts @@ -128,3 +128,6 @@ export function createWorkspaceViewStore(): EngineStoreHandle['create']>['actions'] diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index cf7c55b3e1..704027f216 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -1,14 +1,52 @@ import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, vi } from 'vitest' +import type { + SessionListState, SessionReference, SessionSummary, +} from '@deepseek-ai/dsh-api-session-controller/client' +import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client' +import { + type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected, + type RenameSessionInjected, type RowToastInjected, type SessionRenameDialogInjected, type WorkspaceViewStoreHandle, +} from '../src/client/contract/slots.ts' import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx' +import { ArchiveSessionMenuItem, ArchiveSessionRowButton } from '../src/client/session-actions/ArchiveSession.tsx' +import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.tsx' +import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx' +import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx' +import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' +import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' +import { UNGROUPED_KEY } from '../src/client/tree.ts' import { apply as hostApply } from '../src/index.ts' -import type { SessionReference } from '@deepseek-ai/dsh-api-session-controller/client' + +const sid = (id: string) => id as SessionId +const summary = (id: string, updatedAt: number): SessionSummary => ({ + id: sid(id), displayTitle: id, running: false, blank: false, updatedAt, retainedBy: {}, +}) +const sessionState = (items: readonly SessionSummary[]): SessionListState => ({ + ids: items.map(item => item.id), + byId: Object.fromEntries(items.map(item => [item.id, item])), + phase: 'ready', + projectionsBySession: {}, jobsBySession: {}, +}) +const workspace = (id: string, sessionIds: readonly string[]): WorkspaceView => ({ + workspaceId: id as WorkspaceId, path: `/projects/${id}`, title: id, + sessionIds: sessionIds.map(sid), createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', +}) +const workspaceState = ( + items: readonly WorkspaceView[], + archivedSessionIds: readonly SessionId[] = [], + pinnedSessionIds: readonly SessionId[] = [], +): WorkspaceSnapshot => ({ + items, archivedSessionIds, pinnedSessionIds, state: 'idle', phase: 'ready', error: null, +}) async function bench() { const ctx = new Context() @@ -44,29 +82,29 @@ async function bench() { operation: (reference: SessionReference) => unknown, ) => await operation(retain(target))) const fork = vi.fn(async () => 'forked' as never) + const pinSession = vi.fn(async () => undefined) + const unpinSession = vi.fn(async () => undefined) + // The Host snapshots the injected hooks derive from and a pin's order write + // reads at completion; a test replaces them whole, so an unchanged snapshot + // keeps its identity between reads. + let workspaceSnapshot = workspaceState([]) + let sessionSnapshot = sessionState([]) const subscribe = () => () => {} + const workspacesSubscribe = vi.fn(subscribe) ctx.provide('workspaces', { - list: { - getSnapshot: () => ({ - items: [], archivedSessionIds: [], pinnedSessionIds: [], state: 'idle', phase: 'ready', error: null, - }), - subscribe, - }, + list: { getSnapshot: () => workspaceSnapshot, subscribe: workspacesSubscribe }, create, rename, delete: vi.fn(async () => undefined), insertBefore: vi.fn(async () => undefined), archiveSession: vi.fn(async () => undefined), + unarchiveSession: vi.fn(async () => undefined), + pinSession, + unpinSession, insertSessionBefore: vi.fn(async () => ({})), } as never) ctx.provide('sessions', { - list: { - getSnapshot: () => ({ - ids: [], byId: {}, phase: 'ready', - projectionsBySession: {}, jobsBySession: {}, - }), - subscribe, - }, + list: { getSnapshot: () => sessionSnapshot, subscribe }, create: vi.fn(async () => 'created' as never), retain, using, @@ -89,18 +127,50 @@ async function bench() { ctx.provide('locale', locale) return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, - retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, + retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, + workspacesSubscribe, + setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, + setSessions: (snapshot: SessionListState): void => { sessionSnapshot = snapshot }, } } -type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace' +type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace' | 'shell.overlay' -/** Declare any subset of the holes with a single root registration ('root' is a single slot). */ +const MENU_ITEM = 'sidebar.workspaces.session.menu.item' +const ROW_ACTION = 'sidebar.workspaces.session.row.action' +type RowListName = typeof MENU_ITEM | typeof ROW_ACTION | 'shell.overlay' + +/** Declare any subset of the holes with a single root registration ('root' is a single slot); the overlay is a list. */ function declare(slots: SlotRegistry, ...names: HoleName[]): () => void { - const children = Object.fromEntries(names.map(name => [name, { kind: 'single', scope: 'root' }])) + const children = Object.fromEntries(names.map(name => [ + name, { kind: name === 'shell.overlay' ? 'list' : 'single', scope: 'root' }, + ])) return slots.register({ name: 'root', children } as never, () => null) } +/** The one entry registered under `id` in a list. */ +function entry(slots: SlotRegistry, key: RowListName, id: string): StoredEntry { + const found = slots.entries(key).find(candidate => candidate.options.id === id) + if (found === undefined) throw new Error(`no ${key} entry ${id}`) + return found +} + +/** An entry's injected face; the shipped factories ignore the positional store actions. */ +function faceOf(registration: StoredEntry): object { + if (registration.inject === undefined) throw new Error(`entry ${String(registration.options.id)} declares no inject face`) + return registration.inject() +} + +/** The viewing-store instance the browser's declared handle hands the renderer. */ +function viewInstance(slots: SlotRegistry) { + const browser = slots.entries('sidebar.workspaces')[0]! + if (browser.store === undefined) throw new Error('the browser entry declares no viewing store') + return (browser.store as WorkspaceViewStoreHandle).create() +} + +/** Let the injected callbacks' Host-call chains settle: one macrotask drains every pending microtask. */ +const settled = (): Promise => new Promise((resolve) => { setTimeout(resolve, 0) }) + describe('ui-workspace apply', () => { it('keeps the host Loader entry inert', () => { expect(hostApply).not.toThrow() @@ -124,10 +194,268 @@ describe('ui-workspace apply', () => { const after = await bench() await after.ctx.plugin({ inject: [...inject], apply }).await() - declare(after.slots, 'conversation.hero.workspace', 'conversation.empty.workspace') + declare(after.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay') await Promise.resolve() expect(after.slots.entries('conversation.hero.workspace')[0]!.component).toBe(WorkspacePicker) - // expect(after.slots.entries('conversation.empty.workspace')[0]!.component).toBe(WorkspacePicker) + // The row actions follow the browser's own declaration, whenever it lands. + expect(after.slots.entries(MENU_ITEM)).toHaveLength(4) + expect(after.slots.entries(ROW_ACTION)).toHaveLength(2) + expect(after.slots.entries('shell.overlay')).toHaveLength(2) + }) + + it('declares the two Session row lists and registers the shipped actions and overlay surfaces into them', async () => { + const b = await bench() + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + // The menu list binds the row's open state into every entry's hook; the + // hover-button list carries no common face. + expect(b.slots.spec(MENU_ITEM)).toEqual({ + kind: 'list', scope: 'root', inject: { hooks: { menuOpenState: menuOpenStateFactory } }, + }) + expect(b.slots.spec(ROW_ACTION)).toEqual({ kind: 'list', scope: 'root' }) + + const rows = (key: RowListName) => b.slots.entries(key) + .map(registration => [registration.options.id, registration.options.order, registration.component, registration.locale]) + expect(rows(MENU_ITEM)).toEqual([ + ['pin', 100, PinSessionMenuItem, 'workspace'], + ['rename', 200, RenameSessionMenuItem, 'workspace'], + ['fork', 300, ForkSessionMenuItem, 'workspace'], + ['archive', 400, ArchiveSessionMenuItem, 'workspace'], + ]) + expect(rows(ROW_ACTION)).toEqual([ + ['archive', 100, ArchiveSessionRowButton, 'workspace'], + ['pin', 200, PinSessionRowButton, 'workspace'], + ]) + expect(rows('shell.overlay')).toEqual([ + ['workspace.session-rename', undefined, SessionRenameDialog, 'workspace'], + ['workspace.row-toast', undefined, RowActionToast, 'workspace'], + ]) + // Only the browser declares the viewing store; its handle hands out the + // one instance the injected callbacks write view state through. The + // row actions and overlay surfaces declare none. + const browser = b.slots.entries('sidebar.workspaces')[0]! + expect(browser.store).toBeDefined() + expect(viewInstance(b.slots)).toBe(viewInstance(b.slots)) + for (const registration of [...b.slots.entries(MENU_ITEM), ...b.slots.entries(ROW_ACTION), ...b.slots.entries('shell.overlay')]) { + expect(registration.store).toBeUndefined() + } + // Each share raises its own notices inside its callbacks. + for (const id of ['pin', 'archive']) { + expect(faceOf(entry(b.slots, MENU_ITEM, id))).not.toHaveProperty('notify') + expect(faceOf(entry(b.slots, ROW_ACTION, id))).not.toHaveProperty('notify') + } + }) + + it('derives the pinned and archived Sets from the Workspace snapshot, rebuilt only when it changes', async () => { + const b = await bench() + b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [sid('two')], [sid('one')])) + declare(b.slots, 'sidebar.workspaces') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const pin = faceOf(entry(b.slots, MENU_ITEM, 'pin')) as PinSessionInjected + const pinButton = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected + const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected + const pinned = pin.hooks.pinned.getSnapshot() + const archived = pin.hooks.archived.getSnapshot() + expect(pinned).toEqual(new Set(['one'])) + expect(archived).toEqual(new Set(['two'])) + // One source per set, shared by every entry and held while the snapshot stands. + expect(pin.hooks.pinned.getSnapshot()).toBe(pinned) + expect(pinButton.hooks.pinned.getSnapshot()).toBe(pinned) + expect(archive.hooks.archived.getSnapshot()).toBe(archived) + // Subscriptions ride the Workspace Controller's list source. + const listener = vi.fn() + const unsubscribe = pin.hooks.pinned.subscribe(listener) + expect(b.workspacesSubscribe).toHaveBeenCalledWith(listener) + unsubscribe() + + b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [], [sid('one'), sid('two')])) + expect(pin.hooks.pinned.getSnapshot()).toEqual(new Set(['one', 'two'])) + expect(pin.hooks.pinned.getSnapshot()).not.toBe(pinned) + expect(archive.hooks.archived.getSnapshot()).toEqual(new Set()) + }) + + it('pins through the navigation service, which fronts the Session in its group and the flat list of the browser view', async () => { + const b = await bench() + b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two', 'three'])])) + b.setSessions(sessionState([summary('one', 3), summary('two', 2), summary('three', 1)])) + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const view = viewInstance(b.slots) + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + expect(view.getSnapshot().sessionOrderByAccount).toEqual({}) + + const pin = faceOf(entry(b.slots, MENU_ITEM, 'pin')) as PinSessionInjected + pin.pinSession(sid('three')) + expect(b.pinSession).toHaveBeenCalledWith('three') + await vi.waitFor(() => { + expect(view.getSnapshot().sessionOrderByAccount).toEqual({ + alpha: ['three', 'one', 'two'], + [UNGROUPED_KEY]: [], + [FLAT_SESSION_ORDER_KEY]: ['three', 'one', 'two'], + }) + }) + // The saved positions lead without leaving Last updated, and a successful pin raises no notice. + expect(view.getSnapshot().orderBy).toBe('updated') + expect(toast.hooks.toast.getSnapshot()).toBeNull() + + // The hover button's face is the same behavior. + const pinButton = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected + pinButton.pinSession(sid('one')) + expect(b.pinSession).toHaveBeenLastCalledWith('one') + await vi.waitFor(() => { + expect(view.getSnapshot().sessionOrderByAccount.alpha).toEqual(['one', 'three', 'two']) + }) + + // Unpin leaves the saved orders as they are. + const before = view.getSnapshot().sessionOrderByAccount + pin.unpinSession(sid('one')) + expect(b.unpinSession).toHaveBeenCalledWith('one') + await settled() + expect(view.getSnapshot().sessionOrderByAccount).toBe(before) + expect(toast.hooks.toast.getSnapshot()).toBeNull() + }) + + it('raises the pin and unpin failure notices and writes no order', async () => { + const b = await bench() + b.setWorkspaces(workspaceState([workspace('alpha', ['one'])])) + b.setSessions(sessionState([summary('one', 1)])) + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const view = viewInstance(b.slots) + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const pin = faceOf(entry(b.slots, ROW_ACTION, 'pin')) as PinSessionInjected + + b.pinSession.mockRejectedValueOnce(new Error('pin wire down')) + pin.pinSession(sid('one')) + await vi.waitFor(() => { expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'pinFailed', seq: 1 }) }) + b.unpinSession.mockRejectedValueOnce(new Error('unpin wire down')) + pin.unpinSession(sid('one')) + await vi.waitFor(() => { expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'unpinFailed', seq: 2 }) }) + expect(view.getSnapshot().sessionOrderByAccount).toEqual({}) + }) + + it('archives through the navigation service and raises the archived notice; Host rejections are console diagnostics', async () => { + const b = await bench() + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const archiveSession = vi.spyOn(b.ctx.uiWorkspace, 'archiveSession').mockResolvedValue(undefined) + const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined) + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const archive = faceOf(entry(b.slots, ROW_ACTION, 'archive')) as ArchiveSessionInjected + + archive.archiveSession(sid('one')) + expect(archiveSession).toHaveBeenCalledWith('one') + await vi.waitFor(() => { + expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archived', sessionId: 'one', seq: 1 }) + }) + // The menu row's face is the same behavior; a restore raises no notice. + const archiveRow = faceOf(entry(b.slots, MENU_ITEM, 'archive')) as ArchiveSessionInjected + archiveRow.unarchiveSession(sid('one')) + expect(unarchiveSession).toHaveBeenCalledWith('one') + await settled() + expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archived', sessionId: 'one', seq: 1 }) + + const archiveRejection = new Error('archive exploded') + const unarchiveRejection = new Error('unarchive exploded') + archiveSession.mockRejectedValueOnce(archiveRejection) + unarchiveSession.mockRejectedValueOnce(unarchiveRejection) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + archive.archiveSession(sid('two')) + await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session archive rejected:', archiveRejection) }) + archive.unarchiveSession(sid('two')) + await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session unarchive rejected:', unarchiveRejection) }) + } finally { + warn.mockRestore() + } + // A rejected archive raises no notice. + expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archived', sessionId: 'one', seq: 1 }) + }) + + it('the notice share takes the notice down, undoes an archive, and shows the archived rows', async () => { + const b = await bench() + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined) + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected + const view = viewInstance(b.slots) + + // The browser raises the not-openable notice into the same entry, and the source notifies. + expect(toast.hooks.toast.getSnapshot()).toBeNull() + const noticed = vi.fn() + const unsubscribe = toast.hooks.toast.subscribe(noticed) + browser.notifyArchivedNotOpenable() + expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archivedNotOpenable', seq: 1 }) + expect(noticed).toHaveBeenCalledOnce() + toast.dismissToast() + expect(toast.hooks.toast.getSnapshot()).toBeNull() + unsubscribe() + + expect(view.getSnapshot().archivedFilter).toBe('default') + toast.showArchived() + expect(view.getSnapshot().archivedFilter).toBe('show') + + toast.undoArchive(sid('one')) + expect(unarchiveSession).toHaveBeenCalledWith('one') + // A rejected undo is a console diagnostic. + const rejection = new Error('unarchive exploded') + unarchiveSession.mockRejectedValueOnce(rejection) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + toast.undoArchive(sid('two')) + await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session unarchive rejected:', rejection) }) + } finally { + warn.mockRestore() + } + }) + + it('routes fork and rename through their shares, the rename dialog, and the browser face', async () => { + const b = await bench() + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const unarchiveSession = vi.spyOn(b.ctx.uiWorkspace, 'unarchiveSession').mockResolvedValue(undefined) + + // Fork goes through the navigation service, which leaves the child unselected. + const forkSession = vi.spyOn(b.ctx.uiWorkspace, 'forkSession') + const fork = faceOf(entry(b.slots, MENU_ITEM, 'fork')) as ForkSessionInjected + b.retain.mockClear() + fork.forkSession('session' as never) + await forkSession.mock.results[0]!.value + expect(b.fork).toHaveBeenCalledWith({ sessionId: 'session', increaseTitle: true }) + expect(b.retain).not.toHaveBeenCalled() + + // The rename row raises the request the dialog entry reads; settling clears it. + const rename = faceOf(entry(b.slots, MENU_ITEM, 'rename')) as RenameSessionInjected + const dialog = faceOf(entry(b.slots, 'shell.overlay', 'workspace.session-rename')) as SessionRenameDialogInjected + expect(dialog.hooks.renameRequest.getSnapshot()).toBeNull() + const requested = vi.fn() + const unsubscribeRequest = dialog.hooks.renameRequest.subscribe(requested) + rename.requestSessionRename('session' as never, 'Old title') + expect(dialog.hooks.renameRequest.getSnapshot()).toEqual({ sessionId: 'session', currentTitle: 'Old title' }) + expect(requested).toHaveBeenCalled() + unsubscribeRequest() + dialog.settleSessionRename() + expect(dialog.hooks.renameRequest.getSnapshot()).toBeNull() + // The dialog's rename hop reaches the Session face and rethrows a business error. + await dialog.renameSession('session' as never, 'renamed session') + expect(b.using).toHaveBeenCalledWith('session', { source: 'workspaceOperation' }, expect.any(Function)) + expect(b.renameSession).toHaveBeenCalledWith('renamed session') + b.renameSession.mockResolvedValueOnce({ + ok: false, error: new RemoteError('gateway/internal', 'title write failed', {}), + } as never) + await expect(dialog.renameSession('session' as never, 'again')).rejects.toThrow('title write failed') + + // The browser raises the same rename request from a title double-click, + // restores from its search results, and carries none of the row verbs itself. + const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected + browser.requestSessionRename('session' as never, 'Row title') + expect(dialog.hooks.renameRequest.getSnapshot()).toEqual({ sessionId: 'session', currentTitle: 'Row title' }) + for (const verb of ['forkSession', 'archiveSession', 'pinSession', 'unpinSession', 'renameSession', 'undoArchive', 'showArchived']) { + expect(browser).not.toHaveProperty(verb) + } + await browser.unarchiveSession('session' as never) + expect(unarchiveSession).toHaveBeenCalledWith('session') }) it('routes browser actions and picker creation to the services', async () => { @@ -136,7 +464,7 @@ describe('ui-workspace apply', () => { await b.ctx.plugin({ inject: [...inject], apply }).await() const startSession = vi.spyOn(b.ctx.uiWorkspace, 'startSession').mockImplementation(() => undefined) - const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)() + const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected // Both arms delegate to the shared Session navigation action. browser.startSession('ws' as never) expect(startSession).toHaveBeenCalledWith('ws') @@ -151,23 +479,12 @@ describe('ui-workspace apply', () => { }) expect(b.search).toHaveBeenCalledWith('match', signal) expect(browser.searchResultLimit).toBe(20) - await browser.renameSession('session' as never, 'renamed session') - expect(b.using).toHaveBeenCalledWith( - 'session', { source: 'workspaceOperation' }, expect.any(Function), - ) - expect(b.renameSession).toHaveBeenCalledWith('renamed session') - b.retain.mockClear() - const forkSession = vi.spyOn(b.ctx.uiWorkspace, 'forkSession') - browser.forkSession('session' as never) - await forkSession.mock.results[0]!.value - expect(b.retain).not.toHaveBeenCalled() - expect(b.fork).toHaveBeenCalledWith({ sessionId: 'session', increaseTitle: true }) await browser.renameWorkspace('ws' as never, 'renamed') expect(b.rename).toHaveBeenCalledWith('ws', 'renamed') await browser.createWorkspace({ path: '/tmp/browser-project' }) expect(b.create).toHaveBeenCalledWith({ path: '/tmp/browser-project' }) - const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)() + const picker = faceOf(b.slots.entries('conversation.hero.workspace')[0]!) as WorkspacePickerInjected await picker.createWorkspace({ path: '/tmp/project' }) expect(b.create).toHaveBeenCalledWith({ path: '/tmp/project' }) }) @@ -179,10 +496,9 @@ describe('ui-workspace apply', () => { // Registration declared the child holes (declaration = render authorization). expect(b.slots.spec('sidebar.workspaces.directoryFlow')).toMatchObject({ kind: 'single' }) expect(b.slots.spec('conversation.hero.workspace.directoryFlow')).toMatchObject({ kind: 'single' }) - expect(b.slots.spec('sidebar.workspaces.session.menu.action')).toEqual({ kind: 'list', scope: 'root' }) - const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)() - const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)() + const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected + const picker = faceOf(b.slots.entries('conversation.hero.workspace')[0]!) as WorkspacePickerInjected expect(browser.hooks.directoryFlow.getSnapshot()).toBe(false) expect(browser.hooks.hostInfo.getSnapshot()).toMatchObject({ home: undefined }) expect(picker.hooks.directoryFlow.getSnapshot()).toBe(false) @@ -207,19 +523,27 @@ describe('ui-workspace apply', () => { }) as never) declare(b.slots, 'sidebar.workspaces') await b.ctx.plugin({ inject: [...inject], apply }).await() - const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)() + const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected await expect(browser.searchSessions('needle', new AbortController().signal)) .rejects.toThrow('index unavailable') }) it('unregisters every entry on teardown', async () => { const b = await bench() - declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace') + declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay') const fiber = b.ctx.plugin({ inject: [...inject], apply }) await fiber.await() + expect(b.slots.entries(MENU_ITEM)).toHaveLength(4) + expect(b.slots.entries(ROW_ACTION)).toHaveLength(2) + expect(b.slots.entries('shell.overlay')).toHaveLength(2) await fiber.dispose() expect(b.slots.entries('sidebar.workspaces')).toHaveLength(0) expect(b.slots.entries('conversation.hero.workspace')).toHaveLength(0) - // expect(b.slots.entries('conversation.empty.workspace')).toHaveLength(0) + // The row lists collapse with the browser declaration; the overlay list + // (declared by the shell) keeps no ui-workspace entry behind. + expect(b.slots.spec(MENU_ITEM)).toBeUndefined() + expect(b.slots.entries(MENU_ITEM)).toHaveLength(0) + expect(b.slots.entries(ROW_ACTION)).toHaveLength(0) + expect(b.slots.entries('shell.overlay')).toHaveLength(0) }) }) diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index 9e137d99b9..1797b94423 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -1,28 +1,27 @@ // @vitest-environment jsdom /** * The session-rename assembly chain on SlotTestRuntime (real apply, real - * WorkspaceBrowser occupying the sidebar hole): row menu → rename dialog → - * the injected renameSession hop (sessions.binding → ISession.rename) → on - * the accepted unary response the dialog closes and the row re-labels from - * the list state — no push-frame wait. Coverage split: the assembled-app - * snapshot (apps/web/tests/session-actions.snapshot.ts) pins the full-app - * transcript; the - * verb's wire behavior stays with the Session Controller client package - * (session.spec.ts#rename), the dialog's own arms with rows.spec / - * workspace-browser.spec. + * WorkspaceBrowser occupying the sidebar hole, the shipped row actions and + * the overlay surfaces registered by the same apply): row menu → rename + * request → the `shell.overlay` dialog → the injected renameSession hop + * (sessions.binding → ISession.rename) → on the accepted unary response the + * dialog closes and the row re-labels from the list state — no push-frame + * wait. Coverage split: the assembled-app snapshot + * (apps/web/tests/session-actions.snapshot.ts) pins the full-app transcript; + * the verb's wire behavior stays with the Session Controller client package + * (session.spec.ts#rename), the entries' own arms with + * session-actions.client.spec, the row's list rendering with rows.client.spec. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, waitFor, within } from '@testing-library/react' import type { ISession } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client' import { SessionSeq, type SessionId } from '@deepseek-ai/dsh-session/types' -import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import { RemoteError, SlotTestRuntime, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' -import { - apply, inject, type SessionMenuActionOwnerProps, -} from '@deepseek-ai/dsh-client-ui-workspace/client' +import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' // The service reads its initial locale from the browser; these specs assert // the shipped Chinese copy, so they state the browser they assume. @@ -48,10 +47,36 @@ async function createRuntime(): Promise { return runtime } -/** Test-owned sidebar shell role: declares and renders the browsing region. */ -type FrameProps = PropsRenderSlots<'sidebar.workspaces'> +/** Test-owned shell role: declares and renders the browsing region and the frame-wide overlay list. */ +type FrameProps = PropsRenderSlots<'sidebar.workspaces' | 'shell.overlay'> function SidebarFrame({ renderSlot }: FrameProps) { - return <>{renderSlot('sidebar.workspaces', { wide: true, expandSidebar: () => {} })} + return ( + <> + {renderSlot('sidebar.workspaces', { wide: true, expandSidebar: () => {} })} + {renderSlot('shell.overlay', {})} + + ) +} + +/** Declare the sidebar hole and the overlay list the rename dialog and the row notices mount in. */ +async function declareFrame(runtime: SlotTestRuntime): Promise { + await runtime.root.declare( + { + 'sidebar.workspaces': { kind: 'single', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } as never, + SidebarFrame as never, + ) +} + +/** One Workspace holding the fixture Session. */ +async function seedWorkspace(runtime: SlotTestRuntime): Promise { + await runtime.workspaces.update((draft) => { + draft.items = [{ + workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha', + sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', + }] as never + }) } describe('session rename through the assembled browser', () => { @@ -64,46 +89,51 @@ describe('session rename through the assembled browser', () => { session: { rename: vi.fn() }, }) await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready - await runtime.workspaces.update((draft) => { - draft.items = [{ - workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha', - sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', - }] as never - }) - await runtime.root.declare( - { 'sidebar.workspaces': { kind: 'single', scope: 'root' } } as never, - SidebarFrame as never, - ) + await seedWorkspace(runtime) + await declareFrame(runtime) await runtime.mount({ inject: [...inject], apply }) const registerAction = (id: string, order: number, priority: number, label: string) => { runtime.slots.register( - { name: 'sidebar.workspaces.session.menu.action', id, order, priority }, - ({ sessionId, displayTitle }: SessionMenuActionOwnerProps) => ( - { selected(id, sessionId, displayTitle) }}>{label} - ), + { name: 'sidebar.workspaces.session.menu.item', id, order, priority }, + ({ sessionId, displayTitle, useMenuOpenState }: PropsRuntime<'sidebar.workspaces.session.menu.item'>) => { + const [, setMenuOpen] = useMenuOpenState() + return ( + { + setMenuOpen(false) + selected(id, sessionId, displayTitle) + }}> + {label} + + ) + }, ) } - // List display order stays primary even when the later registration has - // the lower shadowing priority assigned to dynamic browser packages. - registerAction('earlier', 10, -1, 'Earlier action') - registerAction('later', 20, -2, 'Later action') + // `order` places plugin rows after the shipped rows (100/200/300/400) + // even when the later registration has the lower shadowing priority + // assigned to dynamic browser packages; the first plugin row opens the + // plugin group with a hairline. + registerAction('export', 500, -1, 'Export action') + registerAction('last', 600, -2, 'Last action') const view = runtime.renderRoot() const row = (await view.findByText('Session title')).closest('[role="treeitem"]')! const trigger = within(row as HTMLElement).getByLabelText('会话“Session title”的操作') fireEvent.click(trigger) expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - '置顶会话', '重命名', '分叉会话', '归档会话', 'Earlier action', 'Later action', + '置顶会话', '重命名', '分叉会话', '归档会话', 'Export action', 'Last action', ]) - const later = view.getByRole('menuitem', { name: 'Later action' }) - const earlier = view.getByRole('menuitem', { name: 'Earlier action' }) + expect(view.getAllByRole('separator')).toHaveLength(1) + const last = view.getByRole('menuitem', { name: 'Last action' }) + const exportRow = view.getByRole('menuitem', { name: 'Export action' }) trigger.focus() fireEvent.keyDown(trigger, { key: 'End' }) - expect(document.activeElement).toBe(later) - fireEvent.keyDown(later, { key: 'ArrowUp' }) - expect(document.activeElement).toBe(earlier) - fireEvent.click(earlier) - expect(selected).toHaveBeenCalledWith('earlier', SID, 'Session title') + expect(document.activeElement).toBe(last) + fireEvent.keyDown(last, { key: 'ArrowUp' }) + expect(document.activeElement).toBe(exportRow) + fireEvent.click(exportRow) + expect(selected).toHaveBeenCalledWith('export', SID, 'Session title') + // The plugin row dismissed the menu through the bound open-state hook; + // the list returns focus to the trigger. expect(view.queryByRole('menu')).toBeNull() await act(async () => { await Promise.resolve() }) expect(document.activeElement).toBe(trigger) @@ -121,16 +151,8 @@ describe('session rename through the assembled browser', () => { session: { rename }, }) await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready - await runtime.workspaces.update((draft) => { - draft.items = [{ - workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha', - sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', - }] as never - }) - await runtime.root.declare( - { 'sidebar.workspaces': { kind: 'single', scope: 'root' } } as never, - SidebarFrame as never, - ) + await seedWorkspace(runtime) + await declareFrame(runtime) await runtime.mount({ inject: [...inject], apply }) const view = runtime.renderRoot() @@ -138,6 +160,8 @@ describe('session rename through the assembled browser', () => { const row = (await view.findByText('旧标题')).closest('[role="treeitem"]')! fireEvent.click(within(row as HTMLElement).getByLabelText('会话“旧标题”的操作')) fireEvent.click(view.getByRole('menuitem', { name: '重命名', hidden: true })) + // The rename row dismissed the menu; the dialog lives in the overlay list. + expect(view.queryByRole('menu')).toBeNull() // The dialog seeds from the current title; submit a padded value. const input = await view.findByLabelText('会话名称') as HTMLInputElement @@ -169,16 +193,8 @@ describe('session rename through the assembled browser', () => { session: { rename }, }) await runtime.sessions.retainFor(runtime.ctx, SID, { source: 'mainView' }).ready - await runtime.workspaces.update((draft) => { - draft.items = [{ - workspaceId: 'w1' as WorkspaceId, title: 'alpha', path: '/w/alpha', - sessionIds: [SID], createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', - }] as never - }) - await runtime.root.declare( - { 'sidebar.workspaces': { kind: 'single', scope: 'root' } } as never, - SidebarFrame as never, - ) + await seedWorkspace(runtime) + await declareFrame(runtime) await runtime.mount({ inject: [...inject], apply }) const view = runtime.renderRoot() await runtime.flush() diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index 950abad4e1..e2bd6eada3 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -6,9 +6,9 @@ import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/clie import type { SessionId } from '@deepseek-ai/dsh-session/types' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' -import { MenuAction } from '@deepseek-ai/dsh-client-ui-primitives' +import { MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' -import type { SessionMenuActionOwnerProps } from '../src/client/contract/slots.ts' +import type { MenuOpenState, SessionRowOwnerProps } from '../src/client/contract/slots.ts' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { RowDragProps } from '../src/client/rows/Rows.tsx' import { @@ -25,13 +25,18 @@ const tEn = makeTranslate(en, commonEn) as never const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId -const renderNoSessionActions: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] = () => null +/** The two row lists a Session row renders. */ +type RowSlotName = 'sidebar.workspaces.session.menu.item' | 'sidebar.workspaces.session.row.action' +type RowRenderSlot = PropsRenderSlots['renderSlot'] +type SessionNodeItemProps = ComponentProps -// Direct row specs use the real required Slot share, empty unless the case supplies an occupant. -function SessionNodeItem({ renderSlot = renderNoSessionActions, ...props }: Omit< - ComponentProps, 'renderSlot' -> & Partial, 'renderSlot'>>) { - return +const renderNoRowEntries: RowRenderSlot = () => null + +// Direct row specs use the real required Slot share, empty unless the case supplies entries. +function SessionNodeItem({ renderSlot = renderNoRowEntries, onRenameRequest = () => {}, ...props }: Omit< + SessionNodeItemProps, 'renderSlot' | 'onRenameRequest' +> & Partial>) { + return } /** Half detection reads the row rect; jsdom rects are all-zero by default. */ @@ -79,13 +84,12 @@ describe('workspace browser rows', () => { id: sid('flat'), title: 'Flat Session', blank: false, running: false, runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } - const view = render() + const view = render() const title = screen.getByText('Flat Session') expect(title.previousElementSibling).toBeNull() view.rerender() + onOpen={vi.fn()} flat t={t} />) expect(screen.getByText('Flat Session').previousElementSibling?.querySelector('[data-state="ongoing"]')).toBeTruthy() }) @@ -175,8 +179,7 @@ describe('workspace browser rows', () => { } const onOpen = vi.fn() render( - , + , ) const row = screen.getByRole('treeitem') @@ -194,8 +197,7 @@ describe('workspace browser rows', () => { pinned: false, archived: false, } render( - , + , ) const row = screen.getByRole('treeitem') const title = screen.getByText(node.title) @@ -236,8 +238,7 @@ describe('workspace browser rows', () => { pinned: false, archived: false, } render( - , + , ) const row = screen.getByRole('treeitem') const title = screen.getByText(node.title) @@ -258,8 +259,7 @@ describe('workspace browser rows', () => { runningSubagentCount: 0, completed: false, hasActiveSchedule: true, updatedAt: 0, pinned: false, archived: false, } const view = render( - , + , ) const assertIndicator = (): HTMLElement => { @@ -277,8 +277,7 @@ describe('workspace browser rows', () => { expect(onOpen).toHaveBeenCalledWith(node.id) view.rerender( - , + , ) assertIndicator() }) @@ -290,8 +289,7 @@ describe('workspace browser rows', () => { id: sid('s1'), title: 'One', blank: false, running: false, runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, ...over, }} - currentId={undefined} now={0} onOpen={vi.fn()} - onRename={vi.fn()} onFork={vi.fn()} onArchive={vi.fn()} onUnarchive={vi.fn()} onPin={vi.fn()} t={t} + currentId={undefined} now={0} onOpen={vi.fn()} t={t} />, ) const stateDot = (view: ReturnType) => @@ -322,8 +320,7 @@ describe('workspace browser rows', () => { id: sid('owner'), title: 'Delegating', blank: false, running: false, runningSubagentCount: 2, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } - render() + render() const row = screen.getByRole('treeitem') expect(row.querySelector('[data-state="ongoing"]')).not.toBeNull() expect(screen.getByText('2 个子代理运行中')).toBeTruthy() @@ -344,8 +341,7 @@ describe('workspace browser rows', () => { id: sid('owner'), title: 'Delegating', blank: false, running: true, runningSubagentCount: 1, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } - render() + render() const row = screen.getByRole('treeitem') expect(row.querySelectorAll('[data-state="ongoing"]')).toHaveLength(1) expect(screen.getByText('进行中')).toBeTruthy() @@ -365,8 +361,7 @@ describe('workspace browser rows', () => { id: sid('owner'), title: 'Needs input', blank: false, pendingInteraction: 'question', running: false, runningSubagentCount: 1, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } - render() + render() const row = screen.getByRole('treeitem') expect(row.querySelector('[data-state="warning"]')).not.toBeNull() expect(row.querySelector('[data-state="ongoing"]')).toBeNull() @@ -512,10 +507,13 @@ describe('workspace browser rows', () => { id: sid('s-blank'), title: 'ignored', blank: true, running: false, runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } - render() - // The placeholder has no content yet: no row verbs, no "now" stamp. + const rendered = vi.fn() + const renderSlot: RowRenderSlot = (name: RowSlotName) => { rendered(name); return null } + render() + // The placeholder has no content yet: no row verbs (neither list is + // asked for anything), no "now" stamp. expect(screen.queryByRole('button', { name: /会话.*的操作/ })).toBeNull() + expect(rendered).not.toHaveBeenCalled() expect(screen.queryByText('刚刚')).toBeNull() // The hover card keeps title + status but drops the timestamp line. const wrapper = screen.getByRole('treeitem').parentElement as HTMLElement @@ -530,85 +528,104 @@ describe('workspace browser rows', () => { } }) - it('session row menu opens without opening the session and dispatches rename, fork, and archive', () => { + it('session row menu opens without opening the session and Escape closes it', () => { const onOpen = vi.fn() - const onRename = vi.fn() - const onFork = vi.fn() - const onArchive = vi.fn() const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } - render() - fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) - expect(onOpen).not.toHaveBeenCalled() - // Archive is not destructive (log and accounting slot remain): no danger styling. - expect(screen.getByRole('menuitem', { name: '归档会话' }).className).not.toMatch(/danger/) - // Rename dispatches with the current display title (dialog prefill). - fireEvent.click(screen.getByRole('menuitem', { name: '重命名' })) - expect(screen.queryByRole('menu')).toBeNull() - expect(onRename).toHaveBeenCalledWith(node.id, 'One') - expect(onOpen).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) - fireEvent.click(screen.getByRole('menuitem', { name: '分叉会话' })) - expect(onFork).toHaveBeenCalledWith(node.id) - // Archive dispatches without opening the session. - fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) - fireEvent.click(screen.getByRole('menuitem', { name: '归档会话' })) - expect(onArchive).toHaveBeenCalledWith(node.id) - expect(onRename).toHaveBeenCalledOnce() + render() + const trigger = screen.getByRole('button', { name: '会话“One”的操作' }) + fireEvent.click(trigger) + expect(screen.getByRole('menu')).toBeTruthy() expect(onOpen).not.toHaveBeenCalled() // Escape closes without selecting (Menu onClose path). - fireEvent.click(screen.getByRole('button', { name: '会话“One”的操作' })) fireEvent.keyDown(document, { key: 'Escape' }) expect(screen.queryByRole('menu')).toBeNull() + // The trigger toggles: a second click closes the menu it opened. + fireEvent.click(trigger) + fireEvent.click(trigger) + expect(screen.queryByRole('menu')).toBeNull() + expect(onOpen).not.toHaveBeenCalled() }) - it('appends plugin actions after built-ins with the Session owner props', async () => { + it('renders the menu list with the row identity and open state, and returns focus to the trigger after an entry closes it', async () => { const onOpen = vi.fn() - const onPluginAction = vi.fn() + const onEntry = vi.fn() const rendered = vi.fn() - const renderSlot: PropsRenderSlots<'sidebar.workspaces.session.menu.action'>['renderSlot'] = (name, value) => { - // The generic framework signature cannot narrow its owner from a runtime key in a test stub. - const owner = value as unknown as SessionMenuActionOwnerProps - const { sessionId, displayTitle } = owner - rendered(name, value) + // A stub satisfies the generic render signature only with erased parameter + // types; it narrows the owner and the occurrence options itself. + const renderSlot: RowRenderSlot = (name: RowSlotName, owner: object, opts?: object) => { + const { sessionId, displayTitle } = owner as SessionRowOwnerProps + const hookContext = opts !== undefined && 'hookContext' in opts ? opts.hookContext : undefined + rendered(name, owner, hookContext) + if (name !== 'sidebar.workspaces.session.menu.item') return null + // The stub stands in for the renderer, which binds this occurrence's + // hookContext into the entries' useMenuOpenState hook. + const [open, setMenuOpen] = hookContext as MenuOpenState return ( - { - onPluginAction(sessionId, displayTitle) + { + setMenuOpen(false) + onEntry(sessionId, displayTitle, open) }}> Export - + ) } const node: SessionNode = { id: sid('s1'), title: 'One', blank: false, running: false, runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, } - render(<> - - ) + render() + // Both lists receive the row identity; only the menu list carries the open state. + expect(rendered).toHaveBeenCalledWith( + 'sidebar.workspaces.session.menu.item', { sessionId: node.id, displayTitle: 'One' }, [false, expect.any(Function)], + ) + expect(rendered).toHaveBeenCalledWith( + 'sidebar.workspaces.session.row.action', { sessionId: node.id, displayTitle: 'One' }, undefined, + ) + expect(screen.queryByRole('menuitem')).toBeNull() const trigger = screen.getByRole('button', { name: '会话“One”的操作' }) trigger.focus() fireEvent.click(trigger) - const actions = screen.getAllByRole('menuitem') - expect(actions.map(action => action.textContent)).toEqual(['置顶会话', '重命名', '分叉会话', '归档会话', 'Export']) + expect(screen.getAllByRole('menuitem').map(item => item.textContent)).toEqual(['Export']) + expect(rendered).toHaveBeenCalledWith( + 'sidebar.workspaces.session.menu.item', { sessionId: node.id, displayTitle: 'One' }, [true, expect.any(Function)], + ) fireEvent.click(screen.getByRole('menuitem', { name: 'Export' })) - await act(async () => { await Promise.resolve() }) - expect(rendered).toHaveBeenCalledWith('sidebar.workspaces.session.menu.action', expect.any(Object)) - const owner = rendered.mock.calls.at(-1)?.[1] as SessionMenuActionOwnerProps | undefined - expect(owner?.sessionId).toBe(node.id) - expect(owner?.displayTitle).toBe('One') - expect(onPluginAction).toHaveBeenCalledWith(node.id, 'One') + expect(onEntry).toHaveBeenCalledWith(node.id, 'One', true) + // The entry dismissed the menu through the state pair; the list returns focus. expect(screen.queryByRole('menu')).toBeNull() + await act(async () => { await Promise.resolve() }) expect(document.activeElement).toBe(trigger) expect(onOpen).not.toHaveBeenCalled() }) + it('renders the row action list inside the actions area after the menu trigger', () => { + const onOpen = vi.fn() + const onQuick = vi.fn() + const renderSlot: RowRenderSlot = (name: RowSlotName) => name === 'sidebar.workspaces.session.row.action' + ? ( + diff --git a/packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx b/packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx index 43e4a7365b..0555303425 100644 --- a/packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/ArchiveSession.tsx @@ -49,10 +49,7 @@ export function ArchiveSessionRowButton({ type="button" className={css.iconButton} aria-label={t(archived ? 'menu.unarchiveSession' : 'menu.archiveSession')} - onClick={(e) => { - e.stopPropagation() - ;(archived ? unarchiveSession : archiveSession)(sessionId) - }} + onClick={() => { (archived ? unarchiveSession : archiveSession)(sessionId) }} > {archived ? : } diff --git a/packages/client/ui-workspace/src/client/session-actions/PinSession.tsx b/packages/client/ui-workspace/src/client/session-actions/PinSession.tsx index efbe4263ba..00ce1bff80 100644 --- a/packages/client/ui-workspace/src/client/session-actions/PinSession.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/PinSession.tsx @@ -60,10 +60,7 @@ export function PinSessionRowButton(props: SessionRowActionProps { - e.stopPropagation() - ;(pinned ? unpinSession : pinSession)(sessionId) - }} + onClick={() => { (pinned ? unpinSession : pinSession)(sessionId) }} > {pinned ? : } diff --git a/packages/client/ui-workspace/tests/rows.client.spec.tsx b/packages/client/ui-workspace/tests/rows.client.spec.tsx index e2bd6eada3..f41199824f 100644 --- a/packages/client/ui-workspace/tests/rows.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.client.spec.tsx @@ -190,6 +190,24 @@ describe('workspace browser rows', () => { expect(onOpen).toHaveBeenCalledWith(node.id) }) + it('keeps a row.action entry click in the strip, so a plain button does not open the row', () => { + const node: SessionNode = { + id: sid('session'), title: 'Session', blank: false, running: false, + runningSubagentCount: 0, completed: false, hasActiveSchedule: false, updatedAt: 0, pinned: false, archived: false, + } + const onOpen = vi.fn() + const pluginAction = vi.fn() + const renderSlot: RowRenderSlot = (name: RowSlotName) => (name === 'sidebar.workspaces.session.row.action' + ? + : null) + render() + fireEvent.click(screen.getByRole('button', { name: 'plugin' })) + expect(pluginAction).toHaveBeenCalledOnce() + expect(onOpen).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('treeitem')) + expect(onOpen).toHaveBeenCalledWith(node.id) + }) + it('reveals a clipped session title by scrolling it while the row is hovered', () => { const node: SessionNode = { id: sid('clipped'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false, diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index a6e025b67c..ce5cb47dda 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -132,27 +132,17 @@ describe('pin action', () => { expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(pin.unpinSession)) }) - it('row button toggles the pin without opening the row', () => { - const onRowClick = vi.fn() + it('row button toggles the pin', () => { const pin = pinShare() - const view = render( -
- -
, - ) + const view = render() fireEvent.click(screen.getByRole('button', { name: '置顶会话' })) expect(pin.pinSession).toHaveBeenCalledWith(sid('one')) expect(pin.unpinSession).not.toHaveBeenCalled() - view.rerender( -
- -
, - ) + view.rerender() fireEvent.click(screen.getByRole('button', { name: '取消置顶' })) expect(pin.unpinSession).toHaveBeenCalledWith(sid('one')) expect(pin.pinSession).toHaveBeenCalledOnce() - expect(onRowClick).not.toHaveBeenCalled() }) it('offers nothing on an archived Session', () => { @@ -199,25 +189,15 @@ describe('archive action', () => { expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(archive.unarchiveSession)) }) - it('row button archives and restores without opening the row', () => { - const onRowClick = vi.fn() + it('row button archives and restores', () => { const archive = archiveShare() - const view = render( -
- -
, - ) + const view = render() fireEvent.click(screen.getByRole('button', { name: '归档会话' })) expect(archive.archiveSession).toHaveBeenCalledWith(sid('one')) - view.rerender( -
- -
, - ) + view.rerender() fireEvent.click(screen.getByRole('button', { name: '取消归档' })) expect(archive.unarchiveSession).toHaveBeenCalledWith(sid('one')) expect(archive.archiveSession).toHaveBeenCalledOnce() - expect(onRowClick).not.toHaveBeenCalled() }) }) diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index f05857cc47..a8e10756e4 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -16,6 +16,7 @@ import { LayoutController } from '@deepseek-ai/dsh-client-ui-layout/client' import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client' import { DirectoryBrowseError, UiWorkspaceService } from '../src/client/navigation.ts' import { createWorkspaceViewStore, FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' +import { UNGROUPED_KEY } from '../src/client/tree.ts' const sid = (id: string): SessionId => SessionId(id) const wid = (id: string): WorkspaceId => id as WorkspaceId @@ -447,6 +448,57 @@ describe('UiWorkspaceService', () => { expect(b.view.getSnapshot().sessionOrderByAccount.a).toEqual(['three', 'one', 'two']) }) + it('keeps newer saved orders when a pending pin completes', async () => { + const b = bench({ + workspaces: workspaceState([workspace('a', [sid('one'), sid('two'), sid('three')])]), + sessions: sessionState([summary('one', { updatedAt: 3 }), summary('two', { updatedAt: 2 }), summary('three', { updatedAt: 1 })]), + }) + const pending = Promise.withResolvers() + const hostPin = b.workspaces.onPin + b.workspaces.onPin = async (sessionId) => { await pending.promise; await hostPin(sessionId) } + const pin = b.uiWorkspace.pinSession(sid('three')) + b.view.actions.setSessionOrder('a', ['two', 'one', 'three'], {}) + b.view.actions.setSessionOrder(FLAT_SESSION_ORDER_KEY, ['two', 'one', 'three'], {}) + pending.resolve(undefined) + await pin + expect(b.view.getSnapshot().sessionOrderByAccount).toMatchObject({ + a: ['three', 'two', 'one'], + [FLAT_SESSION_ORDER_KEY]: ['three', 'two', 'one'], + }) + }) + + it('uses the membership current at completion when a Workspace disappears during a pending pin', async () => { + const b = bench({ + workspaces: workspaceState([workspace('a', [sid('one'), sid('two')])]), + sessions: sessionState([summary('one', { updatedAt: 2 }), summary('two', { updatedAt: 1 })]), + }) + const pending = Promise.withResolvers() + const hostPin = b.workspaces.onPin + b.workspaces.onPin = async (sessionId) => { await pending.promise; await hostPin(sessionId) } + const pin = b.uiWorkspace.pinSession(sid('two')) + b.workspaces.list.update(state => ({ ...state, items: [] })) + pending.resolve(undefined) + await pin + expect(b.view.getSnapshot().sessionOrderByAccount).not.toHaveProperty('a') + expect(b.view.getSnapshot().sessionOrderByAccount).toMatchObject({ + [UNGROUPED_KEY]: ['two', 'one'], + [FLAT_SESSION_ORDER_KEY]: ['two', 'one'], + }) + }) + + it('keeps saved Workspace members whose summaries are temporarily missing when pinning in Last updated', async () => { + const b = bench({ + workspaces: workspaceState([workspace('a', [sid('one'), sid('two'), sid('three')])]), + sessions: sessionState([summary('one', { updatedAt: 3 }), summary('two', { updatedAt: 2 }), summary('three', { updatedAt: 1 })]), + }) + await b.uiWorkspace.pinSession(sid('one')) + expect(b.view.getSnapshot().sessionOrderByAccount.a).toEqual(['one', 'two', 'three']) + b.sessions.list.set(sessionState([summary('one', { updatedAt: 3 }), summary('three', { updatedAt: 1 })])) + await b.uiWorkspace.pinSession(sid('three')) + expect(b.view.getSnapshot().orderBy).toBe('updated') + expect(b.view.getSnapshot().sessionOrderByAccount.a).toEqual(['three', 'one', 'two']) + }) + it('reuses only an unarchived member blank and coalesces concurrent creation', async () => { const b = bench({ sessions: sessionState([ From ee61acfe7efd977de80304ea47f0d61887ca1444 Mon Sep 17 00:00:00 2001 From: imccyu Date: Sun, 20 Sep 2026 13:33:58 +0800 Subject: [PATCH 23/24] docs(client): describe session row entries as plain menuitem buttons The Client Slot catalog serves `cordis-client-runner` closures, which cannot `require` anything, so the `sidebar.workspaces.session.menu.item` example now renders a `role="menuitem"` `