From b92235c490e4d831a27fc2775048b9cc5434ba3e Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 14:26:25 +0800 Subject: [PATCH 001/113] docs: record model-facing session query tools --- ...model-facing-session-query-tools.i18n.yaml | 6 +++ ...-07-24-model-facing-session-query-tools.md | 51 +++++++++++++++++++ ...-24-model-facing-session-query-tools.zh.md | 51 +++++++++++++++++++ 3 files changed, 108 insertions(+) create mode 100644 .agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md create mode 100644 .agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml new file mode 100644 index 0000000000..feab70bc44 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 +2026-07-24-model-facing-session-query-tools.md: 27842c2799c3898de4bd9f0fd8171911b0e965cd +2026-07-24-model-facing-session-query-tools.zh.md: 899f63fb7bf6cc6357d25cf90e077b6e2f80afa1 diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md new file mode 100644 index 0000000000..27842c2799 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -0,0 +1,51 @@ +# Agent Note: Model-facing session query tools + +Status: implemented + +English | [中文](2026-07-24-model-facing-session-query-tools.zh.md) + +## Problem + +The unified `ctx.sessionQuery` service exposes exact reads, filters, relationship traces, and full-text search over live-preferred session logs, but models cannot use that service directly. Giving a model the provider request types would also expose unstable pagination cursors, trusted corpus scope, storage-shaped time values, and result records that are more convenient for programmatic consumers than for reasoning. Large traces and event payloads introduce a separate output-size concern, but solving that concern inside this consumer would duplicate the harness-wide spill mechanism and make session-query tools disagree with other tools. + +## Decision + +`@deepseek-ai/dsh-tool-session-query` is the model-facing consumer of `ctx.sessionQuery`. It registers five narrow read-only tools: `session_search`, `session_event_search`, `session_trace`, `session_event_trace`, and `session_event_read`. The package imports the interface rather than the SQLite implementation, owns model argument validation and readable text rendering, and contributes one concise prompt section that teaches the prior-history search and search-to-trace/read workflow. + +`session_search` groups full-text matches by session and exposes typed session and event metadata filters. `session_event_search` searches one session, defaulting to the caller's current session. `session_trace` returns the complete authorized ancestor chain and recursive descendant trees. `session_event_trace` returns every known positional replacement and direct provenance relationship for one event. `session_event_read` returns the exact target event as unabridged JSON and optionally summarizes a bounded raw-event window; omitted `before` and `after` values mean target-only. + +Model-facing filters use flat snake-case fields. Timestamps are timezone-qualified ISO 8601 strings at the tool boundary, convert to inclusive epoch-millisecond ranges for the service, and render as UTC ISO 8601. List values are ORed inside one filter while separate filters are ANDed. Parent ids and the root-session marker share one parent clause. Event type strings remain open because `SessionEventMap` is merge-extensible; availability and event surface use closed values. + +## Workspace authority + +Every executor derives its caller from immutable `ToolExecution.exec.agent` identity and never accepts a model-supplied workspace. A target is authorized only when its persisted `cwd` exactly equals the caller session's `cwd`. Cross-session search always adds that workspace filter, direct reads and traces authorize before loading the target, and lineage rendering stops at an unauthorized ancestor or descendant subtree without revealing the hidden session id. A caller whose session has no `cwd` can inspect only its own session; missing agent identity fails closed. + +The search tools expose prior work rather than the operation that is performing the search. `session_search` omits the caller's session. When `session_event_search` targets the caller's session, it intersects the requested sequence range with the event immediately before the current `step/start`, excluding the current assistant message and tool call as well as the query arguments indexed from that call. + +## Cursor-free results and spill + +Neither search tool exposes a cursor, offset, page size, or model-controlled result limit. One execution follows provider cursors while the observed generation remains valid and collects up to the configured `maxSearchResults`, which defaults to 100. A capped result tells the model to narrow its query or filters; a generation change reports that the whole search must be retried. Search execution carries a configurable `searchTimeoutMs`, defaulting to 30 seconds, through the tool deadline and the service abort signal. + +Trace and read tools likewise expose no lineage or character pagination. Canonical results are plain text and remain complete within the service's existing event-window and search-count resource bounds. The generic `tools/post-execute` spill policy owns inline byte retention: when a configured deployment receives oversized text, it replaces that text with a bounded preview plus an opaque locator and retrieval hint while preserving the complete result in its spill store. The session-query consumer neither imports `ctx.spillStore` nor implements a second truncation format. + +Session-level results include the latest folded title when available. Absence is rendered as untitled; a title read failure preserves the base result, renders an unavailable marker, and logs the underlying error. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. + +## Host composition + +The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.sessionQuery`. TUI and Web use their existing timeout and spill policies. ACP mounts the same timeout policy and private local spill backend with the shared 50,000-byte inline threshold, so the five tools have one model-facing contract across hosts. Web also mounts the SQLite query backend at its persistence root; generic tool presentation requires no session-query-specific client plugin. + +## Alternatives considered + +- **Expose provider cursors to the model** — rejected because recording a tool result or starting the next model step changes the relevant session or global generation, so a cursor is usually stale before the model can reuse it. +- **Add tool-local truncation, offsets, or spill files** — rejected because the post-execute spill policy already owns complete-result retention and retrieval across tools. +- **Allow every persisted session or model-supplied workspace filters** — rejected because `ctx.sessionQuery` is a trusted service and the model-facing consumer must enforce the caller's authority boundary. +- **Combine search, tracing, and exact reads into one operation selector** — rejected because narrow names give the model clearer schemas, defaults, presentation intents, and follow-up choices. +- **Return only one lineage hop** — rejected because spill removes the inline-size motivation while one-hop output would omit relationships with no continuation path. + +## Verification + +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, title fallbacks, rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while a keyless model transcript pins the prompt guidance, schemas, representative search/trace/read output, and oversized-result spill behavior. + +## Consequences + +Models gain provider-independent access to prior session work without receiving storage authority or continuation state. Search has a finite per-call work bound and may require a narrower query to reach matches beyond the first 100; complete traces and event payloads may become spill references instead of inline text. Exact string `cwd` equality favors a conservative security boundary over resolving symlink-equivalent paths. Custom compositions may mount the tool without spill, but then they explicitly accept complete inline trace and read results. diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md new file mode 100644 index 0000000000..899f63fb7b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -0,0 +1,51 @@ +# Agent Note: 面向模型的会话查询工具 + +Status: implemented + +[English](2026-07-24-model-facing-session-query-tools.md) | 中文 + +## 问题 + +统一的 `ctx.sessionQuery` 服务对优先使用实时数据的会话日志提供精确读取、过滤、关系追踪与全文搜索,但模型无法直接使用该服务。若把提供方请求类型交给模型,还会暴露不稳定的分页游标、受信任的语料范围、存储形态的时间值,以及更适合程序化消费者而非模型推理的结果记录。大型追踪与事件负载另有输出大小问题,但若在该消费者内部解决,就会重复 harness 的通用 spill 机制,并使会话查询工具与其他工具的行为不一致。 + +## 决策 + +`@deepseek-ai/dsh-tool-session-query` 是 `ctx.sessionQuery` 面向模型的消费者。它注册五个职责单一的只读工具:`session_search`、`session_event_search`、`session_trace`、`session_event_trace` 和 `session_event_read`。该包依赖接口而非 SQLite 实现,负责模型参数校验与易读文本渲染,并贡献一个精简的提示词段,说明历史搜索以及从搜索转向追踪/读取的工作流。 + +`session_search` 按会话聚合全文匹配,并公开带类型的会话与事件元数据过滤条件。`session_event_search` 搜索一个会话,默认目标为调用者的当前会话。`session_trace` 返回完整的已授权祖先链与递归后代树。`session_event_trace` 返回一个事件所有已知的位置替换关系与直接来源关系。`session_event_read` 以未删节 JSON 返回准确的目标事件,并可选择汇总一个有界的原始事件窗口;省略 `before` 与 `after` 时只返回目标。 + +面向模型的过滤条件使用扁平的 snake-case 字段。工具边界上的时间戳采用带时区的 ISO 8601 字符串,转换为服务使用的闭区间毫秒时间戳,并以 UTC ISO 8601 渲染。同一个过滤条件中的列表值按 OR 组合,不同过滤条件按 AND 组合。父会话 id 与根会话标记共用一个父级条件。由于 `SessionEventMap` 可通过声明合并扩展,事件类型字符串保持开放;可用状态与事件表层使用封闭取值。 + +## 工作区权限 + +每个执行器都从不可变的 `ToolExecution.exec.agent` 身份推导调用者,绝不接受模型提供的工作区。只有当目标持久化的 `cwd` 与调用者会话的 `cwd` 完全相同时,目标才获授权。跨会话搜索始终附加该工作区过滤条件;直接读取与追踪在加载目标前完成授权;谱系渲染在遇到未授权的祖先或后代子树时停止,且不泄露被隐藏的会话 id。调用者会话没有 `cwd` 时只能检查自身会话;缺少 agent 身份时按失败关闭处理。 + +搜索工具公开的是既往工作,而不是正在执行搜索的操作本身。`session_search` 排除调用者会话。`session_event_search` 以调用者会话为目标时,会把请求的序号范围与当前 `step/start` 之前的最后一个事件取交集,从而排除当前 assistant 消息、工具调用,以及从该次调用中建立索引的查询参数。 + +## 无游标结果与 spill + +两个搜索工具都不向模型公开游标、偏移量、页大小或模型可控的结果限制。一次执行会在观察到的代保持有效时持续跟随提供方游标,并收集不超过配置项 `maxSearchResults` 的结果,其默认值为 100。达到上限的结果会要求模型缩小查询或过滤范围;代发生变化时会报告必须重试完整搜索。搜索执行通过工具截止时间与服务中止信号传递可配置的 `searchTimeoutMs`,默认值为 30 秒。 + +追踪与读取工具同样不公开谱系分页或字符分页。规范结果采用纯文本,并在服务已有的事件窗口与搜索数量资源边界内保持完整。通用的 `tools/post-execute` spill 策略负责行内字节保留:当已配置的部署收到过大的文本时,该策略会用有界预览、不可透明推导的定位符与读取提示替换文本,同时在 spill 存储中保留完整结果。会话查询消费者既不导入 `ctx.spillStore`,也不实现第二套截断格式。 + +会话级结果在可用时包含最新折叠标题。没有标题时渲染为未命名;标题读取失败时保留基础结果,渲染不可用标记,并记录底层错误。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 + +## 宿主组合 + +发布的 ACP、TUI 与 Web 组合都在 `ctx.sessionQuery` 旁挂载该消费者。TUI 与 Web 使用已有的超时与 spill 策略。ACP 挂载同一超时策略与私有本地 spill 后端,并采用共享的 50,000 字节行内阈值,因此五个工具在各宿主中具有同一面向模型的契约。Web 还在其持久化根目录挂载 SQLite 查询后端;通用工具表现无需会话查询专用客户端插件。 + +## 考虑过的替代方案 + +- **向模型公开提供方游标**:不予采纳,因为记录工具结果或开始下一个模型步骤会改变相关会话或全局代,导致游标通常在模型能够复用前就已过期。 +- **增加工具本地截断、偏移量或 spill 文件**:不予采纳,因为执行后 spill 策略已经统一负责各工具的完整结果保留与读取。 +- **允许访问所有持久化会话或由模型提供工作区过滤条件**:不予采纳,因为 `ctx.sessionQuery` 是受信任服务,面向模型的消费者必须执行调用者权限边界。 +- **把搜索、追踪与精确读取合并为一个带操作选择器的工具**:不予采纳,因为职责单一的名称能为模型提供更清晰的 schema、默认值、表现意图与后续选择。 +- **只返回一层谱系**:不予采纳,因为 spill 已消除行内大小方面的理由,而单层输出会遗漏关系且没有继续读取路径。 + +## 验证 + +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、标题回退、渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥模型 transcript 则固定提示词指导、schema、代表性搜索/追踪/读取输出和超大结果 spill 行为。 + +## 后果 + +模型无需获得存储权限或继续状态,即可通过与提供方无关的方式访问既往会话工作。搜索具有有限的单次调用工作边界,若要命中前 100 条以后的结果,可能需要缩小查询;完整追踪与事件负载可能表现为 spill 引用而不是行内文本。严格的 `cwd` 字符串相等选择了保守安全边界,而不解析通过符号链接等价的路径。自定义组合可以在不挂载 spill 的情况下使用该工具,但这表示它们明确接受完整追踪与读取结果直接出现在行内。 From a350e95165cd136a946a218f829935d9775060e3 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 15:09:55 +0800 Subject: [PATCH 002/113] feat(session-query): add model-facing tools (round 1) --- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 2 +- docs/architecture.zh.md | 2 +- docs/capability-seams.md | 4 +- docs/config-catalog.md | 16 + docs/module-graph.md | 9 + docs/tool-catalog.md | 234 +++++ examples/acp-agent/composition.md | 12 + examples/acp-agent/cordis.yml | 18 + examples/acp-agent/tests/acp.snapshot.ts | 7 + .../snapshots/session-query-spill/input.json | 7 + .../session-query-spill/session.jsonl | 34 + .../session-query-spill/stdout.expected.jsonl | 10 + .../text-turn/system-prompt.expected.md | 2 + .../text-turn/tool-schemas.expected.json | 204 ++++ examples/package.json | 1 + examples/tui-agent/composition.md | 3 + examples/tui-agent/cordis.yml | 6 + packages/examples/acp-demo/README.md | 2 +- packages/examples/acp-demo/package.json | 1 + .../examples/acp-demo/tests/load-path.e2e.ts | 15 +- packages/examples/tui-demo/README.md | 2 +- packages/host/runtime/package.json | 2 + packages/host/runtime/src/boot.ts | 7 +- .../host/runtime/tests/host-runtime.spec.ts | 18 + packages/host/runtime/tsconfig.json | 6 + packages/session-query/README.md | 3 +- .../tool-session-query/README.md | 72 ++ .../tool-session-query/package.json | 57 ++ .../tool-session-query/src/index.ts | 961 ++++++++++++++++++ .../tool-session-query/src/invariant.ts | 30 + .../tests/sqlite-integration.spec.ts | 100 ++ .../tests/tool-session-query.spec.ts | 796 +++++++++++++++ .../tool-session-query/tsconfig.json | 40 + .../support/acp-snapshot/src/normalize.ts | 5 + .../acp-snapshot/tests/normalize.spec.ts | 22 + pnpm-lock.yaml | 58 ++ scripts/gen-doc-graphs.ts | 4 +- scripts/gen-tool-catalog.ts | 17 + tsconfig.host.json | 1 + 40 files changed, 2781 insertions(+), 13 deletions(-) create mode 100644 examples/acp-agent/tests/snapshots/session-query-spill/input.json create mode 100644 examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl create mode 100644 examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl create mode 100644 packages/session-query/tool-session-query/README.md create mode 100644 packages/session-query/tool-session-query/package.json create mode 100644 packages/session-query/tool-session-query/src/index.ts create mode 100644 packages/session-query/tool-session-query/src/invariant.ts create mode 100644 packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts create mode 100644 packages/session-query/tool-session-query/tests/tool-session-query.spec.ts create mode 100644 packages/session-query/tool-session-query/tsconfig.json diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 20553e1b90..6e47d0b420 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.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 -architecture.md: d1051eecf51d8d1c7f8c235b0c5dd80478b43316 -architecture.zh.md: 502c0248a9d2c62af165ce07eb19489b76c5f6ee +architecture.md: b362a4cb97aa04223805ce7f2892f9fe9b4104cf +architecture.zh.md: 3791cb619448b70005d42ea98f11869082e943fa diff --git a/docs/architecture.md b/docs/architecture.md index d1051eecf5..b362a4cb97 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -43,7 +43,7 @@ Harnesses are [Cordis](cordis-primer.md) contexts whose packages contribute serv | `ctx.workflows` | [`workflow/`](../packages/workflow/README.md) | script-driven multi-agent orchestration | | `ctx.goals` | [`goal/`](../packages/goal/README.md) | persisted same-session goals | | `ctx.sessionPersistence` | [`session-persistence/`](../packages/session-persistence/README.md) | durable session-log storage | -| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | `session-query` interface: concrete live-preferred exact/filter/trace; exactly two abstract FTS methods via `session-query-sqlite` | +| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | Live-preferred exact/filter/trace interface, SQLite FTS backend, and workspace-authorized model tools | | `ctx.sessionTitle` | [`session-title/`](../packages/session-title/README.md) | log-backed fallbacks plus one optional asynchronous provider | | `ctx.invariants` | [`support/invariants`](../packages/support/invariants/README.md) | package-name-selected registry for package-owned runtime checks | diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 502c0248a9..3791cb6194 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -43,7 +43,7 @@ | `ctx.workflows` | [`workflow/`](../packages/workflow/README.md) | 脚本驱动的多 agent 编排 | | `ctx.goals` | [`goal/`](../packages/goal/README.md) | 持久化的同会话目标 | | `ctx.sessionPersistence` | [`session-persistence/`](../packages/session-persistence/README.md) | 会话日志的持久化存储 | -| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | `session-query` 接口:精确检索、过滤与追踪采用实时优先的具体实现;恰有两个全文搜索方法为抽象方法,由 `session-query-sqlite` 实现 | +| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | 实时优先的精确检索/过滤/追踪接口、SQLite 全文搜索后端,以及经工作区授权的模型工具 | | `ctx.sessionTitle` | [`session-title/`](../packages/session-title/README.md) | 基于日志的回退标题,以及单个可选的异步提供方 | | `ctx.invariants` | [`support/invariants`](../packages/support/invariants/README.md) | 按包名筛选包自有运行时检查的注册表 | diff --git a/docs/capability-seams.md b/docs/capability-seams.md index a27d325e31..4806a86e72 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -38,6 +38,7 @@ flowchart LR pkg_acp["acp"] svc_sessionQuery["ctx.sessionQuery
Session reads, traces, filters, and search"] pkg_session_reference["session-reference"] + pkg_tool_session_query["tool-session-query"] svc_sessionReferences["ctx.sessionReferences
Cross-session snapshot preparation"] pkg_tui["tui"] pkg_session_title["session-title"] @@ -223,6 +224,7 @@ flowchart LR svc_sessionPersistence --> pkg_session_query_sqlite svc_sessionPersistence --> pkg_tool_bash svc_sessionQuery --> pkg_session_reference + svc_sessionQuery --> pkg_tool_session_query svc_sessionReferences --> pkg_acp svc_sessionReferences --> pkg_tui svc_sessions --> pkg_agent @@ -276,7 +278,7 @@ flowchart LR | `ctx.sessions` | `core` | [`session`](../packages/core/session) | - | [`agent-loop`](../packages/core/agent-loop), [`agent`](../packages/core/agent), [`cli-demo`](../packages/examples/cli-demo), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite), [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`invariants`](../packages/support/invariants) | - | Owns append-only Session instances and emits the durable session event feed. | | `ctx.invariants` | `core` | [`invariants`](../packages/support/invariants) | - | [`session`](../packages/core/session), [`agent`](../packages/core/agent), [`scope`](../packages/core/scope), [`agent-loop`](../packages/core/agent-loop) | - | Companion subpaths register owner-local checks; the service owns selection, uniqueness, child fibers, and package-attributed failures. | | `ctx.sessionPersistence` | `seam` | [`session-persistence`](../packages/session-persistence/session-persistence) | [`session-persistence-jsonl`](../packages/session-persistence/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session-persistence/session-persistence-sqlite) | [`agent-loop`](../packages/core/agent-loop), [`tool-bash`](../packages/bash/tool-bash), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`acp`](../packages/ui/acp), [`session-query`](../packages/session-query/session-query), [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | - | Backends persist the same SessionEvent vocabulary; apps choose a backend at composition time. | -| `ctx.sessionQuery` | `seam` | [`session-query`](../packages/session-query/session-query) | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | [`session-reference`](../packages/context/session-reference) | - | The interface supplies exact reads, filters, and traces; its concrete backend adds full-text reconciliation, ranking, snippets, and cursor generations on the same service. | +| `ctx.sessionQuery` | `seam` | [`session-query`](../packages/session-query/session-query) | [`session-query-sqlite`](../packages/session-query/session-query-sqlite) | [`session-reference`](../packages/context/session-reference), [`tool-session-query`](../packages/session-query/tool-session-query) | - | The interface supplies exact reads, filters, and traces; its concrete backend adds full-text reconciliation, ranking, snippets, and cursor generations, while the model consumer owns workspace authority and cursor-free rendering. | | `ctx.sessionReferences` | `core` | [`session-reference`](../packages/context/session-reference) | - | [`tui`](../packages/ui/tui), [`acp`](../packages/ui/acp) | - | Projects bounded current-surface conversation snapshots into durable untrusted message context; host adapters own mention syntax. | | `ctx.sessionTitle` | `seam` | [`session-title`](../packages/session-title/session-title) | [`session-title-first-message-llm`](../packages/session-title/session-title-first-message-llm), [`session-title-all-messages-llm`](../packages/session-title/session-title-all-messages-llm) | - | - | Owns the deterministic fallback, latest-title fold, and sole optional asynchronous provider registration. | | `ctx.systemPrompt` | `core` | [`system-prompt`](../packages/core/system-prompt) | - | [`agent-loop`](../packages/core/agent-loop), [`tools`](../packages/core/tools), [`tool-fs`](../packages/fs/tool-fs), [`tool-pty`](../packages/pty/tool-pty), [`tool-web`](../packages/web/tool-web) | - | Collects prompt sections and model-facing tool schemas for each step. | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 985e493184..d76443579a 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1423,6 +1423,22 @@ export interface Config { Source: [`packages/workflow/tool-ralph/src/index.ts:23`](../packages/workflow/tool-ralph/src/index.ts) +## `@deepseek-ai/dsh-tool-session-query` + +Requires: `tools` · `systemPrompt` · `sessionQuery` + +```ts config-catalog +/** Deployment-owned search count and timeout bounds. */ +export interface Config { + /** Maximum authorized hits returned by one search call. Defaults to 100. */ + maxSearchResults?: number + /** Cooperative full-text search deadline in milliseconds. Defaults to 30000. */ + searchTimeoutMs?: number +} +``` + +Source: [`packages/session-query/tool-session-query/src/index.ts:50`](../packages/session-query/tool-session-query/src/index.ts) + ## `@deepseek-ai/dsh-tool-skill` Requires: `tools` · `skills` diff --git a/docs/module-graph.md b/docs/module-graph.md index 7e2ee76934..5600279890 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -106,6 +106,7 @@ flowchart TD subgraph group_session_query["packages/session-query"] pkg_session_query["session-query"] pkg_session_query_sqlite["session-query-sqlite"] + pkg_tool_session_query["tool-session-query"] end subgraph group_session_title["packages/session-title"] pkg_session_title["session-title"] @@ -570,6 +571,13 @@ flowchart TD pkg_session_checkpoint_policy --> pkg_session pkg_session_checkpoint_policy --> pkg_session_persistence pkg_session_checkpoint_policy --> pkg_tools + pkg_tool_session_query --> pkg_invariants + pkg_tool_session_query --> pkg_llm + pkg_tool_session_query --> pkg_session + pkg_tool_session_query --> pkg_session_query + pkg_tool_session_query --> pkg_system_prompt + pkg_tool_session_query --> pkg_timeout + pkg_tool_session_query --> pkg_tools pkg_agent_loop_testkit --> pkg_agent pkg_agent_loop_testkit --> pkg_invariants pkg_agent_loop_testkit --> pkg_llm @@ -883,6 +891,7 @@ flowchart TD | [`tool-cordis`](../packages/cordis/tool-cordis) | `cordis` | [`invariants`](../packages/support/invariants), [`scope`](../packages/core/scope), [`tools`](../packages/core/tools) | | [`hooks-codex`](../packages/hooks/hooks-codex) | `hooks` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/hooks/hook-protocol), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools) | | [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy) | `session-persistence` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`tools`](../packages/core/tools) | +| [`tool-session-query`](../packages/session-query/tool-session-query) | `session-query` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) | | [`agent-loop-testkit`](../packages/support/agent-loop-testkit) | `support` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-ask-user`](../packages/ui/tool-ask-user) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | | [`workspace-context`](../packages/context/workspace-context) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 4f9de3644f..10f7fc74d9 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -27,6 +27,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.tools`, `ctx.lsp`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The lsp tool keeps provider selection and language-server subprocesses behind ctx.lsp, so its model-visible schema stays stable across providers. Requires a registered provider (e.g. `@deepseek-ai/dsh-lsp-local`) at runtime; without one, a query returns the structured `LSP_UNAVAILABLE` error rather than changing the schema. | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`, `ctx.workflows`, `ctx.subagents`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents every fresh round)` | `tool/call`, `tool/result`, `workflow and child session events during execution` | - | A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap. | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.tools`, `ctx.skills` | `tool/call`, `tool/result` | - | - | +| `@deepseek-ai/dsh-tool-session-query` | `session_event_read`, `session_event_search`, `session_event_trace`, `session_search`, `session_trace` | `ctx.tools`, `ctx.systemPrompt`, `ctx.sessionQuery`, `a calling Agent for workspace authority` | `tool/call`, `tool/result` | - | The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. Default ACP, TUI, and Web compositions enforce the declared search timeout and apply the generic tool-result spill policy. | | `@deepseek-ai/dsh-tool-subagent` | `subagent` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped example agents load this package once per subagent backend, so the model additionally sees `subagent_fork` (bound to the fork backend) with an identical schema — see `examples/tui-agent/cordis.yml` and `examples/acp-agent/cordis.yml`. | | `@deepseek-ai/dsh-tool-tasks` | `task_kill`, `task_list`, `task_output` | `ctx.tools`, `ctx.tasks`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `context/message via agent.inject() for background completion notices` | - | The kind-agnostic background-task control surface: background bash commands, PTY sends, and subagents are read, listed, and killed through the same three tools. Loading the plugin attaches the control surface that arms producers' `ctx.tasks.start()`. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist or ACP plan. | @@ -778,6 +779,239 @@ Load the full instructions for an available skill. Call this with the exact skil Source: [`packages/skill/tool-skill/src/index.ts`](../packages/skill/tool-skill/src/index.ts) +## `@deepseek-ai/dsh-tool-session-query` + +### `session_event_read` + +Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. + +```json +{ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] +} +``` + +Source: [`packages/session-query/tool-session-query/src/index.ts`](../packages/session-query/tool-session-query/src/index.ts) + +### `session_event_search` + +Search prior events in one authorized session; the current session excludes the step performing this call. + +```json +{ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] +} +``` + +Source: [`packages/session-query/tool-session-query/src/index.ts`](../packages/session-query/tool-session-query/src/index.ts) + +### `session_event_trace` + +Read every direct replacement and provenance relationship for one event in an authorized session. + +```json +{ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] +} +``` + +Source: [`packages/session-query/tool-session-query/src/index.ts`](../packages/session-query/tool-session-query/src/index.ts) + +### `session_search` + +Search prior sessions in the caller workspace and return the strongest matching event from each session. + +```json +{ + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] +} +``` + +Source: [`packages/session-query/tool-session-query/src/index.ts`](../packages/session-query/tool-session-query/src/index.ts) + +### `session_trace` + +Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. + +```json +{ + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } +} +``` + +Source: [`packages/session-query/tool-session-query/src/index.ts`](../packages/session-query/tool-session-query/src/index.ts) + +The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. Default ACP, TUI, and Web compositions enforce the declared search timeout and apply the generic tool-result spill policy. + ## `@deepseek-ai/dsh-tool-subagent` ### `subagent` diff --git a/examples/acp-agent/composition.md b/examples/acp-agent/composition.md index 841639fd90..b81676f382 100644 --- a/examples/acp-agent/composition.md +++ b/examples/acp-agent/composition.md @@ -29,6 +29,14 @@ flowchart LR bundle_agent_core --> spine_sessions["ctx.sessions"] bundle_agent_core --> spine_tools["ctx.tools + tool-bash"] bundle_agent_core --> spine_loop["ctx.agents + ctx.agentLoop"] + plugin_acp_tool_session_query["tool-session-query
@deepseek-ai/dsh-tool-session-query"] + cfg --> plugin_acp_tool_session_query + plugin_acp_timeout_policy["timeout-policy
@deepseek-ai/dsh-timeout-policy"] + cfg --> plugin_acp_timeout_policy + plugin_acp_spill_local["spill-local
@deepseek-ai/dsh-spill-local"] + cfg --> plugin_acp_spill_local + plugin_acp_spill_policy["spill-policy
@deepseek-ai/dsh-spill-policy"] + cfg --> plugin_acp_spill_policy plugin_acp_plan_mode["plan-mode
@deepseek-ai/dsh-plan-mode"] cfg --> plugin_acp_plan_mode plugin_acp_tool_ask_user["tool-ask-user
@deepseek-ai/dsh-tool-ask-user"] @@ -78,6 +86,10 @@ flowchart LR | `approval` | `@deepseek-ai/dsh-user-approval` | | `permission` | `@deepseek-ai/dsh-permission` | | `acp-agent` | `@deepseek-ai/dsh-acp-demo` | +| `tool-session-query` | `@deepseek-ai/dsh-tool-session-query` | +| `timeout-policy` | `@deepseek-ai/dsh-timeout-policy` | +| `spill-local` | `@deepseek-ai/dsh-spill-local` | +| `spill-policy` | `@deepseek-ai/dsh-spill-policy` | | `plan-mode` | `@deepseek-ai/dsh-plan-mode` | | `tool-ask-user` | `@deepseek-ai/dsh-tool-ask-user` | | `token-meter` | `@deepseek-ai/dsh-token-meter` | diff --git a/examples/acp-agent/cordis.yml b/examples/acp-agent/cordis.yml index d0f9b43367..3e7235c35c 100644 --- a/examples/acp-agent/cordis.yml +++ b/examples/acp-agent/cordis.yml @@ -65,6 +65,24 @@ Verify your work by running the code or tests. Keep answers brief and factual. +# Workspace-authorized prior-session search and exact trace/read tools. The app +# above owns ctx.sessionQuery; this leaf owns the model-facing consumer. +- id: tool-session-query + name: '@deepseek-ai/dsh-tool-session-query' + +# Enforce declared search deadlines and spill oversized plain-text tool output +# without introducing a session-query-specific truncation path. +- id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' + +- id: spill-local + name: '@deepseek-ai/dsh-spill-local' + +- id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: 50000 + # Plan mode is additive to the canonical ACP server. The ACP bridge projects # it onto the protocol picker; sandbox and approval remain independent options. - id: plan-mode diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index e35d47cea0..a19f863de6 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -100,6 +100,13 @@ const SCENARIOS: Scenario[] = [ configPath: FS_CONFIG, }, { name: 'bash-spill', hasModelTurn: true, recorded: false, configPath: FS_CONFIG }, + { + name: 'session-query-spill', + hasModelTurn: true, + recorded: false, + configPath: FS_CONFIG, + posixOnly: true, + }, { name: 'pty-tools', hasModelTurn: true, diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/input.json b/examples/acp-agent/tests/snapshots/session-query-spill/input.json new file mode 100644 index 0000000000..0e0abb74a2 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/session-query-spill/input.json @@ -0,0 +1,7 @@ +{ + "steps": [ + { "op": "initialize" }, + { "op": "newSession" }, + { "op": "prompt", "text": "Read request event 4 with session_event_read, verify the complete spill was retained, then reply DONE." } + ] +} diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl b/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl new file mode 100644 index 0000000000..c4b4f54047 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl @@ -0,0 +1,34 @@ +{"type":"session","version":0,"id":"{{sessionId}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"turn/start","seq":0,"time":0,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} +{"type":"user/message","seq":1,"time":0,"data":{"content":[{"type":"text","text":"Read request event 4 with session_event_read, verify the complete spill was retained, then reply DONE."}],"source":{"kind":"user"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":0,"data":{"title":"Read request event 4 with","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":0,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":6,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"call_session_query_spill","name":"session_event_read","argumentsDelta":"{\"seq\":4}"}}} +{"type":"assistant/chunk","seq":7,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_session_query_spill","name":"session_event_read","arguments":"{\"seq\":4}"}}}} +{"type":"assistant/chunk","seq":8,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":9,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":10,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_session_query_spill","name":"session_event_read","arguments":"{\"seq\":4}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} +{"type":"tool/call","seq":11,"time":0,"data":{"turn":1,"step":1,"callId":"call_session_query_spill","name":"session_event_read","arguments":"{\"seq\":4}"}} +{"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"call_session_query_spill","content":[{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": 1784876318672,\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted 39431 bytes. Full formatted result stored at: /tmp/dsh-acp-snap-035d1d054/session-ac29d2afe494/505bce11df84-session_event_read.txt. Use read with offset/limit, or grep this path to search within it.)"}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} +{"type":"step/end","seq":13,"time":0,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":14,"time":0,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":15,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":16,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"call_verify_session_query_spill","name":"bash","argumentsDelta":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}}} +{"type":"assistant/chunk","seq":17,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}}}} +{"type":"assistant/chunk","seq":18,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} +{"type":"assistant/chunk","seq":19,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"tool-call","id":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} +{"type":"tool/call","seq":21,"time":0,"data":{"turn":1,"step":2,"callId":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}} +{"type":"tool/result","seq":22,"time":0,"data":{"turn":1,"step":2,"callId":"call_verify_session_query_spill","content":[{"type":"text","text":"SPILL_CANONICAL_OK\n"}],"isError":false},"sourceEventSeqs":[21],"surfaceOp":"append"} +{"type":"step/end","seq":23,"time":0,"data":{"turn":1,"step":2}} +{"type":"step/start","seq":24,"time":0,"data":{"turn":1,"step":3}} +{"type":"assistant/chunk","seq":25,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} +{"type":"assistant/chunk","seq":26,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"text-delta","index":0,"text":"DONE"}}} +{"type":"assistant/chunk","seq":27,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":28,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":2}}}} +{"type":"assistant/chunk","seq":29,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":30,"time":0,"data":{"turn":1,"step":3,"content":[{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":2}},"sourceEventSeqs":[25,26,27,28,29],"surfaceOp":"append"} +{"type":"step/end","seq":31,"time":0,"data":{"turn":1,"step":3}} +{"type":"turn/end","seq":32,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl new file mode 100644 index 0000000000..a1a65b452c --- /dev/null +++ b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl @@ -0,0 +1,10 @@ +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[|clear|edit |pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Read request event 4 with","updatedAt":"{{updatedAt}}"}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_session_query_spill","title":"Read event 4","kind":"read","status":"in_progress","rawInput":{"seq":4}}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": {{eventTime}},\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted 39431 bytes. Full formatted result stored at: {{spillLocator:session_event_read.txt}}. Use read with offset/limit, or grep this path to search within it.)"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_verify_session_query_spill","title":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK","kind":"execute","status":"in_progress","rawInput":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK","content":[{"type":"content","content":{"type":"text","text":"Verify complete session query spill"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_verify_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nSPILL_CANONICAL_OK\n```"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md index 17e6773a03..68bdd841c7 100644 --- a/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json index b01e7683d1..02237f770b 100644 --- a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json @@ -238,6 +238,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/package.json b/examples/package.json index 1b4e28c4fd..9e9534379d 100644 --- a/examples/package.json +++ b/examples/package.json @@ -59,6 +59,7 @@ "@deepseek-ai/dsh-tool-goal": "workspace:*", "@deepseek-ai/dsh-tool-lsp": "workspace:*", "@deepseek-ai/dsh-tool-ralph": "workspace:*", + "@deepseek-ai/dsh-tool-session-query": "workspace:*", "@deepseek-ai/dsh-tool-subagent": "workspace:*", "@deepseek-ai/dsh-tool-todo": "workspace:*", "@deepseek-ai/dsh-tool-workflow": "workspace:*", diff --git a/examples/tui-agent/composition.md b/examples/tui-agent/composition.md index fd6d163952..557923b733 100644 --- a/examples/tui-agent/composition.md +++ b/examples/tui-agent/composition.md @@ -23,6 +23,8 @@ flowchart LR bundle_agent_core --> spine_sessions["ctx.sessions"] bundle_agent_core --> spine_tools["ctx.tools + tool-bash"] bundle_agent_core --> spine_loop["ctx.agents + ctx.agentLoop"] + plugin_tui_tool_session_query["tool-session-query
@deepseek-ai/dsh-tool-session-query"] + cfg --> plugin_tui_tool_session_query plugin_tui_session_title_llm["session-title-llm
@deepseek-ai/dsh-session-title-first-message-llm"] cfg --> plugin_tui_session_title_llm plugin_tui_token_meter["token-meter
@deepseek-ai/dsh-token-meter"] @@ -71,6 +73,7 @@ flowchart LR | `llm-deepseek` | `@deepseek-ai/dsh-llm-deepseek` | | `bash` | `@deepseek-ai/dsh-bash-local` | | `tui-agent` | `@deepseek-ai/dsh-tui-demo` | +| `tool-session-query` | `@deepseek-ai/dsh-tool-session-query` | | `session-title-llm` | `@deepseek-ai/dsh-session-title-first-message-llm` | | `token-meter` | `@deepseek-ai/dsh-token-meter` | | `tool-result-prune` | `@deepseek-ai/dsh-compact-tool-result-prune` | diff --git a/examples/tui-agent/cordis.yml b/examples/tui-agent/cordis.yml index 3070fcdc01..479ad24d09 100644 --- a/examples/tui-agent/cordis.yml +++ b/examples/tui-agent/cordis.yml @@ -7,6 +7,7 @@ - id: hmr name: '@cordisjs/plugin-hmr' + disabled: !!js process.env.CI === 'true' config: root: ['.'] @@ -52,6 +53,11 @@ Verify your work by running the code or tests. Keep answers brief and factual. +# The app above owns ctx.sessionQuery; expose its workspace-authorized +# prior-session search and exact trace/read operations to the model. +- id: tool-session-query + name: '@deepseek-ai/dsh-tool-session-query' + # Model-made session titles on the first-message cadence: replaces the spine's # deterministic fallback title with a short model summary. The TUI renders the # logged `session/title` as the banner subtitle and the terminal window title. diff --git a/packages/examples/acp-demo/README.md b/packages/examples/acp-demo/README.md index 93d89d6557..bd8c980993 100644 --- a/packages/examples/acp-demo/README.md +++ b/packages/examples/acp-demo/README.md @@ -15,7 +15,7 @@ stdout is the ACP JSON-RPC channel, so the cluster is defined as much by what it | `@deepseek-ai/dsh-command-goal` | the discoverable direct `/goal` producer; the app enables the spine's persisted-goal stack with it | | `@deepseek-ai/dsh-user-interaction` | the human question/answer seam used by clients that can complete ACP elicitation requests | | `@deepseek-ai/dsh-session-persistence-jsonl` | durable JSONL session log (the bridge advertises `loadSession`) | -| `@deepseek-ai/dsh-session-query-sqlite` + `@deepseek-ai/dsh-session-reference` | combined exact/FTS session queries and bounded `dsh-session:` snapshots | +| `@deepseek-ai/dsh-session-query-sqlite` + `@deepseek-ai/dsh-session-reference` | combined exact/FTS session queries and bounded `dsh-session:` snapshots; the default leaf adds the model-facing query tools | | `@deepseek-ai/dsh-session-checkpoint-policy` | semantic durability barriers before model requests and top-level tool effects, plus completed-step checkpoints | | `@deepseek-ai/dsh-acp` | the bridge that owns stdout for JSON-RPC and provides ACP-backed user answers when a leaf explicitly exposes a user-question tool | | ~~`@deepseek-ai/dsh-tool-ask-user`~~ | **omitted by default** — ACP elicitation support is still client-dependent, so leaves must opt in deliberately | diff --git a/packages/examples/acp-demo/package.json b/packages/examples/acp-demo/package.json index 36de692404..ad1ece0095 100644 --- a/packages/examples/acp-demo/package.json +++ b/packages/examples/acp-demo/package.json @@ -70,6 +70,7 @@ "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", "@deepseek-ai/dsh-session-reference": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-tool-session-query": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/dsh-user-interaction": "workspace:^", "@deepseek-ai/dsh-workspace-context": "workspace:^", diff --git a/packages/examples/acp-demo/tests/load-path.e2e.ts b/packages/examples/acp-demo/tests/load-path.e2e.ts index 982fac3b50..a866aaa243 100644 --- a/packages/examples/acp-demo/tests/load-path.e2e.ts +++ b/packages/examples/acp-demo/tests/load-path.e2e.ts @@ -29,8 +29,9 @@ const tsxLoader = fileURLToPath(import.meta.resolve('tsx')) // Repo root is four levels up from packages/examples/acp-demo/tests. const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url)) -// A minimal leaf that loads this app + the two backends — the same shape as -// examples/acp-agent/cordis.yml, inlined so the package test owns its fixture. +// A minimal leaf that loads this app + the two backends and the shipped +// session-query consumer/policies — the same shape as examples/acp-agent/cordis.yml, +// inlined so the package test owns its fixture. const CORDIS_YML = ` - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' @@ -45,6 +46,16 @@ const CORDIS_YML = ` model: deepseek-v4-flash persona: 'You are a test agent.' workspaceContext: false +- id: tool-session-query + name: '@deepseek-ai/dsh-tool-session-query' +- id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' +- id: spill-local + name: '@deepseek-ai/dsh-spill-local' +- id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: 50000 ` interface Spawned { diff --git a/packages/examples/tui-demo/README.md b/packages/examples/tui-demo/README.md index a20a0fae9d..5bcbed615c 100644 --- a/packages/examples/tui-demo/README.md +++ b/packages/examples/tui-demo/README.md @@ -13,7 +13,7 @@ Use [`@deepseek-ai/dsh-cli-demo`](../cli-demo/README.md) for pipes, scripts, and | `@deepseek-ai/dsh-command-goal` | Direct `/goal` status and mutation over the spine's persisted-goal stack | | `@deepseek-ai/dsh-session-persistence-jsonl` | Durable session log under `persistenceRoot` | | `@deepseek-ai/dsh-session-checkpoint-policy` | Semantic durability barriers before model requests and top-level tool effects, plus completed-step checkpoints | -| `@deepseek-ai/dsh-session-query-sqlite` + `@deepseek-ai/dsh-session-reference` | Combined exact/FTS session queries and bounded `@session` snapshots consumed by the TUI | +| `@deepseek-ai/dsh-session-query-sqlite` + `@deepseek-ai/dsh-session-reference` | Combined exact/FTS session queries and bounded `@session` snapshots consumed by the TUI; the default leaf adds the model-facing query tools | | `@deepseek-ai/dsh-user-interaction` | Provider-neutral human question service | | `@deepseek-ai/dsh-tui` | Full-screen transcript, editor, tool cards, plan, and question overlays | | `@deepseek-ai/dsh-tool-ask-user` | Model-facing `ask_user_question` tool | diff --git a/packages/host/runtime/package.json b/packages/host/runtime/package.json index 94a544fb74..f6d43afae0 100644 --- a/packages/host/runtime/package.json +++ b/packages/host/runtime/package.json @@ -41,6 +41,7 @@ "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-session-title-first-message-llm": "workspace:^", "@deepseek-ai/dsh-skill": "workspace:^", @@ -58,6 +59,7 @@ "@deepseek-ai/dsh-tool-fs": "workspace:^", "@deepseek-ai/dsh-tool-fs-search": "workspace:^", "@deepseek-ai/dsh-tool-skill": "workspace:^", + "@deepseek-ai/dsh-tool-session-query": "workspace:^", "@deepseek-ai/dsh-tool-subagent": "workspace:^", "@deepseek-ai/dsh-tool-tasks": "workspace:^", "@deepseek-ai/dsh-tool-todo": "workspace:^", diff --git a/packages/host/runtime/src/boot.ts b/packages/host/runtime/src/boot.ts index c0960ab678..353f74d0b6 100644 --- a/packages/host/runtime/src/boot.ts +++ b/packages/host/runtime/src/boot.ts @@ -5,6 +5,7 @@ */ import { Context } from 'cordis' +import { join } from 'node:path' import Timer from '@cordisjs/plugin-timer' import LlmService from '@deepseek-ai/dsh-llm' import SessionStore from '@deepseek-ai/dsh-session' @@ -18,6 +19,8 @@ import TaskService from '@deepseek-ai/dsh-tasks' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' +import SessionQuerySqlite from '@deepseek-ai/dsh-session-query-sqlite' +import * as toolSessionQuery from '@deepseek-ai/dsh-tool-session-query' import LocalBashExecutor from '@deepseek-ai/dsh-bash-local' import * as toolBash from '@deepseek-ai/dsh-tool-bash' import * as toolTodo from '@deepseek-ai/dsh-tool-todo' @@ -61,7 +64,7 @@ const DEFAULT_SESSION_TITLE_LLM_CONFIG: SessionTitleLlmConfig = { /** Options for bootHost — the assembly-layer composition knobs. */ export interface BootHostOptions { - /** Root directory for JSONL session persistence. */ + /** Root for JSONL persistence and parent directory of the derived session-query SQLite index. */ persistenceRoot: string /** Workspace-instruction byte budget/config, or false to disable AGENTS.md/CLAUDE.md loading. */ workspaceContext: workspaceContext.Config | false @@ -131,6 +134,8 @@ export async function bootHost(options: BootHostOptions): Promise { await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LlmDeepSeek, {}) await ctx.plugin(SessionPersistenceJsonl, { root: options.persistenceRoot }) + await ctx.plugin(SessionQuerySqlite, { path: join(options.persistenceRoot, 'session-query.db') }) + await ctx.plugin(toolSessionQuery, {}) await ctx.plugin(LocalBashExecutor, {}) // Tool suite mirroring the demo:repl composition (repl-agent/cordis.yml + // the agent-spine bundle) so web sessions get the same coding-agent tool diff --git a/packages/host/runtime/tests/host-runtime.spec.ts b/packages/host/runtime/tests/host-runtime.spec.ts index c30e07b50b..1b58a6511b 100644 --- a/packages/host/runtime/tests/host-runtime.spec.ts +++ b/packages/host/runtime/tests/host-runtime.spec.ts @@ -141,6 +141,24 @@ describe('bootHost / startHost', () => { await handle.dispose() }) + it('assembles workspace-authorized session query tools over the derived SQLite index', async () => { + const persistenceRoot = mkdtempSync(join(tmpdir(), 'dsh-boot-session-query-')) + const handle = await bootHost({ + persistenceRoot, + workspaceContext: false, + }) + expect(handle.ctx.get('sessionQuery')).toBeDefined() + expect(handle.ctx.tools.schemas().map(schema => schema.name)).toEqual(expect.arrayContaining([ + 'session_search', + 'session_event_search', + 'session_trace', + 'session_event_trace', + 'session_event_read', + ])) + expect(handle.ctx.tools.get('session_search')?.timeoutMs).toBe(30_000) + await handle.dispose() + }) + it('startHost assembles api + handler over the same defaults and dedupes dispose', async () => { const running = await boot() expect(running.defaults).toMatchObject({ provider: 'scripted', model: 'test-model' }) diff --git a/packages/host/runtime/tsconfig.json b/packages/host/runtime/tsconfig.json index aee28b5371..b0cef9eb16 100644 --- a/packages/host/runtime/tsconfig.json +++ b/packages/host/runtime/tsconfig.json @@ -47,6 +47,12 @@ { "path": "../../session-persistence/session-persistence-jsonl" }, + { + "path": "../../session-query/session-query-sqlite" + }, + { + "path": "../../session-query/tool-session-query" + }, { "path": "../../bash/bash-local" }, diff --git a/packages/session-query/README.md b/packages/session-query/README.md index f79d35936c..503a9cfed8 100644 --- a/packages/session-query/README.md +++ b/packages/session-query/README.md @@ -6,5 +6,6 @@ Trusted exact reads, relationship traces, provider-independent semantic filterin |---|---|---| | [`session-query/`](session-query/README.md) | Combined service contract with concrete logical-corpus reads, traces, and semantic filters plus abstract full-text methods | `ctx.sessionQuery` | | [`session-query-sqlite/`](session-query-sqlite/README.md) | Concrete service backend with SQLite FTS5 persistent bases and live overlays | `ctx.sessionQuery` | +| [`tool-session-query/`](tool-session-query/README.md) | Workspace-authorized model-facing search, lineage, relationship, and exact event tools | — | -The family is independent of compaction: it reads canonical lineage, surface operations, logged provenance, and semantic event text but does not participate in compaction policy or execution. One abstract service combines every query operation, and one concrete backend owns the full-text lifecycle without a provider registry or coordinator. +The query service is independent of compaction: it reads canonical lineage, surface operations, logged provenance, and semantic event text but does not participate in compaction policy or execution. One abstract service combines every query operation, one concrete backend owns the full-text lifecycle without a provider registry or coordinator, and the consumer leaves oversized plain-text results to the generic post-execute spill policy. diff --git a/packages/session-query/tool-session-query/README.md b/packages/session-query/tool-session-query/README.md new file mode 100644 index 0000000000..2a5ad72f9c --- /dev/null +++ b/packages/session-query/tool-session-query/README.md @@ -0,0 +1,72 @@ +# @deepseek-ai/dsh-tool-session-query + +Workspace-authorized model tools over `ctx.sessionQuery`. The package depends only on the unified interface and registers `session_search`, `session_event_search`, `session_trace`, `session_event_trace`, and `session_event_read`. + +## Configuration + +| Key | Default | Meaning | +|---|---:|---| +| `maxSearchResults` | `100` | Maximum authorized non-self hits collected across internal provider pages | +| `searchTimeoutMs` | `30000` | Cooperative deadline attached to both full-text search tools | + +The caller comes exclusively from `ToolExecution.exec.agent`. Cross-session access requires exact equality between the target and caller session `cwd` values; a caller without `cwd` can inspect only itself. Search never exposes provider cursors, offsets, page sizes, or a model-controlled limit. Timestamps at the tool boundary require an explicit `Z` or numeric offset and become inclusive epoch-millisecond filters. + +`session_search` always omits the caller session. A current-session `session_event_search` stops immediately before the step that invoked it, so the active assistant output and logged tool call cannot match themselves. Direct targets are authorized before trace, event, or title reads. Lineage output replaces unauthorized ancestor and descendant boundaries with markers that contain no hidden session id. + +The package deliberately performs no byte or character truncation and does not import a spill backend. Deployments that need bounded inline output mount `@deepseek-ai/dsh-spill-policy`, which can replace the rendered text after execution while retaining the complete result. + +## Model Experience + +### System prompt + +#### What the model sees + +The model receives one fixed prior-history guidance section. + +##### Prior-history guidance + +```markdown +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. +``` + +#### Token effect + +One fixed concise section is present on each request while the plugin is mounted. + +#### KV Cache effect + +Prefix-stable while the plugin and guidance text are unchanged. + +### Tool schemas + +#### What the model sees + +The model sees the generated [`session_search`, `session_event_search`, `session_trace`, `session_event_trace`, and `session_event_read` schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-query). Search filters add fixed schema tokens, while cursors, workspace paths, output pagination, and model-controlled result limits remain absent. + +#### Token effect + +Five fixed read-only schemas are sent on each request while visible. + +#### KV Cache effect + +Prefix-stable while tool visibility and definitions are unchanged. + +### Tool results + +#### What the model sees + +Each successful call emits one plain-text block. Search results include titles and best-match excerpts; traces include all authorized relationships; event reads include unabridged target JSON. The generic spill policy may replace oversized inline text with its preview, opaque locator, and retrieval hint. + +#### Token effect + +Results are data-dependent and remain in logged tool history until compaction; `maxSearchResults` bounds search-hit count. + +#### KV Cache effect + +Append-only result text follows the reusable request prefix and does not invalidate earlier cache entries. + +## Known Limitations and Deferred Work + +- Search returns at most the deployment cap and asks the model to narrow its query when more matches exist; it offers no continuation token. +- Workspace identity is conservative exact-string `cwd` equality, so symlink-equivalent paths do not share authority. +- Custom compositions without the generic spill policy accept complete trace and event payloads inline. diff --git a/packages/session-query/tool-session-query/package.json b/packages/session-query/tool-session-query/package.json new file mode 100644 index 0000000000..9438ddb1de --- /dev/null +++ b/packages/session-query/tool-session-query/package.json @@ -0,0 +1,57 @@ +{ + "name": "@deepseek-ai/dsh-tool-session-query", + "description": "Workspace-authorized model-facing session history search, trace, and event read tools", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-invariants": "^0.0.1", + "@deepseek-ai/dsh-llm": "^0.0.1", + "@deepseek-ai/dsh-session": "^0.0.1", + "@deepseek-ai/dsh-session-query": "^0.0.1", + "@deepseek-ai/dsh-system-prompt": "^0.0.1", + "@deepseek-ai/dsh-timeout": "^0.0.1", + "@deepseek-ai/dsh-tools": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "dependencies": { + "schemastery": "^3.18.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-agent": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-persistence": "workspace:^", + "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", + "@deepseek-ai/dsh-session-query": "workspace:^", + "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", + "@deepseek-ai/dsh-session-title": "workspace:^", + "@deepseek-ai/dsh-system-prompt": "workspace:^", + "@deepseek-ai/dsh-timeout": "workspace:^", + "@deepseek-ai/dsh-tools": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts new file mode 100644 index 0000000000..c8c7350604 --- /dev/null +++ b/packages/session-query/tool-session-query/src/index.ts @@ -0,0 +1,961 @@ +/** + * Model-facing, workspace-authorized session-history search and read tools. + * + * @module @deepseek-ai/dsh-tool-session-query + */ + +import type { Context } from 'cordis' +import z from 'schemastery' +import { HarnessError } from '@deepseek-ai/dsh-llm' +import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import { + SessionId, + type SessionEvent, + type SessionEventType, + type SessionHeader, + type SessionId as SessionIdValue, +} from '@deepseek-ai/dsh-session' +import { + SessionQueryError, + extractSessionEventText, + type SessionAvailability, + type SessionEventMetadataFilter, + type SessionEventSearchHit, + type SessionEventSurface, + type SessionEventTrace, + type SessionEventWindow, + type SessionLineageNode, + type SessionLineageTrace, + type SessionRecord, + type SessionResultFilter, + type SessionSearchCursor, + type SessionSearchHit, +} from '@deepseek-ai/dsh-session-query' +import { defineTool, type GenericCallView, type ToolRunContext } from '@deepseek-ai/dsh-tools' +import type {} from '@deepseek-ai/dsh-system-prompt' + +/** Cordis plugin name used by Loader diagnostics. */ +export const name = 'tool-session-query' + +/** Capability services required by the model-facing consumer. */ +export const inject = ['tools', 'systemPrompt', 'sessionQuery'] + +/** Default maximum number of authorized search hits returned by one call. */ +export const DEFAULT_MAX_SEARCH_RESULTS = 100 + +/** Default cooperative deadline for either full-text search tool. */ +export const DEFAULT_SEARCH_TIMEOUT_MS = 30_000 + +/** Deployment-owned search count and timeout bounds. */ +export interface Config { + /** Maximum authorized hits returned by one search call. Defaults to 100. */ + maxSearchResults?: number + /** Cooperative full-text search deadline in milliseconds. Defaults to 30000. */ + searchTimeoutMs?: number +} + +/** Schemastery config for Loader defaults and generated configuration docs. */ +export const Config: z = z.object({ + maxSearchResults: z.number().step(1).min(1).default(DEFAULT_MAX_SEARCH_RESULTS), + searchTimeoutMs: z.number().step(1).min(1).max(MAX_TIMER_DELAY_MS).default(DEFAULT_SEARCH_TIMEOUT_MS), +}) + +interface ResolvedConfig { + readonly maxSearchResults: number + readonly searchTimeoutMs: number +} + +interface SessionSearchArgs { + query: string + session_ids?: string[] + created_at_from?: string + created_at_to?: string + parent_session_ids?: string[] + include_root_sessions?: boolean + availability?: SessionAvailability[] + event_seq_from?: number + event_seq_to?: number + event_time_from?: string + event_time_to?: string + event_types?: string[] + event_surfaces?: SessionEventSurface[] +} + +interface EventSearchArgs { + session_id?: string + query: string + seq_from?: number + seq_to?: number + time_from?: string + time_to?: string + event_types?: string[] + surfaces?: SessionEventSurface[] +} + +interface SessionTargetArgs { + session_id?: string +} + +interface EventTargetArgs extends SessionTargetArgs { + seq: number +} + +interface EventReadArgs extends EventTargetArgs { + before?: number + after?: number +} + +interface Caller { + readonly id: SessionIdValue + readonly header: SessionHeader + readonly events: readonly SessionEvent[] +} + +interface TitleView { + readonly text: string + readonly unavailableCode?: string +} + +interface CompleteTitleMap extends ReadonlyMap { + get(id: SessionIdValue): TitleView +} + +interface SearchCollection { + readonly items: T[] + readonly capped: boolean +} + +interface AuthorizedDescendant { + readonly record: SessionRecord + readonly descendants: Array +} + +const SESSION_SEARCH_PARAMETERS = { + query: { type: 'string', required: true, description: 'Literal full-text query over prior session history.' }, + session_ids: { type: 'array', items: { type: 'string' }, description: 'Optional session ids to include.' }, + created_at_from: { type: 'string', description: 'Inclusive timezone-qualified ISO 8601 creation-time lower bound.' }, + created_at_to: { type: 'string', description: 'Inclusive timezone-qualified ISO 8601 creation-time upper bound.' }, + parent_session_ids: { type: 'array', items: { type: 'string' }, description: 'Optional direct parent session ids.' }, + include_root_sessions: { type: 'boolean', description: 'Include sessions with no parent in the parent filter.' }, + availability: { + type: 'array', + items: { type: 'string', enum: ['live', 'persisted'] }, + description: 'Require at least one selected source availability.', + }, + event_seq_from: { type: 'integer', description: 'Inclusive event sequence lower bound.' }, + event_seq_to: { type: 'integer', description: 'Inclusive event sequence upper bound.' }, + event_time_from: { type: 'string', description: 'Inclusive timezone-qualified ISO 8601 event-time lower bound.' }, + event_time_to: { type: 'string', description: 'Inclusive timezone-qualified ISO 8601 event-time upper bound.' }, + event_types: { type: 'array', items: { type: 'string' }, description: 'Event types to include.' }, + event_surfaces: { + type: 'array', + items: { type: 'string', enum: ['current', 'shadowed', 'log-only'] }, + description: 'Event surfaces to include.', + }, +} as const + +const EVENT_SEARCH_PARAMETERS = { + session_id: { type: 'string', description: 'Target session id. Omit for the current session.' }, + query: { type: 'string', required: true, description: 'Literal full-text query over the target session.' }, + seq_from: { type: 'integer', description: 'Inclusive event sequence lower bound.' }, + seq_to: { type: 'integer', description: 'Inclusive event sequence upper bound.' }, + time_from: { type: 'string', description: 'Inclusive timezone-qualified ISO 8601 event-time lower bound.' }, + time_to: { type: 'string', description: 'Inclusive timezone-qualified ISO 8601 event-time upper bound.' }, + event_types: { type: 'array', items: { type: 'string' }, description: 'Event types to include.' }, + surfaces: { + type: 'array', + items: { type: 'string', enum: ['current', 'shadowed', 'log-only'] }, + description: 'Event surfaces to include.', + }, +} as const + +const TARGET_SESSION_PARAMETER = { + session_id: { type: 'string', description: 'Target session id. Omit for the current session.' }, +} as const + +const TEXT_OUTPUT = { + schema: { type: 'string' as const }, + render: (_args: unknown, value: string) => [{ type: 'text' as const, text: value }], +} + +const PROMPT_TEXT = + 'Use session_search to find relevant work from prior sessions, or session_event_search to search earlier ' + + 'events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with ' + + 'session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data.' + +/** Register all five tools and their shared model guidance. */ +export function apply(ctx: Context, config: Config): void { + const resolved = resolveConfig(config) + ctx.systemPrompt.section({ + name: 'tool:session-query', + order: 113, + text: PROMPT_TEXT, + }) + + ctx.tools.register(defineTool({ + name: 'session_search', + description: 'Search prior sessions in the caller workspace and return the strongest matching event from each session.', + parameters: SESSION_SEARCH_PARAMETERS, + output: TEXT_OUTPUT, + timeoutMs: resolved.searchTimeoutMs, + isConcurrencySafe: () => true, + execute: (args, exec) => executeSessionSearch(ctx, args, exec, resolved.maxSearchResults), + presentCall: presentSessionSearchCall, + })) + + ctx.tools.register(defineTool({ + name: 'session_event_search', + description: 'Search prior events in one authorized session; the current session excludes the step performing this call.', + parameters: EVENT_SEARCH_PARAMETERS, + output: TEXT_OUTPUT, + timeoutMs: resolved.searchTimeoutMs, + isConcurrencySafe: () => true, + execute: (args, exec) => executeEventSearch(ctx, args, exec, resolved.maxSearchResults), + presentCall: presentEventSearchCall, + })) + + ctx.tools.register(defineTool({ + name: 'session_trace', + description: 'Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.', + parameters: TARGET_SESSION_PARAMETER, + output: TEXT_OUTPUT, + isConcurrencySafe: () => true, + execute: (args, exec) => executeSessionTrace(ctx, args, exec), + presentCall: presentSessionTraceCall, + })) + + ctx.tools.register(defineTool({ + name: 'session_event_trace', + description: 'Read every direct replacement and provenance relationship for one event in an authorized session.', + parameters: { + ...TARGET_SESSION_PARAMETER, + seq: { type: 'integer', required: true, description: 'Target event sequence number.' }, + }, + output: TEXT_OUTPUT, + isConcurrencySafe: () => true, + execute: (args, exec) => executeEventTrace(ctx, args, exec), + presentCall: args => presentEventTargetCall('Trace event', args), + })) + + ctx.tools.register(defineTool({ + name: 'session_event_read', + description: 'Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.', + parameters: { + ...TARGET_SESSION_PARAMETER, + seq: { type: 'integer', required: true, description: 'Target event sequence number.' }, + before: { type: 'integer', description: 'Number of preceding raw events to summarize. Omit for none.' }, + after: { type: 'integer', description: 'Number of following raw events to summarize. Omit for none.' }, + }, + output: TEXT_OUTPUT, + isConcurrencySafe: () => true, + execute: (args, exec) => executeEventRead(ctx, args, exec), + presentCall: args => presentEventTargetCall('Read event', args), + })) +} + +function resolveConfig(config: Config): ResolvedConfig { + const maxSearchResults = config.maxSearchResults ?? DEFAULT_MAX_SEARCH_RESULTS + const searchTimeoutMs = config.searchTimeoutMs ?? DEFAULT_SEARCH_TIMEOUT_MS + if (!Number.isSafeInteger(maxSearchResults) || maxSearchResults < 1) { + throw new TypeError('tool-session-query: maxSearchResults must be a positive safe integer') + } + if (!Number.isInteger(searchTimeoutMs) || searchTimeoutMs < 1 || searchTimeoutMs > MAX_TIMER_DELAY_MS) { + throw new TypeError( + `tool-session-query: searchTimeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`, + ) + } + return { maxSearchResults, searchTimeoutMs } +} + +function callerOf(exec: ToolRunContext): Caller { + const agent = exec.agent + if (agent === undefined) { + throw new HarnessError( + 'session query tools require an agent-bound caller', + 'SESSION_QUERY_TOOL_MISSING_AGENT', + ) + } + return { + id: agent.session.id, + header: agent.session.header, + events: agent.session.events, + } +} + +function targetId(args: SessionTargetArgs, caller: Caller): SessionIdValue { + return args.session_id === undefined ? caller.id : SessionId(args.session_id) +} + +async function authorizeTarget( + ctx: Context, + caller: Caller, + target: SessionIdValue, + signal: AbortSignal, +): Promise { + if (target === caller.id) return + const cwd = caller.header.cwd + if (cwd === undefined) throw unauthorizedTarget() + signal.throwIfAborted() + const records = await ctx.sessionQuery.filterSessions([ + { kind: 'id', values: [target] }, + { kind: 'cwd', values: [cwd] }, + ]) + signal.throwIfAborted() + if (records.length !== 1) throw unauthorizedTarget() +} + +function unauthorizedTarget(): HarnessError { + return new HarnessError( + 'session target is outside the caller workspace', + 'SESSION_QUERY_TOOL_UNAUTHORIZED', + ) +} + +async function executeSessionSearch( + ctx: Context, + args: SessionSearchArgs, + exec: ToolRunContext, + maxResults: number, +): Promise { + const caller = callerOf(exec) + const cwd = caller.header.cwd + if (cwd === undefined) { + throw new HarnessError( + 'cross-session search is unavailable because the caller session has no workspace', + 'SESSION_QUERY_TOOL_UNAUTHORIZED', + ) + } + const query = normalizeQuery(args.query) + const sessionFilters = buildSessionFilters(args) + sessionFilters.push({ kind: 'cwd', values: [cwd] }) + const eventFilters = buildEventFilters({ + seqFrom: args.event_seq_from, + seqTo: args.event_seq_to, + timeFrom: args.event_time_from, + timeTo: args.event_time_to, + eventTypes: args.event_types, + surfaces: args.event_surfaces, + }) + const collected = await collectPages( + maxResults, + exec.signal, + cursor => ctx.sessionQuery.searchSessions({ + query, + sessionFilters, + eventFilters, + ...cursor === undefined ? {} : { cursor }, + }, { signal: exec.signal }), + hit => hit.header.id !== caller.id && recordAuthorized(hit, caller), + ) + + const parentIds = collected.items + .map(hit => hit.header.parentSession) + .filter((id): id is SessionIdValue => id !== undefined) + const authorizedParents = await authorizeSessionIds(ctx, caller, parentIds, exec.signal) + const titles = await readTitles(ctx, collected.items.map(hit => hit.header.id), exec.signal) + return formatSessionSearch(collected, titles, authorizedParents) +} + +async function executeEventSearch( + ctx: Context, + args: EventSearchArgs, + exec: ToolRunContext, + maxResults: number, +): Promise { + const caller = callerOf(exec) + const sessionId = targetId(args, caller) + await authorizeTarget(ctx, caller, sessionId, exec.signal) + const query = normalizeQuery(args.query) + const range = sequenceRange(args.seq_from, args.seq_to) + if (sessionId === caller.id) { + const stepStart = caller.events.findLast(event => event.type === 'step/start') + if (stepStart === undefined) { + throw new HarnessError( + 'current-session search requires an active step boundary', + 'SESSION_QUERY_TOOL_NO_CURRENT_STEP', + ) + } + range.to = Math.min(range.to ?? Number.MAX_SAFE_INTEGER, stepStart.seq - 1) + } + const title = await readTitle(ctx, sessionId, exec.signal) + if (range.from !== undefined && range.to !== undefined && range.from > range.to) { + return formatEventSearch(sessionId, title, { items: [], capped: false }) + } + const filters = buildEventFilters({ + seqFrom: range.from, + seqTo: range.to, + timeFrom: args.time_from, + timeTo: args.time_to, + eventTypes: args.event_types, + surfaces: args.surfaces, + }) + const collected = await collectPages( + maxResults, + exec.signal, + cursor => ctx.sessionQuery.searchEvents({ + sessionId, + query, + filters, + ...cursor === undefined ? {} : { cursor }, + }, { signal: exec.signal }), + () => true, + ) + return formatEventSearch(sessionId, title, collected) +} + +async function executeSessionTrace( + ctx: Context, + args: SessionTargetArgs, + exec: ToolRunContext, +): Promise { + const caller = callerOf(exec) + const sessionId = targetId(args, caller) + await authorizeTarget(ctx, caller, sessionId, exec.signal) + const trace = await ctx.sessionQuery.traceSession(sessionId) + exec.signal.throwIfAborted() + + const ancestors: SessionRecord[] = [] + let ancestorBoundary = false + for (const ancestor of trace.ancestors) { + if (!recordAuthorized(ancestor, caller)) { + ancestorBoundary = true + break + } + ancestors.push(ancestor) + } + if (ancestors.length === trace.ancestors.length && !trace.complete) ancestorBoundary = true + const descendants = authorizeDescendants(trace.descendants, caller) + const visibleIds = [ + trace.target.header.id, + ...ancestors.map(record => record.header.id), + ...descendantIds(descendants), + ] + const titles = await readTitles(ctx, visibleIds, exec.signal) + return formatSessionTrace(trace, ancestors, ancestorBoundary, descendants, titles) +} + +async function executeEventTrace( + ctx: Context, + args: EventTargetArgs, + exec: ToolRunContext, +): Promise { + assertNonNegativeSafeInteger('seq', args.seq) + const caller = callerOf(exec) + const sessionId = targetId(args, caller) + await authorizeTarget(ctx, caller, sessionId, exec.signal) + const trace = await ctx.sessionQuery.traceEvent({ sessionId, seq: args.seq }) + exec.signal.throwIfAborted() + const title = await readTitle(ctx, sessionId, exec.signal) + return formatEventTrace(sessionId, title, trace) +} + +async function executeEventRead( + ctx: Context, + args: EventReadArgs, + exec: ToolRunContext, +): Promise { + assertNonNegativeSafeInteger('seq', args.seq) + if (args.before !== undefined) assertNonNegativeSafeInteger('before', args.before) + if (args.after !== undefined) assertNonNegativeSafeInteger('after', args.after) + const caller = callerOf(exec) + const sessionId = targetId(args, caller) + await authorizeTarget(ctx, caller, sessionId, exec.signal) + const window = await ctx.sessionQuery.readEvent({ + sessionId, + seq: args.seq, + ...args.before === undefined ? {} : { before: args.before }, + ...args.after === undefined ? {} : { after: args.after }, + }) + exec.signal.throwIfAborted() + const title = await readTitle(ctx, sessionId, exec.signal) + return formatEventRead(sessionId, title, window) +} + +function buildSessionFilters(args: SessionSearchArgs): SessionResultFilter[] { + const filters: SessionResultFilter[] = [] + if (args.session_ids !== undefined) { + assertNonEmptyArray('session_ids', args.session_ids) + filters.push({ kind: 'id', values: args.session_ids.map(SessionId) }) + } + const created = timestampRange('created_at', args.created_at_from, args.created_at_to) + if (created !== undefined) filters.push({ kind: 'created-at', ...created }) + if (args.parent_session_ids !== undefined || args.include_root_sessions === true) { + const values: Array = [] + if (args.parent_session_ids !== undefined) { + assertNonEmptyArray('parent_session_ids', args.parent_session_ids) + values.push(...args.parent_session_ids.map(SessionId)) + } + if (args.include_root_sessions === true) values.push(null) + filters.push({ kind: 'parent', values }) + } + if (args.availability !== undefined) { + assertNonEmptyArray('availability', args.availability) + filters.push({ kind: 'availability', values: args.availability }) + } + return filters +} + +interface EventFilterInput { + readonly seqFrom?: number | undefined + readonly seqTo?: number | undefined + readonly timeFrom?: string | undefined + readonly timeTo?: string | undefined + readonly eventTypes?: string[] | undefined + readonly surfaces?: SessionEventSurface[] | undefined +} + +function buildEventFilters(input: EventFilterInput): SessionEventMetadataFilter[] { + const filters: SessionEventMetadataFilter[] = [] + const seq = sequenceRange(input.seqFrom, input.seqTo) + if (seq.from !== undefined || seq.to !== undefined) filters.push({ kind: 'seq', ...seq }) + const time = timestampRange('time', input.timeFrom, input.timeTo) + if (time !== undefined) filters.push({ kind: 'time', ...time }) + if (input.eventTypes !== undefined) { + assertNonEmptyArray('event_types', input.eventTypes) + filters.push({ kind: 'type', values: input.eventTypes as SessionEventType[] }) + } + if (input.surfaces !== undefined) { + assertNonEmptyArray('surfaces', input.surfaces) + filters.push({ kind: 'surface', values: input.surfaces }) + } + return filters +} + +function normalizeQuery(value: string): string { + const query = value.trim().replace(/\s+/gu, ' ') + if (query.length === 0) { + throw new SessionQueryError( + 'session-search query must contain non-whitespace text', + 'SESSION_QUERY_INVALID_QUERY', + ) + } + if (query.includes('\0')) { + throw new SessionQueryError( + 'session-search query must not contain NUL', + 'SESSION_QUERY_INVALID_QUERY', + ) + } + return query +} + +function sequenceRange( + from: number | undefined, + to: number | undefined, +): { from?: number; to?: number } { + if (from !== undefined) assertNonNegativeSafeInteger('sequence lower bound', from) + if (to !== undefined) assertNonNegativeSafeInteger('sequence upper bound', to) + if (from !== undefined && to !== undefined && from > to) { + throw invalidRange('sequence', 'from must be less than or equal to to') + } + return { + ...from === undefined ? {} : { from }, + ...to === undefined ? {} : { to }, + } +} + +function timestampRange( + name: string, + from: string | undefined, + to: string | undefined, +): { from?: number; to?: number } | undefined { + if (from === undefined && to === undefined) return undefined + const fromMs = from === undefined ? undefined : parseIsoTimestamp(`${name}_from`, from) + const toMs = to === undefined ? undefined : parseIsoTimestamp(`${name}_to`, to) + if (fromMs !== undefined && toMs !== undefined && fromMs > toMs) { + throw invalidRange(name, 'from must be less than or equal to to') + } + return { + ...fromMs === undefined ? {} : { from: fromMs }, + ...toMs === undefined ? {} : { to: toMs }, + } +} + +const ISO_TIMESTAMP = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|([+-])(\d{2}):(\d{2}))$/ + +function parseIsoTimestamp(name: string, value: string): number { + const match = ISO_TIMESTAMP.exec(value) + if (match === null) { + throw invalidRange(name, 'must be an ISO 8601 timestamp with Z or a numeric offset') + } + const year = Number(match[1]) + const month = Number(match[2]) + const day = Number(match[3]) + const hour = Number(match[4]) + const minute = Number(match[5]) + const second = Number(match[6] ?? 0) + const offsetHour = Number(match[10] ?? 0) + const offsetMinute = Number(match[11] ?? 0) + if ( + month < 1 || month > 12 + || day < 1 || day > daysInMonth(year, month) + || hour > 23 || minute > 59 || second > 59 + || offsetHour > 23 || offsetMinute > 59 + ) { + throw invalidRange(name, 'must be a valid ISO 8601 timestamp') + } + const timestamp = Date.parse(value) + return timestamp +} + +function daysInMonth(year: number, month: number): number { + if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28 + return [4, 6, 9, 11].includes(month) ? 30 : 31 +} + +function invalidRange(name: string, detail: string): SessionQueryError { + return new SessionQueryError( + `session ${name} range ${detail}`, + 'SESSION_QUERY_INVALID_FILTER', + ) +} + +function assertNonNegativeSafeInteger(name: string, value: number): void { + if (!Number.isSafeInteger(value) || value < 0) { + throw new SessionQueryError( + `${name} must be a non-negative safe integer`, + 'SESSION_QUERY_INVALID_FILTER', + ) + } +} + +function assertNonEmptyArray(name: string, values: readonly unknown[]): void { + if (values.length === 0) { + throw new SessionQueryError( + `${name} must contain at least one value when supplied`, + 'SESSION_QUERY_INVALID_FILTER', + ) + } +} + +async function collectPages( + maxResults: number, + signal: AbortSignal, + request: (cursor?: SessionSearchCursor) => Promise<{ + readonly items: readonly T[] + readonly nextCursor?: SessionSearchCursor + }>, + accept: (item: T) => boolean, +): Promise> { + const items: T[] = [] + const seen = new Set() + let cursor: SessionSearchCursor | undefined + while (true) { + signal.throwIfAborted() + let page: Awaited> + try { + page = await request(cursor) + } catch (error: unknown) { + if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_STALE_CURSOR') { + throw new SessionQueryError( + 'session history changed while paging; retry the complete search call', + 'SESSION_QUERY_STALE_CURSOR', + { cause: error }, + ) + } + throw error + } + signal.throwIfAborted() + for (const item of page.items) { + if (!accept(item)) continue + items.push(item) + if (items.length === maxResults) { + return { + items, + capped: page.nextCursor !== undefined || item !== page.items.at(-1), + } + } + } + if (page.nextCursor === undefined) return { items, capped: false } + if (seen.has(page.nextCursor)) { + throw new SessionQueryError( + 'session-search provider repeated a continuation cursor', + 'SESSION_QUERY_INVALID_CURSOR', + ) + } + seen.add(page.nextCursor) + cursor = page.nextCursor + } +} + +function recordAuthorized(record: SessionRecord, caller: Caller): boolean { + if (record.header.id === caller.id) return true + return caller.header.cwd !== undefined && record.header.cwd === caller.header.cwd +} + +async function authorizeSessionIds( + ctx: Context, + caller: Caller, + ids: readonly SessionIdValue[], + signal: AbortSignal, +): Promise> { + const unique = [...new Set(ids)] + const authorized = new Set() + if (unique.includes(caller.id)) authorized.add(caller.id) + const cwd = caller.header.cwd + const other = unique.filter(id => id !== caller.id) + if (cwd === undefined || other.length === 0) return authorized + signal.throwIfAborted() + const records = await ctx.sessionQuery.filterSessions([ + { kind: 'id', values: other }, + { kind: 'cwd', values: [cwd] }, + ]) + signal.throwIfAborted() + for (const record of records) authorized.add(record.header.id) + return authorized +} + +async function readTitles( + ctx: Context, + ids: readonly SessionIdValue[], + signal: AbortSignal, +): Promise { + const result = new Map() + for (const id of new Set(ids)) { + result.set(id, await readTitle(ctx, id, signal)) + } + return result as CompleteTitleMap +} + +async function readTitle( + ctx: Context, + id: SessionIdValue, + signal: AbortSignal, +): Promise { + signal.throwIfAborted() + try { + const title = await ctx.sessionQuery.readTitle(id) + signal.throwIfAborted() + return { text: title?.title ?? 'untitled' } + } catch (error: unknown) { + if (signal.aborted) signal.throwIfAborted() + const code = error instanceof HarnessError ? error.code : 'UNKNOWN' + ctx.logger.warn(`tool-session-query: title read failed for session "${id}": ${fullError(error)}`) + return { text: 'untitled', unavailableCode: code } + } +} + +function fullError(error: unknown): string { + return error instanceof Error ? error.stack ?? String(error) : String(error) +} + +function authorizeDescendants( + nodes: readonly SessionLineageNode[], + caller: Caller, +): Array { + return nodes.map((node) => { + if (!recordAuthorized(node.session, caller)) return null + return { + record: node.session, + descendants: authorizeDescendants(node.descendants, caller), + } + }) +} + +function descendantIds(nodes: readonly (AuthorizedDescendant | null)[]): SessionIdValue[] { + const ids: SessionIdValue[] = [] + for (const node of nodes) { + if (node === null) continue + ids.push(node.record.header.id, ...descendantIds(node.descendants)) + } + return ids +} + +function titleText(view: TitleView): string { + return view.unavailableCode === undefined + ? view.text + : `${view.text} (title unavailable: ${view.unavailableCode})` +} + +function formatSessionSearch( + collected: SearchCollection, + titles: CompleteTitleMap, + authorizedParents: ReadonlySet, +): string { + if (collected.items.length === 0) return 'No prior session matches found.' + const lines = [`Session search results (${collected.items.length}):`] + for (const [index, hit] of collected.items.entries()) { + const parent = hit.header.parentSession === undefined + ? 'root' + : authorizedParents.has(hit.header.parentSession) + ? hit.header.parentSession + : '[outside workspace]' + const availability = [ + hit.live ? 'live' : undefined, + hit.persisted ? 'persisted' : undefined, + ].filter((value): value is string => value !== undefined).join(', ') || 'unavailable' + lines.push( + '', + `${index + 1}. Session ${hit.header.id} — ${titleText(titles.get(hit.header.id))}`, + ` Created: ${formatTime(hit.header.createdAt)}`, + ` Parent: ${parent}`, + ` Availability: ${availability}`, + ` Best match: seq ${hit.bestMatch.seq} | ${hit.bestMatch.type} | ${hit.bestMatch.surface} | ${formatTime(hit.bestMatch.time)}`, + ` Snippet: ${hit.bestMatch.snippet}`, + ) + } + if (collected.capped) { + lines.push('', 'Result cap reached. Narrow the query or add filters to find additional matches.') + } + return lines.join('\n') +} + +function formatEventSearch( + sessionId: SessionIdValue, + title: TitleView, + collected: SearchCollection, +): string { + const lines = [`Session ${sessionId} — ${titleText(title)}`] + if (collected.items.length === 0) { + lines.push('', 'No prior event matches found.') + return lines.join('\n') + } + lines.push('', `Event search results (${collected.items.length}):`) + for (const [index, hit] of collected.items.entries()) { + lines.push( + `${index + 1}. seq ${hit.seq} | ${hit.type} | ${hit.surface} | ${formatTime(hit.time)}`, + ` Snippet: ${hit.snippet}`, + ) + } + if (collected.capped) { + lines.push('', 'Result cap reached. Narrow the query or add filters to find additional matches.') + } + return lines.join('\n') +} + +function formatSessionTrace( + trace: SessionLineageTrace, + ancestors: readonly SessionRecord[], + ancestorBoundary: boolean, + descendants: readonly (AuthorizedDescendant | null)[], + titles: CompleteTitleMap, +): string { + const lines = [ + `Session ${trace.target.header.id} — ${titleText(titles.get(trace.target.header.id))}`, + `Created: ${formatTime(trace.target.header.createdAt)}`, + `Availability: ${availabilityText(trace.target)}`, + '', + 'Ancestors (nearest first):', + ] + if (ancestors.length === 0 && !ancestorBoundary) lines.push('- none (target is a root session)') + for (const record of ancestors) { + lines.push(`- ${record.header.id} — ${titleText(titles.get(record.header.id))} | ${formatTime(record.header.createdAt)} | ${availabilityText(record)}`) + } + if (ancestorBoundary) lines.push('- [outside workspace boundary]') + lines.push('', 'Descendants:') + if (descendants.length === 0) lines.push('- none') + else renderDescendants(lines, descendants, titles, 0) + return lines.join('\n') +} + +function renderDescendants( + lines: string[], + nodes: readonly (AuthorizedDescendant | null)[], + titles: CompleteTitleMap, + depth: number, +): void { + for (const node of nodes) { + const indent = ' '.repeat(depth) + if (node === null) { + lines.push(`${indent}- [outside workspace subtree]`) + continue + } + const id = node.record.header.id + lines.push(`${indent}- ${id} — ${titleText(titles.get(id))} | ${formatTime(node.record.header.createdAt)} | ${availabilityText(node.record)}`) + renderDescendants(lines, node.descendants, titles, depth + 1) + } +} + +function formatEventTrace( + sessionId: SessionIdValue, + title: TitleView, + trace: SessionEventTrace, +): string { + return [ + `Session ${sessionId} — ${titleText(title)}`, + `Target: seq ${trace.target.seq} | ${trace.target.type} | ${trace.target.surface} | ${formatTime(trace.target.time)}`, + `Replaced by: ${trace.replacedBy ?? 'none'}`, + `Replacement chain: ${seqList(trace.replacementChain)}`, + `Events replaced by target: ${seqList(trace.replacedEventSeqs)}`, + `Direct provenance sources: ${seqList(trace.sourceEventSeqs)}`, + `Direct derived events: ${seqList(trace.derivedEventSeqs)}`, + ].join('\n') +} + +function formatEventRead( + sessionId: SessionIdValue, + title: TitleView, + window: SessionEventWindow, +): string { + const before = window.events.filter(event => event.seq < window.target.seq) + const after = window.events.filter(event => event.seq > window.target.seq) + const lines = [ + `Session ${sessionId} — ${titleText(title)}`, + `Target event seq ${window.target.seq}:`, + '```json', + JSON.stringify(window.target, null, 2), + '```', + ] + if (before.length > 0) { + lines.push('', 'Before:') + for (const event of before) lines.push(formatNeighbor(event)) + } + if (after.length > 0) { + lines.push('', 'After:') + for (const event of after) lines.push(formatNeighbor(event)) + } + return lines.join('\n') +} + +function formatNeighbor(event: SessionEvent): string { + const text = extractSessionEventText(event) + return `- seq ${event.seq} | ${event.type} | ${formatTime(event.time)}` + + (text.length === 0 ? ' | (no semantic text)' : `\n ${text.replaceAll('\n', '\n ')}`) +} + +function availabilityText(record: SessionRecord): string { + return [ + record.live ? 'live' : undefined, + record.persisted ? 'persisted' : undefined, + ].filter((value): value is string => value !== undefined).join(', ') || 'unavailable' +} + +function seqList(values: readonly number[]): string { + return values.length === 0 ? 'none' : values.join(', ') +} + +function formatTime(value: number): string { + return new Date(value).toISOString() +} + +function presentSessionSearchCall(args: SessionSearchArgs): GenericCallView { + return { card: 'generic', kind: 'search', title: 'Search prior sessions', rawInput: args.query } +} + +function presentEventSearchCall(args: EventSearchArgs): GenericCallView { + return { card: 'generic', kind: 'search', title: 'Search session events', rawInput: args.query } +} + +function presentSessionTraceCall(args: SessionTargetArgs): GenericCallView { + return { + card: 'generic', + kind: 'read', + title: args.session_id === undefined ? 'Trace current session' : `Trace session ${args.session_id}`, + ...args.session_id === undefined ? {} : { rawInput: args.session_id }, + } +} + +function presentEventTargetCall( + action: string, + args: EventTargetArgs, +): GenericCallView { + return { + card: 'generic', + kind: 'read', + title: `${action} ${args.seq}`, + rawInput: { + ...args.session_id === undefined ? {} : { session_id: args.session_id }, + seq: args.seq, + }, + } +} diff --git a/packages/session-query/tool-session-query/src/invariant.ts b/packages/session-query/tool-session-query/src/invariant.ts new file mode 100644 index 0000000000..73f0e35409 --- /dev/null +++ b/packages/session-query/tool-session-query/src/invariant.ts @@ -0,0 +1,30 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-tool-session-query`. + * @module @deepseek-ai/dsh-tool-session-query/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-tool-session-query' + +/** Cordis companion plugin name. */ +export const name = 'tool-session-query-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: this read-only model adapter owns no event or mutable + * data relationship beyond the registries that already validate registration. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts b/packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts new file mode 100644 index 0000000000..fb85bdc309 --- /dev/null +++ b/packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts @@ -0,0 +1,100 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { CallId } from '@deepseek-ai/dsh-llm' +import SessionStore, { + SESSION_FORMAT_VERSION, + SessionId, + type Session, +} from '@deepseek-ai/dsh-session' +import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' +import SessionQuerySqlite from '@deepseek-ai/dsh-session-query-sqlite' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry from '@deepseek-ai/dsh-tools' +import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' + +const temporaryDirectories: string[] = [] +const contexts: Context[] = [] + +afterEach(async () => { + for (const ctx of contexts.splice(0)) await ctx.fiber.dispose() + for (const directory of temporaryDirectories.splice(0)) { + await rm(directory, { recursive: true, force: true }) + } +}) + +function fakeAgent(session: Session): Agent { + return { id: session.id, session } as unknown as Agent +} + +describe('tool-session-query with the real SQLite provider', () => { + it('searches live prior-step history and a persisted same-workspace log', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-tool-session-query-')) + temporaryDirectories.push(root) + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(SessionPersistenceJsonl, { root, compression: 'none' }) + await ctx.plugin(SessionQuerySqlite, { path: join(root, 'session-query.db') }) + await ctx.plugin(ToolSessionQuery) + + const persisted = SessionId('persisted') + await ctx.sessionPersistence.create({ + version: SESSION_FORMAT_VERSION, + id: persisted, + createdAt: 1, + cwd: '/work', + }) + await ctx.sessionPersistence.append(persisted, [{ + type: 'user/message', + seq: 0, + time: 2, + data: { + content: [{ type: 'text', text: 'persisted integration needle' }], + source: { kind: 'user' }, + }, + surfaceOp: 'append', + }]) + + const caller = ctx.sessions.create(SessionId('caller'), { + meta: { createdAt: 10, cwd: '/work' }, + }) + caller.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + caller.append( + 'user/message', + { content: [{ type: 'text', text: 'live integration needle' }], source: { kind: 'user' } }, + { surfaceOp: 'append' }, + ) + caller.append('step/start', { turn: 1, step: 1 }) + + let call = 0 + const execute = (name: string, args: unknown) => ctx.tools.execute({ + name, + arguments: args, + callId: CallId(`integration-${++call}`), + signal: new AbortController().signal, + agent: fakeAgent(caller), + }) + + const sessions = await execute('session_search', { query: 'persisted integration needle' }) + expect(sessions.isError).toBe(false) + expect(sessions.content.map(block => block.type === 'text' ? block.text : '').join('\n')) + .toContain('Session persisted') + const persistedEvents = await execute('session_event_search', { + session_id: persisted, + query: 'persisted integration needle', + }) + expect(persistedEvents.isError).toBe(false) + expect(persistedEvents.content.map(block => block.type === 'text' ? block.text : '').join('\n')) + .toContain('seq 0') + const liveEvents = await execute('session_event_search', { query: 'live integration needle' }) + expect(liveEvents.isError).toBe(false) + expect(liveEvents.content.map(block => block.type === 'text' ? block.text : '').join('\n')) + .toContain('seq 1') + }) +}) diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts new file mode 100644 index 0000000000..60136d4f83 --- /dev/null +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -0,0 +1,796 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context, type Fiber } from 'cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { CallId, HarnessError } from '@deepseek-ai/dsh-llm' +import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import SessionStore, { + SESSION_FORMAT_VERSION, + SessionId, + type Session, + type SessionHeader, + type SessionId as SessionIdValue, +} from '@deepseek-ai/dsh-session' +import SessionQueryService, { + SessionQueryError, + SessionSearchCursor, + type SessionEventSearchHit, + type SessionEventSearchRequest, + type SessionSearchExecContext, + type SessionSearchHit, + type SessionSearchPage, + type SessionSearchRequest, +} from '@deepseek-ai/dsh-session-query' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRegistry, { type ToolExecutionResult } from '@deepseek-ai/dsh-tools' +import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' + +const activeContexts: Context[] = [] + +afterEach(async () => { + vi.restoreAllMocks() + for (const ctx of activeContexts.splice(0)) await ctx.fiber.dispose() + FakeQuery.reset() +}) + +function header(id: string, cwd: string | undefined, createdAt = 1, parentSession?: SessionIdValue): SessionHeader { + return { + version: SESSION_FORMAT_VERSION, + id: SessionId(id), + createdAt, + ...cwd === undefined ? {} : { cwd }, + ...parentSession === undefined ? {} : { parentSession }, + } +} + +function createSession( + ctx: Context, + id: string, + cwd: string | undefined, + createdAt = 1, + parentSession?: SessionIdValue, +): Session { + return ctx.sessions.create(SessionId(id), { + meta: { + createdAt, + ...cwd === undefined ? {} : { cwd }, + ...parentSession === undefined ? {} : { parentSession }, + }, + }) +} + +function openStep(session: Session, text = 'prior needle'): void { + session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + session.append( + 'user/message', + { content: [{ type: 'text', text }], source: { kind: 'user' } }, + { surfaceOp: 'append' }, + ) + session.append('step/start', { turn: 1, step: 1 }) +} + +function fakeAgent(session: Session): Agent { + return { id: session.id, session } as unknown as Agent +} + +function sessionHit( + id: string, + cwd: string | undefined, + text = 'needle excerpt', + parentSession?: SessionIdValue, +): SessionSearchHit { + return { + header: header(id, cwd, 100, parentSession), + live: true, + persisted: false, + bestMatch: { + sessionId: SessionId(id), + seq: 4, + type: 'assistant/message', + time: 200, + surface: 'current', + snippet: text, + }, + } +} + +function eventHit(sessionId: SessionIdValue, seq: number, text = 'needle excerpt'): SessionEventSearchHit { + return { + sessionId, + seq, + type: 'user/message', + time: 200 + seq, + surface: 'current', + snippet: text, + } +} + +class FakeQuery extends SessionQueryService { + static sessionSearch: ( + request: SessionSearchRequest, + exec?: SessionSearchExecContext, + ) => Promise> = () => Promise.resolve({ items: [] }) + + static eventSearch: ( + request: SessionEventSearchRequest, + exec?: SessionSearchExecContext, + ) => Promise> = () => Promise.resolve({ items: [] }) + + static sessionRequests: SessionSearchRequest[] = [] + static eventRequests: SessionEventSearchRequest[] = [] + static searchSignals: Array = [] + static titles = new Map() + + static reset(): void { + this.sessionSearch = () => Promise.resolve({ items: [] }) + this.eventSearch = () => Promise.resolve({ items: [] }) + this.sessionRequests = [] + this.eventRequests = [] + this.searchSignals = [] + this.titles = new Map() + } + + override searchSessions( + request: SessionSearchRequest, + exec?: SessionSearchExecContext, + ): Promise> { + FakeQuery.sessionRequests.push(request) + FakeQuery.searchSignals.push(exec?.signal) + return FakeQuery.sessionSearch(request, exec) + } + + override searchEvents( + request: SessionEventSearchRequest, + exec?: SessionSearchExecContext, + ): Promise> { + FakeQuery.eventRequests.push(request) + FakeQuery.searchSignals.push(exec?.signal) + return FakeQuery.eventSearch(request, exec) + } + + override async readTitle(sessionId: SessionIdValue) { + const value = FakeQuery.titles.get(sessionId) + if (value instanceof Error) throw value + if (value === undefined) return super.readTitle(sessionId) + return { + title: value, + messageSeqs: [], + source: { kind: 'fallback' as const }, + eventSeq: 0, + updatedAt: 1, + } + } +} + +interface Mounted { + readonly ctx: Context + readonly fiber: Fiber + readonly caller: Session + call(name: string, args: unknown, options?: { agent?: Agent; signal?: AbortSignal }): Promise +} + +async function mount( + config: ToolSessionQuery.Config = {}, + callerCwd: string | null = '/work', +): Promise { + const ctx = new Context() + activeContexts.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(FakeQuery) + const fiber = await ctx.plugin(ToolSessionQuery, config) + const caller = createSession(ctx, 'caller', callerCwd ?? undefined, 10) + openStep(caller) + let calls = 0 + return { + ctx, + fiber, + caller, + call: (toolName, args, options = {}) => ctx.tools.execute({ + name: toolName, + arguments: args, + callId: CallId(`call-${++calls}`), + signal: options.signal ?? new AbortController().signal, + ...options.agent === undefined ? { agent: fakeAgent(caller) } : { agent: options.agent }, + }), + } +} + +function text(result: ToolExecutionResult): string { + return result.content.map(block => block.type === 'text' ? block.text : '').join('\n') +} + +function errorCode(result: ToolExecutionResult): string | undefined { + return result.isError ? result.error.info?.code : undefined +} + +describe('registration and schemas', () => { + it('registers the five cursor-free tools, prompt, timeouts, and pure generic presenters, then disposes them', async () => { + const mounted = await mount({ maxSearchResults: 7, searchTimeoutMs: 1234 }) + const names = mounted.ctx.tools.schemas().map(schema => schema.name) + expect(names).toEqual([ + 'session_search', + 'session_event_search', + 'session_trace', + 'session_event_trace', + 'session_event_read', + ]) + const sessionSchema = mounted.ctx.tools.schemas().find(schema => schema.name === 'session_search') + expect(sessionSchema?.parameters).not.toHaveProperty('properties.cursor') + expect(sessionSchema?.parameters).not.toHaveProperty('properties.limit') + expect(sessionSchema?.parameters).not.toHaveProperty('properties.cwd') + expect(mounted.ctx.tools.get('session_search')?.timeoutMs).toBe(1234) + expect(mounted.ctx.tools.get('session_trace')?.timeoutMs).toBeUndefined() + const safeArgs: Record = { + session_search: { query: 'q' }, + session_event_search: { query: 'q' }, + session_trace: {}, + session_event_trace: { seq: 0 }, + session_event_read: { seq: 0 }, + } + for (const name of names) { + expect(mounted.ctx.tools.get(name)?.isConcurrencySafe?.(safeArgs[name])).toBe(true) + } + expect(mounted.ctx.tools.get('session_search')?.output.render({}, 'rendered')) + .toEqual([{ type: 'text', text: 'rendered' }]) + expect(mounted.ctx.tools.get('session_search')?.presentCall?.({ query: 'needle' })) + .toEqual({ card: 'generic', kind: 'search', title: 'Search prior sessions', rawInput: 'needle' }) + expect(mounted.ctx.tools.get('session_event_search')?.presentCall?.({ query: 'needle' })) + .toEqual({ card: 'generic', kind: 'search', title: 'Search session events', rawInput: 'needle' }) + expect(mounted.ctx.tools.get('session_trace')?.presentCall?.({})) + .toEqual({ card: 'generic', kind: 'read', title: 'Trace current session' }) + expect(mounted.ctx.tools.get('session_trace')?.presentCall?.({ session_id: 'other' })) + .toEqual({ card: 'generic', kind: 'read', title: 'Trace session other', rawInput: 'other' }) + expect(mounted.ctx.tools.get('session_event_trace')?.presentCall?.({ session_id: 'other', seq: 3 })) + .toEqual({ + card: 'generic', + kind: 'read', + title: 'Trace event 3', + rawInput: { session_id: 'other', seq: 3 }, + }) + expect(mounted.ctx.tools.get('session_event_read')?.presentCall?.({ seq: 4 })) + .toEqual({ card: 'generic', kind: 'read', title: 'Read event 4', rawInput: { seq: 4 } }) + const assembly = await mounted.ctx.systemPrompt.assemble() + expect(assembly.sections.find(section => section.name === 'tool:session-query')?.text) + .toContain('prior sessions') + + await mounted.fiber.dispose() + expect(mounted.ctx.tools.schemas().map(schema => schema.name)).toEqual([]) + expect((await mounted.ctx.systemPrompt.assemble()).sections.map(section => section.name)) + .not.toContain('tool:session-query') + }) + + it('fails invalid direct config before registering anything', async () => { + const mounted = await mount() + for (const maxSearchResults of [0, 1.5, Number.NaN]) { + expect(() => { ToolSessionQuery.apply(mounted.ctx, { maxSearchResults }) }) + .toThrow('maxSearchResults') + } + for (const searchTimeoutMs of [0, 1.5, Number.POSITIVE_INFINITY, MAX_TIMER_DELAY_MS + 1]) { + expect(() => { ToolSessionQuery.apply(mounted.ctx, { searchTimeoutMs }) }) + .toThrow(`no greater than ${MAX_TIMER_DELAY_MS}`) + } + expect(() => { ToolSessionQuery.apply(new Context(), {}) }).toThrow() + }) + + it('expresses the complete Node timer range in the Loader config schema', () => { + expect(new ToolSessionQuery.Config({ searchTimeoutMs: MAX_TIMER_DELAY_MS })) + .toEqual({ maxSearchResults: 100, searchTimeoutMs: MAX_TIMER_DELAY_MS }) + expect(() => new ToolSessionQuery.Config({ searchTimeoutMs: 1.5 })).toThrow() + expect(() => new ToolSessionQuery.Config({ searchTimeoutMs: MAX_TIMER_DELAY_MS + 1 })).toThrow() + }) +}) + +describe('input validation and translation', () => { + it.each([ + [{ query: ' ' }, 'SESSION_QUERY_INVALID_QUERY'], + [{ query: 'bad\0query' }, 'SESSION_QUERY_INVALID_QUERY'], + [{ query: 'q', session_ids: [] }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', parent_session_ids: [] }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', availability: [] }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', availability: ['archived'] }, 'INVALID_ARGS'], + [{ query: 'q', event_types: [] }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', event_surfaces: [] }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', event_surfaces: ['hidden'] }, 'INVALID_ARGS'], + [{ query: 'q', event_seq_from: -1 }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', event_seq_to: Number.MAX_SAFE_INTEGER + 1 }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', event_seq_from: 2, event_seq_to: 1 }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-07-24T10:00:00' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-02-30T10:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2100-02-29T10:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-04-31T10:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-01-01T24:00:00Z' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-01-01T00:60:00Z' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-01-01T00:00:60Z' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-01-01T00:00:00+24:00' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ query: 'q', created_at_from: '2026-01-01T00:00:00+00:60' }, 'SESSION_QUERY_INVALID_FILTER'], + [{ + query: 'q', + created_at_from: '2026-07-25T00:00:00Z', + created_at_to: '2026-07-24T00:00:00Z', + }, 'SESSION_QUERY_INVALID_FILTER'], + ])('rejects invalid search arguments %#', async (args, code) => { + const mounted = await mount() + const result = await mounted.call('session_search', args) + expect(errorCode(result)).toBe(code) + }) + + it('normalizes the query and compiles inclusive session/event filters with one parent OR clause', async () => { + const mounted = await mount() + await mounted.call('session_search', { + query: ' alpha beta ', + session_ids: ['a', 'b'], + created_at_from: '2026-07-24T00:00:00+08:00', + created_at_to: '2026-07-24T01:00:00+08:00', + parent_session_ids: ['parent'], + include_root_sessions: true, + availability: ['live'], + event_seq_from: 2, + event_seq_to: 9, + event_time_from: '2026-07-24T00:00:00Z', + event_time_to: '2026-07-24T01:00:00Z', + event_types: ['plugin/open-event'], + event_surfaces: ['shadowed'], + }) + expect(FakeQuery.sessionRequests).toHaveLength(1) + expect(FakeQuery.sessionRequests[0]).toEqual({ + query: 'alpha beta', + sessionFilters: [ + { kind: 'id', values: ['a', 'b'] }, + { + kind: 'created-at', + from: Date.parse('2026-07-24T00:00:00+08:00'), + to: Date.parse('2026-07-24T01:00:00+08:00'), + }, + { kind: 'parent', values: ['parent', null] }, + { kind: 'availability', values: ['live'] }, + { kind: 'cwd', values: ['/work'] }, + ], + eventFilters: [ + { kind: 'seq', from: 2, to: 9 }, + { + kind: 'time', + from: Date.parse('2026-07-24T00:00:00Z'), + to: Date.parse('2026-07-24T01:00:00Z'), + }, + { kind: 'type', values: ['plugin/open-event'] }, + { kind: 'surface', values: ['shadowed'] }, + ], + }) + }) + + it('compiles one-sided timestamps and independent root/parent clauses', async () => { + const mounted = await mount() + await mounted.call('session_search', { + query: 'q', + created_at_from: '2024-02-29T00:00Z', + include_root_sessions: true, + event_time_to: '2000-02-29T00:00Z', + }) + expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({ + kind: 'created-at', + from: Date.parse('2024-02-29T00:00Z'), + }) + expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({ + kind: 'parent', + values: [null], + }) + expect(FakeQuery.sessionRequests[0]?.eventFilters).toContainEqual({ + kind: 'time', + to: Date.parse('2000-02-29T00:00Z'), + }) + + await mounted.call('session_search', { + query: 'q', + parent_session_ids: ['parent'], + }) + expect(FakeQuery.sessionRequests[1]?.sessionFilters).toContainEqual({ + kind: 'parent', + values: ['parent'], + }) + }) +}) + +describe('workspace authority and lineage redaction', () => { + it('fails closed without an agent and for direct cross-workspace targets', async () => { + const mounted = await mount() + createSession(mounted.ctx, 'outside', '/outside') + const missing = await mounted.ctx.tools.execute({ + name: 'session_trace', + arguments: {}, + callId: CallId('missing-agent'), + signal: new AbortController().signal, + }) + expect(errorCode(missing)).toBe('SESSION_QUERY_TOOL_MISSING_AGENT') + const denied = await mounted.call('session_event_read', { session_id: 'outside', seq: 0 }) + expect(errorCode(denied)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + expect(text(denied)).not.toContain('session "outside"') + }) + + it('allows only self for a null-cwd caller and denies cross-session search', async () => { + const mounted = await mount({}, null) + const own = await mounted.call('session_trace', {}) + expect(own.isError).toBe(false) + expect(text(own)).toContain('Session caller') + expect(errorCode(await mounted.call('session_search', { query: 'q' }))) + .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + createSession(mounted.ctx, 'other', undefined) + expect(errorCode(await mounted.call('session_trace', { session_id: 'other' }))) + .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + }) + + it('redacts an unauthorized ancestor and prunes unauthorized descendant subtrees without hidden ids', async () => { + const mounted = await mount() + const hiddenParent = createSession(mounted.ctx, 'hidden-parent-secret', '/outside') + const target = createSession(mounted.ctx, 'target', '/work', 20, hiddenParent.id) + const visible = createSession(mounted.ctx, 'visible-child', '/work', 30, target.id) + const hidden = createSession(mounted.ctx, 'hidden-child-secret', '/outside', 40, target.id) + createSession(mounted.ctx, 'hidden-grandchild-secret', '/work', 50, hidden.id) + FakeQuery.titles.set(target.id, 'Target title') + FakeQuery.titles.set(visible.id, 'Visible title') + + const result = await mounted.call('session_trace', { session_id: target.id }) + const output = text(result) + expect(output).toContain('Target title') + expect(output).toContain('visible-child') + expect(output).toContain('[outside workspace boundary]') + expect(output).toContain('[outside workspace subtree]') + expect(output).not.toContain('hidden-parent-secret') + expect(output).not.toContain('hidden-child-secret') + expect(output).not.toContain('hidden-grandchild-secret') + }) + + it('renders authorized ancestors and an unresolved lineage boundary without leaking it', async () => { + const mounted = await mount() + const root = createSession(mounted.ctx, 'visible-root', '/work', 5) + const target = createSession(mounted.ctx, 'visible-target', '/work', 6, root.id) + const complete = text(await mounted.call('session_trace', { session_id: target.id })) + expect(complete).toContain('visible-root') + + const missingParent = SessionId('missing-parent-secret') + const incomplete = createSession(mounted.ctx, 'incomplete-target', '/work', 7, missingParent) + const redacted = text(await mounted.call('session_trace', { session_id: incomplete.id })) + expect(redacted).toContain('[outside workspace boundary]') + expect(redacted).not.toContain(missingParent) + }) + + it('renders unavailable trace records and keeps a self-id descendant authorized', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'trace-unavailable', '/work') + const [record] = await mounted.ctx.sessionQuery.filterSessions([{ kind: 'id', values: [target.id] }]) + const [callerRecord] = await mounted.ctx.sessionQuery.filterSessions([{ + kind: 'id', + values: [mounted.caller.id], + }]) + if (record === undefined || callerRecord === undefined) throw new Error('expected live records') + const unavailable = { ...record, live: false, persisted: false } + const persisted = { ...callerRecord, live: false, persisted: true } + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValue({ + target: unavailable, + ancestors: [], + descendants: [{ session: persisted, descendants: [] }], + complete: true, + root: unavailable, + }) + const output = text(await mounted.call('session_trace', { session_id: target.id })) + expect(output).toContain('Availability: unavailable') + expect(output).toContain(mounted.caller.id) + expect(output).toContain('persisted') + }) +}) + +describe('search paging, prior-history bounds, titles, and cancellation', () => { + it('drains hidden internal pages to the authorized non-self cap and masks an unauthorized parent id', async () => { + const mounted = await mount({ maxSearchResults: 2 }) + const outside = createSession(mounted.ctx, 'outside-parent-secret', '/outside') + const a = createSession(mounted.ctx, 'a', '/work') + const b = createSession(mounted.ctx, 'b', '/work') + FakeQuery.titles.set(a.id, 'Alpha') + FakeQuery.titles.set(b.id, 'Beta') + const c1 = SessionSearchCursor('c1') + const c2 = SessionSearchCursor('c2') + FakeQuery.sessionSearch = (request) => { + if (request.cursor === undefined) { + return Promise.resolve({ + items: [ + sessionHit('caller', '/work'), + sessionHit('unauthorized', '/outside'), + ], + nextCursor: c1, + }) + } + if (request.cursor === c1) { + return Promise.resolve({ + items: [sessionHit('a', '/work', 'first', outside.id)], + nextCursor: c2, + }) + } + return Promise.resolve({ + items: [sessionHit('b', '/work', 'second')], + nextCursor: SessionSearchCursor('more'), + }) + } + + const result = await mounted.call('session_search', { query: 'needle' }) + const output = text(result) + expect(FakeQuery.sessionRequests).toHaveLength(3) + expect(FakeQuery.sessionRequests.every(request => request.limit === undefined)).toBe(true) + expect(FakeQuery.sessionRequests.map(request => request.cursor)).toEqual([undefined, c1, c2]) + expect(output).toContain('Session a — Alpha') + expect(output).toContain('Session b — Beta') + expect(output).toContain('Parent: [outside workspace]') + expect(output).not.toContain('outside-parent-secret') + expect(output).toContain('Result cap reached') + }) + + it('preserves stale-cursor diagnostics without transparently restarting', async () => { + const mounted = await mount({ maxSearchResults: 2 }) + const cursor = SessionSearchCursor('stale-next') + FakeQuery.sessionSearch = request => request.cursor === undefined + ? Promise.resolve({ items: [], nextCursor: cursor }) + : Promise.reject(new SessionQueryError('stale provider generation', 'SESSION_QUERY_STALE_CURSOR')) + const result = await mounted.call('session_search', { query: 'needle' }) + expect(errorCode(result)).toBe('SESSION_QUERY_STALE_CURSOR') + expect(text(result)).toContain('retry the complete search call') + expect(FakeQuery.sessionRequests).toHaveLength(2) + }) + + it('rejects a repeated internal cursor instead of looping', async () => { + const mounted = await mount() + const cursor = SessionSearchCursor('repeat') + FakeQuery.sessionSearch = () => Promise.resolve({ items: [], nextCursor: cursor }) + const result = await mounted.call('session_search', { query: 'needle' }) + expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_CURSOR') + expect(FakeQuery.sessionRequests).toHaveLength(2) + }) + + it('renders authorized parent ids and all availability states', async () => { + const mounted = await mount({ maxSearchResults: 3 }) + const parent = createSession(mounted.ctx, 'parent', '/work') + const child = createSession(mounted.ctx, 'child', '/work', 2, parent.id) + const callerChild = createSession(mounted.ctx, 'caller-child', '/work', 3, mounted.caller.id) + FakeQuery.sessionSearch = () => Promise.resolve({ + items: [ + { ...sessionHit(child.id, '/work', 'both', parent.id), live: true, persisted: true }, + { ...sessionHit(callerChild.id, '/work', 'persisted', mounted.caller.id), live: false, persisted: true }, + { ...sessionHit('unavailable', '/work', 'neither'), live: false, persisted: false }, + ], + }) + const output = text(await mounted.call('session_search', { query: 'needle' })) + expect(output).toContain('Parent: parent') + expect(output).toContain(`Parent: ${mounted.caller.id}`) + expect(output).toContain('Availability: live, persisted') + expect(output).toContain('Availability: persisted') + expect(output).toContain('Availability: unavailable') + }) + + it('intersects current-session search with the event before the latest step and leaves other targets unchanged', async () => { + const mounted = await mount() + FakeQuery.eventSearch = request => Promise.resolve({ + items: [eventHit(request.sessionId, 1)], + }) + await mounted.call('session_event_search', { + query: 'prior', + seq_from: 0, + seq_to: 99, + }) + expect(FakeQuery.eventRequests[0]?.filters).toContainEqual({ kind: 'seq', from: 0, to: 1 }) + + const other = createSession(mounted.ctx, 'other', '/work') + await mounted.call('session_event_search', { + session_id: other.id, + query: 'prior', + seq_from: 0, + seq_to: 99, + }) + expect(FakeQuery.eventRequests[1]?.filters).toContainEqual({ kind: 'seq', from: 0, to: 99 }) + }) + + it('returns no current-session hits without calling FTS when the user range starts in the active step', async () => { + const mounted = await mount() + const result = await mounted.call('session_event_search', { + query: 'prior', + seq_from: 2, + }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('No prior event matches found.') + expect(FakeQuery.eventRequests).toEqual([]) + }) + + it('requires a current step boundary and drains event pages to a capped result', async () => { + const mounted = await mount({ maxSearchResults: 2 }) + const noStep = createSession(mounted.ctx, 'no-step', '/work') + const missing = await mounted.call( + 'session_event_search', + { query: 'q' }, + { agent: fakeAgent(noStep) }, + ) + expect(errorCode(missing)).toBe('SESSION_QUERY_TOOL_NO_CURRENT_STEP') + + const other = createSession(mounted.ctx, 'paged-events', '/work') + const cursor = SessionSearchCursor('events-next') + FakeQuery.eventSearch = request => request.cursor === undefined + ? Promise.resolve({ items: [eventHit(other.id, 1)], nextCursor: cursor }) + : Promise.resolve({ items: [eventHit(other.id, 2), eventHit(other.id, 3)] }) + const result = await mounted.call('session_event_search', { + session_id: other.id, + query: 'q', + }) + expect(FakeQuery.eventRequests.map(request => request.cursor)).toEqual([undefined, cursor]) + expect(text(result)).toContain('Result cap reached') + }) + + it('preserves base results when a title read fails, annotates the code, and logs the full error', async () => { + const mounted = await mount() + const hit = createSession(mounted.ctx, 'hit', '/work') + const failure = new HarnessError('title backend failed', 'TITLE_BACKEND') + FakeQuery.titles.set(hit.id, failure) + FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] }) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + const result = await mounted.call('session_search', { query: 'needle' }) + expect(result.isError).toBe(false) + expect(text(result)).toContain('untitled (title unavailable: TITLE_BACKEND)') + expect(warn).toHaveBeenCalledWith(expect.stringContaining('title backend failed')) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('HarnessError')) + }) + + it('reports unknown title failures and preserves an Error without a stack', async () => { + const mounted = await mount() + const first = createSession(mounted.ctx, 'unknown-title', '/work') + const second = createSession(mounted.ctx, 'stackless-title', '/work') + const stackless = new Error('stackless') + Object.defineProperty(stackless, 'stack', { value: undefined }) + const readTitle = vi.spyOn(mounted.ctx.sessionQuery, 'readTitle') + .mockRejectedValueOnce('string failure') + .mockRejectedValueOnce(stackless) + FakeQuery.sessionSearch = () => Promise.resolve({ + items: [ + sessionHit(first.id, '/work'), + sessionHit(second.id, '/work'), + ], + }) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + const result = await mounted.call('session_search', { query: 'needle' }) + expect(text(result)).toContain('title unavailable: UNKNOWN') + expect(readTitle).toHaveBeenCalledTimes(2) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('string failure')) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('Error: stackless')) + }) + + it('does not downgrade cancellation during title enrichment', async () => { + const mounted = await mount() + const hit = createSession(mounted.ctx, 'abort-title', '/work') + const controller = new AbortController() + FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] }) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitle').mockImplementation(() => { + controller.abort() + return Promise.reject(new Error('cancelled title')) + }) + const result = await mounted.call('session_search', { query: 'needle' }, { signal: controller.signal }) + expect(result.isError).toBe(true) + expect(text(result)).not.toContain('title unavailable') + }) + + it('passes the exact execution signal to every FTS page and stops on cancellation', async () => { + const mounted = await mount() + const controller = new AbortController() + let started!: () => void + const bodyStarted = new Promise((resolve) => { started = resolve }) + FakeQuery.sessionSearch = (_request, exec) => new Promise((_resolve, reject) => { + started() + exec?.signal?.addEventListener('abort', () => { + reject(new SessionQueryError('aborted', 'SESSION_QUERY_ABORTED')) + }, { once: true }) + }) + const pending = mounted.call('session_search', { query: 'needle' }, { signal: controller.signal }) + await bodyStarted + controller.abort() + const result = await pending + expect(result.isError).toBe(true) + expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') + expect(FakeQuery.searchSignals).toEqual([controller.signal]) + }) +}) + +describe('trace and exact read rendering', () => { + it('renders every event relationship sequence and a UTC target timestamp', async () => { + const mounted = await mount() + const session = createSession(mounted.ctx, 'relationships', '/work') + session.append( + 'user/message', + { content: [{ type: 'text', text: 'source' }], source: { kind: 'user' } }, + { surfaceOp: 'append' }, + ) + session.append( + 'assistant/message', + { + turn: 1, + step: 1, + content: [{ type: 'text', text: 'replacement' }], + provenance: { provider: 'test', model: 'test' }, + }, + { surfaceOp: { op: 'replace', start: 0, end: 0 }, sourceEventSeqs: [0] }, + ) + const result = await mounted.call('session_event_trace', { session_id: session.id, seq: 0 }) + expect(text(result)).toContain('Replacement chain: 1') + expect(text(result)).toContain('Direct derived events: 1') + expect(text(result)).toContain(new Date(session.events[0]?.time ?? 0).toISOString()) + }) + + it('renders unabridged fenced target JSON and readable semantic neighbor summaries', async () => { + const mounted = await mount() + const session = createSession(mounted.ctx, 'read', '/work') + session.append( + 'user/message', + { content: [{ type: 'text', text: 'before semantic text' }], source: { kind: 'user' } }, + { surfaceOp: 'append' }, + ) + session.append( + 'assistant/message', + { + turn: 1, + step: 1, + content: [{ type: 'text', text: 'target full text' }], + provenance: { provider: 'test', model: 'test' }, + }, + { surfaceOp: 'append' }, + ) + session.append( + 'context/message', + { content: [{ type: 'text', text: 'after semantic text' }], source: { kind: 'plugin', plugin: 'test' } }, + { surfaceOp: 'append' }, + ) + const result = await mounted.call('session_event_read', { + session_id: session.id, + seq: 1, + before: 1, + after: 1, + }) + const output = text(result) + expect(output).toContain('```json') + expect(output).toContain('"text": "target full text"') + expect(output).toContain('before semantic text') + expect(output).toContain('after semantic text') + expect(output).not.toContain('truncated') + }) + + it('renders empty event relationships and neighbors without semantic text', async () => { + const mounted = await mount() + const session = createSession(mounted.ctx, 'empty-relations', '/work') + session.append('step/start', { turn: 1, step: 1 }) + session.append('step/end', { turn: 1, step: 1 }) + + const trace = text(await mounted.call('session_event_trace', { + session_id: session.id, + seq: 0, + })) + expect(trace).toContain('Replaced by: none') + expect(trace).toContain('Replacement chain: none') + + const onlyAfter = text(await mounted.call('session_event_read', { + session_id: session.id, + seq: 0, + after: 1, + })) + expect(onlyAfter).not.toContain('Before:') + expect(onlyAfter).toContain('(no semantic text)') + + const onlyBefore = text(await mounted.call('session_event_read', { + session_id: session.id, + seq: 1, + before: 1, + })) + expect(onlyBefore).toContain('Before:') + expect(onlyBefore).not.toContain('After:') + }) + + it.each([ + ['session_event_trace', { seq: -1 }], + ['session_event_read', { seq: Number.MAX_SAFE_INTEGER + 1 }], + ['session_event_read', { seq: 0, before: -1 }], + ['session_event_read', { seq: 0, after: 1.5 }, 'INVALID_ARGS'], + ])('rejects invalid exact-read integers for %s', async (name, args, expected = 'SESSION_QUERY_INVALID_FILTER') => { + const mounted = await mount() + expect(errorCode(await mounted.call(name, args))).toBe(expected) + }) +}) diff --git a/packages/session-query/tool-session-query/tsconfig.json b/packages/session-query/tool-session-query/tsconfig.json new file mode 100644 index 0000000000..561b414216 --- /dev/null +++ b/packages/session-query/tool-session-query/tsconfig.json @@ -0,0 +1,40 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": ["src"], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../core/session" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../session-query" + }, + { + "path": "../../support/invariants" + }, + { + "path": "../../util/timeout" + } + ] +} diff --git a/packages/support/acp-snapshot/src/normalize.ts b/packages/support/acp-snapshot/src/normalize.ts index b32c5c0574..a4cd595b12 100644 --- a/packages/support/acp-snapshot/src/normalize.ts +++ b/packages/support/acp-snapshot/src/normalize.ts @@ -12,11 +12,13 @@ const SYSTEM = '{{system}}' const TOOLS = '{{tools}}' const MESSAGE_PREFIX = '{{messagePrefix}}' const UPDATED_AT = '{{updatedAt}}' +const EVENT_TIME = '{{eventTime}}' /** A cwd-rooted path after volatile cwd replacement, through its last separator-delimited segment. */ const CWD_ROOTED_PATH_RE = /\{\{cwd\}\}(?:[\\/][^\s<>"'`]+)+/g const PATH_TAG_RE = /()([^<]*)(<\/path>)/g const ADDITIONAL_INSTRUCTIONS_PATH_RE = /(Additional instructions from: )([^\r\n]+)/g +const EMBEDDED_EVENT_TIME_RE = /("time": )\d+(?=,\r?\n)/g /** A UUID v4 string, the shape `randomUUID()` produces for session ids. */ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi @@ -72,6 +74,9 @@ function scrubString(value: string, ctx: NormalizeContext, cwdPathMode: CwdPathM } out = out.replace(LOCAL_SPILL_PATH_RE, (_match, name: string) => `{{spillLocator:${name}}}`) out = out.replace(SNAPSHOT_SPILL_PATH_RE, (_match, name: string) => `{{spillLocator:${name}}}`) + // Exact event-read tools render pretty JSON inside a text block. The event's + // wall-clock time is volatile even though its seq and payload are deterministic. + out = out.replace(EMBEDDED_EVENT_TIME_RE, `$1${EVENT_TIME}`) for (const id of ctx.sessionIds) out = out.split(id).join(SESSION_ID) out = out.replace(UUID_RE, SESSION_ID) return out diff --git a/packages/support/acp-snapshot/tests/normalize.spec.ts b/packages/support/acp-snapshot/tests/normalize.spec.ts index bdd85491d2..b74dd49e49 100644 --- a/packages/support/acp-snapshot/tests/normalize.spec.ts +++ b/packages/support/acp-snapshot/tests/normalize.spec.ts @@ -123,6 +123,28 @@ Additional instructions from: nested\AGENTS.md`, expect(out).not.toContain('2026-07-20T17:03:13.689Z') }) + it('stabilizes a pretty-printed event timestamp embedded in tool-result text', () => { + const raw = JSON.stringify({ + jsonrpc: '2.0', + method: 'session/update', + params: { + update: { + sessionUpdate: 'tool_call_update', + content: [{ + type: 'content', + content: { + type: 'text', + text: 'Target event:\n```json\n{\n "seq": 4,\n "time": 1784876275593,\n "data": {}\n}\n```', + }, + }], + }, + }, + }) + const out = normalizeStdout(raw, ctx) + expect(out).toContain('\\"time\\": {{eventTime}}') + expect(out).not.toContain('1784876275593') + }) + it('throws on a non-JSON stdout line (the purity check)', () => { const raw = `${JSON.stringify({ jsonrpc: '2.0', id: 1 })}\noops a log leaked\n` expect(() => normalizeStdout(raw, ctx)).toThrow() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0e0d5cd798..322d6c658c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -363,6 +363,9 @@ importers: '@deepseek-ai/dsh-tool-ralph': specifier: workspace:* version: link:../packages/workflow/tool-ralph + '@deepseek-ai/dsh-tool-session-query': + specifier: workspace:* + version: link:../packages/session-query/tool-session-query '@deepseek-ai/dsh-tool-subagent': specifier: workspace:* version: link:../packages/subagent/tool-subagent @@ -1348,6 +1351,9 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt + '@deepseek-ai/dsh-tool-session-query': + specifier: workspace:^ + version: link:../../session-query/tool-session-query '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools @@ -2115,6 +2121,9 @@ importers: '@deepseek-ai/dsh-session-persistence-jsonl': specifier: workspace:^ version: link:../../session-persistence/session-persistence-jsonl + '@deepseek-ai/dsh-session-query-sqlite': + specifier: workspace:^ + version: link:../../session-query/session-query-sqlite '@deepseek-ai/dsh-session-title': specifier: workspace:^ version: link:../../session-title/session-title @@ -2163,6 +2172,9 @@ importers: '@deepseek-ai/dsh-tool-fs-search': specifier: workspace:^ version: link:../../fs/tool-fs-search + '@deepseek-ai/dsh-tool-session-query': + specifier: workspace:^ + version: link:../../session-query/tool-session-query '@deepseek-ai/dsh-tool-skill': specifier: workspace:^ version: link:../../skill/tool-skill @@ -2900,6 +2912,52 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@vendor+loader) + packages/session-query/tool-session-query: + dependencies: + schemastery: + specifier: ^3.18.0 + version: 3.18.0 + devDependencies: + '@deepseek-ai/dsh-agent': + specifier: workspace:^ + version: link:../../core/agent + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@deepseek-ai/dsh-llm': + specifier: workspace:^ + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:^ + version: link:../../core/session + '@deepseek-ai/dsh-session-persistence': + specifier: workspace:^ + version: link:../../session-persistence/session-persistence + '@deepseek-ai/dsh-session-persistence-jsonl': + specifier: workspace:^ + version: link:../../session-persistence/session-persistence-jsonl + '@deepseek-ai/dsh-session-query': + specifier: workspace:^ + version: link:../session-query + '@deepseek-ai/dsh-session-query-sqlite': + specifier: workspace:^ + version: link:../session-query-sqlite + '@deepseek-ai/dsh-session-title': + specifier: workspace:^ + version: link:../../session-title/session-title + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:^ + version: link:../../core/system-prompt + '@deepseek-ai/dsh-timeout': + specifier: workspace:^ + version: link:../../util/timeout + '@deepseek-ai/dsh-tools': + specifier: workspace:^ + version: link:../../core/tools + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/session-title/session-title: dependencies: schemastery: diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 5cfa05bc2f..309cd36c19 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -138,8 +138,8 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Session reads, traces, filters, and search', mode: 'seam', implementations: ['session-query-sqlite'], - consumers: ['session-reference'], - note: 'The interface supplies exact reads, filters, and traces; its concrete backend adds full-text reconciliation, ranking, snippets, and cursor generations on the same service.', + consumers: ['session-reference', 'tool-session-query'], + note: 'The interface supplies exact reads, filters, and traces; its concrete backend adds full-text reconciliation, ranking, snippets, and cursor generations, while the model consumer owns workspace authority and cursor-free rendering.', }, { key: 'sessionReferences', diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index cc85d48ba5..118ac61b0a 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -11,6 +11,8 @@ import { basename, resolve } from 'node:path' import { Context } from 'cordis' import type { ToolSchema } from '@deepseek-ai/dsh-llm' import AgentRegistry from '@deepseek-ai/dsh-agent' +import SessionStore from '@deepseek-ai/dsh-session' +import SessionQuerySqlite from '@deepseek-ai/dsh-session-query-sqlite' import GoalService from '@deepseek-ai/dsh-goal' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { type Config as ToolsConfig } from '@deepseek-ai/dsh-tools' @@ -39,6 +41,7 @@ import * as ToolGoal from '@deepseek-ai/dsh-tool-goal' import Lsp from '@deepseek-ai/dsh-lsp' import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp' import * as ToolSkill from '@deepseek-ai/dsh-tool-skill' +import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' import * as ToolTasks from '@deepseek-ai/dsh-tool-tasks' import * as ToolTodo from '@deepseek-ai/dsh-tool-todo' import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent' @@ -316,6 +319,20 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolSkill) }, }, + { + pkg: '@deepseek-ai/dsh-tool-session-query', + dir: 'tool-session-query', + source: 'packages/session-query/tool-session-query/src/index.ts', + requires: ['ctx.tools', 'ctx.systemPrompt', 'ctx.sessionQuery', 'a calling Agent for workspace authority'], + writes: ['tool/call', 'tool/result'], + async mount(ctx) { + await ctx.plugin(SessionStore) + await ctx.plugin(SessionQuerySqlite, { path: ':memory:' }) + await ctx.plugin(ToolSessionQuery) + }, + note: + 'The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. Default ACP, TUI, and Web compositions enforce the declared search timeout and apply the generic tool-result spill policy.', + }, { pkg: '@deepseek-ai/dsh-tool-subagent', dir: 'tool-subagent', diff --git a/tsconfig.host.json b/tsconfig.host.json index a13bcf35e3..b67bfb222d 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -44,6 +44,7 @@ { "path": "./packages/session-persistence/session-persistence-sqlite" }, { "path": "./packages/session-query/session-query" }, { "path": "./packages/session-query/session-query-sqlite" }, + { "path": "./packages/session-query/tool-session-query" }, { "path": "./packages/session-title/session-title" }, { "path": "./packages/session-title/session-title-llm" }, { "path": "./packages/session-title/session-title-first-message-llm" }, From b488147c95a4f68b7da6026105fe4e285f53d9a5 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 15:19:53 +0800 Subject: [PATCH 003/113] docs: correct session-query verification record (round 2) --- .../2026-07-24-model-facing-session-query-tools.i18n.yaml | 4 ++-- .../feature/2026-07-24-model-facing-session-query-tools.md | 2 +- .../feature/2026-07-24-model-facing-session-query-tools.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml index feab70bc44..8169bc5977 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 -2026-07-24-model-facing-session-query-tools.md: 27842c2799c3898de4bd9f0fd8171911b0e965cd -2026-07-24-model-facing-session-query-tools.zh.md: 899f63fb7bf6cc6357d25cf90e077b6e2f80afa1 +2026-07-24-model-facing-session-query-tools.md: 521b62fdc668f5c2e208118640be5cec99561a5c +2026-07-24-model-facing-session-query-tools.zh.md: 9be772b33e0e14f503ab2c762a831493381266fd diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md index 27842c2799..521b62fdc6 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -44,7 +44,7 @@ The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.se ## Verification -Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, title fallbacks, rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while a keyless model transcript pins the prompt guidance, schemas, representative search/trace/read output, and oversized-result spill behavior. +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus exact event-read spill and retention behavior. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md index 899f63fb7b..9be772b33e 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -44,7 +44,7 @@ Status: implemented ## 验证 -包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、标题回退、渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥模型 transcript 则固定提示词指导、schema、代表性搜索/追踪/读取输出和超大结果 spill 行为。 +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及精确事件读取的 spill 与保留行为。 ## 后果 From bc47884a770d2754c8023803435e69b44955aab9 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 15:42:24 +0800 Subject: [PATCH 004/113] fix session-query CI invariants --- examples/tui-agent/cordis.yml | 1 - packages/core/tools/tests/gen-tool-catalog.spec.ts | 2 +- packages/examples/acp-demo/package.json | 1 - pnpm-lock.yaml | 3 --- 4 files changed, 1 insertion(+), 6 deletions(-) diff --git a/examples/tui-agent/cordis.yml b/examples/tui-agent/cordis.yml index 479ad24d09..4fccfff1c7 100644 --- a/examples/tui-agent/cordis.yml +++ b/examples/tui-agent/cordis.yml @@ -7,7 +7,6 @@ - id: hmr name: '@cordisjs/plugin-hmr' - disabled: !!js process.env.CI === 'true' config: root: ['.'] diff --git a/packages/core/tools/tests/gen-tool-catalog.spec.ts b/packages/core/tools/tests/gen-tool-catalog.spec.ts index f3e32786b6..3754595f56 100644 --- a/packages/core/tools/tests/gen-tool-catalog.spec.ts +++ b/packages/core/tools/tests/gen-tool-catalog.spec.ts @@ -23,7 +23,7 @@ describe('gen-tool-catalog collectToolCatalog', () => { it('boots every shipped tool package and harvests its model-facing schemas', async () => { const catalog = await collectToolCatalog() const names = catalog.flatMap(entry => entry.schemas.map(s => s.name)).sort() - expect(names).toEqual(['ask_user_question', 'bash', 'cordis_inspect', 'cordis_mount', 'cordis_unmount', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'lsp', 'ralph', 'read', 'run_code', 'skill', 'subagent', 'task_kill', 'task_list', 'task_output', 'terminal_close', 'terminal_list', 'terminal_open', 'terminal_read', 'terminal_send', 'terminal_signal', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'write']) + expect(names).toEqual(['ask_user_question', 'bash', 'cordis_inspect', 'cordis_mount', 'cordis_unmount', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'glob', 'grep', 'lsp', 'ralph', 'read', 'run_code', 'session_event_read', 'session_event_search', 'session_event_trace', 'session_search', 'session_trace', 'skill', 'subagent', 'task_kill', 'task_list', 'task_output', 'terminal_close', 'terminal_list', 'terminal_open', 'terminal_read', 'terminal_send', 'terminal_signal', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'write']) // Every tool carries a JSON-Schema `parameters` object (what the model sees). for (const entry of catalog) { for (const schema of entry.schemas) { diff --git a/packages/examples/acp-demo/package.json b/packages/examples/acp-demo/package.json index ad1ece0095..36de692404 100644 --- a/packages/examples/acp-demo/package.json +++ b/packages/examples/acp-demo/package.json @@ -70,7 +70,6 @@ "@deepseek-ai/dsh-session-query-sqlite": "workspace:^", "@deepseek-ai/dsh-session-reference": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", - "@deepseek-ai/dsh-tool-session-query": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/dsh-user-interaction": "workspace:^", "@deepseek-ai/dsh-workspace-context": "workspace:^", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 322d6c658c..3adfc3222b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1351,9 +1351,6 @@ importers: '@deepseek-ai/dsh-system-prompt': specifier: workspace:^ version: link:../../core/system-prompt - '@deepseek-ai/dsh-tool-session-query': - specifier: workspace:^ - version: link:../../session-query/tool-session-query '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools From 01b70fd6fd6e91b29e27e868add3efd4b8a932ba Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 15:58:03 +0800 Subject: [PATCH 005/113] fix review findings for session queries --- .../tool-session-query/src/index.ts | 7 ++--- .../tests/tool-session-query.spec.ts | 27 +++++++++++++++++-- .../support/acp-snapshot/src/normalize.ts | 11 +++++--- .../acp-snapshot/tests/normalize.spec.ts | 24 ++++++++++++++++- 4 files changed, 58 insertions(+), 11 deletions(-) diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index c8c7350604..02b6d2ceb8 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -658,13 +658,10 @@ async function collectPages( signal.throwIfAborted() for (const item of page.items) { if (!accept(item)) continue - items.push(item) if (items.length === maxResults) { - return { - items, - capped: page.nextCursor !== undefined || item !== page.items.at(-1), - } + return { items, capped: true } } + items.push(item) } if (page.nextCursor === undefined) return { items, capped: false } if (seen.has(page.nextCursor)) { diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index 60136d4f83..017070eefc 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -506,8 +506,10 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => }) } return Promise.resolve({ - items: [sessionHit('b', '/work', 'second')], - nextCursor: SessionSearchCursor('more'), + items: [ + sessionHit('b', '/work', 'second'), + sessionHit('additional-authorized', '/work', 'third'), + ], }) } @@ -523,6 +525,27 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => expect(output).toContain('Result cap reached') }) + it('does not report a cap when only rejected hits remain after the authorized limit', async () => { + const mounted = await mount({ maxSearchResults: 1 }) + const cursor = SessionSearchCursor('rejected-tail') + FakeQuery.sessionSearch = request => request.cursor === undefined + ? Promise.resolve({ + items: [sessionHit('authorized', '/work')], + nextCursor: cursor, + }) + : Promise.resolve({ + items: [ + sessionHit(mounted.caller.id, '/work'), + sessionHit('outside', '/outside'), + ], + }) + + const output = text(await mounted.call('session_search', { query: 'needle' })) + expect(FakeQuery.sessionRequests.map(request => request.cursor)).toEqual([undefined, cursor]) + expect(output).toContain('Session authorized') + expect(output).not.toContain('Result cap reached') + }) + it('preserves stale-cursor diagnostics without transparently restarting', async () => { const mounted = await mount({ maxSearchResults: 2 }) const cursor = SessionSearchCursor('stale-next') diff --git a/packages/support/acp-snapshot/src/normalize.ts b/packages/support/acp-snapshot/src/normalize.ts index a4cd595b12..258de0fd53 100644 --- a/packages/support/acp-snapshot/src/normalize.ts +++ b/packages/support/acp-snapshot/src/normalize.ts @@ -19,6 +19,8 @@ const CWD_ROOTED_PATH_RE = /\{\{cwd\}\}(?:[\\/][^\s<>"'`]+)+/g const PATH_TAG_RE = /()([^<]*)(<\/path>)/g const ADDITIONAL_INSTRUCTIONS_PATH_RE = /(Additional instructions from: )([^\r\n]+)/g const EMBEDDED_EVENT_TIME_RE = /("time": )\d+(?=,\r?\n)/g +const EVENT_READ_RESULT_RE + = /^Session [^\r\n]+ — [^\r\n]+\r?\nTarget event seq \d+:\r?\n```json\r?\n\{\r?\n/ /** A UUID v4 string, the shape `randomUUID()` produces for session ids. */ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi @@ -74,9 +76,12 @@ function scrubString(value: string, ctx: NormalizeContext, cwdPathMode: CwdPathM } out = out.replace(LOCAL_SPILL_PATH_RE, (_match, name: string) => `{{spillLocator:${name}}}`) out = out.replace(SNAPSHOT_SPILL_PATH_RE, (_match, name: string) => `{{spillLocator:${name}}}`) - // Exact event-read tools render pretty JSON inside a text block. The event's - // wall-clock time is volatile even though its seq and payload are deterministic. - out = out.replace(EMBEDDED_EVENT_TIME_RE, `$1${EVENT_TIME}`) + // Exact event-read results render pretty JSON inside a distinctive text + // envelope. Restrict time scrubbing to that envelope so JSON printed by + // models, bash, or unrelated tools remains regression-visible. + if (EVENT_READ_RESULT_RE.test(out)) { + out = out.replace(EMBEDDED_EVENT_TIME_RE, `$1${EVENT_TIME}`) + } for (const id of ctx.sessionIds) out = out.split(id).join(SESSION_ID) out = out.replace(UUID_RE, SESSION_ID) return out diff --git a/packages/support/acp-snapshot/tests/normalize.spec.ts b/packages/support/acp-snapshot/tests/normalize.spec.ts index b74dd49e49..b4bc813cda 100644 --- a/packages/support/acp-snapshot/tests/normalize.spec.ts +++ b/packages/support/acp-snapshot/tests/normalize.spec.ts @@ -134,7 +134,7 @@ Additional instructions from: nested\AGENTS.md`, type: 'content', content: { type: 'text', - text: 'Target event:\n```json\n{\n "seq": 4,\n "time": 1784876275593,\n "data": {}\n}\n```', + text: 'Session prior — title\nTarget event seq 4:\n```json\n{\n "seq": 4,\n "time": 1784876275593,\n "data": {}\n}\n```', }, }], }, @@ -145,6 +145,28 @@ Additional instructions from: nested\AGENTS.md`, expect(out).not.toContain('1784876275593') }) + it('preserves event-like timestamps in unrelated output text', () => { + const raw = JSON.stringify({ + jsonrpc: '2.0', + method: 'session/update', + params: { + update: { + sessionUpdate: 'tool_call_update', + content: [{ + type: 'content', + content: { + type: 'text', + text: 'bash output:\n```json\n{\n "time": 1784876275593,\n "data": {}\n}\n```', + }, + }], + }, + }, + }) + const out = normalizeStdout(raw, ctx) + expect(out).toContain('1784876275593') + expect(out).not.toContain('{{eventTime}}') + }) + it('throws on a non-JSON stdout line (the purity check)', () => { const raw = `${JSON.stringify({ jsonrpc: '2.0', id: 1 })}\noops a log leaked\n` expect(() => normalizeStdout(raw, ctx)).toThrow() From c1f364b33929493d970245cca3ca3b656795dcd7 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 16:16:07 +0800 Subject: [PATCH 006/113] test: refresh session-query ACP snapshots --- .../system-prompt.expected.md | 78 ++++ .../tool-schemas.expected.json | 204 +++++++++ .../both-mode-turn/system-prompt.expected.md | 78 ++++ .../both-mode-turn/tool-schemas.expected.json | 204 +++++++++ .../code-mode-turn/system-prompt.expected.md | 78 ++++ .../system-prompt.expected.md | 78 ++++ .../lsp-definition/system-prompt.expected.md | 2 + .../lsp-definition/tool-schemas.expected.json | 204 +++++++++ .../model-switching/system-prompt.expected.md | 4 + .../tool-schemas.expected.json | 408 ++++++++++++++++++ .../system-prompt.expected.md | 4 + .../tool-schemas.expected.json | 408 ++++++++++++++++++ .../plan-mode/system-prompt.expected.md | 4 + .../plan-mode/tool-schemas.expected.json | 408 ++++++++++++++++++ .../pty-tools/system-prompt.expected.md | 2 + .../pty-tools/tool-schemas.expected.json | 204 +++++++++ .../session-query-spill/session.jsonl | 8 +- .../session-query-spill/stdout.expected.jsonl | 2 +- .../skill-load/system-prompt.expected.md | 2 + .../skill-load/tool-schemas.expected.json | 204 +++++++++ .../system-prompt.expected.md | 2 + .../tool-schemas.expected.json | 204 +++++++++ 22 files changed, 2785 insertions(+), 5 deletions(-) diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md index 73c31413bf..8fae73812d 100644 --- a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -139,6 +141,77 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; + /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ + session_event_read: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + /** Number of preceding raw events to summarize. Omit for none. */ + before?: number; + /** Number of following raw events to summarize. Omit for none. */ + after?: number; + } & Record; + /** Search prior events in one authorized session; the current session excludes the step performing this call. */ + session_event_search: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Literal full-text query over the target session. */ + query: string; + /** Inclusive event sequence lower bound. */ + seq_from?: number; + /** Inclusive event sequence upper bound. */ + seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read every direct replacement and provenance relationship for one event in an authorized session. */ + session_event_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + } & Record; + /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ + session_search: { + /** Literal full-text query over prior session history. */ + query: string; + /** Optional session ids to include. */ + session_ids?: string[]; + /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ + created_at_from?: string; + /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ + created_at_to?: string; + /** Optional direct parent session ids. */ + parent_session_ids?: string[]; + /** Include sessions with no parent in the parent filter. */ + include_root_sessions?: boolean; + /** Require at least one selected source availability. */ + availability?: ("live" | "persisted")[]; + /** Inclusive event sequence lower bound. */ + event_seq_from?: number; + /** Inclusive event sequence upper bound. */ + event_seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + event_time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + event_time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + event_surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ + session_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -348,6 +421,11 @@ interface ToolOutputMap { }[]; totalLines: number; }; + session_event_read: string; + session_event_search: string; + session_event_trace: string; + session_search: string; + session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json index 6b50a5d220..a0ab8af765 100644 --- a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json @@ -311,6 +311,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md index 8744029272..014455b3fd 100644 --- a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -122,6 +124,77 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; + /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ + session_event_read: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + /** Number of preceding raw events to summarize. Omit for none. */ + before?: number; + /** Number of following raw events to summarize. Omit for none. */ + after?: number; + } & Record; + /** Search prior events in one authorized session; the current session excludes the step performing this call. */ + session_event_search: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Literal full-text query over the target session. */ + query: string; + /** Inclusive event sequence lower bound. */ + seq_from?: number; + /** Inclusive event sequence upper bound. */ + seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read every direct replacement and provenance relationship for one event in an authorized session. */ + session_event_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + } & Record; + /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ + session_search: { + /** Literal full-text query over prior session history. */ + query: string; + /** Optional session ids to include. */ + session_ids?: string[]; + /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ + created_at_from?: string; + /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ + created_at_to?: string; + /** Optional direct parent session ids. */ + parent_session_ids?: string[]; + /** Include sessions with no parent in the parent filter. */ + include_root_sessions?: boolean; + /** Require at least one selected source availability. */ + availability?: ("live" | "persisted")[]; + /** Inclusive event sequence lower bound. */ + event_seq_from?: number; + /** Inclusive event sequence upper bound. */ + event_seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + event_time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + event_time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + event_surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ + session_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -319,6 +392,11 @@ interface ToolOutputMap { }[]; totalLines: number; }; + session_event_read: string; + session_event_search: string; + session_event_trace: string; + session_search: string; + session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json index 7ceeec4042..8626f46680 100644 --- a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json @@ -254,6 +254,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md index 8744029272..014455b3fd 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -122,6 +124,77 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; + /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ + session_event_read: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + /** Number of preceding raw events to summarize. Omit for none. */ + before?: number; + /** Number of following raw events to summarize. Omit for none. */ + after?: number; + } & Record; + /** Search prior events in one authorized session; the current session excludes the step performing this call. */ + session_event_search: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Literal full-text query over the target session. */ + query: string; + /** Inclusive event sequence lower bound. */ + seq_from?: number; + /** Inclusive event sequence upper bound. */ + seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read every direct replacement and provenance relationship for one event in an authorized session. */ + session_event_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + } & Record; + /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ + session_search: { + /** Literal full-text query over prior session history. */ + query: string; + /** Optional session ids to include. */ + session_ids?: string[]; + /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ + created_at_from?: string; + /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ + created_at_to?: string; + /** Optional direct parent session ids. */ + parent_session_ids?: string[]; + /** Include sessions with no parent in the parent filter. */ + include_root_sessions?: boolean; + /** Require at least one selected source availability. */ + availability?: ("live" | "persisted")[]; + /** Inclusive event sequence lower bound. */ + event_seq_from?: number; + /** Inclusive event sequence upper bound. */ + event_seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + event_time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + event_time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + event_surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ + session_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -319,6 +392,11 @@ interface ToolOutputMap { }[]; totalLines: number; }; + session_event_read: string; + session_event_search: string; + session_event_trace: string; + session_search: string; + session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md index 8744029272..014455b3fd 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -122,6 +124,77 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; + /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ + session_event_read: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + /** Number of preceding raw events to summarize. Omit for none. */ + before?: number; + /** Number of following raw events to summarize. Omit for none. */ + after?: number; + } & Record; + /** Search prior events in one authorized session; the current session excludes the step performing this call. */ + session_event_search: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Literal full-text query over the target session. */ + query: string; + /** Inclusive event sequence lower bound. */ + seq_from?: number; + /** Inclusive event sequence upper bound. */ + seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read every direct replacement and provenance relationship for one event in an authorized session. */ + session_event_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + /** Target event sequence number. */ + seq: number; + } & Record; + /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ + session_search: { + /** Literal full-text query over prior session history. */ + query: string; + /** Optional session ids to include. */ + session_ids?: string[]; + /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ + created_at_from?: string; + /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ + created_at_to?: string; + /** Optional direct parent session ids. */ + parent_session_ids?: string[]; + /** Include sessions with no parent in the parent filter. */ + include_root_sessions?: boolean; + /** Require at least one selected source availability. */ + availability?: ("live" | "persisted")[]; + /** Inclusive event sequence lower bound. */ + event_seq_from?: number; + /** Inclusive event sequence upper bound. */ + event_seq_to?: number; + /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ + event_time_from?: string; + /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ + event_time_to?: string; + /** Event types to include. */ + event_types?: string[]; + /** Event surfaces to include. */ + event_surfaces?: ("current" | "shadowed" | "log-only")[]; + } & Record; + /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ + session_trace: { + /** Target session id. Omit for the current session. */ + session_id?: string; + } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -319,6 +392,11 @@ interface ToolOutputMap { }[]; totalLines: number; }; + session_event_read: string; + session_event_search: string; + session_event_trace: string; + session_search: string; + session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md index 7bde8fe289..cb50752e91 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md @@ -17,6 +17,8 @@ Track every background task id you start. You are notified in-session when a tas Use search/read for ordinary navigation. Use lsp when textual matches are ambiguous or before a change requires precise definitions, implementations, or references. Positions are one-based line and character (UTF-16) at the cursor; an off-symbol position may return no results. findReferences always includes the declaration. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json index b42a434388..4e34a49176 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json @@ -275,6 +275,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md index e5f8f35c02..371780ab3d 100644 --- a/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/model-switching/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -43,6 +45,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json index ef40784fa5..8bfac915b0 100644 --- a/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/model-switching/tool-schemas.expected.json @@ -238,6 +238,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", @@ -788,6 +992,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md index 3ee1805568..55b309bbc3 100644 --- a/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/permission-switching/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. @@ -42,6 +44,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json index ef40784fa5..8bfac915b0 100644 --- a/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/permission-switching/tool-schemas.expected.json @@ -238,6 +238,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", @@ -788,6 +992,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/plan-mode/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/plan-mode/system-prompt.expected.md index df467239bd..a46e43ec2e 100644 --- a/examples/acp-agent/tests/snapshots/plan-mode/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/plan-mode/system-prompt.expected.md @@ -28,6 +28,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -56,6 +58,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/plan-mode/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/plan-mode/tool-schemas.expected.json index ef40784fa5..8bfac915b0 100644 --- a/examples/acp-agent/tests/snapshots/plan-mode/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/plan-mode/tool-schemas.expected.json @@ -238,6 +238,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", @@ -788,6 +992,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md index df065a83cb..ccce83d9b7 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md @@ -17,6 +17,8 @@ Use a terminal session only when work needs persistent terminal state or interac Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json index 529b1419da..0748a0f153 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json @@ -238,6 +238,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl b/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl index c4b4f54047..6d8a294c1e 100644 --- a/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl +++ b/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl @@ -15,12 +15,12 @@ {"type":"step/end","seq":13,"time":0,"data":{"turn":1,"step":1}} {"type":"step/start","seq":14,"time":0,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":15,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} -{"type":"assistant/chunk","seq":16,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"call_verify_session_query_spill","name":"bash","argumentsDelta":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}}} -{"type":"assistant/chunk","seq":17,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}}}} +{"type":"assistant/chunk","seq":16,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"call_verify_session_query_spill","name":"bash","argumentsDelta":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \\\"$file\\\" && grep -q session_event_search \\\"$file\\\" && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}}} +{"type":"assistant/chunk","seq":17,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \\\"$file\\\" && grep -q session_event_search \\\"$file\\\" && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}}}} {"type":"assistant/chunk","seq":18,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}}} {"type":"assistant/chunk","seq":19,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} -{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"tool-call","id":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} -{"type":"tool/call","seq":21,"time":0,"data":{"turn":1,"step":2,"callId":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}} +{"type":"assistant/message","seq":20,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"tool-call","id":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \\\"$file\\\" && grep -q session_event_search \\\"$file\\\" && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[15,16,17,18,19],"surfaceOp":"append"} +{"type":"tool/call","seq":21,"time":0,"data":{"turn":1,"step":2,"callId":"call_verify_session_query_spill","name":"bash","arguments":"{\"command\":\"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \\\"$file\\\" && grep -q session_event_search \\\"$file\\\" && echo SPILL_CANONICAL_OK\",\"description\":\"Verify complete session query spill\"}"}} {"type":"tool/result","seq":22,"time":0,"data":{"turn":1,"step":2,"callId":"call_verify_session_query_spill","content":[{"type":"text","text":"SPILL_CANONICAL_OK\n"}],"isError":false},"sourceEventSeqs":[21],"surfaceOp":"append"} {"type":"step/end","seq":23,"time":0,"data":{"turn":1,"step":2}} {"type":"step/start","seq":24,"time":0,"data":{"turn":1,"step":3}} diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl index a1a65b452c..e0629f89a2 100644 --- a/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl @@ -4,7 +4,7 @@ {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Read request event 4 with","updatedAt":"{{updatedAt}}"}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_session_query_spill","title":"Read event 4","kind":"read","status":"in_progress","rawInput":{"seq":4}}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": {{eventTime}},\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted 39431 bytes. Full formatted result stored at: {{spillLocator:session_event_read.txt}}. Use read with offset/limit, or grep this path to search within it.)"}}]}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_verify_session_query_spill","title":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK","kind":"execute","status":"in_progress","rawInput":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); test $(wc -c < $file) -gt 40000 && grep -q request/header $file && echo SPILL_CANONICAL_OK","content":[{"type":"content","content":{"type":"text","text":"Verify complete session query spill"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_verify_session_query_spill","title":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \"$file\" && grep -q session_event_search \"$file\" && echo SPILL_CANONICAL_OK","kind":"execute","status":"in_progress","rawInput":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \"$file\" && grep -q session_event_search \"$file\" && echo SPILL_CANONICAL_OK","content":[{"type":"content","content":{"type":"text","text":"Verify complete session query spill"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_verify_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nSPILL_CANONICAL_OK\n```"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} {"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md index 17e6773a03..68bdd841c7 100644 --- a/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json index b01e7683d1..02237f770b 100644 --- a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json @@ -238,6 +238,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md index 6cd8d5725f..45c9e0970c 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md @@ -15,6 +15,8 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json index b01e7683d1..02237f770b 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json @@ -238,6 +238,210 @@ ] } }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", From 6be11539e26ab2aef651cca1e85943c5e692d1f5 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 16:40:08 +0800 Subject: [PATCH 007/113] fix: bind session authorization to observations --- ...model-facing-session-query-tools.i18n.yaml | 4 +- ...-07-24-model-facing-session-query-tools.md | 6 +- ...-24-model-facing-session-query-tools.zh.md | 6 +- docs/config-catalog.md | 4 +- docs/cordis-catalog/services.md | 19 ++- docs/core-data-structures/session-query.md | 30 +++++ .../session-query-spill/stdout.expected.jsonl | 2 +- .../tests/session-reference.spec.ts | 7 +- .../cordis/tool-cordis/src/api-catalog.ts | 24 +++- .../session-query-sqlite/src/index.ts | 63 ++++++---- .../session-query-sqlite/tests/sqlite.spec.ts | 7 +- .../session-query/session-query/README.md | 6 +- .../session-query/session-query/src/index.ts | 33 ++++-- .../session-query/session-query/src/types.ts | 21 ++++ .../tests/search-helpers.spec.ts | 4 +- .../session-query/tests/test-service.ts | 13 ++- .../tool-session-query/src/index.ts | 60 +++++++--- .../tests/tool-session-query.spec.ts | 109 +++++++++++++++--- .../support/acp-snapshot/src/normalize.ts | 3 + .../acp-snapshot/tests/normalize.spec.ts | 8 +- packages/ui/acp/tests/harness.ts | 7 +- packages/ui/tui/tests/session-query.ts | 7 +- scripts/gen-cordis-catalog.ts | 3 + scripts/type-equiv.manifest.json | 15 +++ 24 files changed, 361 insertions(+), 100 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml index 8169bc5977..361145cb02 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 -2026-07-24-model-facing-session-query-tools.md: 521b62fdc668f5c2e208118640be5cec99561a5c -2026-07-24-model-facing-session-query-tools.zh.md: 9be772b33e0e14f503ab2c762a831493381266fd +2026-07-24-model-facing-session-query-tools.md: 68169d8af7176ee1725a3c58bf97530f56a0765b +2026-07-24-model-facing-session-query-tools.zh.md: dfeae26a548b5e498e76fce259f7610106de7ec2 diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md index 521b62fdc6..68169d8af7 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -18,7 +18,7 @@ Model-facing filters use flat snake-case fields. Timestamps are timezone-qualifi ## Workspace authority -Every executor derives its caller from immutable `ToolExecution.exec.agent` identity and never accepts a model-supplied workspace. A target is authorized only when its persisted `cwd` exactly equals the caller session's `cwd`. Cross-session search always adds that workspace filter, direct reads and traces authorize before loading the target, and lineage rendering stops at an unauthorized ancestor or descendant subtree without revealing the hidden session id. A caller whose session has no `cwd` can inspect only its own session; missing agent identity fails closed. +Every executor derives its caller from immutable `ToolExecution.exec.agent` identity and never accepts a model-supplied workspace. A target is authorized only when its observed `cwd` exactly equals the caller session's `cwd`. Cross-session search always adds that workspace filter. Direct operations preflight the target and then validate the header returned from the same service observation as every event-search page, event trace, event read, lineage target, or folded title before rendering its payload. This prevents a live or persisted target replacement between the check and use from crossing the workspace boundary. Lineage rendering stops at an unauthorized ancestor or descendant subtree without revealing the hidden session id. A caller whose session has no `cwd` can inspect only its own session; missing agent identity fails closed. The search tools expose prior work rather than the operation that is performing the search. `session_search` omits the caller's session. When `session_event_search` targets the caller's session, it intersects the requested sequence range with the event immediately before the current `step/start`, excluding the current assistant message and tool call as well as the query arguments indexed from that call. @@ -28,7 +28,7 @@ Neither search tool exposes a cursor, offset, page size, or model-controlled res Trace and read tools likewise expose no lineage or character pagination. Canonical results are plain text and remain complete within the service's existing event-window and search-count resource bounds. The generic `tools/post-execute` spill policy owns inline byte retention: when a configured deployment receives oversized text, it replaces that text with a bounded preview plus an opaque locator and retrieval hint while preserving the complete result in its spill store. The session-query consumer neither imports `ctx.spillStore` nor implements a second truncation format. -Session-level results include the latest folded title when available. Absence is rendered as untitled; a title read failure preserves the base result, renders an unavailable marker, and logs the underlying error. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. +Session-level results include the latest folded title when available. Absence is rendered as untitled; an operational title read failure preserves the base result, renders an unavailable marker, and logs the underlying error, while an authorization mismatch fails closed. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. ## Host composition @@ -44,7 +44,7 @@ The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.se ## Verification -Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus exact event-read spill and retention behavior. +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md index 9be772b33e..dfeae26a54 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -18,7 +18,7 @@ Status: implemented ## 工作区权限 -每个执行器都从不可变的 `ToolExecution.exec.agent` 身份推导调用者,绝不接受模型提供的工作区。只有当目标持久化的 `cwd` 与调用者会话的 `cwd` 完全相同时,目标才获授权。跨会话搜索始终附加该工作区过滤条件;直接读取与追踪在加载目标前完成授权;谱系渲染在遇到未授权的祖先或后代子树时停止,且不泄露被隐藏的会话 id。调用者会话没有 `cwd` 时只能检查自身会话;缺少 agent 身份时按失败关闭处理。 +每个执行器都从不可变的 `ToolExecution.exec.agent` 身份推导调用者,绝不接受模型提供的工作区。只有当目标观测中的 `cwd` 与调用者会话的 `cwd` 完全相同时,目标才获授权。跨会话搜索始终附加该工作区过滤条件。直接操作先预检目标,然后在渲染负载前,校验与每一页事件搜索结果、事件追踪、事件读取、谱系目标或折叠标题来自同一服务观测的会话头。这样,即使实时或持久化目标在检查与使用之间被替换,也无法跨越工作区边界。谱系渲染在遇到未授权的祖先或后代子树时停止,且不泄露被隐藏的会话 id。调用者会话没有 `cwd` 时只能检查自身会话;缺少 agent 身份时按失败关闭处理。 搜索工具公开的是既往工作,而不是正在执行搜索的操作本身。`session_search` 排除调用者会话。`session_event_search` 以调用者会话为目标时,会把请求的序号范围与当前 `step/start` 之前的最后一个事件取交集,从而排除当前 assistant 消息、工具调用,以及从该次调用中建立索引的查询参数。 @@ -28,7 +28,7 @@ Status: implemented 追踪与读取工具同样不公开谱系分页或字符分页。规范结果采用纯文本,并在服务已有的事件窗口与搜索数量资源边界内保持完整。通用的 `tools/post-execute` spill 策略负责行内字节保留:当已配置的部署收到过大的文本时,该策略会用有界预览、不可透明推导的定位符与读取提示替换文本,同时在 spill 存储中保留完整结果。会话查询消费者既不导入 `ctx.spillStore`,也不实现第二套截断格式。 -会话级结果在可用时包含最新折叠标题。没有标题时渲染为未命名;标题读取失败时保留基础结果,渲染不可用标记,并记录底层错误。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 +会话级结果在可用时包含最新折叠标题。没有标题时渲染为未命名;标题读取发生操作性失败时保留基础结果、渲染不可用标记并记录底层错误,而授权不匹配则按失败关闭处理。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 ## 宿主组合 @@ -44,7 +44,7 @@ Status: implemented ## 验证 -包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及精确事件读取的 spill 与保留行为。 +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 ## 后果 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d76443579a..3fb5238ff0 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1027,7 +1027,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' Depends on: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) -Source: [`packages/session-query/session-query-sqlite/src/index.ts:74`](../packages/session-query/session-query-sqlite/src/index.ts) +Source: [`packages/session-query/session-query-sqlite/src/index.ts:75`](../packages/session-query/session-query-sqlite/src/index.ts) ## `@deepseek-ai/dsh-session-reference` @@ -1437,7 +1437,7 @@ export interface Config { } ``` -Source: [`packages/session-query/tool-session-query/src/index.ts:50`](../packages/session-query/tool-session-query/src/index.ts) +Source: [`packages/session-query/tool-session-query/src/index.ts:51`](../packages/session-query/tool-session-query/src/index.ts) ## `@deepseek-ai/dsh-tool-skill` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index c5d6d88d5c..a01b275a30 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -986,9 +986,9 @@ abstract searchSessions( request: SessionSearchRequest, exec?: SessionSearchExec * Search events within one live-preferred logical session. * @param request - target session, query text, filters, page size, and cursor. * @param exec - optional cancellation control. - * @returns matching event hits in deterministic relevance order. + * @returns matching event hits and their target header from one indexed generation. */ -abstract searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, ): Promise> +abstract searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, ): Promise /** * List the complete logical corpus using live-preferred records. @@ -1010,6 +1010,13 @@ async filterSessions(filters: readonly SessionResultFilter[]): Promise +/** + * Fold the latest title and return its source header from one corpus observation. + * @param sessionId - live or persisted session id to read. + * @returns cloned source header and optional latest title snapshot. + */ +async readTitleSnapshot(sessionId: SessionId): Promise + /** * List lightweight raw-log event records for one logical session. * @param sessionId - live-preferred session id to read. @@ -1044,10 +1051,10 @@ async traceSession(sessionId: SessionId): Promise /** * Trace one event's direct positional and provenance relationships. * @param request - target session id and event seq. - * @returns direct links plus the target's positional replacement chain. + * @returns source header, direct links, and the target's positional replacement chain. * @throws when source resolution fails, the target is absent, or surface/provenance validation fails. */ -async traceEvent(request: SessionEventTraceRequest): Promise +async traceEvent(request: SessionEventTraceRequest): Promise /** * Read one full event plus a bounded raw-log context window. @@ -1057,9 +1064,9 @@ async traceEvent(request: SessionEventTraceRequest): Promise async readEvent(request: SessionEventReadRequest): Promise ``` -Types: [SessionEventReadRequest](../core-data-structures/session-query.md) · [SessionEventRecord](../core-data-structures/session-query.md) · [SessionEventResultFilter](../core-data-structures/session-query.md) · [SessionEventSearchDocument](../core-data-structures/session-query.md) · [SessionEventSearchHit](../core-data-structures/session-query.md) · [SessionEventSearchRequest](../core-data-structures/session-query.md) · [SessionEventTrace](../core-data-structures/session-query.md) · [SessionEventTraceRequest](../core-data-structures/session-query.md) · [SessionEventWindow](../core-data-structures/session-query.md) · [SessionId](../core-data-structures/core.md) · [SessionLineageTrace](../core-data-structures/session-query.md) · [SessionRecord](../core-data-structures/session-query.md) · [SessionResultFilter](../core-data-structures/session-query.md) · [SessionSearchExecContext](../core-data-structures/session-query.md) · [SessionSearchHit](../core-data-structures/session-query.md) · [SessionSearchPage](../core-data-structures/session-query.md) · [SessionSearchRequest](../core-data-structures/session-query.md) · [SessionSurfaceSnapshot](../core-data-structures/session-query.md) · [SessionTitleSnapshot](../core-data-structures/session-title.md) +Types: [SessionEventReadRequest](../core-data-structures/session-query.md) · [SessionEventRecord](../core-data-structures/session-query.md) · [SessionEventResultFilter](../core-data-structures/session-query.md) · [SessionEventSearchDocument](../core-data-structures/session-query.md) · [SessionEventSearchPage](../core-data-structures/session-query.md) · [SessionEventSearchRequest](../core-data-structures/session-query.md) · [SessionEventTraceObservation](../core-data-structures/session-query.md) · [SessionEventTraceRequest](../core-data-structures/session-query.md) · [SessionEventWindow](../core-data-structures/session-query.md) · [SessionId](../core-data-structures/core.md) · [SessionLineageTrace](../core-data-structures/session-query.md) · [SessionRecord](../core-data-structures/session-query.md) · [SessionResultFilter](../core-data-structures/session-query.md) · [SessionSearchExecContext](../core-data-structures/session-query.md) · [SessionSearchHit](../core-data-structures/session-query.md) · [SessionSearchPage](../core-data-structures/session-query.md) · [SessionSearchRequest](../core-data-structures/session-query.md) · [SessionSurfaceSnapshot](../core-data-structures/session-query.md) · [SessionTitleObservation](../core-data-structures/session-query.md) · [SessionTitleSnapshot](../core-data-structures/session-title.md) -Source: [`packages/session-query/session-query/src/index.ts:73`](../../packages/session-query/session-query/src/index.ts) +Source: [`packages/session-query/session-query/src/index.ts:74`](../../packages/session-query/session-query/src/index.ts) ## `ctx.sessionReferences` — `SessionReferenceService` diff --git a/docs/core-data-structures/session-query.md b/docs/core-data-structures/session-query.md index 0fe1596aaf..2cd7650dbc 100644 --- a/docs/core-data-structures/session-query.md +++ b/docs/core-data-structures/session-query.md @@ -39,6 +39,18 @@ interface SessionSurfaceSnapshot { } ``` +`SessionTitleObservation` applies the same atomic-observation rule to title folding, so an authorization consumer can validate the source header that supplied the title. + +```ts type-equiv +/** Latest folded title bound to the same session-header observation. */ +interface SessionTitleObservation { + /** Cloned header selected with the event log used for the title fold. */ + session: SessionHeader + /** Latest title snapshot, absent when the observed log has no title. */ + title?: SessionTitleSnapshot +} +``` + ```ts type-equiv /** Lightweight metadata for one event within a logical session. */ interface SessionEventRecord { @@ -146,6 +158,16 @@ interface SessionSearchPage { } ``` +Unlike grouped cross-session hits, a within-session search must also expose its observed target header even when the page contains no hits. + +```ts type-equiv +/** Event-search results bound to the indexed target-session observation. */ +interface SessionEventSearchPage extends SessionSearchPage { + /** Cloned target header from the same indexed generation as `items`. */ + session: SessionHeader +} +``` + ```ts type-equiv /** One event full-text search hit with a bounded plain-text excerpt. */ interface SessionEventSearchHit extends SessionEventRecord { @@ -267,6 +289,14 @@ interface SessionEventTrace { } ``` +```ts type-equiv +/** Event relationships bound to the same session-header observation. */ +interface SessionEventTraceObservation extends SessionEventTrace { + /** Cloned header selected with the event log used for the trace. */ + session: SessionHeader +} +``` + ## Errors The closed code union distinguishes request validation, missing targets, malformed surface logs, optional-backend failure, and contradictory source metadata. diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl index e0629f89a2..0f4bee73ca 100644 --- a/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl +++ b/examples/acp-agent/tests/snapshots/session-query-spill/stdout.expected.jsonl @@ -3,7 +3,7 @@ {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[|clear|edit |pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"Read request event 4 with","updatedAt":"{{updatedAt}}"}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_session_query_spill","title":"Read event 4","kind":"read","status":"in_progress","rawInput":{"seq":4}}}} -{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": {{eventTime}},\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted 39431 bytes. Full formatted result stored at: {{spillLocator:session_event_read.txt}}. Use read with offset/limit, or grep this path to search within it.)"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": {{eventTime}},\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted {{eventOmittedBytes}} bytes. Full formatted result stored at: {{spillLocator:session_event_read.txt}}. Use read with offset/limit, or grep this path to search within it.)"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call","toolCallId":"call_verify_session_query_spill","title":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \"$file\" && grep -q session_event_search \"$file\" && echo SPILL_CANONICAL_OK","kind":"execute","status":"in_progress","rawInput":"file=$(find /tmp/dsh-acp-snap-035d1d054 -name '*-session_event_read.txt' -type f); grep -q request/header \"$file\" && grep -q session_event_search \"$file\" && echo SPILL_CANONICAL_OK","content":[{"type":"content","content":{"type":"text","text":"Verify complete session query spill"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"tool_call_update","toolCallId":"call_verify_session_query_spill","status":"completed","content":[{"type":"content","content":{"type":"text","text":"```console\nSPILL_CANONICAL_OK\n```"}}]}}} {"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"DONE"}}}} diff --git a/packages/context/session-reference/tests/session-reference.spec.ts b/packages/context/session-reference/tests/session-reference.spec.ts index 2470ae8d93..4bcc95af16 100644 --- a/packages/context/session-reference/tests/session-reference.spec.ts +++ b/packages/context/session-reference/tests/session-reference.spec.ts @@ -23,9 +23,12 @@ class TestSessionQueryService extends SessionQueryService { } override searchEvents( - ..._args: Parameters + ...args: Parameters ): ReturnType { - return Promise.resolve({ items: [] }) + return this.readSurface(args[0].sessionId).then(surface => ({ + session: surface.session, + items: [], + })) } } diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index ffc1670f4e..caab8c0076 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -491,8 +491,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ jsDoc: '/**\n * Search the live-preferred logical corpus and group by session.\n * @param request - query text, metadata filters, page size, and cursor.\n * @param exec - optional cancellation control.\n * @returns session hits ranked by their strongest matching event.\n */', }, { - signature: 'abstract searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, ): Promise>', - jsDoc: '/**\n * Search events within one live-preferred logical session.\n * @param request - target session, query text, filters, page size, and cursor.\n * @param exec - optional cancellation control.\n * @returns matching event hits in deterministic relevance order.\n */', + signature: 'abstract searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, ): Promise', + jsDoc: '/**\n * Search events within one live-preferred logical session.\n * @param request - target session, query text, filters, page size, and cursor.\n * @param exec - optional cancellation control.\n * @returns matching event hits and their target header from one indexed generation.\n */', }, { signature: 'listSessions(): Promise', @@ -506,6 +506,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: 'async readTitle(sessionId: SessionId): Promise', jsDoc: '/**\n * Fold the latest log-backed title from one live-preferred logical session.\n * @param sessionId - live or persisted session id to read.\n * @returns latest title snapshot, or `undefined` when the log has no title event.\n */', }, + { + signature: 'async readTitleSnapshot(sessionId: SessionId): Promise', + jsDoc: '/**\n * Fold the latest title and return its source header from one corpus observation.\n * @param sessionId - live or persisted session id to read.\n * @returns cloned source header and optional latest title snapshot.\n */', + }, { signature: 'async listEvents(sessionId: SessionId): Promise', jsDoc: '/**\n * List lightweight raw-log event records for one logical session.\n * @param sessionId - live-preferred session id to read.\n * @returns event records in ascending seq order.\n */', @@ -523,8 +527,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ jsDoc: '/**\n * Trace known ancestry and descendants from one corpus observation.\n * @param sessionId - logical session id to trace.\n * @returns a complete lineage or an explicit unresolved parent boundary.\n * @throws when corpus resolution fails, the target is absent, or its known ancestry cycles.\n */', }, { - signature: 'async traceEvent(request: SessionEventTraceRequest): Promise', - jsDoc: '/**\n * Trace one event\'s direct positional and provenance relationships.\n * @param request - target session id and event seq.\n * @returns direct links plus the target\'s positional replacement chain.\n * @throws when source resolution fails, the target is absent, or surface/provenance validation fails.\n */', + signature: 'async traceEvent(request: SessionEventTraceRequest): Promise', + jsDoc: '/**\n * Trace one event\'s direct positional and provenance relationships.\n * @param request - target session id and event seq.\n * @returns source header, direct links, and the target\'s positional replacement chain.\n * @throws when source resolution fails, the target is absent, or surface/provenance validation fails.\n */', }, { signature: 'async readEvent(request: SessionEventReadRequest): Promise', @@ -1761,6 +1765,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionEventSearchHit', declaration: 'export interface SessionEventSearchHit extends SessionEventRecord {\n snippet: string;\n}', }, + { + name: 'SessionEventSearchPage', + declaration: 'export interface SessionEventSearchPage extends SessionSearchPage {\n session: SessionHeader;\n}', + }, { name: 'SessionEventSearchRequest', declaration: 'export interface SessionEventSearchRequest {\n sessionId: SessionId;\n query: string;\n filters?: readonly SessionEventMetadataFilter[];\n limit?: number;\n cursor?: SessionSearchCursor;\n}', @@ -1773,6 +1781,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionEventTrace', declaration: 'export interface SessionEventTrace {\n target: SessionEventRecord;\n replacedBy?: number;\n replacementChain: number[];\n replacedEventSeqs: number[];\n sourceEventSeqs: number[];\n derivedEventSeqs: number[];\n}', }, + { + name: 'SessionEventTraceObservation', + declaration: 'export interface SessionEventTraceObservation extends SessionEventTrace {\n session: SessionHeader;\n}', + }, { name: 'SessionEventTraceRequest', declaration: 'export interface SessionEventTraceRequest {\n sessionId: SessionId;\n seq: number;\n}', @@ -1873,6 +1885,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionTitleModelProvenance', declaration: 'export interface SessionTitleModelProvenance {\n readonly provider: string;\n readonly model: string;\n}', }, + { + name: 'SessionTitleObservation', + declaration: 'export interface SessionTitleObservation {\n session: SessionHeader;\n title?: SessionTitleSnapshot;\n}', + }, { name: 'SessionTitleProvider', declaration: 'export interface SessionTitleProvider {\n readonly id: SessionTitleProviderId;\n readonly automatic: SessionTitleAutomaticMode;\n generate(request: SessionTitleProviderRequest): Promise;\n}', diff --git a/packages/session-query/session-query-sqlite/src/index.ts b/packages/session-query/session-query-sqlite/src/index.ts index 5e795d4d2c..b3ff8feb07 100644 --- a/packages/session-query/session-query-sqlite/src/index.ts +++ b/packages/session-query/session-query-sqlite/src/index.ts @@ -25,6 +25,7 @@ import type { Config as SessionQueryConfig, SessionEventSearchDocument, SessionEventSearchHit, + SessionEventSearchPage, SessionEventSearchRequest, SessionSearchExecContext, SessionSearchHit, @@ -133,7 +134,7 @@ interface IndexedLiveRow { generation: number } -interface SearchRow { +interface SessionHeaderRow { session_id: string version: number created_at: number @@ -141,6 +142,9 @@ interface SearchRow { parent_session: string | null seed_length: number | null delegation_depth: number | null +} + +interface SearchRow extends SessionHeaderRow { live: number persisted: number seq: number @@ -247,27 +251,30 @@ export class SessionQuerySqlite extends SessionQueryService { override async searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, - ): Promise> { + ): Promise { const normalized = normalizeEventRequest(request, this.config) const signal = exec?.signal return this._serialized(signal, async () => { await this._ensureReady(signal) const persistenceBinding = await this._reconcile(signal) assertNotAborted(signal) - const generation = this._targetGeneration(normalized.sessionId, persistenceBinding) + const target = this._targetObservation(normalized.sessionId, persistenceBinding) const fingerprint = requestFingerprint(normalized) const offset = normalized.cursor === undefined ? 0 - : decodeCursor(normalized.cursor, this._instance, 'events', fingerprint, generation) + : decodeCursor(normalized.cursor, this._instance, 'events', fingerprint, target.generation) const rows = this._queryEvents(normalized, offset, persistenceBinding) - return page(rows, normalized.limit, row => this._eventHit(row), cursorOffset => encodeCursor({ - version: 1, - instance: this._instance, - scope: 'events', - fingerprint, - generation, - offset: cursorOffset, - }), offset) + return { + session: target.header, + ...page(rows, normalized.limit, row => this._eventHit(row), cursorOffset => encodeCursor({ + version: 1, + instance: this._instance, + scope: 'events', + fingerprint, + generation: target.generation, + offset: cursorOffset, + }), offset), + } }) } @@ -643,17 +650,33 @@ export class SessionQuerySqlite extends SessionQueryService { `).all(...bindings) as unknown as SearchRow[] } - private _targetGeneration(sessionId: SessionId, persistenceBinding: PersistenceBinding): string { + private _targetObservation( + sessionId: SessionId, + persistenceBinding: PersistenceBinding, + ): { header: SessionHeader; generation: string } { const db = this._requireDb() const live = db.prepare( - 'SELECT generation FROM temp.live_sessions WHERE id = ?', - ).get(sessionId) as { generation: number } | undefined - if (live !== undefined) return `live:${live.generation}` + `SELECT + id AS session_id, version, created_at, cwd, parent_session, seed_length, delegation_depth, generation + FROM temp.live_sessions + WHERE id = ?`, + ).get(sessionId) as (SessionHeaderRow & { generation: number }) | undefined + if (live !== undefined) { + return { header: rowHeader(live), generation: `live:${live.generation}` } + } if (persistenceBinding.service !== undefined) { const persisted = db.prepare( - 'SELECT generation FROM persisted_sessions WHERE id = ?', - ).get(sessionId) as { generation: number } | undefined - if (persisted !== undefined) return `persisted:${this._persistenceEpoch}:${persisted.generation}` + `SELECT + id AS session_id, version, created_at, cwd, parent_session, seed_length, delegation_depth, generation + FROM persisted_sessions + WHERE id = ?`, + ).get(sessionId) as (SessionHeaderRow & { generation: number }) | undefined + if (persisted !== undefined) { + return { + header: rowHeader(persisted), + generation: `persisted:${this._persistenceEpoch}:${persisted.generation}`, + } + } } throw new SessionQueryError( `session "${sessionId}" not found`, @@ -835,7 +858,7 @@ function sameHeader(a: SessionHeader, b: SessionHeader): boolean { && (a.delegationDepth ?? 0) === (b.delegationDepth ?? 0) } -function rowHeader(row: SearchRow): SessionHeader { +function rowHeader(row: SessionHeaderRow): SessionHeader { return { version: row.version, id: row.session_id as SessionId, diff --git a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts index 1923c6f3eb..71892159d5 100644 --- a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts +++ b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts @@ -179,7 +179,10 @@ describe('SQLite session search', () => { ) await expect(ctx.sessionQuery.searchEvents({ sessionId: session.id, query: 'AI' })) - .resolves.toMatchObject({ items: [{ sessionId: session.id, seq: 0, snippet: 'An AI helper' }] }) + .resolves.toMatchObject({ + session: { ...session.header, seedLength: 1 }, + items: [{ sessionId: session.id, seq: 0, snippet: 'An AI helper' }], + }) await expect(ctx.sessionQuery.searchSessions({ query: 'AI' })) .resolves.toMatchObject({ items: [{ header: { ...session.header, seedLength: 1 }, live: true, persisted: false }] }) }) @@ -1307,7 +1310,7 @@ describe('SQLite schema, cancellation, and real persistence integration', () => await expect(ctx.sessionQuery.searchSessions({ query: 'SQLite needle' })) .resolves.toMatchObject({ items: [{ header: meta, persisted: true, live: false }] }) await expect(ctx.sessionQuery.searchEvents({ sessionId: meta.id, query: 'SQLite needle' })) - .resolves.toMatchObject({ items: [{ sessionId: meta.id, seq: 0 }] }) + .resolves.toMatchObject({ session: meta, items: [{ sessionId: meta.id, seq: 0 }] }) await expect(ctx.sessionQuery.searchEvents({ sessionId: SessionId('absent'), query: 'needle' })) .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND')) await search.dispose() diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index a83317ecf8..2b26ea8e43 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -7,12 +7,12 @@ - `listSessions()` reads current persistence metadata, merges live records with live precedence, and returns cloned records in deterministic newest-first order. - `filterSessions(filters)` applies provider-independent session metadata and availability predicates to that same cloned logical corpus. - `filterEvents(sessionId, filters)` extracts first-party semantic documents and applies provider-independent metadata and literal-text predicates in ascending seq order. -- `readTitle(sessionId)` loads one live-preferred or persisted log and folds its latest `session/title` event into a `SessionTitleSnapshot`; it returns `undefined` when the known session has no title. +- `readTitleSnapshot(sessionId)` loads one live-preferred or persisted log and returns the cloned source header with its latest folded `session/title` event. `readTitle(sessionId)` is the title-only convenience view; it returns `undefined` when the known session has no title. - `listEvents(sessionId)` loads the live-preferred raw log and classifies each event as `current`, `shadowed`, or `log-only` with the shared `dsh-session` surface fold. - `readSurface(sessionId)` returns one cloned header, raw-log capture boundary, and the complete folded current surface in model-history order. A live session wins over persistence; compaction is observed before or after its replacement append, never as a synthetic mixture. - `readEvent(request)` returns a cloned header, the full target event, and a bounded raw-seq window. `before` and `after` default to zero and may not exceed `readWindowMax`. - `traceSession(sessionId)` reads the corpus once and returns immediate-to-outward ancestors plus deterministic recursive descendant trees. `complete: false` identifies the first missing parent; a target-connected cycle fails with `SESSION_QUERY_INVALID_LINEAGE`. -- `traceEvent(request)` loads the logical log once and returns direct positional replacements and direct logged provenance. `replacementChain` follows positional replacers to the final replacement; provenance links remain non-transitive. +- `traceEvent(request)` loads the logical log once and returns its cloned source header with direct positional replacements and direct logged provenance. `replacementChain` follows positional replacers to the final replacement; provenance links remain non-transitive. Persistence is optional and may mount or unmount dynamically. Cross-corpus listing and lineage tracing fail with `SESSION_QUERY_PERSISTENCE_FAILED` while mounted persistence is unreadable. A title, event read, or trace targeting a known live session does not consult persistence, so durable backend health cannot make current in-memory state unreadable. Persisted title and event operations list before loading and reject a metadata mismatch rather than combining inconsistent observations. `listSessions()` remains lightweight and does not load logs or index titles. @@ -24,7 +24,7 @@ The text clause is deliberately independent of FTS providers: caller text is esc ## Full-text methods -`SessionQueryService.searchSessions(request, exec?)` groups the logical corpus by strongest matching event; `searchEvents(request, exec?)` searches one logical session. These are the service's only abstract methods. Both return pages whose continuation is an owned branded `SessionSearchCursor`, accept optional cancellation, and expose snippets without provider-specific numeric scores. Search requests accept only metadata event filters, because literal-text filtering is the scan path described above. +`SessionQueryService.searchSessions(request, exec?)` groups the logical corpus by strongest matching event; `searchEvents(request, exec?)` searches one logical session. These are the service's only abstract methods. Both return pages whose continuation is an owned branded `SessionSearchCursor`, accept optional cancellation, and expose snippets without provider-specific numeric scores. An event-search page also carries the cloned target header from the same indexed generation as its hits, allowing authorization consumers to bind policy to the payload observation. Search requests accept only metadata event filters, because literal-text filtering is the scan path described above. The package has no provider coordinator, fallback implementation, or standalone concrete plugin. A concrete service backend inherits the implemented reads, filters, and traces while owning full-text observation, reconciliation, ranking, cursor generations, and query execution; the first implementation is [`@deepseek-ai/dsh-session-query-sqlite`](../session-query-sqlite/README.md). diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index 2028f908c1..9f44a103fc 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -10,12 +10,12 @@ import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' import type { SessionEventResultFilter, + SessionEventSearchPage, SessionEventReadRequest, SessionEventRecord, - SessionEventSearchHit, SessionEventSearchDocument, SessionEventSearchRequest, - SessionEventTrace, + SessionEventTraceObservation, SessionEventTraceRequest, SessionEventWindow, SessionLineageTrace, @@ -26,6 +26,7 @@ import type { SessionSearchPage, SessionSearchRequest, SessionSurfaceSnapshot, + SessionTitleObservation, } from './types.ts' import { SESSION_QUERY_READ_WINDOW_MAX, @@ -103,12 +104,12 @@ export abstract class SessionQueryService extends Service { * Search events within one live-preferred logical session. * @param request - target session, query text, filters, page size, and cursor. * @param exec - optional cancellation control. - * @returns matching event hits in deterministic relevance order. + * @returns matching event hits and their target header from one indexed generation. */ abstract searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, - ): Promise> + ): Promise /** * List the complete logical corpus using live-preferred records. @@ -134,8 +135,21 @@ export abstract class SessionQueryService extends Service { * @returns latest title snapshot, or `undefined` when the log has no title event. */ async readTitle(sessionId: SessionId): Promise { + return (await this.readTitleSnapshot(sessionId)).title + } + + /** + * Fold the latest title and return its source header from one corpus observation. + * @param sessionId - live or persisted session id to read. + * @returns cloned source header and optional latest title snapshot. + */ + async readTitleSnapshot(sessionId: SessionId): Promise { const loaded = await this._corpus.load(sessionId) - return foldSessionTitle(loaded.events) + const title = foldSessionTitle(loaded.events) + return { + session: loaded.header, + ...title === undefined ? {} : { title }, + } } /** @@ -204,12 +218,15 @@ export abstract class SessionQueryService extends Service { /** * Trace one event's direct positional and provenance relationships. * @param request - target session id and event seq. - * @returns direct links plus the target's positional replacement chain. + * @returns source header, direct links, and the target's positional replacement chain. * @throws when source resolution fails, the target is absent, or surface/provenance validation fails. */ - async traceEvent(request: SessionEventTraceRequest): Promise { + async traceEvent(request: SessionEventTraceRequest): Promise { const loaded = await this._corpus.load(request.sessionId) - return tracing.traceEvent(request.sessionId, loaded.events, request.seq) + return { + session: loaded.header, + ...tracing.traceEvent(request.sessionId, loaded.events, request.seq), + } } /** diff --git a/packages/session-query/session-query/src/types.ts b/packages/session-query/session-query/src/types.ts index b231bd9f78..72537918e1 100644 --- a/packages/session-query/session-query/src/types.ts +++ b/packages/session-query/session-query/src/types.ts @@ -12,6 +12,7 @@ import type { SessionId, SurfaceEvent, } from '@deepseek-ai/dsh-session' +import type { SessionTitleSnapshot } from '@deepseek-ai/dsh-session-title' import type { SessionSearchCursor } from './cursor.ts' export type { SessionSearchCursor } from './cursor.ts' @@ -108,6 +109,12 @@ export interface SessionEventTrace { derivedEventSeqs: number[] } +/** Event relationships bound to the same session-header observation. */ +export interface SessionEventTraceObservation extends SessionEventTrace { + /** Cloned header selected with the event log used for the trace. */ + session: SessionHeader +} + /** Request for one event plus raw neighboring log context. */ export interface SessionEventReadRequest { /** Session that owns the target event. */ @@ -134,6 +141,14 @@ export interface SessionEventWindow { endSeq: number } +/** Latest folded title bound to the same session-header observation. */ +export interface SessionTitleObservation { + /** Cloned header selected with the event log used for the title fold. */ + session: SessionHeader + /** Latest title snapshot, absent when the observed log has no title. */ + title?: SessionTitleSnapshot +} + /** Inclusive numeric interval used by time and sequence filters. */ export interface SessionResultRange { /** Inclusive lower bound. */ @@ -184,6 +199,12 @@ export interface SessionSearchPage { nextCursor?: SessionSearchCursor } +/** Event-search results bound to the indexed target-session observation. */ +export interface SessionEventSearchPage extends SessionSearchPage { + /** Cloned target header from the same indexed generation as `items`. */ + session: SessionHeader +} + /** Controls shared by cross-session and within-session search calls. */ export interface SessionSearchExecContext { /** Abort caller waiting and interrupt provider work where supported. */ diff --git a/packages/session-query/session-query/tests/search-helpers.spec.ts b/packages/session-query/session-query/tests/search-helpers.spec.ts index 327048b8c1..e141487f32 100644 --- a/packages/session-query/session-query/tests/search-helpers.spec.ts +++ b/packages/session-query/session-query/tests/search-helpers.spec.ts @@ -213,8 +213,10 @@ it('registers exact and abstract search behavior under one ctx key', async () => const ctx = new Context() await ctx.plugin(SessionStore) const fiber = await ctx.plugin(TestSessionQueryService) + const session = ctx.sessions.create(id) await expect(ctx.sessionQuery.searchSessions({ query: 'AI' })).resolves.toEqual({ items: [] }) - await expect(ctx.sessionQuery.searchEvents({ sessionId: id, query: 'AI' })).resolves.toEqual({ items: [] }) + await expect(ctx.sessionQuery.searchEvents({ sessionId: id, query: 'AI' })) + .resolves.toEqual({ session: session.header, items: [] }) await fiber.dispose() expect(ctx.sessionQuery).toBeUndefined() }) diff --git a/packages/session-query/session-query/tests/test-service.ts b/packages/session-query/session-query/tests/test-service.ts index e37b0f71ff..9572e76e08 100644 --- a/packages/session-query/session-query/tests/test-service.ts +++ b/packages/session-query/session-query/tests/test-service.ts @@ -1,6 +1,6 @@ import SessionQueryService from '@deepseek-ai/dsh-session-query' import type { - SessionEventSearchHit, + SessionEventSearchPage, SessionEventSearchRequest, SessionSearchExecContext, SessionSearchHit, @@ -17,10 +17,13 @@ export class TestSessionQueryService extends SessionQueryService { return Promise.resolve({ items: [] }) } - override searchEvents( - _request: SessionEventSearchRequest, + override async searchEvents( + request: SessionEventSearchRequest, _exec?: SessionSearchExecContext, - ): Promise> { - return Promise.resolve({ items: [] }) + ): Promise { + return { + session: (await this.readSurface(request.sessionId)).session, + items: [], + } } } diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index 02b6d2ceb8..92be54d46b 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -20,9 +20,10 @@ import { extractSessionEventText, type SessionAvailability, type SessionEventMetadataFilter, + type SessionEventSearchPage, type SessionEventSearchHit, type SessionEventSurface, - type SessionEventTrace, + type SessionEventTraceObservation, type SessionEventWindow, type SessionLineageNode, type SessionLineageTrace, @@ -352,7 +353,7 @@ async function executeSessionSearch( .map(hit => hit.header.parentSession) .filter((id): id is SessionIdValue => id !== undefined) const authorizedParents = await authorizeSessionIds(ctx, caller, parentIds, exec.signal) - const titles = await readTitles(ctx, collected.items.map(hit => hit.header.id), exec.signal) + const titles = await readTitles(ctx, caller, collected.items.map(hit => hit.header.id), exec.signal) return formatSessionSearch(collected, titles, authorizedParents) } @@ -377,7 +378,7 @@ async function executeEventSearch( } range.to = Math.min(range.to ?? Number.MAX_SAFE_INTEGER, stepStart.seq - 1) } - const title = await readTitle(ctx, sessionId, exec.signal) + const title = await readTitle(ctx, caller, sessionId, exec.signal) if (range.from !== undefined && range.to !== undefined && range.from > range.to) { return formatEventSearch(sessionId, title, { items: [], capped: false }) } @@ -392,12 +393,16 @@ async function executeEventSearch( const collected = await collectPages( maxResults, exec.signal, - cursor => ctx.sessionQuery.searchEvents({ - sessionId, - query, - filters, - ...cursor === undefined ? {} : { cursor }, - }, { signal: exec.signal }), + async (cursor): Promise => { + const page = await ctx.sessionQuery.searchEvents({ + sessionId, + query, + filters, + ...cursor === undefined ? {} : { cursor }, + }, { signal: exec.signal }) + assertObservedTargetAuthorized(caller, sessionId, page.session) + return page + }, () => true, ) return formatEventSearch(sessionId, title, collected) @@ -413,6 +418,7 @@ async function executeSessionTrace( await authorizeTarget(ctx, caller, sessionId, exec.signal) const trace = await ctx.sessionQuery.traceSession(sessionId) exec.signal.throwIfAborted() + assertObservedTargetAuthorized(caller, sessionId, trace.target.header) const ancestors: SessionRecord[] = [] let ancestorBoundary = false @@ -430,7 +436,7 @@ async function executeSessionTrace( ...ancestors.map(record => record.header.id), ...descendantIds(descendants), ] - const titles = await readTitles(ctx, visibleIds, exec.signal) + const titles = await readTitles(ctx, caller, visibleIds, exec.signal) return formatSessionTrace(trace, ancestors, ancestorBoundary, descendants, titles) } @@ -445,7 +451,8 @@ async function executeEventTrace( await authorizeTarget(ctx, caller, sessionId, exec.signal) const trace = await ctx.sessionQuery.traceEvent({ sessionId, seq: args.seq }) exec.signal.throwIfAborted() - const title = await readTitle(ctx, sessionId, exec.signal) + assertObservedTargetAuthorized(caller, sessionId, trace.session) + const title = await readTitle(ctx, caller, sessionId, exec.signal) return formatEventTrace(sessionId, title, trace) } @@ -467,7 +474,8 @@ async function executeEventRead( ...args.after === undefined ? {} : { after: args.after }, }) exec.signal.throwIfAborted() - const title = await readTitle(ctx, sessionId, exec.signal) + assertObservedTargetAuthorized(caller, sessionId, window.session) + const title = await readTitle(ctx, caller, sessionId, exec.signal) return formatEventRead(sessionId, title, window) } @@ -676,8 +684,20 @@ async function collectPages( } function recordAuthorized(record: SessionRecord, caller: Caller): boolean { - if (record.header.id === caller.id) return true - return caller.header.cwd !== undefined && record.header.cwd === caller.header.cwd + return headerAuthorized(record.header, caller) +} + +function headerAuthorized(header: SessionHeader, caller: Caller): boolean { + if (header.id === caller.id) return true + return caller.header.cwd !== undefined && header.cwd === caller.header.cwd +} + +function assertObservedTargetAuthorized( + caller: Caller, + target: SessionIdValue, + observed: SessionHeader, +): void { + if (observed.id !== target || !headerAuthorized(observed, caller)) throw unauthorizedTarget() } async function authorizeSessionIds( @@ -704,28 +724,32 @@ async function authorizeSessionIds( async function readTitles( ctx: Context, + caller: Caller, ids: readonly SessionIdValue[], signal: AbortSignal, ): Promise { const result = new Map() for (const id of new Set(ids)) { - result.set(id, await readTitle(ctx, id, signal)) + result.set(id, await readTitle(ctx, caller, id, signal)) } return result as CompleteTitleMap } async function readTitle( ctx: Context, + caller: Caller, id: SessionIdValue, signal: AbortSignal, ): Promise { signal.throwIfAborted() try { - const title = await ctx.sessionQuery.readTitle(id) + const observation = await ctx.sessionQuery.readTitleSnapshot(id) signal.throwIfAborted() - return { text: title?.title ?? 'untitled' } + assertObservedTargetAuthorized(caller, id, observation.session) + return { text: observation.title?.title ?? 'untitled' } } catch (error: unknown) { if (signal.aborted) signal.throwIfAborted() + if (error instanceof HarnessError && error.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') throw error const code = error instanceof HarnessError ? error.code : 'UNKNOWN' ctx.logger.warn(`tool-session-query: title read failed for session "${id}": ${fullError(error)}`) return { text: 'untitled', unavailableCode: code } @@ -866,7 +890,7 @@ function renderDescendants( function formatEventTrace( sessionId: SessionIdValue, title: TitleView, - trace: SessionEventTrace, + trace: SessionEventTraceObservation, ): string { return [ `Session ${sessionId} — ${titleText(title)}`, diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index 017070eefc..ae62161f14 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -14,6 +14,7 @@ import SessionQueryService, { SessionQueryError, SessionSearchCursor, type SessionEventSearchHit, + type SessionEventSearchPage, type SessionEventSearchRequest, type SessionSearchExecContext, type SessionSearchHit, @@ -113,7 +114,10 @@ class FakeQuery extends SessionQueryService { static eventSearch: ( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, - ) => Promise> = () => Promise.resolve({ items: [] }) + ) => Promise = request => Promise.resolve({ + session: header(request.sessionId, '/work'), + items: [], + }) static sessionRequests: SessionSearchRequest[] = [] static eventRequests: SessionEventSearchRequest[] = [] @@ -122,7 +126,10 @@ class FakeQuery extends SessionQueryService { static reset(): void { this.sessionSearch = () => Promise.resolve({ items: [] }) - this.eventSearch = () => Promise.resolve({ items: [] }) + this.eventSearch = request => Promise.resolve({ + session: header(request.sessionId, '/work'), + items: [], + }) this.sessionRequests = [] this.eventRequests = [] this.searchSignals = [] @@ -141,22 +148,25 @@ class FakeQuery extends SessionQueryService { override searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchExecContext, - ): Promise> { + ): Promise { FakeQuery.eventRequests.push(request) FakeQuery.searchSignals.push(exec?.signal) return FakeQuery.eventSearch(request, exec) } - override async readTitle(sessionId: SessionIdValue) { + override async readTitleSnapshot(sessionId: SessionIdValue) { const value = FakeQuery.titles.get(sessionId) if (value instanceof Error) throw value - if (value === undefined) return super.readTitle(sessionId) + if (value === undefined) return super.readTitleSnapshot(sessionId) return { - title: value, - messageSeqs: [], - source: { kind: 'fallback' as const }, - eventSeq: 0, - updatedAt: 1, + session: (await this.readSurface(sessionId)).session, + title: { + title: value, + messageSeqs: [], + source: { kind: 'fallback' as const }, + eventSeq: 0, + updatedAt: 1, + }, } } } @@ -477,6 +487,69 @@ describe('workspace authority and lineage redaction', () => { expect(output).toContain(mounted.caller.id) expect(output).toContain('persisted') }) + + it('rejects every payload observation whose target moved after pre-authorization', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'moving-target', '/work') + target.append( + 'user/message', + { content: [{ type: 'text', text: 'authorized payload' }], source: { kind: 'user' } }, + { surfaceOp: 'append' }, + ) + const movedHeader = header(target.id, '/outside') + + FakeQuery.eventSearch = () => Promise.resolve({ + session: movedHeader, + items: [eventHit(target.id, 0, 'secret event hit')], + }) + const search = await mounted.call('session_event_search', { + session_id: target.id, + query: 'secret', + }) + expect(errorCode(search)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + expect(text(search)).not.toContain('secret event hit') + + const lineage = await mounted.ctx.sessionQuery.traceSession(target.id) + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValueOnce({ + ...lineage, + target: { ...lineage.target, header: movedHeader }, + }) + expect(errorCode(await mounted.call('session_trace', { session_id: target.id }))) + .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + + const eventTrace = await mounted.ctx.sessionQuery.traceEvent({ sessionId: target.id, seq: 0 }) + vi.spyOn(mounted.ctx.sessionQuery, 'traceEvent').mockResolvedValueOnce({ + ...eventTrace, + session: movedHeader, + }) + expect(errorCode(await mounted.call('session_event_trace', { session_id: target.id, seq: 0 }))) + .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + + const eventWindow = await mounted.ctx.sessionQuery.readEvent({ sessionId: target.id, seq: 0 }) + vi.spyOn(mounted.ctx.sessionQuery, 'readEvent').mockResolvedValueOnce({ + ...eventWindow, + session: movedHeader, + }) + expect(errorCode(await mounted.call('session_event_read', { session_id: target.id, seq: 0 }))) + .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + + FakeQuery.sessionSearch = () => Promise.resolve({ + items: [sessionHit(target.id, '/work', 'safe hit')], + }) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockResolvedValueOnce({ + session: movedHeader, + title: { + title: 'secret moved title', + messageSeqs: [], + source: { kind: 'fallback' }, + eventSeq: 0, + updatedAt: 1, + }, + }) + const titled = await mounted.call('session_search', { query: 'safe' }) + expect(errorCode(titled)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + expect(text(titled)).not.toContain('secret moved title') + }) }) describe('search paging, prior-history bounds, titles, and cancellation', () => { @@ -590,6 +663,7 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => it('intersects current-session search with the event before the latest step and leaves other targets unchanged', async () => { const mounted = await mount() FakeQuery.eventSearch = request => Promise.resolve({ + session: header(request.sessionId, '/work'), items: [eventHit(request.sessionId, 1)], }) await mounted.call('session_event_search', { @@ -633,8 +707,15 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const other = createSession(mounted.ctx, 'paged-events', '/work') const cursor = SessionSearchCursor('events-next') FakeQuery.eventSearch = request => request.cursor === undefined - ? Promise.resolve({ items: [eventHit(other.id, 1)], nextCursor: cursor }) - : Promise.resolve({ items: [eventHit(other.id, 2), eventHit(other.id, 3)] }) + ? Promise.resolve({ + session: header(other.id, '/work'), + items: [eventHit(other.id, 1)], + nextCursor: cursor, + }) + : Promise.resolve({ + session: header(other.id, '/work'), + items: [eventHit(other.id, 2), eventHit(other.id, 3)], + }) const result = await mounted.call('session_event_search', { session_id: other.id, query: 'q', @@ -663,7 +744,7 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const second = createSession(mounted.ctx, 'stackless-title', '/work') const stackless = new Error('stackless') Object.defineProperty(stackless, 'stack', { value: undefined }) - const readTitle = vi.spyOn(mounted.ctx.sessionQuery, 'readTitle') + const readTitle = vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot') .mockRejectedValueOnce('string failure') .mockRejectedValueOnce(stackless) FakeQuery.sessionSearch = () => Promise.resolve({ @@ -685,7 +766,7 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const hit = createSession(mounted.ctx, 'abort-title', '/work') const controller = new AbortController() FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] }) - vi.spyOn(mounted.ctx.sessionQuery, 'readTitle').mockImplementation(() => { + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockImplementation(() => { controller.abort() return Promise.reject(new Error('cancelled title')) }) diff --git a/packages/support/acp-snapshot/src/normalize.ts b/packages/support/acp-snapshot/src/normalize.ts index 258de0fd53..2de8d922db 100644 --- a/packages/support/acp-snapshot/src/normalize.ts +++ b/packages/support/acp-snapshot/src/normalize.ts @@ -13,12 +13,14 @@ const TOOLS = '{{tools}}' const MESSAGE_PREFIX = '{{messagePrefix}}' const UPDATED_AT = '{{updatedAt}}' const EVENT_TIME = '{{eventTime}}' +const EVENT_OMITTED_BYTES = '{{eventOmittedBytes}}' /** A cwd-rooted path after volatile cwd replacement, through its last separator-delimited segment. */ const CWD_ROOTED_PATH_RE = /\{\{cwd\}\}(?:[\\/][^\s<>"'`]+)+/g const PATH_TAG_RE = /()([^<]*)(<\/path>)/g const ADDITIONAL_INSTRUCTIONS_PATH_RE = /(Additional instructions from: )([^\r\n]+)/g const EMBEDDED_EVENT_TIME_RE = /("time": )\d+(?=,\r?\n)/g +const EVENT_READ_OMITTED_BYTES_RE = /(\r?\n\r?\n\(Omitted )\d+( bytes\.)/g const EVENT_READ_RESULT_RE = /^Session [^\r\n]+ — [^\r\n]+\r?\nTarget event seq \d+:\r?\n```json\r?\n\{\r?\n/ @@ -81,6 +83,7 @@ function scrubString(value: string, ctx: NormalizeContext, cwdPathMode: CwdPathM // models, bash, or unrelated tools remains regression-visible. if (EVENT_READ_RESULT_RE.test(out)) { out = out.replace(EMBEDDED_EVENT_TIME_RE, `$1${EVENT_TIME}`) + out = out.replace(EVENT_READ_OMITTED_BYTES_RE, `$1${EVENT_OMITTED_BYTES}$2`) } for (const id of ctx.sessionIds) out = out.split(id).join(SESSION_ID) out = out.replace(UUID_RE, SESSION_ID) diff --git a/packages/support/acp-snapshot/tests/normalize.spec.ts b/packages/support/acp-snapshot/tests/normalize.spec.ts index b4bc813cda..a4d0b4ad95 100644 --- a/packages/support/acp-snapshot/tests/normalize.spec.ts +++ b/packages/support/acp-snapshot/tests/normalize.spec.ts @@ -134,7 +134,7 @@ Additional instructions from: nested\AGENTS.md`, type: 'content', content: { type: 'text', - text: 'Session prior — title\nTarget event seq 4:\n```json\n{\n "seq": 4,\n "time": 1784876275593,\n "data": {}\n}\n```', + text: 'Session prior — title\nTarget event seq 4:\n```json\n{\n "seq": 4,\n "time": 1784876275593,\n "data": {}\n}\n```\n\n(Omitted 39387 bytes. Full formatted result stored at: /tmp/result.txt.)', }, }], }, @@ -142,7 +142,9 @@ Additional instructions from: nested\AGENTS.md`, }) const out = normalizeStdout(raw, ctx) expect(out).toContain('\\"time\\": {{eventTime}}') + expect(out).toContain('Omitted {{eventOmittedBytes}} bytes') expect(out).not.toContain('1784876275593') + expect(out).not.toContain('39387') }) it('preserves event-like timestamps in unrelated output text', () => { @@ -156,7 +158,7 @@ Additional instructions from: nested\AGENTS.md`, type: 'content', content: { type: 'text', - text: 'bash output:\n```json\n{\n "time": 1784876275593,\n "data": {}\n}\n```', + text: 'bash output:\n```json\n{\n "time": 1784876275593,\n "data": {}\n}\n```\n\n(Omitted 39387 bytes. Full formatted result stored at: /tmp/result.txt.)', }, }], }, @@ -164,7 +166,9 @@ Additional instructions from: nested\AGENTS.md`, }) const out = normalizeStdout(raw, ctx) expect(out).toContain('1784876275593') + expect(out).toContain('39387') expect(out).not.toContain('{{eventTime}}') + expect(out).not.toContain('{{eventOmittedBytes}}') }) it('throws on a non-JSON stdout line (the purity check)', () => { diff --git a/packages/ui/acp/tests/harness.ts b/packages/ui/acp/tests/harness.ts index fa7700c5f3..155ccb5b34 100644 --- a/packages/ui/acp/tests/harness.ts +++ b/packages/ui/acp/tests/harness.ts @@ -45,9 +45,12 @@ class TestSessionQueryService extends SessionQueryService { } override searchEvents( - ..._args: Parameters + ...args: Parameters ): ReturnType { - return Promise.resolve({ items: [] }) + return this.readSurface(args[0].sessionId).then(surface => ({ + session: surface.session, + items: [], + })) } } diff --git a/packages/ui/tui/tests/session-query.ts b/packages/ui/tui/tests/session-query.ts index d9083ad6d1..67efcebf45 100644 --- a/packages/ui/tui/tests/session-query.ts +++ b/packages/ui/tui/tests/session-query.ts @@ -9,8 +9,11 @@ export class TestSessionQueryService extends SessionQueryService { } override searchEvents( - ..._args: Parameters + ...args: Parameters ): ReturnType { - return Promise.resolve({ items: [] }) + return this.readSurface(args[0].sessionId).then(surface => ({ + session: surface.session, + items: [], + })) } } diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 8318d59996..ef924b1b03 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -124,8 +124,10 @@ export const LINK_MAP: Record = { SessionEventResultFilter: 'session-query.md', SessionEventSearchDocument: 'session-query.md', SessionEventSearchHit: 'session-query.md', + SessionEventSearchPage: 'session-query.md', SessionEventSearchRequest: 'session-query.md', SessionEventTrace: 'session-query.md', + SessionEventTraceObservation: 'session-query.md', SessionEventTraceRequest: 'session-query.md', SessionEventWindow: 'session-query.md', SessionLineageTrace: 'session-query.md', @@ -135,6 +137,7 @@ export const LINK_MAP: Record = { SessionSearchHit: 'session-query.md', SessionSearchPage: 'session-query.md', SessionSearchRequest: 'session-query.md', + SessionTitleObservation: 'session-query.md', SessionTitleProvider: 'session-title.md', SessionTitleSnapshot: 'session-title.md', SkillDefinition: 'skills.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 89a0778827..6b7d86f77b 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -394,6 +394,11 @@ "symbol": "SessionSurfaceSnapshot", "source": "packages/session-query/session-query/src/types.ts" }, + { + "doc": "docs/core-data-structures/session-query.md", + "symbol": "SessionTitleObservation", + "source": "packages/session-query/session-query/src/types.ts" + }, { "doc": "docs/core-data-structures/session-query.md", "symbol": "SessionEventRecord", @@ -434,6 +439,11 @@ "symbol": "SessionEventTrace", "source": "packages/session-query/session-query/src/types.ts" }, + { + "doc": "docs/core-data-structures/session-query.md", + "symbol": "SessionEventTraceObservation", + "source": "packages/session-query/session-query/src/types.ts" + }, { "doc": "docs/core-data-structures/session-reference.md", "symbol": "SessionReferenceInput", @@ -1194,6 +1204,11 @@ "symbol": "SessionSearchPage", "source": "packages/session-query/session-query/src/types.ts" }, + { + "doc": "docs/core-data-structures/session-query.md", + "symbol": "SessionEventSearchPage", + "source": "packages/session-query/session-query/src/types.ts" + }, { "doc": "docs/core-data-structures/session-query.md", "symbol": "SessionEventSearchHit", From def026e5bc90c3b9eaecf4360c41e19a6b113b88 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 17:06:10 +0800 Subject: [PATCH 008/113] fix: harden session trace authorization --- .../tool-session-query/src/index.ts | 78 +++++++++--- .../tests/tool-session-query.spec.ts | 119 ++++++++++++++++++ 2 files changed, 183 insertions(+), 14 deletions(-) diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index 92be54d46b..e7b8b1ef88 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -131,6 +131,18 @@ interface AuthorizedDescendant { readonly descendants: Array } +interface DescendantProjectionFrame { + readonly node: SessionLineageNode + readonly target: Array + readonly next: DescendantProjectionFrame | undefined +} + +interface DescendantVisit { + readonly node: AuthorizedDescendant | null + readonly depth: number + readonly next: DescendantVisit | undefined +} + const SESSION_SEARCH_PARAMETERS = { query: { type: 'string', required: true, description: 'Literal full-text query over prior session history.' }, session_ids: { type: 'array', items: { type: 'string' }, description: 'Optional session ids to include.' }, @@ -688,7 +700,7 @@ function recordAuthorized(record: SessionRecord, caller: Caller): boolean { } function headerAuthorized(header: SessionHeader, caller: Caller): boolean { - if (header.id === caller.id) return true + if (header.id === caller.id) return header.cwd === caller.header.cwd return caller.header.cwd !== undefined && header.cwd === caller.header.cwd } @@ -764,20 +776,60 @@ function authorizeDescendants( nodes: readonly SessionLineageNode[], caller: Caller, ): Array { - return nodes.map((node) => { - if (!recordAuthorized(node.session, caller)) return null - return { - record: node.session, - descendants: authorizeDescendants(node.descendants, caller), + const result: Array = [] + let pending: DescendantProjectionFrame | undefined + for (const node of [...nodes].reverse()) { + pending = { node, target: result, next: pending } + } + while (pending !== undefined) { + const current = pending + pending = current.next + if (!recordAuthorized(current.node.session, caller)) { + current.target.push(null) + continue } - }) + const projected: AuthorizedDescendant = { + record: current.node.session, + descendants: [], + } + current.target.push(projected) + for (const child of [...current.node.descendants].reverse()) { + pending = { + node: child, + target: projected.descendants, + next: pending, + } + } + } + return result +} + +function * visitDescendants( + nodes: readonly (AuthorizedDescendant | null)[], +): Generator { + let pending: DescendantVisit | undefined + for (const node of [...nodes].reverse()) { + pending = { node, depth: 0, next: pending } + } + while (pending !== undefined) { + const current = pending + pending = current.next + yield current + if (current.node === null) continue + for (const child of [...current.node.descendants].reverse()) { + pending = { + node: child, + depth: current.depth + 1, + next: pending, + } + } + } } function descendantIds(nodes: readonly (AuthorizedDescendant | null)[]): SessionIdValue[] { const ids: SessionIdValue[] = [] - for (const node of nodes) { - if (node === null) continue - ids.push(node.record.header.id, ...descendantIds(node.descendants)) + for (const { node } of visitDescendants(nodes)) { + if (node !== null) ids.push(node.record.header.id) } return ids } @@ -865,7 +917,7 @@ function formatSessionTrace( if (ancestorBoundary) lines.push('- [outside workspace boundary]') lines.push('', 'Descendants:') if (descendants.length === 0) lines.push('- none') - else renderDescendants(lines, descendants, titles, 0) + else renderDescendants(lines, descendants, titles) return lines.join('\n') } @@ -873,9 +925,8 @@ function renderDescendants( lines: string[], nodes: readonly (AuthorizedDescendant | null)[], titles: CompleteTitleMap, - depth: number, ): void { - for (const node of nodes) { + for (const { node, depth } of visitDescendants(nodes)) { const indent = ' '.repeat(depth) if (node === null) { lines.push(`${indent}- [outside workspace subtree]`) @@ -883,7 +934,6 @@ function renderDescendants( } const id = node.record.header.id lines.push(`${indent}- ${id} — ${titleText(titles.get(id))} | ${formatTime(node.record.header.createdAt)} | ${availabilityText(node.record)}`) - renderDescendants(lines, node.descendants, titles, depth + 1) } } diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index ae62161f14..8aa8376d67 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -16,6 +16,7 @@ import SessionQueryService, { type SessionEventSearchHit, type SessionEventSearchPage, type SessionEventSearchRequest, + type SessionLineageNode, type SessionSearchExecContext, type SessionSearchHit, type SessionSearchPage, @@ -450,6 +451,65 @@ describe('workspace authority and lineage redaction', () => { expect(output).not.toContain('hidden-grandchild-secret') }) + it('renders branching descendants in source preorder with one indented marker per pruned subtree', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'branch-target', '/work', 20) + const [targetRecord] = await mounted.ctx.sessionQuery.filterSessions([{ + kind: 'id', + values: [target.id], + }]) + if (targetRecord === undefined) throw new Error('expected target record') + const firstId = SessionId('branch-first') + const nestedId = SessionId('branch-nested') + const hiddenId = SessionId('branch-hidden-secret') + const hiddenDescendantId = SessionId('branch-hidden-descendant-secret') + const lastId = SessionId('branch-last') + const descendants: SessionLineageNode[] = [ + { + session: { ...targetRecord, header: header(firstId, '/work', 30) }, + descendants: [ + { + session: { ...targetRecord, header: header(nestedId, '/work', 40) }, + descendants: [], + }, + { + session: { ...targetRecord, header: header(hiddenId, '/outside', 50) }, + descendants: [{ + session: { ...targetRecord, header: header(hiddenDescendantId, '/work', 60) }, + descendants: [], + }], + }, + ], + }, + { + session: { ...targetRecord, header: header(lastId, '/work', 70) }, + descendants: [], + }, + ] + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValue({ + target: targetRecord, + ancestors: [], + descendants, + complete: true, + root: targetRecord, + }) + const titleReads: SessionIdValue[] = [] + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockImplementation((sessionId) => { + titleReads.push(sessionId) + return Promise.resolve({ session: header(sessionId, '/work') }) + }) + + const output = text(await mounted.call('session_trace', { session_id: target.id })) + expect(output.slice(output.indexOf('Descendants:'))).toBe([ + 'Descendants:', + '- branch-first — untitled | 1970-01-01T00:00:00.030Z | live', + ' - branch-nested — untitled | 1970-01-01T00:00:00.040Z | live', + ' - [outside workspace subtree]', + '- branch-last — untitled | 1970-01-01T00:00:00.070Z | live', + ].join('\n')) + expect(titleReads).toEqual([target.id, firstId, nestedId, lastId]) + }) + it('renders authorized ancestors and an unresolved lineage boundary without leaking it', async () => { const mounted = await mount() const root = createSession(mounted.ctx, 'visible-root', '/work', 5) @@ -550,6 +610,30 @@ describe('workspace authority and lineage redaction', () => { expect(errorCode(titled)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') expect(text(titled)).not.toContain('secret moved title') }) + + it('rejects a default self read when its same-id observation moved after caller capture', async () => { + const mounted = await mount() + const secret = mounted.caller.append( + 'context/message', + { + content: [{ type: 'text', text: 'same-id moved secret' }], + source: { kind: 'plugin', plugin: 'test' }, + }, + { surfaceOp: 'append' }, + ) + const window = await mounted.ctx.sessionQuery.readEvent({ + sessionId: mounted.caller.id, + seq: secret.seq, + }) + vi.spyOn(mounted.ctx.sessionQuery, 'readEvent').mockResolvedValueOnce({ + ...window, + session: header(mounted.caller.id, '/outside'), + }) + + const denied = await mounted.call('session_event_read', { seq: secret.seq }) + expect(errorCode(denied)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + expect(text(denied)).not.toContain('same-id moved secret') + }) }) describe('search paging, prior-history bounds, titles, and cancellation', () => { @@ -797,6 +881,41 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => }) describe('trace and exact read rendering', () => { + it('renders a deeply nested lineage without recursive consumer traversal', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'deep-target', '/work') + const [targetRecord] = await mounted.ctx.sessionQuery.filterSessions([{ + kind: 'id', + values: [target.id], + }]) + if (targetRecord === undefined) throw new Error('expected target record') + const depth = 3_000 + let descendants: SessionLineageNode[] = [] + for (let index = depth; index >= 1; index -= 1) { + descendants = [{ + session: { + ...targetRecord, + header: header(`deep-${index}`, '/work', index), + }, + descendants, + }] + } + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockResolvedValue({ + target: targetRecord, + ancestors: [], + descendants, + complete: true, + root: targetRecord, + }) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockImplementation(sessionId => Promise.resolve({ + session: header(sessionId, '/work'), + })) + + const output = text(await mounted.call('session_trace', { session_id: target.id })) + expect(output).toContain('Descendants:\n- deep-1 —') + expect(output).toContain(`${' '.repeat(depth - 1)}- deep-${depth} —`) + }) + it('renders every event relationship sequence and a UTC target timestamp', async () => { const mounted = await mount() const session = createSession(mounted.ctx, 'relationships', '/work') From f5fc7ac04a83719c8c067ad44c720bd0ed472fc7 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 17:25:32 +0800 Subject: [PATCH 009/113] test: scope event snapshot normalization --- .../support/acp-snapshot/src/normalize.ts | 19 +++++++++++-------- .../acp-snapshot/tests/normalize.spec.ts | 6 ++++-- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/packages/support/acp-snapshot/src/normalize.ts b/packages/support/acp-snapshot/src/normalize.ts index 2de8d922db..f21340bc59 100644 --- a/packages/support/acp-snapshot/src/normalize.ts +++ b/packages/support/acp-snapshot/src/normalize.ts @@ -19,10 +19,10 @@ const EVENT_OMITTED_BYTES = '{{eventOmittedBytes}}' const CWD_ROOTED_PATH_RE = /\{\{cwd\}\}(?:[\\/][^\s<>"'`]+)+/g const PATH_TAG_RE = /()([^<]*)(<\/path>)/g const ADDITIONAL_INSTRUCTIONS_PATH_RE = /(Additional instructions from: )([^\r\n]+)/g -const EMBEDDED_EVENT_TIME_RE = /("time": )\d+(?=,\r?\n)/g +const EMBEDDED_EVENT_TIME_RE = /^( "time": )\d+(?=,\r?$)/gm const EVENT_READ_OMITTED_BYTES_RE = /(\r?\n\r?\n\(Omitted )\d+( bytes\.)/g -const EVENT_READ_RESULT_RE - = /^Session [^\r\n]+ — [^\r\n]+\r?\nTarget event seq \d+:\r?\n```json\r?\n\{\r?\n/ +const EVENT_READ_TARGET_REGION_RE + = /^Session [^\r\n]+ — [^\r\n]+\r?\nTarget event seq \d+:\r?\n```json\r?\n\{\r?\n[\s\S]*?(?=\r?\n```(?:\r?\n|$)|\r?\n\r?\n\(Omitted )/ /** A UUID v4 string, the shape `randomUUID()` produces for session ids. */ const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi @@ -78,11 +78,14 @@ function scrubString(value: string, ctx: NormalizeContext, cwdPathMode: CwdPathM } out = out.replace(LOCAL_SPILL_PATH_RE, (_match, name: string) => `{{spillLocator:${name}}}`) out = out.replace(SNAPSHOT_SPILL_PATH_RE, (_match, name: string) => `{{spillLocator:${name}}}`) - // Exact event-read results render pretty JSON inside a distinctive text - // envelope. Restrict time scrubbing to that envelope so JSON printed by - // models, bash, or unrelated tools remains regression-visible. - if (EVENT_READ_RESULT_RE.test(out)) { - out = out.replace(EMBEDDED_EVENT_TIME_RE, `$1${EVENT_TIME}`) + // Exact event-read results render the target as pretty JSON inside a + // distinctive envelope. Restrict time scrubbing to that fenced target so + // neighbor, model, bash, and unrelated tool text remains regression-visible. + if (EVENT_READ_TARGET_REGION_RE.test(out)) { + out = out.replace( + EVENT_READ_TARGET_REGION_RE, + target => target.replace(EMBEDDED_EVENT_TIME_RE, `$1${EVENT_TIME}`), + ) out = out.replace(EVENT_READ_OMITTED_BYTES_RE, `$1${EVENT_OMITTED_BYTES}$2`) } for (const id of ctx.sessionIds) out = out.split(id).join(SESSION_ID) diff --git a/packages/support/acp-snapshot/tests/normalize.spec.ts b/packages/support/acp-snapshot/tests/normalize.spec.ts index a4d0b4ad95..f2e4b74da7 100644 --- a/packages/support/acp-snapshot/tests/normalize.spec.ts +++ b/packages/support/acp-snapshot/tests/normalize.spec.ts @@ -123,7 +123,7 @@ Additional instructions from: nested\AGENTS.md`, expect(out).not.toContain('2026-07-20T17:03:13.689Z') }) - it('stabilizes a pretty-printed event timestamp embedded in tool-result text', () => { + it('stabilizes only the top-level event timestamp and spill byte count in event-read text', () => { const raw = JSON.stringify({ jsonrpc: '2.0', method: 'session/update', @@ -134,7 +134,7 @@ Additional instructions from: nested\AGENTS.md`, type: 'content', content: { type: 'text', - text: 'Session prior — title\nTarget event seq 4:\n```json\n{\n "seq": 4,\n "time": 1784876275593,\n "data": {}\n}\n```\n\n(Omitted 39387 bytes. Full formatted result stored at: /tmp/result.txt.)', + text: 'Session prior — title\nTarget event seq 4:\n```json\n{\n "seq": 4,\n "time": 1784876275593,\n "data": {\n "time": 31337,\n "note": "model-visible"\n }\n}\n```\n\nAfter:\n "time": 424242,\n neighbor semantic text\n\n(Omitted 39387 bytes. Full formatted result stored at: /tmp/result.txt.)', }, }], }, @@ -142,6 +142,8 @@ Additional instructions from: nested\AGENTS.md`, }) const out = normalizeStdout(raw, ctx) expect(out).toContain('\\"time\\": {{eventTime}}') + expect(out).toContain('\\"time\\": 31337') + expect(out).toContain('\\"time\\": 424242') expect(out).toContain('Omitted {{eventOmittedBytes}} bytes') expect(out).not.toContain('1784876275593') expect(out).not.toContain('39387') From fec4ce52cc06aacb9aeb2ad7a7cfe59c4cd068f2 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 18:13:11 +0800 Subject: [PATCH 010/113] fix: batch cancellable title reads --- ...model-facing-session-query-tools.i18n.yaml | 4 +- ...-07-24-model-facing-session-query-tools.md | 4 +- ...-24-model-facing-session-query-tools.zh.md | 4 +- docs/cordis-catalog/services.md | 27 +- docs/core-data-structures/session-query.md | 23 +- .../cordis/tool-cordis/src/api-catalog.ts | 24 +- .../session-persistence-jsonl/src/index.ts | 100 +++-- .../tests/zstd.spec.ts | 71 ++++ .../session-persistence-sqlite/src/index.ts | 18 +- .../session-persistence/README.md | 8 +- .../session-persistence/src/coordinator.ts | 94 ++++- .../session-persistence/src/index.ts | 6 +- .../session-persistence/tests/contract.ts | 15 + .../tests/persistence.spec.ts | 116 +++++- .../session-query/session-query/README.md | 4 +- .../session-query/session-query/src/corpus.ts | 184 ++++++++- .../session-query/session-query/src/index.ts | 46 ++- .../session-query/session-query/src/types.ts | 19 + .../session-query/tests/session-query.spec.ts | 362 +++++++++++++++++- .../tool-session-query/src/index.ts | 37 +- .../tests/tool-session-query.spec.ts | 130 +++++-- scripts/gen-cordis-catalog.ts | 1 + scripts/type-equiv.manifest.json | 5 + 23 files changed, 1152 insertions(+), 150 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml index 361145cb02..7425619403 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 -2026-07-24-model-facing-session-query-tools.md: 68169d8af7176ee1725a3c58bf97530f56a0765b -2026-07-24-model-facing-session-query-tools.zh.md: dfeae26a548b5e498e76fce259f7610106de7ec2 +2026-07-24-model-facing-session-query-tools.md: 0551adc431388d6cdd94b8e03c2976020ec90de4 +2026-07-24-model-facing-session-query-tools.zh.md: f82c0fac52d63ac3c11f48ee2769cb9e9590317c diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md index 68169d8af7..0551adc431 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -28,7 +28,7 @@ Neither search tool exposes a cursor, offset, page size, or model-controlled res Trace and read tools likewise expose no lineage or character pagination. Canonical results are plain text and remain complete within the service's existing event-window and search-count resource bounds. The generic `tools/post-execute` spill policy owns inline byte retention: when a configured deployment receives oversized text, it replaces that text with a bounded preview plus an opaque locator and retrieval hint while preserving the complete result in its spill store. The session-query consumer neither imports `ctx.spillStore` nor implements a second truncation format. -Session-level results include the latest folded title when available. Absence is rendered as untitled; an operational title read failure preserves the base result, renders an unavailable marker, and logs the underlying error, while an authorization mismatch fails closed. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. +Session-level results include the latest folded title when available. Each tool execution batches its unique title ids through one live-preferred corpus observation with at most four persisted-inspection workers and passes the exact tool-execution signal through persisted listing and inspection. Live sources fold directly; each persisted worker folds its completed source to a detached header/title observation and releases the full log before dequeuing another id, so the batch retains only small projected values. For the search tools, the execution signal carries the configured search deadline. Cancellation starts no queued title inspections and rejects the complete tool execution after already-started inspections settle; a missing, malformed, or operationally failed title remains isolated to that id, preserves the base result, renders an unavailable marker, and logs the underlying error, while an authorization mismatch fails closed. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. ## Host composition @@ -44,7 +44,7 @@ The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.se ## Verification -Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md index dfeae26a54..f82c0fac52 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -28,7 +28,7 @@ Status: implemented 追踪与读取工具同样不公开谱系分页或字符分页。规范结果采用纯文本,并在服务已有的事件窗口与搜索数量资源边界内保持完整。通用的 `tools/post-execute` spill 策略负责行内字节保留:当已配置的部署收到过大的文本时,该策略会用有界预览、不可透明推导的定位符与读取提示替换文本,同时在 spill 存储中保留完整结果。会话查询消费者既不导入 `ctx.spillStore`,也不实现第二套截断格式。 -会话级结果在可用时包含最新折叠标题。没有标题时渲染为未命名;标题读取发生操作性失败时保留基础结果、渲染不可用标记并记录底层错误,而授权不匹配则按失败关闭处理。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 +会话级结果在可用时包含最新折叠标题。每次工具执行都会通过一次优先使用实时数据的语料观测批量读取唯一标题 id,最多使用 4 个持久化检查 worker,并将准确的工具执行信号传递给持久化列表与检查操作。实时来源会直接折叠;每个持久化 worker 都会把已完成的来源折叠为分离的会话头/标题观测,并在取出下一个 id 前释放完整日志,因此批次只保留小型投影值。对于搜索工具,该执行信号携带已配置的搜索截止时间。取消不会启动排队中的标题检查,并会在已经启动的检查全部完成后拒绝完整的工具执行;标题缺失、格式错误或发生操作性失败时,错误只影响对应 id,同时保留基础结果、渲染不可用标记并记录底层错误,而授权不匹配则按失败关闭处理。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 ## 宿主组合 @@ -44,7 +44,7 @@ Status: implemented ## 验证 -包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 ## 后果 diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index de4296b85e..c2669885a4 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -941,15 +941,17 @@ abstract load(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEven * This read is serialized with writes for the same id and returns detached * values, so observers cannot mutate backend-owned state. * @param id - the persisted session to inspect. + * @param signal - optional cancellation for queued and backend read work. * @returns the header and valid stored event prefix exactly as observed. */ -abstract inspect(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> +abstract inspect(id: SessionId, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> /** * Lightweight listing from metadata, without a full-log parse. + * @param signal - optional cancellation for backend listing work. * @returns one header per materialized session. */ -abstract list(): Promise +abstract list(signal?: AbortSignal): Promise /** * List materialized sessions with cheap per-log change tokens. @@ -1014,16 +1016,29 @@ async filterSessions(filters: readonly SessionResultFilter[]): Promise +async readTitle( sessionId: SessionId, signal?: AbortSignal, ): Promise /** * Fold the latest title and return its source header from one corpus observation. * @param sessionId - live or persisted session id to read. + * @param signal - optional cancellation for source resolution and title folding. * @returns cloned source header and optional latest title snapshot. */ -async readTitleSnapshot(sessionId: SessionId): Promise +async readTitleSnapshot( sessionId: SessionId, signal?: AbortSignal, ): Promise + +/** + * Fold titles for unique sessions from one cancellable corpus observation. + * + * Results preserve first-occurrence input order. Operational failures stay + * isolated per session, while cancellation rejects the complete operation. + * @param sessionIds - live or persisted session ids to observe. + * @param signal - optional cancellation shared by all source reads. + * @returns one fulfilled or rejected result per unique requested id. + */ +async readTitleSnapshots( sessionIds: readonly SessionId[], signal?: AbortSignal, ): Promise /** * List lightweight raw-log event records for one logical session. @@ -1072,9 +1087,9 @@ async traceEvent(request: SessionEventTraceRequest): Promise ``` -Types: [SessionEventReadRequest](../core-data-structures/session-query.md) · [SessionEventRecord](../core-data-structures/session-query.md) · [SessionEventResultFilter](../core-data-structures/session-query.md) · [SessionEventSearchDocument](../core-data-structures/session-query.md) · [SessionEventSearchPage](../core-data-structures/session-query.md) · [SessionEventSearchRequest](../core-data-structures/session-query.md) · [SessionEventTraceObservation](../core-data-structures/session-query.md) · [SessionEventTraceRequest](../core-data-structures/session-query.md) · [SessionEventWindow](../core-data-structures/session-query.md) · [SessionId](../core-data-structures/core.md) · [SessionLineageTrace](../core-data-structures/session-query.md) · [SessionLogSnapshot](../core-data-structures/session-query.md) · [SessionRecord](../core-data-structures/session-query.md) · [SessionResultFilter](../core-data-structures/session-query.md) · [SessionSearchExecContext](../core-data-structures/session-query.md) · [SessionSearchHit](../core-data-structures/session-query.md) · [SessionSearchPage](../core-data-structures/session-query.md) · [SessionSearchRequest](../core-data-structures/session-query.md) · [SessionSurfaceSnapshot](../core-data-structures/session-query.md) · [SessionTitleObservation](../core-data-structures/session-query.md) · [SessionTitleSnapshot](../core-data-structures/session-title.md) +Types: [SessionEventReadRequest](../core-data-structures/session-query.md) · [SessionEventRecord](../core-data-structures/session-query.md) · [SessionEventResultFilter](../core-data-structures/session-query.md) · [SessionEventSearchDocument](../core-data-structures/session-query.md) · [SessionEventSearchPage](../core-data-structures/session-query.md) · [SessionEventSearchRequest](../core-data-structures/session-query.md) · [SessionEventTraceObservation](../core-data-structures/session-query.md) · [SessionEventTraceRequest](../core-data-structures/session-query.md) · [SessionEventWindow](../core-data-structures/session-query.md) · [SessionId](../core-data-structures/core.md) · [SessionLineageTrace](../core-data-structures/session-query.md) · [SessionLogSnapshot](../core-data-structures/session-query.md) · [SessionRecord](../core-data-structures/session-query.md) · [SessionResultFilter](../core-data-structures/session-query.md) · [SessionSearchExecContext](../core-data-structures/session-query.md) · [SessionSearchHit](../core-data-structures/session-query.md) · [SessionSearchPage](../core-data-structures/session-query.md) · [SessionSearchRequest](../core-data-structures/session-query.md) · [SessionSurfaceSnapshot](../core-data-structures/session-query.md) · [SessionTitleObservation](../core-data-structures/session-query.md) · [SessionTitleObservationResult](../core-data-structures/session-query.md) · [SessionTitleSnapshot](../core-data-structures/session-title.md) -Source: [`packages/session-query/session-query/src/index.ts:75`](../../packages/session-query/session-query/src/index.ts) +Source: [`packages/session-query/session-query/src/index.ts:76`](../../packages/session-query/session-query/src/index.ts) ## `ctx.sessionReferences` — `SessionReferenceService` diff --git a/docs/core-data-structures/session-query.md b/docs/core-data-structures/session-query.md index 265b49d3a2..4886eb3087 100644 --- a/docs/core-data-structures/session-query.md +++ b/docs/core-data-structures/session-query.md @@ -49,7 +49,7 @@ interface SessionSurfaceSnapshot { } ``` -`SessionTitleObservation` applies the same atomic-observation rule to title folding, so an authorization consumer can validate the source header that supplied the title. +`SessionTitleObservation` applies the same atomic-observation rule to title folding, so an authorization consumer can validate the source header that supplied the title. Batch reads return one ordered `SessionTitleObservationResult` per unique requested id: operational failures remain local to that id, while cancellation rejects the complete operation. ```ts type-equiv /** Latest folded title bound to the same session-header observation. */ @@ -61,6 +61,27 @@ interface SessionTitleObservation { } ``` +```ts type-equiv +/** One ordered result from a batch title observation. */ +type SessionTitleObservationResult = + | { + /** Requested session id. */ + sessionId: SessionId + /** Successful atomic header/title observation. */ + status: 'fulfilled' + /** Header and optional latest title from one logical source. */ + value: SessionTitleObservation + } + | { + /** Requested session id. */ + sessionId: SessionId + /** Operational failure isolated to this session. */ + status: 'rejected' + /** Original failure from logical-source resolution or title folding. */ + reason: unknown + } +``` + ```ts type-equiv /** Lightweight metadata for one event within a logical session. */ interface SessionEventRecord { diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 43723acfa8..72785f4e69 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -469,12 +469,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ jsDoc: '/**\n * Load a header and balanced contiguous log. A complete interrupted final\n * turn is preserved and durably closed with missing tool errors plus any open\n * step and turn boundaries; only a torn final record is discarded. Unknown\n * versions and corruption in the committed prefix reject. Implementations\n * MUST NOT crash-repair an identity still bound to a live Session: a balanced\n * live log may return with its stored header as a durable snapshot, while an\n * open live turn rejects.\n * A coordinator-backed cold load reserves the identity across storage awaits,\n * so concurrent publication of a same-id live Session rejects.\n * @param id - the persisted session to reload.\n * @returns the header and a log ending on a balanced `turn/end`.\n */', }, { - signature: 'abstract inspect(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }>', - jsDoc: '/**\n * Inspect a header and its valid contiguous stored prefix without repairing\n * a torn tail, closing an interrupted turn, or publishing coordinator state.\n * This read is serialized with writes for the same id and returns detached\n * values, so observers cannot mutate backend-owned state.\n * @param id - the persisted session to inspect.\n * @returns the header and valid stored event prefix exactly as observed.\n */', + signature: 'abstract inspect(id: SessionId, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }>', + jsDoc: '/**\n * Inspect a header and its valid contiguous stored prefix without repairing\n * a torn tail, closing an interrupted turn, or publishing coordinator state.\n * This read is serialized with writes for the same id and returns detached\n * values, so observers cannot mutate backend-owned state.\n * @param id - the persisted session to inspect.\n * @param signal - optional cancellation for queued and backend read work.\n * @returns the header and valid stored event prefix exactly as observed.\n */', }, { - signature: 'abstract list(): Promise', - jsDoc: '/**\n * Lightweight listing from metadata, without a full-log parse.\n * @returns one header per materialized session.\n */', + signature: 'abstract list(signal?: AbortSignal): Promise', + jsDoc: '/**\n * Lightweight listing from metadata, without a full-log parse.\n * @param signal - optional cancellation for backend listing work.\n * @returns one header per materialized session.\n */', }, { signature: 'abstract listSnapshots(): Promise', @@ -507,12 +507,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ jsDoc: '/**\n * Filter the complete logical corpus with provider-independent predicates.\n * @param filters - ANDed session metadata and availability clauses.\n * @returns matching cloned records in deterministic newest-first order.\n */', }, { - signature: 'async readTitle(sessionId: SessionId): Promise', - jsDoc: '/**\n * Fold the latest log-backed title from one live-preferred logical session.\n * @param sessionId - live or persisted session id to read.\n * @returns latest title snapshot, or `undefined` when the log has no title event.\n */', + signature: 'async readTitle( sessionId: SessionId, signal?: AbortSignal, ): Promise', + jsDoc: '/**\n * Fold the latest log-backed title from one live-preferred logical session.\n * @param sessionId - live or persisted session id to read.\n * @param signal - optional cancellation for source resolution and title folding.\n * @returns latest title snapshot, or `undefined` when the log has no title event.\n */', }, { - signature: 'async readTitleSnapshot(sessionId: SessionId): Promise', - jsDoc: '/**\n * Fold the latest title and return its source header from one corpus observation.\n * @param sessionId - live or persisted session id to read.\n * @returns cloned source header and optional latest title snapshot.\n */', + signature: 'async readTitleSnapshot( sessionId: SessionId, signal?: AbortSignal, ): Promise', + jsDoc: '/**\n * Fold the latest title and return its source header from one corpus observation.\n * @param sessionId - live or persisted session id to read.\n * @param signal - optional cancellation for source resolution and title folding.\n * @returns cloned source header and optional latest title snapshot.\n */', + }, + { + signature: 'async readTitleSnapshots( sessionIds: readonly SessionId[], signal?: AbortSignal, ): Promise', + jsDoc: '/**\n * Fold titles for unique sessions from one cancellable corpus observation.\n *\n * Results preserve first-occurrence input order. Operational failures stay\n * isolated per session, while cancellation rejects the complete operation.\n * @param sessionIds - live or persisted session ids to observe.\n * @param signal - optional cancellation shared by all source reads.\n * @returns one fulfilled or rejected result per unique requested id.\n */', }, { signature: 'async listEvents(sessionId: SessionId): Promise', @@ -1897,6 +1901,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SessionTitleObservation', declaration: 'export interface SessionTitleObservation {\n session: SessionHeader;\n title?: SessionTitleSnapshot;\n}', }, + { + name: 'SessionTitleObservationResult', + declaration: 'export type SessionTitleObservationResult = {\n sessionId: SessionId;\n status: \'fulfilled\';\n value: SessionTitleObservation;\n} | {\n sessionId: SessionId;\n status: \'rejected\';\n reason: unknown;\n};', + }, { name: 'SessionTitleProvider', declaration: 'export interface SessionTitleProvider {\n readonly id: SessionTitleProviderId;\n readonly automatic: SessionTitleAutomaticMode;\n generate(request: SessionTitleProviderRequest): Promise;\n}', diff --git a/packages/session-persistence/session-persistence-jsonl/src/index.ts b/packages/session-persistence/session-persistence-jsonl/src/index.ts index 629c0e3ff1..6b2fe3d0cf 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/index.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/index.ts @@ -131,8 +131,8 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi return this.coordinator.load(id) } - inspect(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { - return this.coordinator.inspect(id) + inspect(id: SessionId, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + return this.coordinator.inspect(id, signal) } // One method serves both public `list` and the backend hook; delegating it to @@ -142,24 +142,33 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi // --- PersistenceBackend hooks (the file-bytes storage primitives) --- /** Read a stored prefix by id across all cwd buckets when cwd is unknown. */ - async loadStored(id: SessionId): Promise | undefined> { + async loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { + signal?.throwIfAborted() await this.ensureRootEncoding() - const path = await this.findLog(id) + signal?.throwIfAborted() + const path = await this.findLog(id, signal) if (path === undefined) return undefined - return this.readPrefix(path, id) + return this.readPrefix(path, id, signal) } /** * Read a stored prefix and convert torn-tail state to the opaque marker the * coordinator can round-trip without knowing the physical encoding. */ - private async readPrefix(path: string, expectedId?: SessionId): Promise> { - const buffer = await readFile(path) + private async readPrefix( + path: string, + expectedId?: SessionId, + signal?: AbortSignal, + ): Promise> { + const buffer = await readFile(path, { signal }) + signal?.throwIfAborted() let prefix: StoredPrefix if (this.compression === 'zstd') { - prefix = await this.readZstdPrefix(buffer) + prefix = await this.readZstdPrefix(buffer, signal) } else { + signal?.throwIfAborted() const { meta, events, committedBytes } = scanLog(buffer) + signal?.throwIfAborted() prefix = { meta, events, @@ -168,30 +177,45 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi : {}, } } + signal?.throwIfAborted() this.assertStoredIdentity(path, prefix.meta, expectedId) return prefix } /** Decode complete frames and retain complete JSONL records from a torn final frame. */ - private async readZstdPrefix(buffer: Buffer): Promise> { + private async readZstdPrefix( + buffer: Buffer, + signal?: AbortSignal, + ): Promise> { + signal?.throwIfAborted() const { frames, tornStart } = scanZstdFrames(buffer) + signal?.throwIfAborted() if (frames.length === 0) throw new Error('empty or header-less Zstandard session log') const plaintextFrames: Buffer[] = [] for (const frame of frames) { + let plaintext: Buffer try { - plaintextFrames.push(await decompressZstdFrame(buffer.subarray(frame.start, frame.end))) + signal?.throwIfAborted() + plaintext = await decompressZstdFrame(buffer.subarray(frame.start, frame.end)) } catch (error) { + /* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */ + if (signal?.aborted) signal.throwIfAborted() throw new Error(`corrupt Zstandard session log: frame at byte ${frame.start} failed validation`, { cause: error }) } + signal?.throwIfAborted() + plaintextFrames.push(plaintext) } const headerFrame = plaintextFrames[0] if (headerFrame === undefined || headerFrame.length === 0 || headerFrame.indexOf(0x0A) !== headerFrame.length - 1) { throw new Error('corrupt Zstandard session log: first frame is not exactly one header line') } + signal?.throwIfAborted() const completePlaintext = Buffer.concat(plaintextFrames) + signal?.throwIfAborted() const completePrefix = scanLog(completePlaintext) + signal?.throwIfAborted() if (completePrefix.committedBytes !== completePlaintext.length) { throw new Error('corrupt Zstandard session log: complete frame contains a torn JSONL record') } @@ -201,12 +225,17 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi let recoveredPlaintext: Buffer = Buffer.alloc(0) try { + signal?.throwIfAborted() recoveredPlaintext = await decompressZstdFrame(buffer.subarray(tornStart)) } catch { + /* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */ + if (signal?.aborted) signal.throwIfAborted() // A structurally incomplete final frame may end before Node's decoder can // emit any plaintext; the complete prior frames remain recoverable. } + signal?.throwIfAborted() const recoveredPrefix = scanLog(Buffer.concat([completePlaintext, recoveredPlaintext])) + signal?.throwIfAborted() /* v8 ignore next 3 -- appending plaintext cannot shorten the already-scanned complete prefix */ if (recoveredPrefix.events.length < completePrefix.events.length) { throw new Error('corrupt Zstandard session log: recovered prefix does not extend complete frames') @@ -247,8 +276,8 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } /** List valid unique stored sessions' metadata (header line only — no full-log parse). */ - async list(): Promise { - return (await this.listArtifacts()).map(artifact => artifact.header) + async list(signal?: AbortSignal): Promise { + return (await this.listArtifacts(signal)).map(artifact => artifact.header) } /** List metadata plus a stat-derived identity for each append-only log. */ @@ -274,17 +303,21 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi return snapshots } - private async listArtifacts(): Promise> { + private async listArtifacts(signal?: AbortSignal): Promise> { + signal?.throwIfAborted() await this.ensureRootEncoding() + signal?.throwIfAborted() const artifacts: Array<{ header: SessionHeader; path: string }> = [] const ids = new Set() - for (const dir of await this.listCwdDirs()) { - for (const name of await this.listArtifactNames(dir)) { + for (const dir of await this.listCwdDirs(signal)) { + for (const name of await this.listArtifactNames(dir, signal)) { + signal?.throwIfAborted() const path = join(dir, name) // Read only headers so listing scales with session count, not log size. const first = this.compression === 'zstd' - ? await this.readFirstZstdLine(path) - : await this.readFirstLine(path) + ? await this.readFirstZstdLine(path, signal) + : await this.readFirstLine(path, signal) + signal?.throwIfAborted() if (first === undefined) continue // empty/half-written file const meta = parseHeaderMeta(first) if (meta === undefined) continue // not a session header @@ -492,18 +525,23 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi * file. Returns undefined if the file is empty or has no complete first line. * Reads in bounded chunks so a huge log costs only the header read. */ - private async readFirstLine(path: string): Promise { + private async readFirstLine(path: string, signal?: AbortSignal): Promise { + signal?.throwIfAborted() const handle = await open(path, 'r') try { + signal?.throwIfAborted() const chunks: Buffer[] = [] const buf = Buffer.alloc(8192) for (;;) { + signal?.throwIfAborted() const { bytesRead } = await handle.read(buf, 0, buf.length, null) + signal?.throwIfAborted() if (bytesRead === 0) return undefined // EOF with no newline → no complete line const slice = buf.subarray(0, bytesRead) const nl = slice.indexOf(0x0a) if (nl !== -1) { chunks.push(slice.subarray(0, nl)) + signal?.throwIfAborted() return Buffer.concat(chunks).toString('utf8') } chunks.push(Buffer.from(slice)) @@ -514,23 +552,34 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } /** Read and validate only the independently compressed header frame. */ - private async readFirstZstdLine(path: string): Promise { + private async readFirstZstdLine(path: string, signal?: AbortSignal): Promise { + signal?.throwIfAborted() const handle = await open(path, 'r') try { + signal?.throwIfAborted() let content = Buffer.alloc(0) const chunk = Buffer.alloc(8192) for (;;) { + signal?.throwIfAborted() const { bytesRead } = await handle.read(chunk, 0, chunk.length, null) + signal?.throwIfAborted() if (bytesRead === 0) return undefined + signal?.throwIfAborted() content = Buffer.concat([content, chunk.subarray(0, bytesRead)]) + signal?.throwIfAborted() const first = scanZstdFrames(content, 1).frames[0] + signal?.throwIfAborted() if (first === undefined) continue let plaintext: Buffer try { + signal?.throwIfAborted() plaintext = await decompressZstdFrame(content.subarray(first.start, first.end)) } catch (error) { + /* v8 ignore next -- decoder failure plus concurrent abort is timing-dependent */ + if (signal?.aborted) signal.throwIfAborted() throw new Error('corrupt Zstandard session log: header frame failed validation', { cause: error }) } + signal?.throwIfAborted() if (plaintext.length === 0 || plaintext.indexOf(0x0A) !== plaintext.length - 1) { throw new Error('corrupt Zstandard session log: first frame is not exactly one header line') } @@ -542,11 +591,12 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } /** Find the unique physical log for an id across every cwd bucket. */ - private async findLog(id: SessionId): Promise { + private async findLog(id: SessionId, signal?: AbortSignal): Promise { const target = encodeSegment(id) + logSuffix(this.compression) const oppositeTarget = encodeSegment(id) + logSuffix(this.oppositeCompression()) const matches: string[] = [] - for (const dir of await this.listCwdDirs()) { + for (const dir of await this.listCwdDirs(signal)) { + signal?.throwIfAborted() const path = join(dir, target) const opposite = join(dir, oppositeTarget) if (await this.exists(opposite)) throw this.encodingMismatch(opposite) @@ -585,9 +635,11 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } /** The cwd-bucket directories under the root (absolute paths). */ - private async listCwdDirs(): Promise { + private async listCwdDirs(signal?: AbortSignal): Promise { try { + signal?.throwIfAborted() const entries = await readdir(this.root, { withFileTypes: true }) + signal?.throwIfAborted() return entries.filter(e => e.isDirectory()).map(e => join(this.root, e.name)) } catch (error) { // Only an absent root means no sessions; rethrow every other I/O failure. @@ -596,8 +648,10 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } } - private async listArtifactNames(dir: string): Promise { + private async listArtifactNames(dir: string, signal?: AbortSignal): Promise { + signal?.throwIfAborted() const entries = await readdir(dir) + signal?.throwIfAborted() const oppositeSuffix = logSuffix(this.oppositeCompression()) const incompatible = entries.find(name => name.endsWith(oppositeSuffix)) if (incompatible !== undefined) throw this.encodingMismatch(`${dir}/${incompatible}`) diff --git a/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts index fcadac1f04..2777281481 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts @@ -16,6 +16,18 @@ const MAGIC = Buffer.from([0x28, 0xB5, 0x2F, 0xFD]) const roots: string[] = [] const contexts: Context[] = [] +interface ZstdReaderInternals { + readZstdPrefix(buffer: Buffer, signal?: AbortSignal): Promise +} + +type HeaderRead = ( + this: FileHandle, + buffer: Buffer, + offset: number, + length: number, + position: number | null, +) => Promise<{ bytesRead: number; buffer: Buffer }> + async function freshRoot(prefix = 'dsh-jsonl-zstd-'): Promise { const root = await mkdtemp(join(tmpdir(), prefix)) roots.push(root) @@ -275,6 +287,65 @@ describe('SessionPersistenceJsonl: default Zstandard encoding', () => { await expect(ctx.sessionPersistence.load(header.id)).rejects.toThrow(/frame at byte .* failed validation/) }) + it('stops multi-frame inspection after cancellation interrupts the active decode', async () => { + const root = await freshRoot() + const ctx = await mount(root) + const header = meta('cancel-zstd-frames') + const headerFrame = await compressZstdFrame(`${JSON.stringify(toHeaderLine(header))}\n`) + const eventFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[0])}\n`) + const laterFrame = await compressZstdFrame(`${JSON.stringify(oneTurnLog()[1])}\n`) + const stream = Buffer.concat([headerFrame, eventFrame, laterFrame]) + expect(scanZstdFrames(stream).frames).toHaveLength(3) + const controller = new AbortController() + const reason = new Error('cancel after Zstandard decode starts') + const reader = ctx.sessionPersistence as unknown as ZstdReaderInternals + const zstdModule = await import('../src/zstd.ts') + const decode = vi.spyOn(zstdModule, 'decompressZstdFrame') + + // readZstdPrefix reaches its first asynchronous decompression before it + // returns this promise. The microtask abort therefore occurs after decode + // starts and must prevent every later frame from reaching the decoder. + const pending = reader.readZstdPrefix(stream, controller.signal) + queueMicrotask(() => { controller.abort(reason) }) + + await expect(pending).rejects.toBe(reason) + expect(decode).toHaveBeenCalledTimes(1) + expect(decode).toHaveBeenCalledWith(headerFrame) + }) + + it.each(['none', 'zstd'] as const)( + 'observes cancellation after each async %s header read during listing', + async (compression) => { + const root = await freshRoot() + const ctx = await mount(root, compression) + const header = meta(`cancel-${compression}-header-read`, '/work') + await ctx.sessionPersistence.create(header) + await ctx.sessionPersistence.append(header.id, oneTurnLog()) + await ctx.sessionPersistence.list() + const path = logPath(root, header.cwd, header.id, compression) + const probe = await open(path, 'r') + const prototype = Object.getPrototypeOf(probe) as { read: HeaderRead } + const originalRead = prototype.read + await probe.close() + const controller = new AbortController() + const reason = new Error(`cancel ${compression} header read`) + const read = vi.spyOn(prototype, 'read').mockImplementation(async function ( + this: FileHandle, + buffer: Buffer, + offset: number, + length: number, + position: number | null, + ) { + const result = await originalRead.call(this, buffer, offset, length, position) + controller.abort(reason) + return result + }) + + await expect(ctx.sessionPersistence.list(controller.signal)).rejects.toBe(reason) + expect(read).toHaveBeenCalledTimes(1) + }, + ) + it('preserves complete records from a torn frame and re-encodes them with crash closers', async () => { const root = await freshRoot() const ctx = await mount(root) diff --git a/packages/session-persistence/session-persistence-sqlite/src/index.ts b/packages/session-persistence/session-persistence-sqlite/src/index.ts index 5804c18282..0c1159f139 100644 --- a/packages/session-persistence/session-persistence-sqlite/src/index.ts +++ b/packages/session-persistence/session-persistence-sqlite/src/index.ts @@ -157,8 +157,8 @@ export class SessionPersistenceSqlite extends SessionPersistence implements Pers return this.coordinator.load(id) } - inspect(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { - return this.coordinator.inspect(id) + inspect(id: SessionId, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + return this.coordinator.inspect(id, signal) } // One method serves both public `list` and the backend hook; delegating it to @@ -167,8 +167,8 @@ export class SessionPersistenceSqlite extends SessionPersistence implements Pers // --- PersistenceBackend hooks (the SQLite storage primitives) --- /** Read a stored prefix by id (ids are globally unique — no scope to scan). */ - loadStored(id: SessionId): Promise | undefined> { - return this.readPrefix(id) + loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { + return this.readPrefix(id, signal) } /** @@ -176,14 +176,17 @@ export class SessionPersistenceSqlite extends SessionPersistence implements Pers * torn-tail marker is the seq from which a never-committed tail must be deleted * (`scanRows` already returns it as `number | undefined`). */ - private async readPrefix(id: SessionId): Promise | undefined> { + private async readPrefix(id: SessionId, signal?: AbortSignal): Promise | undefined> { + signal?.throwIfAborted() await this.ready + signal?.throwIfAborted() const row = this.rowFor(id) if (row === undefined) return undefined const meta = rowToMeta(row) const eventRows = this.db .prepare('SELECT seq, type, time, data, source_event_seqs, surface_op FROM events WHERE session_id = ? ORDER BY seq') .all(id) as unknown as EventRow[] + signal?.throwIfAborted() const { preserved, tornFrom } = scanRows(eventRows) return { meta, events: preserved, ...tornFrom !== undefined ? { tornMarker: tornFrom } : {} } } @@ -251,11 +254,14 @@ export class SessionPersistenceSqlite extends SessionPersistence implements Pers } /** List all materialized sessions' metadata (every row is a materialized session). */ - async list(): Promise { + async list(signal?: AbortSignal): Promise { + signal?.throwIfAborted() await this.ready + signal?.throwIfAborted() const rows = this.db .prepare('SELECT * FROM sessions') .all() as unknown as SessionRow[] + signal?.throwIfAborted() return rows.map(rowToMeta) } diff --git a/packages/session-persistence/session-persistence/README.md b/packages/session-persistence/session-persistence/README.md index 25429bd720..fa734fb736 100644 --- a/packages/session-persistence/session-persistence/README.md +++ b/packages/session-persistence/session-persistence/README.md @@ -12,8 +12,8 @@ The persisted unit IS the existing `SessionEvent` (event-sourced model — the l | `create(meta): Promise` | Register a new session's metadata. MAY defer the physical write until the first `append` (lazy materialization). | | `append(id, events): Promise` | Durably persist a batch. Append-only; first event `seq` == stored next-seq after any repair; rejects non-JSON-serializable data naming the offending type. | | `load(id): Promise<{ meta; events }>` | Return a stored header plus a balanced contiguous log. A live load first flushes its snapshot and rejects while its turn is open; a cold load preserves an interrupted final turn and closes it with synthetic `tool/result`/`step/end?`/`turn/end {interrupted}` events. Only a torn tail fragment is dropped; committed corruption and unknown `version` reject. | -| `inspect(id): Promise<{ meta; events }>` | Return a detached valid stored prefix without truncating a torn tail, synthesizing recovery closers, or publishing coordinator state. Serialized with same-id writes; intended for read models and other observers that must never recover a log. | -| `list(): Promise` | Lightweight listing from metadata, no full-log parse. A zero-event lazily-materialized session is absent from `list`. | +| `inspect(id, signal?): Promise<{ meta; events }>` | Return a detached valid stored prefix without truncating a torn tail, synthesizing recovery closers, or publishing coordinator state. Serialized with same-id writes; the optional signal promptly rejects a queued caller, prevents that queued backend read from starting, and cancels active backend read work. Intended for read models and other observers that must never recover a log. | +| `list(signal?): Promise` | Lightweight listing from metadata, no full-log parse. The optional signal cancels backend listing work. A zero-event lazily-materialized session is absent from `list`. | | `listSnapshots(): Promise` | Lightweight metadata plus an opaque branded per-log revision, without loading event logs. A revision stays equal while that log and its backing store are unchanged, changes after append or mutating load repair, and cannot collide solely because two stores use the same local counter. | ## Invariants every backend must honor @@ -40,10 +40,10 @@ The `PersistenceBackend` hooks (the only seam between the coordinato | Hook | Role | |---|---| | `name` | Backend label for the dispose-failure `AggregateError`. | -| `loadStored(id)` | Read a stored prefix by id across every storage scope. Used by resume/load, non-mutating inspect, live adoption, and the create-collision probe. Returned metadata identifies `id`; an opaque `tornMarker` is present iff a torn tail must be truncated. | +| `loadStored(id, signal?)` | Read a stored prefix by id across every storage scope. Used by resume/load, non-mutating inspect, live adoption, and the create-collision probe. The optional signal belongs to observation-only reads. Returned metadata identifies `id`; an opaque `tornMarker` is present iff a torn tail must be truncated. | | `appendBatch(meta, events, isMaterialized)` | Durably append a contiguous batch, lazily materializing ATOMICALLY when not yet materialized. | | `commitRepair(meta, tornMarker, closers)` | Make a crash repair durable: truncate the torn tail (iff `tornMarker !== undefined` — a marker may be falsy, e.g. seq/offset `0`) and append `closers`. NOT required to be atomic. Used by load (truncate + closers) and live-adoption (truncate only). | -| `list()` | List all stored metadata. | +| `list(signal?)` | List all stored metadata, observing optional cancellation. | | `close?()` | Optional lifecycle teardown (e.g. close a db handle), awaited after the dispose drain. | The coordinator asserts the stored id and compares stored/live cwd before repair or live adoption. Its `inspect()` path validates and clones the prefix without calling `commitRepair` or publishing write state. The `tornMarker` is fully OPAQUE: the coordinator only tests `!== undefined` and round-trips it to `commitRepair`, never inspecting its value (the JSONL backend uses the byte offset to truncate to, the SQLite backend the seq to delete from). A third-party backend MAY implement the abstract service directly without the coordinator, but it must provide the same non-mutating inspection and trustworthy lightweight snapshot revisions. See [the write-coordinator Agent Note](../../../.agents/notes/implemented/architecture/2026-06-18-shared-persistence-write-coordinator.md). diff --git a/packages/session-persistence/session-persistence/src/coordinator.ts b/packages/session-persistence/session-persistence/src/coordinator.ts index fb46aa4877..442011bd2c 100644 --- a/packages/session-persistence/session-persistence/src/coordinator.ts +++ b/packages/session-persistence/session-persistence/src/coordinator.ts @@ -40,8 +40,10 @@ export interface PersistenceBackend { * `id` before repair or state publication. Used by resume/load, live adoption, * and — via `!== undefined` — the create-collision probe. The returned * `tornMarker` is present iff there is a torn tail to truncate. + * @param id - persisted session id to resolve. + * @param signal - optional cancellation for backend read work. */ - loadStored(id: SessionId): Promise | undefined> + loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> /** * Durably append a CONTIGUOUS batch, lazily materializing the session first @@ -60,8 +62,11 @@ export interface PersistenceBackend { */ commitRepair(meta: SessionHeader, tornMarker: TornMarker | undefined, closers: readonly SessionEvent[]): Promise - /** List all stored (materialized) sessions' metadata. */ - list(): Promise + /** + * List all stored (materialized) sessions' metadata. + * @param signal - optional cancellation for backend listing work. + */ + list(signal?: AbortSignal): Promise /** * Optional lifecycle teardown (e.g. close a database handle). Awaited by the @@ -267,14 +272,26 @@ export class PersistenceCoordinator { * Read a detached valid stored prefix without recovery mutations or * coordinator-state publication. * @param id - persisted session to inspect. + * @param signal - optional cancellation for queued and backend read work. * @returns stored header and events before any synthetic recovery closers. */ - inspect(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { - return this.serialize(id, () => this.inspectCore(id)) + inspect(id: SessionId, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + return this.serialize(id, () => this.inspectCore(id, signal), signal) } - private async inspectCore(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { - const stored = await this.backend.loadStored(id) + private async inspectCore( + id: SessionId, + signal?: AbortSignal, + ): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + signal?.throwIfAborted() + let stored: StoredPrefix | undefined + try { + stored = await this.backend.loadStored(id, signal) + } catch (error: unknown) { + if (signal?.aborted) signal.throwIfAborted() + throw error + } + signal?.throwIfAborted() if (stored === undefined) throw new Error(`session "${id}" not found`) this.assertStoredId(id, stored.meta) this.assertVersion(stored.meta) @@ -331,9 +348,19 @@ export class PersistenceCoordinator { * public methods must NOT call each other (deadlock); they call the unserialized * `*Core` helpers instead. */ - private serialize(id: SessionId, op: () => Promise | T): Promise { + private serialize( + id: SessionId, + op: () => Promise | T, + signal?: AbortSignal, + ): Promise { const prior = this.chains.get(id) ?? Promise.resolve() - const next = prior.then(op, op) + let started = false + const run = (): Promise | T => { + signal?.throwIfAborted() + started = true + return op() + } + const next = prior.then(run, run) // Keep the chain alive but swallow this op's rejection for the NEXT waiter // (the caller still sees the real rejection via `next`). const tail = next.then(() => undefined, () => undefined) @@ -343,7 +370,7 @@ export class PersistenceCoordinator { void tail.then(() => { if (this.chains.get(id) === tail) this.chains.delete(id) }) - return next + return signal === undefined ? next : observeQueuedAbort(next, signal, () => started) } /** Build a state for a session discovered in storage but not yet in memory. */ @@ -615,3 +642,50 @@ export class PersistenceCoordinator { live.pending.splice(0, batch.length) } } + +/** + * Give an observation caller a prompt cancellation view of queued work. + * + * The serialized `operation` remains in the same-id chain and checks the signal + * before invoking backend work. Observing its settlement here therefore cannot + * detach a storage read or let a later operation overtake its predecessor. + */ +function observeQueuedAbort( + operation: Promise, + signal: AbortSignal, + started: () => boolean, +): Promise { + return new Promise((resolve, reject) => { + let settled = false + const finish = (callback: () => void): void => { + if (settled) return + settled = true + signal.removeEventListener('abort', onAbort) + callback() + } + const onAbort = (): void => { + if (started()) return + finish(() => { + try { + signal.throwIfAborted() + } catch (reason: unknown) { + rejectObservation(reject, reason) + return + } + /* v8 ignore next -- a native AbortSignal emits abort only after becoming aborted */ + reject(new Error('persistence observation abort event lacked an aborted signal')) + }) + } + signal.addEventListener('abort', onAbort, { once: true }) + operation.then( + (value) => { finish(() => { resolve(value) }) }, + (reason: unknown) => { finish(() => { rejectObservation(reject, reason) }) }, + ) + if (signal.aborted) onAbort() + }) +} + +/** Preserve an exact provider or AbortSignal reason, including legacy non-Error values. */ +function rejectObservation(reject: (reason?: unknown) => void, reason: unknown): void { + reject(reason) +} diff --git a/packages/session-persistence/session-persistence/src/index.ts b/packages/session-persistence/session-persistence/src/index.ts index c785c9354c..9eee07a323 100644 --- a/packages/session-persistence/session-persistence/src/index.ts +++ b/packages/session-persistence/session-persistence/src/index.ts @@ -103,15 +103,17 @@ export abstract class SessionPersistence extends Service { * This read is serialized with writes for the same id and returns detached * values, so observers cannot mutate backend-owned state. * @param id - the persisted session to inspect. + * @param signal - optional cancellation for queued and backend read work. * @returns the header and valid stored event prefix exactly as observed. */ - abstract inspect(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> + abstract inspect(id: SessionId, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> /** * Lightweight listing from metadata, without a full-log parse. + * @param signal - optional cancellation for backend listing work. * @returns one header per materialized session. */ - abstract list(): Promise + abstract list(signal?: AbortSignal): Promise /** * List materialized sessions with cheap per-log change tokens. diff --git a/packages/session-persistence/session-persistence/tests/contract.ts b/packages/session-persistence/session-persistence/tests/contract.ts index ae07bf77aa..eb77235057 100644 --- a/packages/session-persistence/session-persistence/tests/contract.ts +++ b/packages/session-persistence/session-persistence/tests/contract.ts @@ -222,6 +222,21 @@ export function runPersistenceContract(name: string, make: () => Promise { + const { persistence, dispose } = await make() + try { + const reason = new Error('persistence observation cancelled') + const controller = new AbortController() + controller.abort(reason) + + await expect(persistence.list(controller.signal)).rejects.toBe(reason) + await expect(persistence.inspect(SessionId('cancelled-inspect'), controller.signal)) + .rejects.toBe(reason) + } finally { + await dispose() + } + }) + it('lists stable lightweight revisions that change after an append', async () => { const { persistence, dispose } = await make() try { diff --git a/packages/session-persistence/session-persistence/tests/persistence.spec.ts b/packages/session-persistence/session-persistence/tests/persistence.spec.ts index 6b31d0843b..523a88089e 100644 --- a/packages/session-persistence/session-persistence/tests/persistence.spec.ts +++ b/packages/session-persistence/session-persistence/tests/persistence.spec.ts @@ -94,8 +94,8 @@ class MemoryPersistence extends SessionPersistence implements PersistenceBackend return this.coordinator.load(id) } - inspect(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { - return this.coordinator.inspect(id) + inspect(id: SessionId, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + return this.coordinator.inspect(id, signal) } // --- PersistenceBackend hooks (the Map storage primitives) --- @@ -132,7 +132,8 @@ class MemoryPersistence extends SessionPersistence implements PersistenceBackend if (closers.length > 0) entry.events.push(...structuredClone(closers) as SessionEvent[]) } - async list(): Promise { + async list(signal?: AbortSignal): Promise { + signal?.throwIfAborted() return [...this.store.values()].map(e => structuredClone(e.meta)) } @@ -153,10 +154,10 @@ class ControlledBackend implements PersistenceBackend { loadAttempts = 0 repairAttempts = 0 beforeAppend?: (attempt: number) => Promise - beforeLoadStored?: (attempt: number) => Promise + beforeLoadStored?: (attempt: number, signal?: AbortSignal) => Promise - async loadStored(id: SessionId): Promise | undefined> { - await this.beforeLoadStored?.(++this.loadAttempts) + async loadStored(id: SessionId, signal?: AbortSignal): Promise | undefined> { + await this.beforeLoadStored?.(++this.loadAttempts, signal) const entry = this.store.get(id) if (entry === undefined) return undefined return { meta: structuredClone(entry.meta), events: structuredClone(entry.events) } @@ -348,6 +349,109 @@ describe('PersistenceCoordinator stored identity', () => { }) }) +describe('PersistenceCoordinator observation cancellation', () => { + it('promptly rejects a queued inspect without invoking it and keeps the same-id chain healthy', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + const backend = new ControlledBackend() + const id = SessionId('queued-inspect-cancellation') + backend.store.set(id, { meta: meta(id), events: oneTurnLog() }) + const loadGate = Promise.withResolvers() + backend.beforeLoadStored = async (attempt) => { + if (attempt === 1) await loadGate.promise + } + let coordinator!: PersistenceCoordinator + const fiber = await ctx.plugin(Object.assign((inner: Context) => { + coordinator = new PersistenceCoordinator(inner, backend) + }, { inject: ['sessions'] })) + + try { + const prior = coordinator.inspect(id) + await vi.waitFor(() => { expect(backend.loadAttempts).toBe(1) }) + const controller = new AbortController() + const reason = new Error('queued inspect cancelled') + const queued = coordinator.inspect(id, controller.signal) + let observedReason: unknown + const observedAbort = queued.catch((error: unknown) => { + observedReason = error + }) + + controller.abort(reason) + + await vi.waitFor(() => { expect(observedReason).toBe(reason) }) + expect(backend.loadAttempts).toBe(1) + const subsequent = coordinator.inspect(id) + expect(backend.loadAttempts).toBe(1) + + loadGate.resolve(true) + await expect(prior).resolves.toMatchObject({ meta: { id } }) + await observedAbort + await expect(subsequent).resolves.toMatchObject({ meta: { id } }) + expect(backend.loadAttempts).toBe(2) + await vi.waitFor(() => { + expect((coordinator as unknown as CoordinatorInternals).chains.size).toBe(0) + }) + } finally { + loadGate.resolve(true) + await fiber.dispose() + await ctx.fiber.dispose() + } + }) + + it('waits for active cooperative inspection cleanup before rejecting cancellation', async () => { + const ctx = new Context() + await ctx.plugin(SessionStore) + const backend = new ControlledBackend() + const id = SessionId('active-inspect-cancellation') + backend.store.set(id, { meta: meta(id), events: oneTurnLog() }) + const cleanupGate = Promise.withResolvers() + let cleanupComplete = false + backend.beforeLoadStored = async (_attempt, signal) => { + await new Promise((resolve) => { + signal?.addEventListener('abort', () => { + void cleanupGate.promise.then(() => { + cleanupComplete = true + resolve() + }) + }, { once: true }) + }) + throw new Error('backend cancellation after cleanup') + } + let coordinator!: PersistenceCoordinator + const fiber = await ctx.plugin(Object.assign((inner: Context) => { + coordinator = new PersistenceCoordinator(inner, backend) + }, { inject: ['sessions'] })) + + try { + const controller = new AbortController() + const reason = new Error('active inspect cancelled') + const pending = coordinator.inspect(id, controller.signal) + let observedReason: unknown + const observed = pending.catch((error: unknown) => { + observedReason = error + }) + await vi.waitFor(() => { expect(backend.loadAttempts).toBe(1) }) + + controller.abort(reason) + await Promise.resolve() + + expect(observedReason).toBeUndefined() + expect(cleanupComplete).toBe(false) + cleanupGate.resolve(true) + await observed + expect(cleanupComplete).toBe(true) + expect(observedReason).toBe(reason) + const backendFailure = new Error('later inspection failure') + backend.beforeLoadStored = () => Promise.reject(backendFailure) + await expect(coordinator.inspect(id)).rejects.toBe(backendFailure) + } finally { + cleanupGate.resolve(true) + await fiber.dispose() + await ctx.fiber.dispose() + } + }) +}) + describe('PersistenceCoordinator retirement', () => { it('a retiring unmaterialized owner without buffered events releases its id', async () => { const ctx = new Context() diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index 9ee495f48a..8c74f96e3c 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -8,14 +8,14 @@ - `readSession(sessionId)` returns one complete detached raw log after the same core replay validation used by resume; it never enters the session into the live store. - `filterSessions(filters)` applies provider-independent session metadata and availability predicates to that same cloned logical corpus. - `filterEvents(sessionId, filters)` extracts first-party semantic documents and applies provider-independent metadata and literal-text predicates in ascending seq order. -- `readTitleSnapshot(sessionId)` loads one live-preferred or persisted log and returns the cloned source header with its latest folded `session/title` event. `readTitle(sessionId)` is the title-only convenience view; it returns `undefined` when the known session has no title. +- `readTitleSnapshots(sessionIds, signal?)` resolves unique ids from one live-preferred corpus observation, passes cancellation through persisted listing and inspection, and returns ordered per-session settlements so one missing or malformed title source does not discard its peers. Each live source is folded directly, and each persisted worker folds to a detached header/title result and releases the full log before dequeuing another id. Cancellation rejects the whole batch. `readTitleSnapshot(sessionId, signal?)` is the one-observation view; `readTitle(sessionId, signal?)` returns only its optional folded `session/title`. - `listEvents(sessionId)` loads the live-preferred raw log and classifies each event as `current`, `shadowed`, or `log-only` with the shared `dsh-session` surface fold. - `readSurface(sessionId)` returns one cloned header, raw-log capture boundary, and the complete folded current surface in model-history order. A live session wins over persistence; compaction is observed before or after its replacement append, never as a synthetic mixture. - `readEvent(request)` returns a cloned header, the full target event, and a bounded raw-seq window. `before` and `after` default to zero and may not exceed `readWindowMax`. - `traceSession(sessionId)` reads the corpus once and returns immediate-to-outward ancestors plus deterministic recursive descendant trees. `complete: false` identifies the first missing parent; a target-connected cycle fails with `SESSION_QUERY_INVALID_LINEAGE`. - `traceEvent(request)` loads the logical log once and returns its cloned source header with direct positional replacements and direct logged provenance. `replacementChain` follows positional replacers to the final replacement; provenance links remain non-transitive. -Persistence is optional and may mount or unmount dynamically. Cross-corpus listing and lineage tracing fail with `SESSION_QUERY_PERSISTENCE_FAILED` while mounted persistence is unreadable. A title, event read, or trace targeting a known live session does not consult persistence, so durable backend health cannot make current in-memory state unreadable. Persisted title and event operations list before loading and reject a metadata mismatch rather than combining inconsistent observations. `listSessions()` remains lightweight and does not load logs or index titles. +Persistence is optional and may mount or unmount dynamically. Cross-corpus listing and lineage tracing fail with `SESSION_QUERY_PERSISTENCE_FAILED` while mounted persistence is unreadable. A title, event read, or trace targeting a known live session does not consult persistence, so durable backend health cannot make current in-memory state unreadable. Persisted title and event operations list before loading and reject a metadata mismatch rather than combining inconsistent observations. A batch title observation performs one metadata listing, inspects its unique persisted ids with at most four workers, and preserves each title's own observed header for downstream authorization. Cancellation starts no queued inspections and rejects only after already-started workers settle. `listSessions()` remains lightweight and does not load logs or index titles. ## Filtering and extraction diff --git a/packages/session-query/session-query/src/corpus.ts b/packages/session-query/session-query/src/corpus.ts index 0e1753d5ce..ebf0f40bbc 100644 --- a/packages/session-query/session-query/src/corpus.ts +++ b/packages/session-query/session-query/src/corpus.ts @@ -15,6 +15,22 @@ export interface LogicalSession { events: SessionEvent[] } +/** Borrowed source visible only during one synchronous batch projection. */ +export interface LogicalSessionSource { + /** Header selected with `events`; callers must clone retained output. */ + readonly header: SessionHeader + /** Raw events selected with `header`; valid only for the projection call. */ + readonly events: readonly SessionEvent[] +} + +/** One source-projection result in a batch logical-corpus observation. */ +export type LogicalProjectionResult = + | { sessionId: SessionId; status: 'fulfilled'; value: Value } + | { sessionId: SessionId; status: 'rejected'; reason: unknown } + +/** Bound persisted observation fan-out for public batch title reads. */ +const PERSISTED_INSPECT_CONCURRENCY = 4 + /** Resolves a live-preferred corpus against the persistence service mounted now. */ export class SessionCorpus { private _persistence: SessionPersistence | undefined @@ -72,16 +88,7 @@ export class SessionCorpus { if (persistence === undefined) throw notFound(sessionId) const listed = (await listPersisted(persistence)).find(header => header.id === sessionId) if (listed === undefined) throw notFound(sessionId) - let loaded: Awaited> - try { - loaded = await persistence.inspect(sessionId) - } catch (error: unknown) { - throw new SessionQueryError( - `failed to inspect session "${sessionId}": ${errorMessage(error)}`, - 'SESSION_QUERY_PERSISTENCE_FAILED', - { cause: error }, - ) - } + const loaded = await inspectPersisted(persistence, sessionId) const attached = this._ctx.sessions.get(sessionId) if (attached !== undefined) return snapshotLive(attached) assertSessionHeadersCompatible(loaded.meta, listed) @@ -90,11 +97,147 @@ export class SessionCorpus { events: loaded.events.map(event => structuredClone(event)), } } + + /** + * Project unique logical sources immediately from one persistence listing. + * + * The synchronous projector runs before a persisted worker claims its next id. + * Full logs are borrowed only for that call and never retained by the batch. + * @param sessionIds - sessions to resolve in first-occurrence order. + * @param project - synchronous fold that owns/clones every retained value. + * @param signal - cancellation shared by listing and every persisted inspection. + * @returns one fulfilled or rejected projected result per unique requested id. + */ + async projectMany( + sessionIds: readonly SessionId[], + project: (source: LogicalSessionSource) => Value, + signal?: AbortSignal, + ): Promise[]> { + const ids = [...new Set(sessionIds)] + signal?.throwIfAborted() + const resolved = new Map>() + const unresolved: SessionId[] = [] + for (const id of ids) { + const session = this._ctx.sessions.get(id) + if (session === undefined) { + unresolved.push(id) + } else { + resolved.set(id, projectSource(id, sourceLive(session), project, signal)) + } + } + if (unresolved.length === 0) return orderedResults(ids, resolved) + + const persistence = this._persistence + if (persistence === undefined) { + for (const sessionId of unresolved) { + resolved.set(sessionId, { sessionId, status: 'rejected', reason: notFound(sessionId) }) + } + return orderedResults(ids, resolved) + } + + let persisted: SessionHeader[] + try { + persisted = await listPersisted(persistence, signal) + signal?.throwIfAborted() + } catch (error: unknown) { + if (signal?.aborted) signal.throwIfAborted() + for (const sessionId of unresolved) { + resolved.set(sessionId, { sessionId, status: 'rejected', reason: error }) + } + return orderedResults(ids, resolved) + } + const persistedById = new Map(persisted.map(header => [header.id, header])) + const resolvePersisted = async (sessionId: SessionId): Promise => { + const listed = persistedById.get(sessionId) + if (listed === undefined) { + const attached = this._ctx.sessions.get(sessionId) + resolved.set(sessionId, attached === undefined + ? { sessionId, status: 'rejected', reason: notFound(sessionId) } + : projectSource(sessionId, sourceLive(attached), project, signal)) + return + } + try { + signal?.throwIfAborted() + const loaded = await inspectPersisted(persistence, sessionId, signal) + signal?.throwIfAborted() + const attached = this._ctx.sessions.get(sessionId) + if (attached !== undefined) { + resolved.set(sessionId, projectSource(sessionId, sourceLive(attached), project, signal)) + return + } + assertSessionHeadersCompatible(loaded.meta, listed) + resolved.set(sessionId, projectSource(sessionId, { + header: loaded.meta, + events: loaded.events, + }, project, signal)) + } catch (error: unknown) { + if (signal?.aborted) signal.throwIfAborted() + resolved.set(sessionId, { sessionId, status: 'rejected', reason: error }) + } + } + let cursor = 0 + const worker = async (): Promise => { + for (;;) { + signal?.throwIfAborted() + const index = cursor + if (index >= unresolved.length) return + cursor += 1 + await resolvePersisted(unresolved[index] as SessionId) + } + } + const workerCount = Math.min(PERSISTED_INSPECT_CONCURRENCY, unresolved.length) + const settlements = await Promise.allSettled( + Array.from({ length: workerCount }, () => worker()), + ) + if (signal?.aborted) signal.throwIfAborted() + /* v8 ignore start -- per-id failures settle inside resolvePersisted; workers reject only on abort above */ + for (const settlement of settlements) { + if (settlement.status === 'rejected') { + const reason: unknown = settlement.reason + throw reason + } + } + /* v8 ignore stop */ + signal?.throwIfAborted() + return orderedResults(ids, resolved) + } } -async function listPersisted(persistence: SessionPersistence): Promise { +function projectSource( + sessionId: SessionId, + source: LogicalSessionSource, + project: (source: LogicalSessionSource) => Value, + signal?: AbortSignal, +): LogicalProjectionResult { try { - return await persistence.list() + signal?.throwIfAborted() + const value = project(source) + signal?.throwIfAborted() + return { sessionId, status: 'fulfilled', value } + } catch (reason: unknown) { + /* v8 ignore next -- the synchronous projector has no external cancellation yield */ + if (signal?.aborted) signal.throwIfAborted() + return { sessionId, status: 'rejected', reason } + } +} + +function sourceLive(session: Session): LogicalSessionSource { + return { header: session.header, events: session.events } +} + +function orderedResults( + ids: readonly SessionId[], + resolved: ReadonlyMap>, +): LogicalProjectionResult[] { + return ids.map(sessionId => resolved.get(sessionId) as LogicalProjectionResult) +} + +async function listPersisted( + persistence: SessionPersistence, + signal?: AbortSignal, +): Promise { + try { + return await persistence.list(signal) } catch (error: unknown) { throw new SessionQueryError( `session persistence listing failed: ${errorMessage(error)}`, @@ -104,6 +247,23 @@ async function listPersisted(persistence: SessionPersistence): Promise>> { + try { + return await persistence.inspect(sessionId, signal) + } catch (error: unknown) { + if (signal?.aborted) signal.throwIfAborted() + throw new SessionQueryError( + `failed to inspect session "${sessionId}": ${errorMessage(error)}`, + 'SESSION_QUERY_PERSISTENCE_FAILED', + { cause: error }, + ) + } +} + function snapshotLive(session: Session): LogicalSession { return { header: structuredClone(session.header), diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index b38914b3b6..000eb83425 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -28,6 +28,7 @@ import type { SessionSearchRequest, SessionSurfaceSnapshot, SessionTitleObservation, + SessionTitleObservationResult, } from './types.ts' import { SESSION_QUERY_READ_WINDOW_MAX, @@ -148,24 +149,51 @@ export abstract class SessionQueryService extends Service { /** * Fold the latest log-backed title from one live-preferred logical session. * @param sessionId - live or persisted session id to read. + * @param signal - optional cancellation for source resolution and title folding. * @returns latest title snapshot, or `undefined` when the log has no title event. */ - async readTitle(sessionId: SessionId): Promise { - return (await this.readTitleSnapshot(sessionId)).title + async readTitle( + sessionId: SessionId, + signal?: AbortSignal, + ): Promise { + return (await this.readTitleSnapshot(sessionId, signal)).title } /** * Fold the latest title and return its source header from one corpus observation. * @param sessionId - live or persisted session id to read. + * @param signal - optional cancellation for source resolution and title folding. * @returns cloned source header and optional latest title snapshot. */ - async readTitleSnapshot(sessionId: SessionId): Promise { - const loaded = await this._corpus.load(sessionId) - const title = foldSessionTitle(loaded.events) - return { - session: loaded.header, - ...title === undefined ? {} : { title }, - } + async readTitleSnapshot( + sessionId: SessionId, + signal?: AbortSignal, + ): Promise { + const result = (await this.readTitleSnapshots([sessionId], signal))[0] as SessionTitleObservationResult + if (result.status === 'rejected') throw result.reason + return result.value + } + + /** + * Fold titles for unique sessions from one cancellable corpus observation. + * + * Results preserve first-occurrence input order. Operational failures stay + * isolated per session, while cancellation rejects the complete operation. + * @param sessionIds - live or persisted session ids to observe. + * @param signal - optional cancellation shared by all source reads. + * @returns one fulfilled or rejected result per unique requested id. + */ + async readTitleSnapshots( + sessionIds: readonly SessionId[], + signal?: AbortSignal, + ): Promise { + return this._corpus.projectMany(sessionIds, (source): SessionTitleObservation => { + const title = foldSessionTitle(source.events) + return { + session: structuredClone(source.header), + ...title === undefined ? {} : { title }, + } + }, signal) } /** diff --git a/packages/session-query/session-query/src/types.ts b/packages/session-query/session-query/src/types.ts index d3e7196152..b01d80dade 100644 --- a/packages/session-query/session-query/src/types.ts +++ b/packages/session-query/session-query/src/types.ts @@ -157,6 +157,25 @@ export interface SessionTitleObservation { title?: SessionTitleSnapshot } +/** One ordered result from a batch title observation. */ +export type SessionTitleObservationResult = + | { + /** Requested session id. */ + sessionId: SessionId + /** Successful atomic header/title observation. */ + status: 'fulfilled' + /** Header and optional latest title from one logical source. */ + value: SessionTitleObservation + } + | { + /** Requested session id. */ + sessionId: SessionId + /** Operational failure isolated to this session. */ + status: 'rejected' + /** Original failure from logical-source resolution or title folding. */ + reason: unknown + } + /** Inclusive numeric interval used by time and sequence filters. */ export interface SessionResultRange { /** Inclusive lower bound. */ diff --git a/packages/session-query/session-query/tests/session-query.spec.ts b/packages/session-query/session-query/tests/session-query.spec.ts index a69c3bcb93..f88d8be0f6 100644 --- a/packages/session-query/session-query/tests/session-query.spec.ts +++ b/packages/session-query/session-query/tests/session-query.spec.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { Context, type Fiber } from 'cordis' import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionHeader, SessionId as SessionIdType } from '@deepseek-ai/dsh-session' @@ -27,16 +27,31 @@ function eventLog(text = 'hello'): SessionEvent[] { class TestPersistence extends SessionPersistence { static entries = new Map() static listFailure: unknown + static listOverride: ((signal?: AbortSignal) => Promise) | undefined static inspectFailure: unknown static inspectEffect: (() => void) | undefined + static inspectOverride: (( + id: SessionIdType, + signal?: AbortSignal, + ) => Promise<{ meta: SessionHeader; events: SessionEvent[] }>) | undefined static afterList: (() => void) | undefined + static listCalls = 0 + static inspectCalls: SessionIdType[] = [] + static listSignals: Array = [] + static inspectSignals: Array = [] static reset(entries: readonly { meta: SessionHeader; events: SessionEvent[] }[] = []): void { this.entries = new Map(entries.map(entry => [entry.meta.id, structuredClone(entry)])) this.listFailure = undefined + this.listOverride = undefined this.inspectFailure = undefined this.inspectEffect = undefined + this.inspectOverride = undefined this.afterList = undefined + this.listCalls = 0 + this.inspectCalls = [] + this.listSignals = [] + this.inspectSignals = [] } locate(_meta: SessionHeader): undefined { @@ -59,7 +74,15 @@ class TestPersistence extends SessionPersistence { return this.inspect(id) } - inspect(id: SessionIdType): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + inspect( + id: SessionIdType, + signal?: AbortSignal, + ): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + TestPersistence.inspectCalls.push(id) + TestPersistence.inspectSignals.push(signal) + if (TestPersistence.inspectOverride !== undefined) { + return TestPersistence.inspectOverride(id, signal) + } if (TestPersistence.inspectFailure !== undefined) return rejectUnknown(TestPersistence.inspectFailure) const entry = TestPersistence.entries.get(id) if (entry === undefined) return Promise.reject(new Error('missing test session')) @@ -69,7 +92,10 @@ class TestPersistence extends SessionPersistence { return Promise.resolve(result) } - list(): Promise { + list(signal?: AbortSignal): Promise { + TestPersistence.listCalls += 1 + TestPersistence.listSignals.push(signal) + if (TestPersistence.listOverride !== undefined) return TestPersistence.listOverride(signal) if (TestPersistence.listFailure !== undefined) return rejectUnknown(TestPersistence.listFailure) const headers = [...TestPersistence.entries.values()].map(entry => structuredClone(entry.meta)) TestPersistence.afterList?.() @@ -192,6 +218,336 @@ describe('session-query exact reads', () => { expect(Object.keys((await ctx.sessionQuery.listSessions())[0]!)).toEqual(['header', 'live', 'persisted']) }) + it('batches unique persisted title observations through one cancellable corpus scan', async () => { + const first = header('batch-title-first', 1) + const second = header('batch-title-second', 2) + const titleEvent = (title: string, time: number): SessionEvent => ({ + type: 'session/title', + seq: 0, + time, + data: { + title, + messageSeqs: [], + source: { kind: 'fallback' }, + }, + }) + TestPersistence.reset([ + { meta: first, events: [titleEvent('First title', 10)] }, + { meta: second, events: [titleEvent('Second title', 20)] }, + ]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const signal = new AbortController().signal + const missing = SessionId('batch-title-missing') + + const results = await ctx.sessionQuery.readTitleSnapshots( + [second.id, first.id, second.id, missing], + signal, + ) + + expect(results.map(result => [result.sessionId, result.status])).toEqual([ + [second.id, 'fulfilled'], + [first.id, 'fulfilled'], + [missing, 'rejected'], + ]) + expect(results[0]).toMatchObject({ value: { session: second, title: { title: 'Second title' } } }) + expect(results[1]).toMatchObject({ value: { session: first, title: { title: 'First title' } } }) + expect(TestPersistence.listCalls).toBe(1) + expect(TestPersistence.inspectCalls).toEqual([second.id, first.id]) + expect(TestPersistence.listSignals).toEqual([signal]) + expect(TestPersistence.inspectSignals).toEqual([signal, signal]) + }) + + it('bounds persisted title inspection concurrency while preserving ordered results', async () => { + const entries = Array.from({ length: 12 }, (_, index) => { + const meta = header(`bounded-title-${index}`, index) + return { meta, events: eventLog(`title-${index}`) } + }) + TestPersistence.reset(entries) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + let active = 0 + let maximum = 0 + TestPersistence.inspectOverride = async (id) => { + active += 1 + maximum = Math.max(maximum, active) + await new Promise(resolve => setImmediate(resolve)) + active -= 1 + const entry = TestPersistence.entries.get(id) + if (entry === undefined) throw new Error('missing bounded test session') + return structuredClone(entry) + } + + const results = await ctx.sessionQuery.readTitleSnapshots(entries.map(entry => entry.meta.id)) + + expect(maximum).toBe(4) + expect(TestPersistence.listCalls).toBe(1) + expect(TestPersistence.inspectCalls).toEqual(entries.map(entry => entry.meta.id)) + expect(results.map(result => result.sessionId)).toEqual(entries.map(entry => entry.meta.id)) + expect(results.every(result => result.status === 'fulfilled')).toBe(true) + }) + + it('folds and discards each completed log before its worker dequeues another inspection', async () => { + const entries = Array.from({ length: 5 }, (_, index) => ({ + meta: header(`project-title-${index}`, index), + events: [], + })) + TestPersistence.reset(entries) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const timeline: string[] = [] + const releases = new Map void>() + TestPersistence.inspectOverride = id => new Promise((resolve) => { + timeline.push(`inspect:${id}`) + releases.set(id, () => { + const marker = `full-log-marker:${id}` + const titleEvent = { + type: 'session/title', + seq: 1, + time: 20, + data: { + title: `Projected ${id}`, + get messageSeqs() { + timeline.push(`project:${id}`) + return [] + }, + source: { kind: 'fallback' }, + }, + } as unknown as SessionEvent + resolve({ + meta: entries.find(entry => entry.meta.id === id)!.meta, + events: [...eventLog(marker), titleEvent], + }) + }) + }) + const release = (id: SessionIdType): void => { + const settle = releases.get(id) + if (settle === undefined) throw new Error(`inspection ${id} has not started`) + settle() + } + const ids = entries.map(entry => entry.meta.id) + + const pending = ctx.sessionQuery.readTitleSnapshots(ids) + await vi.waitFor(() => { expect(TestPersistence.inspectCalls).toHaveLength(4) }) + release(ids[0]!) + await vi.waitFor(() => { expect(TestPersistence.inspectCalls).toHaveLength(5) }) + + // Heap-retention assertions would depend on nondeterministic GC. This ordering + // is the deterministic guard: a retain-all implementation cannot touch the + // observable title getter until every inspection has completed. + expect(timeline.indexOf(`project:${ids[0]}`)) + .toBeLessThan(timeline.indexOf(`inspect:${ids[4]}`)) + for (const id of ids.slice(1)) release(id) + const results = await pending + + expect(results.map(result => result.sessionId)).toEqual(ids) + expect(JSON.stringify(results)).not.toContain('full-log-marker:') + expect(results.every(result => result.status === 'fulfilled')).toBe(true) + }) + + it('passes cancellation into a stalled persisted title batch and rejects with its reason', async () => { + const persisted = header('stalled-title', 1) + TestPersistence.reset([{ meta: persisted, events: [] }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('title deadline') + let started!: () => void + const inspectStarted = new Promise((resolve) => { started = resolve }) + TestPersistence.inspectOverride = (_id, signal) => new Promise((_resolve, reject) => { + started() + signal?.addEventListener('abort', () => { reject(reason) }, { once: true }) + }) + + const pending = ctx.sessionQuery.readTitleSnapshots([persisted.id], controller.signal) + await inspectStarted + controller.abort(reason) + + await expect(pending).rejects.toBe(reason) + expect(TestPersistence.listSignals).toEqual([controller.signal]) + expect(TestPersistence.inspectSignals).toEqual([controller.signal]) + }) + + it('drains started title inspections after cancellation without starting queued ids', async () => { + const entries = Array.from({ length: 8 }, (_, index) => ({ + meta: header(`cancel-queued-title-${index}`, index), + events: eventLog(`queued-${index}`), + })) + TestPersistence.reset(entries) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('cancel queued title batch') + const releases: Array<() => void> = [] + let abortsObserved = 0 + let inspectionsSettled = 0 + TestPersistence.inspectOverride = (_id, signal) => new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { abortsObserved += 1 }, { once: true }) + releases.push(() => { + inspectionsSettled += 1 + reject(reason) + }) + }) + + const pending = ctx.sessionQuery.readTitleSnapshots( + entries.map(entry => entry.meta.id), + controller.signal, + ) + let batchSettled = false + void pending.then( + () => { batchSettled = true }, + () => { batchSettled = true }, + ) + await vi.waitFor(() => { expect(TestPersistence.inspectCalls).toHaveLength(4) }) + controller.abort(reason) + await vi.waitFor(() => { expect(abortsObserved).toBe(4) }) + + expect(batchSettled).toBe(false) + expect(TestPersistence.inspectCalls).toEqual(entries.slice(0, 4).map(entry => entry.meta.id)) + for (const release of releases) release() + + await expect(pending).rejects.toBe(reason) + expect(inspectionsSettled).toBe(4) + expect(TestPersistence.inspectCalls).toEqual(entries.slice(0, 4).map(entry => entry.meta.id)) + }) + + it('passes cancellation into a stalled persisted title listing and rejects with its reason', async () => { + const persisted = header('stalled-title-list', 1) + TestPersistence.reset([{ meta: persisted, events: [] }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('title listing deadline') + let started!: () => void + const listStarted = new Promise((resolve) => { started = resolve }) + TestPersistence.listOverride = signal => new Promise((_resolve, reject) => { + started() + signal?.addEventListener('abort', () => { reject(reason) }, { once: true }) + }) + + const pending = ctx.sessionQuery.readTitleSnapshots([persisted.id], controller.signal) + await listStarted + controller.abort(reason) + + await expect(pending).rejects.toBe(reason) + expect(TestPersistence.listSignals).toEqual([controller.signal]) + expect(TestPersistence.inspectCalls).toEqual([]) + }) + + it('isolates title read and fold failures while preferring a live owner attached during inspection', async () => { + const attached = header('batch-title-attached', 1) + const failed = header('batch-title-failed', 2) + const malformed = header('batch-title-malformed', 3) + const inspectFailure = new Error('one title inspect failed') + const malformedTitle = { + type: 'session/title', + seq: 0, + time: 30, + data: { + title: 'malformed', + source: { kind: 'fallback' }, + }, + } as unknown as SessionEvent + TestPersistence.reset([ + { meta: attached, events: eventLog('stale persisted') }, + { meta: failed, events: [] }, + { meta: malformed, events: [malformedTitle] }, + ]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + TestPersistence.inspectOverride = (id) => { + if (id === failed.id) return Promise.reject(inspectFailure) + const entry = TestPersistence.entries.get(id) + if (entry === undefined) return Promise.reject(new Error('missing test session')) + if (id === attached.id) { + const session = ctx.sessions.create(attached.id, { meta: { createdAt: attached.createdAt } }) + session.append('session/title', { + title: 'Attached live title', + messageSeqs: [], + source: { kind: 'fallback' }, + }) + } + return Promise.resolve(structuredClone(entry)) + } + + const results = await ctx.sessionQuery.readTitleSnapshots([ + attached.id, + failed.id, + malformed.id, + ]) + + expect(results[0]).toMatchObject({ + status: 'fulfilled', + value: { session: attached, title: { title: 'Attached live title' } }, + }) + expect(results[1]).toMatchObject({ + sessionId: failed.id, + status: 'rejected', + reason: { + code: 'SESSION_QUERY_PERSISTENCE_FAILED', + cause: inspectFailure, + }, + }) + expect(results[2]).toMatchObject({ sessionId: malformed.id, status: 'rejected' }) + if (results[2]?.status !== 'rejected') throw new Error('expected malformed title rejection') + expect(results[2].reason).toBeInstanceOf(TypeError) + }) + + it('preserves live batch results across missing persistence, listing failure, and late attachment', async () => { + const liveOnly = await liveContext() + const live = liveOnly.sessions.create(SessionId('batch-title-live')) + const missing = SessionId('batch-title-no-persistence') + + await expect(liveOnly.sessionQuery.readTitleSnapshots([live.id, live.id])).resolves.toEqual([{ + sessionId: live.id, + status: 'fulfilled', + value: { session: live.header }, + }]) + await expect(liveOnly.sessionQuery.readTitleSnapshots([live.id, missing])).resolves.toMatchObject([ + { sessionId: live.id, status: 'fulfilled' }, + { sessionId: missing, status: 'rejected' }, + ]) + await expect(liveOnly.sessionQuery.readTitleSnapshot(missing)) + .rejects.toThrow(expectCode('SESSION_QUERY_SESSION_NOT_FOUND')) + + const persisted = header('batch-title-persisted', 1) + const late = header('batch-title-late', 2) + TestPersistence.reset([{ meta: persisted, events: [] }]) + const mixed = await liveContext() + const mixedLive = mixed.sessions.create(SessionId('batch-title-mixed-live')) + await mixed.plugin(TestPersistence) + TestPersistence.afterList = () => { + mixed.sessions.create(late.id, { meta: { createdAt: late.createdAt } }) + TestPersistence.afterList = undefined + } + + await expect(mixed.sessionQuery.readTitleSnapshots([ + mixedLive.id, + persisted.id, + late.id, + ])).resolves.toMatchObject([ + { sessionId: mixedLive.id, status: 'fulfilled' }, + { sessionId: persisted.id, status: 'fulfilled' }, + { sessionId: late.id, status: 'fulfilled' }, + ]) + + TestPersistence.reset() + TestPersistence.listFailure = new Error('title listing failed') + const failedList = await liveContext() + const survivingLive = failedList.sessions.create(SessionId('batch-title-list-live')) + await failedList.plugin(TestPersistence) + + await expect(failedList.sessionQuery.readTitleSnapshots([survivingLive.id, missing])) + .resolves.toMatchObject([ + { sessionId: survivingLive.id, status: 'fulfilled' }, + { + sessionId: missing, + status: 'rejected', + reason: expectCode('SESSION_QUERY_PERSISTENCE_FAILED'), + }, + ]) + }) + it('lists live sessions deterministically and returns detached headers', async () => { const ctx = await liveContext() const older = ctx.sessions.create(SessionId('older'), { meta: { createdAt: 1 } }) diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index e7b8b1ef88..999fc1aa40 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -741,8 +741,16 @@ async function readTitles( signal: AbortSignal, ): Promise { const result = new Map() - for (const id of new Set(ids)) { - result.set(id, await readTitle(ctx, caller, id, signal)) + signal.throwIfAborted() + const observations = await ctx.sessionQuery.readTitleSnapshots(ids, signal) + signal.throwIfAborted() + for (const observation of observations) { + if (observation.status === 'rejected') { + result.set(observation.sessionId, unavailableTitle(ctx, observation.sessionId, observation.reason)) + continue + } + assertObservedTargetAuthorized(caller, observation.sessionId, observation.value.session) + result.set(observation.sessionId, { text: observation.value.title?.title ?? 'untitled' }) } return result as CompleteTitleMap } @@ -753,19 +761,18 @@ async function readTitle( id: SessionIdValue, signal: AbortSignal, ): Promise { - signal.throwIfAborted() - try { - const observation = await ctx.sessionQuery.readTitleSnapshot(id) - signal.throwIfAborted() - assertObservedTargetAuthorized(caller, id, observation.session) - return { text: observation.title?.title ?? 'untitled' } - } catch (error: unknown) { - if (signal.aborted) signal.throwIfAborted() - if (error instanceof HarnessError && error.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') throw error - const code = error instanceof HarnessError ? error.code : 'UNKNOWN' - ctx.logger.warn(`tool-session-query: title read failed for session "${id}": ${fullError(error)}`) - return { text: 'untitled', unavailableCode: code } - } + return (await readTitles(ctx, caller, [id], signal)).get(id) +} + +function unavailableTitle( + ctx: Context, + id: SessionIdValue, + error: unknown, +): TitleView { + if (error instanceof HarnessError && error.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') throw error + const code = error instanceof HarnessError ? error.code : 'UNKNOWN' + ctx.logger.warn(`tool-session-query: title read failed for session "${id}": ${fullError(error)}`) + return { text: 'untitled', unavailableCode: code } } function fullError(error: unknown): string { diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index 8aa8376d67..c33b1c9967 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -21,6 +21,7 @@ import SessionQueryService, { type SessionSearchHit, type SessionSearchPage, type SessionSearchRequest, + type SessionTitleObservationResult, } from '@deepseek-ai/dsh-session-query' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { type ToolExecutionResult } from '@deepseek-ai/dsh-tools' @@ -155,20 +156,31 @@ class FakeQuery extends SessionQueryService { return FakeQuery.eventSearch(request, exec) } - override async readTitleSnapshot(sessionId: SessionIdValue) { - const value = FakeQuery.titles.get(sessionId) - if (value instanceof Error) throw value - if (value === undefined) return super.readTitleSnapshot(sessionId) - return { - session: (await this.readSurface(sessionId)).session, - title: { - title: value, - messageSeqs: [], - source: { kind: 'fallback' as const }, - eventSeq: 0, - updatedAt: 1, - }, - } + override async readTitleSnapshots( + sessionIds: readonly SessionIdValue[], + signal?: AbortSignal, + ): Promise { + const observations = await super.readTitleSnapshots(sessionIds, signal) + return observations.map((observation): SessionTitleObservationResult => { + const value = FakeQuery.titles.get(observation.sessionId) + if (value instanceof Error) { + return { sessionId: observation.sessionId, status: 'rejected', reason: value } + } + if (value === undefined || observation.status === 'rejected') return observation + return { + ...observation, + value: { + ...observation.value, + title: { + title: value, + messageSeqs: [], + source: { kind: 'fallback' }, + eventSeq: 0, + updatedAt: 1, + }, + }, + } + }) } } @@ -494,9 +506,13 @@ describe('workspace authority and lineage redaction', () => { root: targetRecord, }) const titleReads: SessionIdValue[] = [] - vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockImplementation((sessionId) => { - titleReads.push(sessionId) - return Promise.resolve({ session: header(sessionId, '/work') }) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockImplementation((sessionIds) => { + titleReads.push(...sessionIds) + return Promise.resolve([...new Set(sessionIds)].map(sessionId => ({ + sessionId, + status: 'fulfilled' as const, + value: { session: header(sessionId, '/work') }, + }))) }) const output = text(await mounted.call('session_trace', { session_id: target.id })) @@ -596,16 +612,20 @@ describe('workspace authority and lineage redaction', () => { FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(target.id, '/work', 'safe hit')], }) - vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockResolvedValueOnce({ - session: movedHeader, - title: { - title: 'secret moved title', - messageSeqs: [], - source: { kind: 'fallback' }, - eventSeq: 0, - updatedAt: 1, + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockResolvedValueOnce([{ + sessionId: target.id, + status: 'fulfilled', + value: { + session: movedHeader, + title: { + title: 'secret moved title', + messageSeqs: [], + source: { kind: 'fallback' }, + eventSeq: 0, + updatedAt: 1, + }, }, - }) + }]) const titled = await mounted.call('session_search', { query: 'safe' }) expect(errorCode(titled)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') expect(text(titled)).not.toContain('secret moved title') @@ -828,9 +848,11 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const second = createSession(mounted.ctx, 'stackless-title', '/work') const stackless = new Error('stackless') Object.defineProperty(stackless, 'stack', { value: undefined }) - const readTitle = vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot') - .mockRejectedValueOnce('string failure') - .mockRejectedValueOnce(stackless) + const readTitles = vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots') + .mockResolvedValueOnce([ + { sessionId: first.id, status: 'rejected', reason: 'string failure' }, + { sessionId: second.id, status: 'rejected', reason: stackless }, + ]) FakeQuery.sessionSearch = () => Promise.resolve({ items: [ sessionHit(first.id, '/work'), @@ -840,7 +862,8 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) const result = await mounted.call('session_search', { query: 'needle' }) expect(text(result)).toContain('title unavailable: UNKNOWN') - expect(readTitle).toHaveBeenCalledTimes(2) + expect(readTitles).toHaveBeenCalledTimes(1) + expect(readTitles.mock.calls[0]?.[0]).toEqual([first.id, second.id]) expect(warn).toHaveBeenCalledWith(expect.stringContaining('string failure')) expect(warn).toHaveBeenCalledWith(expect.stringContaining('Error: stackless')) }) @@ -849,14 +872,43 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const mounted = await mount() const hit = createSession(mounted.ctx, 'abort-title', '/work') const controller = new AbortController() + const cancellation = new Error('cancelled title batch') FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] }) - vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockImplementation(() => { - controller.abort() - return Promise.reject(new Error('cancelled title')) + let started!: () => void + const batchStarted = new Promise((resolve) => { started = resolve }) + const readTitles = vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockImplementation((_ids, signal) => { + started() + return new Promise((_resolve, reject) => { + signal?.addEventListener('abort', () => { reject(cancellation) }, { once: true }) + }) }) - const result = await mounted.call('session_search', { query: 'needle' }, { signal: controller.signal }) + const pending = mounted.call('session_search', { query: 'needle' }, { signal: controller.signal }) + await batchStarted + controller.abort(cancellation) + const result = await pending expect(result.isError).toBe(true) expect(text(result)).not.toContain('title unavailable') + expect(readTitles.mock.calls[0]?.[1]).toBe(controller.signal) + }) + + it('does not downgrade an authorization failure returned by title observation', async () => { + const mounted = await mount() + const hit = createSession(mounted.ctx, 'unauthorized-title-error', '/work') + const failure = new HarnessError( + 'title observation became unauthorized', + 'SESSION_QUERY_TOOL_UNAUTHORIZED', + ) + FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] }) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockResolvedValueOnce([{ + sessionId: hit.id, + status: 'rejected', + reason: failure, + }]) + + const result = await mounted.call('session_search', { query: 'needle' }) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + expect(text(result)).not.toContain('title unavailable') }) it('passes the exact execution signal to every FTS page and stops on cancellation', async () => { @@ -907,9 +959,13 @@ describe('trace and exact read rendering', () => { complete: true, root: targetRecord, }) - vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshot').mockImplementation(sessionId => Promise.resolve({ - session: header(sessionId, '/work'), - })) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockImplementation(sessionIds => Promise.resolve( + [...new Set(sessionIds)].map(sessionId => ({ + sessionId, + status: 'fulfilled' as const, + value: { session: header(sessionId, '/work') }, + })), + )) const output = text(await mounted.call('session_trace', { session_id: target.id })) expect(output).toContain('Descendants:\n- deep-1 —') diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index a68097864e..3fe3a681de 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -139,6 +139,7 @@ export const LINK_MAP: Record = { SessionSearchPage: 'session-query.md', SessionSearchRequest: 'session-query.md', SessionTitleObservation: 'session-query.md', + SessionTitleObservationResult: 'session-query.md', SessionTitleProvider: 'session-title.md', SessionTitleSnapshot: 'session-title.md', SkillDefinition: 'skills.md', diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index ce9d54c217..2213725f7f 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -404,6 +404,11 @@ "symbol": "SessionTitleObservation", "source": "packages/session-query/session-query/src/types.ts" }, + { + "doc": "docs/core-data-structures/session-query.md", + "symbol": "SessionTitleObservationResult", + "source": "packages/session-query/session-query/src/types.ts" + }, { "doc": "docs/core-data-structures/session-query.md", "symbol": "SessionEventRecord", From 0d2e74ed4875a1d6a72c17baa3d230c8415c20f6 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 18:22:00 +0800 Subject: [PATCH 011/113] docs: describe host session-query surface --- packages/host/runtime/README.md | 78 ++++++++++++++++++- .../verify-package-readme-model-experience.ts | 1 - 2 files changed, 74 insertions(+), 5 deletions(-) diff --git a/packages/host/runtime/README.md b/packages/host/runtime/README.md index f7cf7d9de8..15cff947df 100644 --- a/packages/host/runtime/README.md +++ b/packages/host/runtime/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-host-runtime -Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence and immediate fallback titles, optional first-message model summaries, system prompt, tools, agents, agent loop, workspace instructions, local bash, and the provider-neutral user-interaction service), `createApiProxy` implements the [`dsh-host-apiproxy`](../apiproxy/README.md) contract over that composition, and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }`. +Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence, a derived SQLite FTS session-query index, immediate fallback titles, optional first-message model summaries, system prompt, tool and agent registries, agent loop, five workspace-authorized model-facing session-query tools, workspace instructions, local bash, the generic tool-timeout and 50,000-byte spill policies, and the provider-neutral user-interaction service), `createApiProxy` implements the [`dsh-host-apiproxy`](../apiproxy/README.md) contract over that composition, and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }`. Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly two sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`) and headless session-event subscription; consuming clients must not bypass `api` through it. @@ -8,7 +8,7 @@ Which plugins mount and with what defaults is decided only here — shells must | Key | Default | Contract | |---|---:|---| -| `persistenceRoot` | (required) | Root directory for JSONL session persistence. | +| `persistenceRoot` | (required) | Root directory for JSONL session logs and the derived `session-query.db` SQLite FTS index. | | `workspaceContext` | (required) | [`AGENTS.md`/`CLAUDE.md` loader](../../context/workspace-context/README.md) config with an explicit `maxBytes`, or `false` to disable it. | | `provider` | `'deepseek'` | Default provider route injected as agentOptions on create/resume and reported by `host.describe`. | | `model` | `'deepseek-v4-flash'` | Default model id, same single source as `provider`. | @@ -22,11 +22,81 @@ Unary methods take the narrow `RpcRequest

` and echo `request.rpcId`; a prompt ## Model Experience -Indirectly, through the non-blocking first-message title request owned by [`dsh-session-title-llm`](../../session-title/session-title-llm/README.md) when `sessionTitleLlm` is enabled, the provider/model defaults injected into created and resumed agents, the other model-facing plugins `bootHost` mounts, and the logged [workspace-instruction prefix](../../context/workspace-context/README.md#prompt-shape) when `workspaceContext` is enabled. +### Prior-history system prompt + +#### What the model sees + +Every main host agent receives the fixed prior-history guidance below because `bootHost` always mounts the session-query tool plugin. + +##### Prior-history guidance + +```markdown +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. +``` + +#### Token effect + +One fixed concise section is present on every request; `workspaceContext: false` does not remove it. #### KV Cache effect -No main-request invalidation; when enabled, the auxiliary title request has its own cache behavior and leaves the conversation prefix unchanged. +The repeated prefix is stable while the fixed host assembly and guidance text are unchanged. Provider cache availability and eviction remain outside the host contract. + +### Session-query tool schemas + +#### What the model sees + +The fixed assembly mounts the generated [`session_search`, `session_event_search`, `session_trace`, `session_event_trace`, and `session_event_read` schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-query). The schemas expose no workspace path, provider cursor, output page, model-controlled result limit, or timeout argument. + +#### Token effect + +Five fixed read-only schemas are present on every main-agent request; their cost changes only if the host assembly or an agent-scoped visibility policy changes. + +#### KV Cache effect + +The schema prefix is stable while visibility, definitions, and order are unchanged. The host makes no claim that a provider will cache or retain that prefix. + +### Session-query execution and results + +#### What the model sees + +Cross-session results require exact equality with the calling session's workspace, while a caller without a workspace can target only itself. `session_search` excludes the calling session, and `session_event_search` on the current session excludes the step performing the call. Both searches are cursor-free, collect at most 100 authorized results, and carry a cooperative 30-second deadline; the three trace/read tools carry caller cancellation but declare no host deadline. Results are plain text. When a final result exceeds 50,000 UTF-8 bytes, the generic spill policy attempts to retain the complete formatted text in a private session-scoped file and replace it with a bounded preview, locator, and retrieval hint; a spill failure leaves the original result visible. + +#### Token effect + +Call arguments and data-dependent results remain in history until compaction. Search result count is bounded; after a successful spill, only the bounded preview and retrieval notice are resent, while the complete text remains outside model context. + +#### KV Cache effect + +Calls and results append after the reusable request prefix. Compaction may replace earlier history; timeout or spill outcomes change only the appended result text. + +### Workspace instructions + +#### What the model sees + +When `workspaceContext` is enabled, the model receives the logged [workspace-instruction prefix and loaded file contents](../../context/workspace-context/README.md#prompt-shape), bounded by that configuration's explicit `maxBytes`. Setting `workspaceContext: false` removes this surface. + +#### Token effect + +Disabled mode adds no tokens. Enabled mode adds the frozen data-dependent baseline to each request, up to the configured byte budget; later discovered, changed, or removed instructions append bounded history messages. + +#### KV Cache effect + +Prefix-stable within one loop instance because its baseline is frozen. A new or resumed instance recomposes the baseline, while touch-discovered changes during an instance append after the reusable prefix. + +### First-message title auxiliary request + +#### What the model sees + +When `sessionTitleLlm` is enabled, a separate [first-message title model](../../session-title/session-title-first-message-llm/README.md) receives the shared title instruction and a JSON array containing only the first eligible human message. It uses an explicitly configured route or inherits the exact logged main-request route; this auxiliary request does not add text to the main model request or delay its response. + +#### Token effect + +Disabled by default, so it normally adds no model request. With `sessionTitleLlm: true`, a fresh non-fork session makes at most one automatic request capped at 4,096 input bytes and 64 output tokens; an explicit configuration supplies its own caps. The deterministic fallback remains when the auxiliary request fails. + +#### KV Cache effect + +The main conversation prefix is unchanged. The auxiliary request has independent, provider-specific cache behavior; the host does not promise cache reuse. ## Known Limitations and Deferred Work diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index d5fa282a24..5687e51bac 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -66,7 +66,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/fs/fs-sandbox': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' }, 'packages/hooks/hook-protocol': { kind: 'indirect', reason: 'Only the hook bridge plugins render decoded hook output to a model.' }, 'packages/host/apiproxy': { kind: 'none', reason: 'The wire contract and fetch carriers move already-composed messages and register no model surface.' }, - 'packages/host/runtime': { kind: 'indirect', reason: 'The assembly mounts model-facing plugins and injects provider/model defaults into agents.' }, 'packages/host/webserver': { kind: 'none', reason: 'The HTTP carrier bridges browser and API handler and registers no model surface.' }, 'packages/llm/llm': { kind: 'none', reason: 'The adapter registry forwards already-assembled requests unchanged.' }, 'packages/llm/token-meter': { kind: 'indirect', reason: 'The measurement service leaves model-visible changes to its consumers.' }, From 415948dd7b61414a1a7035ac4a42853efa6fa8db Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 18:47:41 +0800 Subject: [PATCH 012/113] fix: redact lineage errors and parse precise times --- .../tool-session-query/src/index.ts | 95 ++++++- .../tests/sqlite-integration.spec.ts | 128 ++++++++++ .../tests/tool-session-query.spec.ts | 234 ++++++++++++++++++ 3 files changed, 448 insertions(+), 9 deletions(-) diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index 999fc1aa40..df1184ffed 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -428,7 +428,19 @@ async function executeSessionTrace( const caller = callerOf(exec) const sessionId = targetId(args, caller) await authorizeTarget(ctx, caller, sessionId, exec.signal) - const trace = await ctx.sessionQuery.traceSession(sessionId) + let trace: SessionLineageTrace + try { + trace = await ctx.sessionQuery.traceSession(sessionId) + } catch (error: unknown) { + exec.signal.throwIfAborted() + if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_INVALID_LINEAGE') { + throw new SessionQueryError( + 'session lineage is invalid', + 'SESSION_QUERY_INVALID_LINEAGE', + ) + } + throw error + } exec.signal.throwIfAborted() assertObservedTargetAuthorized(caller, sessionId, trace.target.header) @@ -579,21 +591,31 @@ function timestampRange( to: string | undefined, ): { from?: number; to?: number } | undefined { if (from === undefined && to === undefined) return undefined - const fromMs = from === undefined ? undefined : parseIsoTimestamp(`${name}_from`, from) - const toMs = to === undefined ? undefined : parseIsoTimestamp(`${name}_to`, to) - if (fromMs !== undefined && toMs !== undefined && fromMs > toMs) { + const fromTimestamp = from === undefined ? undefined : parseIsoTimestamp(`${name}_from`, from) + const toTimestamp = to === undefined ? undefined : parseIsoTimestamp(`${name}_to`, to) + if ( + fromTimestamp !== undefined + && toTimestamp !== undefined + && compareTimestamps(fromTimestamp, toTimestamp) > 0 + ) { throw invalidRange(name, 'from must be less than or equal to to') } return { - ...fromMs === undefined ? {} : { from: fromMs }, - ...toMs === undefined ? {} : { to: toMs }, + ...fromTimestamp === undefined ? {} : { from: timestampLowerBound(fromTimestamp) }, + ...toTimestamp === undefined ? {} : { to: timestampUpperBound(toTimestamp) }, } } const ISO_TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|([+-])(\d{2}):(\d{2}))$/ -function parseIsoTimestamp(name: string, value: string): number { +interface ExactTimestamp { + readonly millisecond: number + /** Canonical decimal digits strictly below one millisecond; no trailing zeroes. */ + readonly remainder: string +} + +function parseIsoTimestamp(name: string, value: string): ExactTimestamp { const match = ISO_TIMESTAMP.exec(value) if (match === null) { throw invalidRange(name, 'must be an ISO 8601 timestamp with Z or a numeric offset') @@ -614,8 +636,63 @@ function parseIsoTimestamp(name: string, value: string): number { ) { throw invalidRange(name, 'must be a valid ISO 8601 timestamp') } - const timestamp = Date.parse(value) - return timestamp + const fraction = match[7] ?? '' + const millisecondDigits = fraction.slice(0, 3).padEnd(3, '0') + const normalized = `${match[1]}-${match[2]}-${match[3]}T${match[4]}:${match[5]}` + + `:${match[6] ?? '00'}.${millisecondDigits}${match[8]}` + const timestamp = Date.parse(normalized) + if (!Number.isSafeInteger(timestamp)) { + throw invalidRange(name, 'must be a valid ISO 8601 timestamp') + } + return { + millisecond: timestamp, + remainder: fraction.slice(3).replace(/0+$/u, ''), + } +} + +function compareTimestamps(left: ExactTimestamp, right: ExactTimestamp): number { + if (left.millisecond !== right.millisecond) { + return left.millisecond < right.millisecond ? -1 : 1 + } + const length = Math.max(left.remainder.length, right.remainder.length) + for (let index = 0; index < length; index += 1) { + const leftDigit = left.remainder[index] ?? '0' + const rightDigit = right.remainder[index] ?? '0' + if (leftDigit !== rightDigit) return leftDigit < rightDigit ? -1 : 1 + } + return 0 +} + +function timestampLowerBound(timestamp: ExactTimestamp): number { + return timestamp.remainder.length === 0 + ? timestamp.millisecond + : nextUpFinite(timestamp.millisecond) +} + +function timestampUpperBound(timestamp: ExactTimestamp): number { + return timestamp.remainder.length === 0 + ? timestamp.millisecond + : nextDownFinite(timestamp.millisecond + 1) +} + +/** Return the adjacent IEEE-754 value toward positive infinity for a finite input. */ +function nextUpFinite(value: number): number { + if (value === 0) return Number.MIN_VALUE + const view = new DataView(new ArrayBuffer(8)) + view.setFloat64(0, value) + const bits = view.getBigUint64(0) + view.setBigUint64(0, value > 0 ? bits + 1n : bits - 1n) + return view.getFloat64(0) +} + +/** Return the adjacent IEEE-754 value toward negative infinity for a finite input. */ +function nextDownFinite(value: number): number { + if (value === 0) return -Number.MIN_VALUE + const view = new DataView(new ArrayBuffer(8)) + view.setFloat64(0, value) + const bits = view.getBigUint64(0) + view.setBigUint64(0, value > 0 ? bits - 1n : bits + 1n) + return view.getFloat64(0) } function daysInMonth(year: number, month: number): number { diff --git a/packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts b/packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts index fb85bdc309..fd7c07538b 100644 --- a/packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts +++ b/packages/session-query/tool-session-query/tests/sqlite-integration.spec.ts @@ -97,4 +97,132 @@ describe('tool-session-query with the real SQLite provider', () => { expect(liveEvents.content.map(block => block.type === 'text' ? block.text : '').join('\n')) .toContain('seq 1') }) + + it('passes finite fractional epoch-millisecond bounds through SQLite comparisons', async () => { + const root = await mkdtemp(join(tmpdir(), 'dsh-tool-session-query-fractional-')) + temporaryDirectories.push(root) + const ctx = new Context() + contexts.push(ctx) + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRegistry) + await ctx.plugin(SessionPersistenceJsonl, { root, compression: 'none' }) + await ctx.plugin(SessionQuerySqlite, { path: join(root, 'session-query.db') }) + await ctx.plugin(ToolSessionQuery) + + const base = Date.parse('2026-07-24T00:00:00.000Z') + const persisted = SessionId('fractional-persisted') + await ctx.sessionPersistence.create({ + version: SESSION_FORMAT_VERSION, + id: persisted, + createdAt: base, + cwd: '/work', + }) + await ctx.sessionPersistence.append(persisted, [ + { + type: 'user/message', + seq: 0, + time: base + 123, + data: { + content: [{ type: 'text', text: 'fractional integration needle' }], + source: { kind: 'user' }, + }, + surfaceOp: 'append', + }, + { + type: 'user/message', + seq: 1, + time: base + 124, + data: { + content: [{ type: 'text', text: 'fractional integration needle' }], + source: { kind: 'user' }, + }, + surfaceOp: 'append', + }, + { + type: 'user/message', + seq: 2, + time: -124, + data: { + content: [{ type: 'text', text: 'pre-epoch fractional needle' }], + source: { kind: 'user' }, + }, + surfaceOp: 'append', + }, + { + type: 'user/message', + seq: 3, + time: -123, + data: { + content: [{ type: 'text', text: 'pre-epoch fractional needle' }], + source: { kind: 'user' }, + }, + surfaceOp: 'append', + }, + ]) + + const caller = ctx.sessions.create(SessionId('fractional-caller'), { + meta: { createdAt: base + 1_000, cwd: '/work' }, + }) + let call = 0 + const execute = (args: unknown) => ctx.tools.execute({ + name: 'session_event_search', + arguments: args, + callId: CallId(`fractional-integration-${++call}`), + signal: new AbortController().signal, + agent: fakeAgent(caller), + }) + + const lowerBound = await execute({ + session_id: persisted, + query: 'fractional integration needle', + time_from: '2026-07-24T00:00:00.12300001Z', + }) + expect(lowerBound.isError).toBe(false) + const lowerText = lowerBound.content.map(block => block.type === 'text' ? block.text : '').join('\n') + expect(lowerText).toContain('seq 1') + expect(lowerText).not.toContain('seq 0') + + const upperBound = await execute({ + session_id: persisted, + query: 'fractional integration needle', + time_to: '2026-07-24T08:00:00.1239999+08:00', + }) + expect(upperBound.isError).toBe(false) + const upperText = upperBound.content.map(block => block.type === 'text' ? block.text : '').join('\n') + expect(upperText).toContain('seq 0') + expect(upperText).not.toContain('seq 1') + + const emptySameMillisecond = await execute({ + session_id: persisted, + query: 'fractional integration needle', + time_from: '2026-07-24T00:00:00.12300001Z', + time_to: '2026-07-24T08:00:00.1239999+08:00', + }) + expect(emptySameMillisecond.isError).toBe(false) + expect(emptySameMillisecond.content.map(block => block.type === 'text' ? block.text : '').join('\n')) + .toContain('No prior event matches found.') + + const preEpochLower = await execute({ + session_id: persisted, + query: 'pre-epoch fractional needle', + time_from: '1969-12-31T23:59:59.87600001Z', + }) + expect(preEpochLower.isError).toBe(false) + const preEpochLowerText = preEpochLower.content + .map(block => block.type === 'text' ? block.text : '').join('\n') + expect(preEpochLowerText).toContain('seq 3') + expect(preEpochLowerText).not.toContain('seq 2') + + const preEpochUpper = await execute({ + session_id: persisted, + query: 'pre-epoch fractional needle', + time_to: '1969-12-31T19:59:59.8769999-04:00', + }) + expect(preEpochUpper.isError).toBe(false) + const preEpochUpperText = preEpochUpper.content + .map(block => block.type === 'text' ? block.text : '').join('\n') + expect(preEpochUpperText).toContain('seq 2') + expect(preEpochUpperText).not.toContain('seq 3') + }) }) diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index c33b1c9967..2afb4e9dc7 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -382,6 +382,137 @@ describe('input validation and translation', () => { }) }) + it.each([ + ['one fractional digit', '2026-07-24T00:00:00.1Z', 100], + ['two fractional digits', '2026-07-24T00:00:00.12Z', 120], + ['three fractional digits', '2026-07-24T00:00:00.123Z', 123], + ])('normalizes %s into an exact integer epoch-millisecond filter', async (_case, value, offset) => { + const mounted = await mount() + await mounted.call('session_search', { + query: 'q', + created_at_from: value, + }) + const expected = Date.parse('2026-07-24T00:00:00.000Z') + offset + expect(Number.isFinite(expected)).toBe(true) + expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({ + kind: 'created-at', + from: expected, + }) + }) + + it('maps exact same-millisecond decimal bounds to adjacent numeric values without collapsing the interval', async () => { + const mounted = await mount() + const base = Date.parse('2026-07-24T00:00:00.000Z') + const result = await mounted.call('session_search', { + query: 'q', + created_at_from: '2026-07-24T00:00:00.12300001Z', + created_at_to: '2026-07-24T08:00:00.1239999+08:00', + }) + + expect(result.isError).toBe(false) + expect(text(result)).toContain('No prior session matches found.') + const range = FakeQuery.sessionRequests[0]?.sessionFilters + ?.find(filter => filter.kind === 'created-at') + expect(range).toBeDefined() + if (range?.kind !== 'created-at' || range.from === undefined || range.to === undefined) { + throw new Error('expected complete created-at range') + } + expect(Number.isFinite(range.from)).toBe(true) + expect(Number.isFinite(range.to)).toBe(true) + expect(range.from).toBeGreaterThan(base + 123) + expect(range.from).toBeLessThan(base + 124) + expect(range.to).toBeGreaterThan(base + 123) + expect(range.to).toBeLessThan(base + 124) + expect(range.from).toBeLessThan(range.to) + }) + + it('rejects exact bounds reversed only below one millisecond before calling the provider', async () => { + const mounted = await mount() + const result = await mounted.call('session_search', { + query: 'q', + created_at_from: '2026-07-24T00:00:00.12300002Z', + created_at_to: '2026-07-24T00:00:00.12300001Z', + }) + + expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_FILTER') + expect(FakeQuery.sessionRequests).toEqual([]) + }) + + it('compares unequal-length exact remainders with implicit trailing decimal zeroes', async () => { + const mounted = await mount() + const ordered = await mounted.call('session_search', { + query: 'q', + created_at_from: '2026-07-24T00:00:00.1231Z', + created_at_to: '2026-07-24T00:00:00.12311Z', + }) + expect(ordered.isError).toBe(false) + + const reversed = await mounted.call('session_search', { + query: 'q', + created_at_from: '2026-07-24T00:00:00.12311Z', + created_at_to: '2026-07-24T00:00:00.1231Z', + }) + expect(errorCode(reversed)).toBe('SESSION_QUERY_INVALID_FILTER') + }) + + it('treats trailing-zero fractional spellings as the same exact instant', async () => { + const mounted = await mount() + const result = await mounted.call('session_search', { + query: 'q', + created_at_from: '2026-07-24T00:00:00.1230000100Z', + created_at_to: '2026-07-24T00:00:00.12300001Z', + }) + + expect(result.isError).toBe(false) + expect(FakeQuery.sessionRequests).toHaveLength(1) + }) + + it('maps fractional bounds correctly across zero and for negative pre-epoch milliseconds', async () => { + const mounted = await mount() + await mounted.call('session_search', { + query: 'q', + created_at_from: '1970-01-01T00:00:00.0000001Z', + event_time_to: '1969-12-31T23:59:59.9999999Z', + }) + expect(FakeQuery.sessionRequests[0]?.sessionFilters).toContainEqual({ + kind: 'created-at', + from: Number.MIN_VALUE, + }) + expect(FakeQuery.sessionRequests[0]?.eventFilters).toContainEqual({ + kind: 'time', + to: -Number.MIN_VALUE, + }) + + await mounted.call('session_event_search', { + query: 'q', + time_from: '1969-12-31T23:59:59.87600001Z', + time_to: '1969-12-31T19:59:59.8769999-04:00', + }) + const range = FakeQuery.eventRequests[0]?.filters?.find(filter => filter.kind === 'time') + expect(range).toBeDefined() + if (range?.kind !== 'time' || range.from === undefined || range.to === undefined) { + throw new Error('expected complete event time range') + } + expect(range.from).toBeGreaterThan(-124) + expect(range.from).toBeLessThan(-123) + expect(range.to).toBeGreaterThan(-124) + expect(range.to).toBeLessThan(-123) + expect(range.from).toBeLessThan(range.to) + }) + + it('rejects a normalized timestamp when the platform parser cannot produce a finite value', async () => { + const mounted = await mount() + vi.spyOn(Date, 'parse').mockReturnValueOnce(Number.NaN) + + const result = await mounted.call('session_search', { + query: 'q', + created_at_from: '2026-07-24T00:00:00.123456Z', + }) + + expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_FILTER') + expect(FakeQuery.sessionRequests).toEqual([]) + }) + it('compiles one-sided timestamps and independent root/parent clauses', async () => { const mounted = await mount() await mounted.call('session_search', { @@ -463,6 +594,109 @@ describe('workspace authority and lineage redaction', () => { expect(output).not.toContain('hidden-grandchild-secret') }) + it('sanitizes a real outside-workspace ancestor cycle before the lineage error reaches the model', async () => { + const mounted = await mount() + const hiddenA = SessionId('hidden-cycle-a-secret') + const hiddenB = SessionId('hidden-cycle-b-secret') + createSession(mounted.ctx, hiddenA, '/outside', 2, hiddenB) + createSession(mounted.ctx, hiddenB, '/outside', 3, hiddenA) + const target = createSession(mounted.ctx, 'visible-cycle-target', '/work', 4, hiddenA) + + const result = await mounted.call('session_trace', { session_id: target.id }) + + expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_LINEAGE') + expect(text(result)).toBe('Error: session lineage is invalid') + const presentation = JSON.stringify(result) + expect(presentation).not.toContain(hiddenA) + expect(presentation).not.toContain(hiddenB) + }) + + it.each([ + { + name: 'typed query error', + makeError: () => new SessionQueryError( + 'unrelated persistence failure', + 'SESSION_QUERY_PERSISTENCE_FAILED', + ), + code: 'SESSION_QUERY_PERSISTENCE_FAILED', + message: 'unrelated persistence failure', + }, + { + name: 'plain error', + makeError: () => new Error('unrelated plain trace failure'), + code: undefined, + message: 'unrelated plain trace failure', + }, + ])('preserves an unrelated $name from lineage tracing', async ({ makeError, code, message }) => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'trace-failure-target', '/work') + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockRejectedValueOnce(makeError()) + + const result = await mounted.call('session_trace', { session_id: target.id }) + + expect(errorCode(result)).toBe(code) + expect(text(result)).toBe(`Error: ${message}`) + }) + + it('preserves caller cancellation while a lineage trace is pending', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'cancelled-trace-target', '/work') + const trace = await mounted.ctx.sessionQuery.traceSession(target.id) + let started!: () => void + const traceStarted = new Promise((resolve) => { started = resolve }) + let finish!: (value: typeof trace) => void + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockImplementation(() => { + started() + return new Promise((resolve) => { finish = resolve }) + }) + const controller = new AbortController() + const cancellation = new SessionQueryError('lineage trace cancelled', 'SESSION_QUERY_ABORTED') + + const pending = mounted.call( + 'session_trace', + { session_id: target.id }, + { signal: controller.signal }, + ) + await traceStarted + controller.abort(cancellation) + finish(trace) + const result = await pending + + expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') + expect(text(result)).toBe('Error: lineage trace cancelled') + }) + + it('gives caller cancellation precedence when a pending trace rejects with invalid lineage', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'cancelled-invalid-lineage-target', '/work') + let started!: () => void + const traceStarted = new Promise((resolve) => { started = resolve }) + let fail!: (error: SessionQueryError) => void + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockImplementation(() => { + started() + return new Promise((_resolve, reject) => { fail = reject }) + }) + const controller = new AbortController() + const cancellation = new SessionQueryError('lineage trace cancelled first', 'SESSION_QUERY_ABORTED') + + const pending = mounted.call( + 'session_trace', + { session_id: target.id }, + { signal: controller.signal }, + ) + await traceStarted + controller.abort(cancellation) + fail(new SessionQueryError( + 'session lineage contains a cycle at "hidden-race-secret"', + 'SESSION_QUERY_INVALID_LINEAGE', + )) + const result = await pending + + expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') + expect(text(result)).toBe('Error: lineage trace cancelled first') + expect(JSON.stringify(result)).not.toContain('hidden-race-secret') + }) + it('renders branching descendants in source preorder with one indented marker per pruned subtree', async () => { const mounted = await mount() const target = createSession(mounted.ctx, 'branch-target', '/work', 20) From fd6713b4967506e654dd7bdf77b067f4ffc57f96 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 00:20:38 +0800 Subject: [PATCH 013/113] docs(testing): propose keyless browser e2e lane for the web GUI Design study for a deterministic, keyless browser e2e lane over the real assembled web chain (chromium -> SSE/HTTP wire -> apiproxy -> agent loop -> persistence), replayed through dsh-llm-replay from recorded session-log fixtures, with aria-tree goldens plus in-process world-state assertions. Synthesized from an OSS prior-art survey (LibreChat, ai-chatbot, lobe-chat, OpenHands, cline, aimock...), a repo seam deep-dive, and three adversarial critiques (doctrine, flakiness, YAGNI). Records the settled shape (no new package, no suite factory, seed via the real persistence API, whenIdle barrier stack, no transient-DOM assertions) and the open questions (LLM seam, Loader-izing dsh web, header pin, golden breadth, settled signal). --- .../2026-07-24-web-gui-browser-e2e-lane.md | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 .agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md diff --git a/.agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md new file mode 100644 index 0000000000..cc7504dae7 --- /dev/null +++ b/.agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md @@ -0,0 +1,92 @@ +# Agent Note: Keyless browser e2e lane for the web GUI + +Status: proposed + +## Problem + +The web GUI ships as a real assembled chain — chromium page → nine client plugin bundles → HTTP unary RPC + two SSE streams → `toFetchHandler`/apiproxy → `bootHost`'s agent loop, tools, and JSONL persistence — and no test exercises that chain keylessly and deterministically. The [GUI testing system](../../implemented/process/2026-07-20-gui-testing-system.md) covers tier 1 (wire isomorphism in node), tier 2 (object-layer state machines), and a tier-3 smoke pair, but the keyless smoke (`apps/web/tests/smoke-fixture.e2e.ts`) drives `FixtureApiClient` behind `?fixture` — no host, no wire, no agent loop — while the full-chain smoke (`smoke-real.e2e.ts`) needs `DEEPSEEK_API_KEY` and a live model, so it is nondeterministic and self-skips in keyless CI. The snapshot philosophy of [docs/testing.md](../../../../docs/testing.md) — record once with a key, replay forever keyless, refresh on format churn — already covers the ACP, headless `stream-json`, and TUI transcript surfaces; the web surface is the one assembled product shape without it. The gap is exactly where the two confirmed GUI P0s hid: the wire carriage chain the fixture client short-circuits. + +## Proposal + +Add a keyless, deterministic browser e2e lane under `apps/web/tests/`, driven by recorded session-log fixtures replayed through `@deepseek-ai/dsh-llm-replay`, asserting the rendered accessibility tree plus in-process world state. No new package; no product-code change except (open question 1) an LLM composition knob. + +### Harness: `apps/web/tests/harness.ts` + +A plain shared-fixture module (the [testing-policy sanctioned shape](../../../../docs/testing.md)), not a package: the gate-worthy logic this lane needs — replay derivation, session parsing, log scrubbing, persistence — already lives in gated packages (`dsh-llm-replay`, `dsh-acp-snapshot`, `dsh-session-persistence-jsonl`); what remains is boot wiring and browser glue, and chromium-driving code cannot hold per-file 100% coverage on the browserless coverage runners. + +`launchWebHarness()` boots the real web assembly in-process from the exported production functions — `startHost({ boot: { persistenceRoot: , workspaceContext: false, cwd: } })`, `installLlmReplay(host.ctx, { file, childFiles, providers })`, `mountWebPlugins(host.ctx)`, `createHostWebPluginRegistry`, `startWebServer({ port: 0, distIndex, apiHandler: host.handler, webPlugins })` — and returns `{ baseUrl, host, workspaceCwd, close }`. This is the web analog of the TUI suite mounting the production bundle in-process ([TUI snapshots](../../implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)): the real entry boundary (`dsh web` bin arg-parsing and dist resolution) stays held by the existing keyless CLI smokes in `smoke-real.e2e.ts`, and the web surface has no `cordis.yml` to bypass — assembly is written in the app per the [GUI layering decision](../../implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md). Replay runs in providers-catalog mode with a `contextWindow` (the TUI suite's `PROVIDERS` shape), never catch-all: with no adapter registered, catch-all mode would make `compact-basic`'s `resolveModelContext` throw into its post-step catch every step, spamming warnings and silently disabling the pressure path instead of proving it inert. + +`seedSession(host, fixtureText)` seeds cold sessions through the real persistence API — a throwaway `Context` mounting `SessionStore` + `SessionPersistenceJsonl` against the host's root, `create()` + `append()`, one `utimes` for deterministic sidebar order (the precedent is `examples/acp-agent/tests/semantic-checkpoint.snapshot.ts`) — never raw file writes, so the seeder needs no knowledge of bucket hashing, filename encoding, or compression. Seeds are validated at seed time (parseable, `seq`-contiguous, ending in `turn/end`) so fixture drift fails loud at the earliest resolvable point rather than as silently dropped frames in the client; a seed not ending in `turn/end` would be mutated by resume's crash repair. + +### Determinism rules + +The barrier stack, in order, for a prompted turn: (1) host-side `await agent.whenIdle()` under a timeout — the idle flip happens after both the `turn/end` append and the persistence flush, so one await covers turn completion and durability; (2) browser settled poll — streaming node detached, composer restored, final text visible; (3) log harvest only after `host.dispose()`. An in-process `turn/end` listener alone is a wrong barrier (it fires before the SSE frame reaches the browser and before the fsync), and file polling is banned (slow on NFS, superseded by `whenIdle`). For history-open scenarios the barrier is a poll for the last expected message's text, then a poll-until-equal aria capture. `networkidle` is banned outright — it never resolves while an SSE stream is open. + +No single-shot transient-DOM assertions: every hop from replay yield to React commit can coalesce chunks, so sampling `[data-streaming]` is a race by construction. Streaming incrementality is asserted from the persisted `assistant/chunk` events (model-visible ⟺ logged makes the log the authoritative proof), optionally corroborated by an in-page MutationObserver latch armed before send — observers cannot miss a commit; polls can. `dsh-llm-replay` gains an opt-in `paceMs` config field (default absent = today's instant yield) as a realism knob so the browser observes genuinely incremental SSE; correctness never leans on the pace. + +Every scenario fails on any pageerror and on the client's connection-loss/gap-repair console warnings: the reconnect machine plus history resync would otherwise self-heal a dead SSE path and the suite would certify a broken wire. Harness `close()` asserts every replay script was fully consumed (all scripts bound, every cursor at end), converting silent underruns and shifted bindings into crisp diagnostics; this is a small additive stats handle on `installLlmReplay`. No vitest retry on the lane — a retried-green race is a flake deferred, and only the chromium launch itself may retry inside the harness, logged. One chromium per file, fresh browser context per scenario, one host per scenario; viewport pinned; selectors anchor on roles, `data-*` attributes, and visible text only. + +### Expected outputs + +One committed golden per scenario: a normalized `ariaSnapshot()` of the conversation region only (`ui.expected.md`) — uuid/cwd/duration tokens normalized, sidebar and other time-bearing chrome structurally excluded, captured poll-until-equal at the settled milestone. The accessibility tree is the mechanization of the client rule "assert what the user would see, never class names": it survives CSS-module hash churn, styling rewrites, and DOM restructuring, and a wholesale component rewrite refreshes it keylessly. Alongside the golden, three or four targeted role/text anchor assertions (heading level, `pre code` content, tool-row accessible name) keep green anchors under a semantics-preserving rewrite so a churned golden diff is reviewable against surviving anchors. World-state assertions ride `host.ctx` session events inline (which tools ran, `turn/end` completed, no error) instead of a second committed log golden: the persisted-log surface is already pinned by the ACP/headless/TUI suites through the same loop and persistence plugins, and re-pinning it here would double refresh cost for no new regression class. `playwright` gets pinned exactly in `apps/web/package.json` — the aria format is Playwright-owned, the one snapshot format in this repo we do not own, so version bumps must be deliberate bump-and-refresh commits. + +### Modes and fixtures + +`DSH_SNAPSHOT` selects replay (default, keyless), record (with key), or refresh (keyless), as inline branches in the specs — the TUI suite's shape, not a suite-factory: at two scenarios the acp-snapshot factory machinery (scenario tables, pinning classes, Windows sidecars, packed-row stabilization) has no owner, and the genuinely shared parts are already exported (`scrubRequestHeaders`, `normalizeSessionLog`, `parseSessionLog`, `installLlmReplay`). Each scenario script splits into drive steps (type, send, `whenIdle`-generic waits — run in all modes, never waiting on model-content selectors) and interaction/assertion steps (expand reasoning, aria capture — replay/refresh only), so record mode cannot hang on a live model answering with a different tool count. Record = drive + harvest the in-memory `session.header` + `session.events` (the TUI `rawSessionLog` shape — no file decompression, so `bootHost` needs no compression knob) + scrub via `scrubRequestHeaders` + a mandatory keyless refresh to regenerate `ui.expected.md`. Web fixtures scrub headers everywhere and pin nowhere, matching the TUI precedent; whether the web surface must instead own a header-class pin per the [pinned-header discipline](../../implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md) is open question 3. Seeds are recorded fixtures under the same inventory and refresh discipline as replay fixtures, never hand-authored one-offs, so `DSH_SNAPSHOT=refresh` heals every committed surface after intentional shape churn and only `assistant/chunk`-shape churn escalates to re-record. A TUI-style `afterAll` fixture guard holds the inventory closed (expected files present, every fixture scrub-fixed-point, no orphan directories). + +### Demo scenarios + +1. **`fresh-round-trip`** — new session, prompt, replay streams reasoning + markdown + a `bash` tool call that really executes (`echo` in the temp workspace) + final text. Asserts settled markdown semantics (heading, code block), the tool card row, composer restore, the aria golden, and inline world state (bash `tool/call` + completed `turn/end` in the session events). The keyless version of the with-key W5 flows. +2. **`seeded-history`** — a recorded session seeded cold; the sidebar lists it, opening it renders tool cards and collapsible reasoning purely from the log. This exercises the implicit cold-resume attach (`session.history` resumes via `agentFor`), cold summaries, history pagination views, and the client fold of historical events — the surface nothing else covers — with zero model calls, so no replay-binding constraints at all. A follow-up-prompt-after-resume scenario is deliberately deferred until the history/live stitch path changes or regresses. + +### Lane wiring and CI stance + +The lane rides `vitest.web.config.ts` (`pnpm run test:web`, serial), which stays gate-exempt exactly as its header comment records. Adding chromium to CI would reverse the "no browser infrastructure in CI" premise recorded in the [GUI testing system note](../../implemented/process/2026-07-20-gui-testing-system.md) and therefore requires its own Agent Note cross-linked from that note, staged as: non-required CI job first, promotion criteria measured (consecutive green runs, wall time, zero-retry flake budget, browser cache strategy on the enterprise runners, whether the runner images carry the chromium system libraries). Deferred out of this proposal; a `TODO(ci-browser)` marks the seam. Scenarios are `posixOnly` initially. Docs updated in the same implementation PR: the [testing policy](../../../../docs/testing.md) names `apps/web/tests/snapshots/` as the web surface's snapshot home with its divergent `DSH_SNAPSHOT=… pnpm run test:web` commands, the GUI testing note's tier map gains the lane (and drops its stale references to the deleted `missions/scripts/verify-*` files), `packages/client/AGENTS.md`'s check ladder mentions it, and the `dsh-acp-snapshot` README's "ACP-specific by design" sentence is corrected — this lane is the third consumer of its normalizers. + +### Open questions + +1. **LLM seam.** Two viable shapes. (a) `BootHostOptions.llm?: 'deepseek' | false` — an assembly toggle in the one module that owns assembly, matching the existing `workspaceContext: Config | false` shape and the reserved-knob sentence in `start.ts`; `llm: false` mounts no adapter, the harness fills the open seam on `host.ctx`, misuse fails loud at the first stream with `NO_ADAPTER`, and keyless boots stop needing any key. (b) Zero product change — a placeholder `DEEPSEEK_API_KEY` env var satisfies `llm-deepseek`'s load-time presence check (twice-precedented in-tree) and replay intercepts ahead of the mounted adapter. (a) is cleaner semantics and honest keylessness at the cost of a test-motivated product field; (b) is free but satisfies a fail-loud check with a lie and leaves a dead adapter mounted. Recommendation: (a), shaped minimal. +2. **Loader-izing `dsh web`.** Making the web host `cordis.yml`-driven like every example would give the ACP-style `cordis.snapshot.yml` replay overlay for free and align with "everything is a plugin", but it reverses the settled "assembly is written in the app" ruling and is a product-architecture decision on its own merits — its own proposal if wanted; this lane does not need it. +3. **Header-class pin.** Strict reading of the pinned-header discipline wants one web scenario pinning `bootHost`'s composed prompt + tool schemas (a header class no ACP scenario covers); the TUI precedent scrubs everywhere and pins nowhere. Cheap middle: pin sidecars on `fresh-round-trip` at record time. Recommendation: follow TUI now (scrub-only), revisit when the web assembly's header diverges further from the repl composition it mirrors. +4. **Golden breadth.** Full conversation-region aria golden (adopted above) versus targeted assertions only. The golden is the "assembled transcript" duty for user-visible changes; the cost is a keyless refresh on every component rewrite. Recommendation: keep the golden + anchors. +5. **Client settled signal.** A `data-dsh-busy` attribute derived from the object layer's pending-RPC/active-stream state would replace multi-condition settled polls with one selector. Presentation-plane observability, no session-log leak — but the current polls suffice for two scenarios. Recommendation: defer until a settled-poll flake actually appears. + +## Prior art + +Surveyed AI-chat/agent web UIs and mocking layers (LibreChat, vercel/ai-chatbot + AI SDK, lobe-chat, open-webui, OpenHands, Chainlit, continue, cline, langfuse, gradio/streamlit; Playwright HAR/route, MSW, Polly/nock, WireMock, aimock). The dominant proven architecture for apps that own their backend is an in-process fake/replay model behind the real backend seam with everything downstream real (LibreChat's `LIBRECHAT_TEST_RUN_HOOK` fake model; ai-chatbot's `MockLanguageModelV3` + `simulateReadableStream`; continue's scripted mock provider classes) — which is what `dsh-llm-replay` already is. Browser-level SSE interception cannot exercise incremental rendering (`route.fulfill` delivers the whole body at once; playwright#33564) and leaves the server SSE stack untested, so projects use it only for edge cases. Chunk pacing as a fixture parameter recurs everywhere (LibreChat 10ms default with slow profiles; ai-chatbot 500ms); real models in CI rot (open-webui's suite grew 120-second timeouts, was disabled, then deleted); sessions are seeded at the persistence layer with controlled timestamps (LibreChat inserts backdated Mongo documents; langfuse seeds its DB). No surveyed project replays a recorded agent-event log through the real backend for UI tests — the closest are provider-level recorded fixtures (aimock) and frontend-level socket history emission (OpenHands MSW) — so the session-log-as-fixture design goes one step beyond prior art along the axis this repo's model-visible ⟺ logged invariant makes natural. + +## Alternatives considered + +**Browser-network SSE interception (`page.route`).** Rejected: `route.fulfill` cannot stream, so incremental token rendering is unexercisable and the server-side SSE/backpressure/close path — where both confirmed P0s hid — goes untested. + +**Mock HTTP provider at `DEEPSEEK_BASE_URL`.** Rejected as the lane's mechanism (kept for the one existing workspace-probe smoke): fixtures become hand-authored OpenAI SSE byte scripts, a second fixture format that drifts from the session-log format the rest of the repo records and replays; the adapter's real HTTP path is with-key e2e's job. + +**Growing the `?fixture` client.** Rejected: tier separation — `FixtureApiClient` exists to test the client shell without a server; everything below the client API seam stays untested by construction. + +**A `packages/support/web-snapshot` package with a `defineWebSnapshotSuite` factory.** Rejected for now: chromium-driving source cannot honestly hold per-file 100% coverage on browserless coverage runners, and at two scenarios the factory generalizes from one consumer while the genuinely shared logic already lives exported in `dsh-llm-replay`/`dsh-acp-snapshot`. Re-entry trigger: a second web-shaped consumer or ≥6 scenarios with demonstrably drifting inline branches; the package boundary would then be drawn browser-free. + +**A committed normalized-session-log golden as a second expected surface.** Rejected: the log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence; here it would double refresh cost and re-test lower tiers, against the tier discipline. Inline world-state assertions on `host.ctx` events keep the world-verification duty. + +**Spawning the `dsh web` bin with a `DSH_SNAPSHOT` replay branch.** Rejected for now: it needs a test-mode branch plus env plumbing in the product bin where the in-process route uses exported production functions with zero product change; the bin's thin glue is covered by the keyless CLI smokes. Becomes free if the web host is ever Loader-ized (open question 2). + +**Changing the wire protocol for testability.** Rejected: the contract already has a first-class keyless isomorphic seam (`InProcessApiClient(toFetchHandler(api))`), the per-event unbatched SSE is exactly what makes replay observable in a browser, and testing a wire we no longer ship would invert the tier's purpose. + +**Real-model browser tests as the keyless lane.** Rejected: nondeterministic by construction; the surveyed cautionary case (open-webui) grew unbounded timeouts and was deleted. The with-key W5 smoke stays as the live-model complement. + +## Acceptance criteria + +- `pnpm run test:web` keyless passes the two scenarios deterministically (no vitest retry), alongside the existing smoke pair, on a checkout with built client bundles and the frontend dist. +- Replay asserts: aria golden equality at the settled milestone, anchor role/text assertions, inline world-state event assertions, zero pageerrors, zero connection-loss/gap-repair console warnings, all replay scripts fully consumed at teardown. +- `DSH_SNAPSHOT=record` with a key re-records `fresh-round-trip` (drive steps only), rewrites its `session.jsonl` scrubbed, and a follow-up `DSH_SNAPSHOT=refresh` regenerates `ui.expected.md` keylessly; `refresh` alone heals goldens after intentional non-chunk shape churn. +- The seeded scenario renders history through the real cold-resume path with zero model calls and leaves the seed fixture byte-identical (closedness validated at seed time). +- Fixture guard holds the snapshot inventory closed; failure produces a bundle under `.artifacts/` (screenshot, console, pageerrors, persistence copy, actual-vs-expected aria). +- Docs land in the same PR: testing.md web-lane entry, GUI testing note tier map + stale verify-script cleanup, client AGENTS.md ladder, acp-snapshot README correction, this note moved to `implemented/` rewritten in present tense. + +## Risks + +- **The aria format is Playwright-owned** — the one committed snapshot format the repo does not control; a version bump can churn every golden. Mitigated by an exact version pin in `apps/web` and a documented bump-and-refresh procedure; residual risk accepted. +- **Replay's first-call-order binding** stays fragile under concurrent browser-driven sessions; the lane constrains scenarios to one prompting session each (the seeded scenario prompts none), and the teardown consumption assertion turns violations into diagnostics rather than surreal transcripts. +- **`compact-basic` shares the session's replay cursor** — a pressure-triggered summarize would consume a script entry; inert for small fixtures under the 128k catalog window, and the consumption assertion catches it if a fixture ever grows past the threshold. +- **CI remains browserless for now**, so the lane guards regressions only where it is run (locally and in any future non-required job) until the CI reversal is separately decided; the runner images' chromium-library situation is unverified. +- **Record-mode nondeterminism** is contained but not eliminated by the drive/assert split: a live model may still produce a transcript whose replay violates a scenario's assertions, requiring prompt tuning at record time (bounded by terse prompts and a chunk-count warning in record mode). +- **jsdom-lane overlap**: component-level rendering is already covered per-plugin; this lane must stay at assembled-transcript altitude (whole-region golden + anchors) or it starts re-testing tier 2 and paying double maintenance. From 9ef0193dd56a56ca4792c12f8296b035201dee85 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:08:10 +0800 Subject: [PATCH 014/113] feat(host-runtime,llm-replay): keyless llm seam + replay pacing/consumption handle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BootHostOptions.llm: 'deepseek' | false — false mounts no adapter, boots keyless, and leaves the llm capability seam open for the embedder to fill on RunningHost.ctx (now the third sanctioned ctx use, JSDoc + README amended); an unfilled seam fails loud with NO_ADAPTER at the first stream. dsh-llm-replay grows two additive surfaces for the web browser e2e lane: paceMs (validated per-chunk delay so a real transport shows incremental delivery; abort during a pace wait cancels promptly) and a ReplayHandle return — dispose() plus assertConsumed(), the teardown check that every recorded script bound and drained, converting silent fixture underruns into diagnostics. Existing callers updated; config catalog regenerated. --- docs/config-catalog.md | 4 +- packages/host/runtime/README.md | 3 +- packages/host/runtime/src/boot.ts | 11 ++- packages/host/runtime/src/start.ts | 9 +- .../host/runtime/tests/host-runtime.spec.ts | 36 ++++++++ packages/support/llm-replay/README.md | 5 +- packages/support/llm-replay/src/index.ts | 88 +++++++++++++++++-- .../llm-replay/tests/llm-replay.spec.ts | 63 ++++++++++++- 8 files changed, 201 insertions(+), 18 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 49a0a1510f..c06fef3d4d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -616,6 +616,8 @@ export interface Config { childFiles?: string[] /** Optional replay-only provider catalog; absent or empty selects catch-all waterfall replay. */ providers?: ReplayProviderConfig[] + /** Optional per-chunk pacing delay in ms (see {@link ReplayConfig.paceMs}); absent keeps burst yield. */ + paceMs?: number } /** One provider route exposed by the replay adapter. */ @@ -641,7 +643,7 @@ export interface ReplayModelConfig { } ``` -Source: [`packages/support/llm-replay/src/index.ts:387`](../packages/support/llm-replay/src/index.ts) +Source: [`packages/support/llm-replay/src/index.ts:453`](../packages/support/llm-replay/src/index.ts) ## `@deepseek-ai/dsh-llm-retry` diff --git a/packages/host/runtime/README.md b/packages/host/runtime/README.md index f7cf7d9de8..4384f591a1 100644 --- a/packages/host/runtime/README.md +++ b/packages/host/runtime/README.md @@ -2,7 +2,7 @@ Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence and immediate fallback titles, optional first-message model summaries, system prompt, tools, agents, agent loop, workspace instructions, local bash, and the provider-neutral user-interaction service), `createApiProxy` implements the [`dsh-host-apiproxy`](../apiproxy/README.md) contract over that composition, and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }`. -Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly two sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`) and headless session-event subscription; consuming clients must not bypass `api` through it. +Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly three sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`), headless session-event subscription, and filling a capability seam the boot options deliberately left open (`llm: false` → the embedder installs its own LLM backend, e.g. the keyless web e2e harness's replay); consuming clients must not bypass `api` through it. ## Configuration @@ -10,6 +10,7 @@ Which plugins mount and with what defaults is decided only here — shells must |---|---:|---| | `persistenceRoot` | (required) | Root directory for JSONL session persistence. | | `workspaceContext` | (required) | [`AGENTS.md`/`CLAUDE.md` loader](../../context/workspace-context/README.md) config with an explicit `maxBytes`, or `false` to disable it. | +| `llm` | `'deepseek'` | LLM adapter selection: `'deepseek'` mounts the DeepSeek adapter (API key required at load); `false` mounts none, boots keyless, and leaves the `llm` seam open for the embedder — an unfilled seam fails loud with `NO_ADAPTER` at the first stream. | | `provider` | `'deepseek'` | Default provider route injected as agentOptions on create/resume and reported by `host.describe`. | | `model` | `'deepseek-v4-flash'` | Default model id, same single source as `provider`. | | `cwd` | `process.cwd()` | Default project directory for a session whose create request omits `cwd`. | diff --git a/packages/host/runtime/src/boot.ts b/packages/host/runtime/src/boot.ts index c0960ab678..e2f24a98ac 100644 --- a/packages/host/runtime/src/boot.ts +++ b/packages/host/runtime/src/boot.ts @@ -65,6 +65,15 @@ export interface BootHostOptions { persistenceRoot: string /** Workspace-instruction byte budget/config, or false to disable AGENTS.md/CLAUDE.md loading. */ workspaceContext: workspaceContext.Config | false + /** + * LLM adapter selection: `'deepseek'` (default) mounts the DeepSeek adapter + * (requires an API key at load), `false` mounts no adapter and leaves the + * `llm` capability seam open for the embedder to fill on the returned ctx + * (e.g. the keyless web e2e harness installing a replay backend). With + * `false` and nothing filled, the first stream fails loud with NO_ADAPTER — + * the earliest resolvable point for an open capability seam. + */ + llm?: 'deepseek' | false /** Default provider route for created/resumed agents (defaults to 'deepseek', the only adapter bootHost registers). */ provider?: string /** Default model id (defaults to 'deepseek-v4-flash', matching the demos). */ @@ -129,7 +138,7 @@ export async function bootHost(options: BootHostOptions): Promise { await ctx.plugin(AgentRegistry) await ctx.plugin(TaskService) await ctx.plugin(AgentLoop, { agents: [] }) - await ctx.plugin(LlmDeepSeek, {}) + if (options.llm !== false) await ctx.plugin(LlmDeepSeek, {}) await ctx.plugin(SessionPersistenceJsonl, { root: options.persistenceRoot }) await ctx.plugin(LocalBashExecutor, {}) // Tool suite mirroring the demo:repl composition (repl-agent/cordis.yml + diff --git a/packages/host/runtime/src/start.ts b/packages/host/runtime/src/start.ts index 94e5f22da1..c389c0de68 100644 --- a/packages/host/runtime/src/start.ts +++ b/packages/host/runtime/src/start.ts @@ -34,9 +34,12 @@ export interface RunningHost { /** * Root context — a formal seam, not an escape hatch: (1) the mount point for * protocol front-door plugins (`dsh acp` = startHost() → ctx.plugin(uiAcp, config)); - * (2) headless session-event subscription. Discipline: consuming clients must - * not bypass `api` through ctx; shells must not ctx.plugin to alter the - * assembly (mounting a front door is the shell's own shape, not an assembly change). + * (2) headless session-event subscription; (3) filling a capability seam the + * boot options deliberately left open (`llm: false` → the embedder installs + * its own LLM backend, e.g. keyless replay). Discipline: consuming clients + * must not bypass `api` through ctx; shells must not ctx.plugin to alter the + * assembly (mounting a front door or filling an explicitly-open seam is the + * shell's own shape, not an assembly change). */ ctx: Context /** Single shutdown exit (ctx.fiber.dispose()). Idempotent: a second call returns the same promise. */ diff --git a/packages/host/runtime/tests/host-runtime.spec.ts b/packages/host/runtime/tests/host-runtime.spec.ts index 4058fdfe2e..92d6534831 100644 --- a/packages/host/runtime/tests/host-runtime.spec.ts +++ b/packages/host/runtime/tests/host-runtime.spec.ts @@ -205,6 +205,42 @@ describe('bootHost / startHost', () => { expect((await ctx.sessionTitle.refresh(agent.session))?.source).toEqual({ kind: 'fallback' }) expect(agent.session.events.some(event => event.type === 'session/title-llm-request')).toBe(false) }) + + it('llm: false boots keyless with no adapter and fails loud at the first stream', async () => { + vi.stubEnv('DEEPSEEK_API_KEY', '') + const handle: HostHandle = await bootHost({ + persistenceRoot: mkdtempSync(join(tmpdir(), 'dsh-boot-keyless-')), + workspaceContext: false, + llm: false, + }) + // The seam is open: nothing routes 'deepseek', so misuse surfaces at the + // earliest resolvable point instead of silently doing provider I/O. + await expect(async () => { + for await (const chunk of handle.ctx.llm.stream({ + provider: 'deepseek', + model: 'deepseek-v4-flash', + messages: [], + })) void chunk + }).rejects.toThrow(/NO_ADAPTER|no adapter/i) + // The embedder can fill the open seam on the returned ctx (the sanctioned + // RunningHost.ctx use) and streams route through the filled adapter. + class ProbeAdapter extends LlmAdapter { + async * stream(): AsyncIterable { + yield * textResponse('keyless-ok') + } + } + handle.ctx.llm.registerAdapter(['deepseek'], new ProbeAdapter()) + const collected: string[] = [] + for await (const chunk of handle.ctx.llm.stream({ + provider: 'deepseek', + model: 'deepseek-v4-flash', + messages: [], + })) { + if (chunk.type === 'text-delta') collected.push(chunk.text) + } + expect(collected.join('')).toBe('keyless-ok') + await handle.dispose() + }) }) describe('host.describe', () => { diff --git a/packages/support/llm-replay/README.md b/packages/support/llm-replay/README.md index 0d89d4337d..e655aa4077 100644 --- a/packages/support/llm-replay/README.md +++ b/packages/support/llm-replay/README.md @@ -24,6 +24,7 @@ Replay keys every call by its calling session id (`GenerateOptions.sessionId`, s | `overrideFile` | string | `$DSH_SNAPSHOT_OVERRIDE` | Optional path to a `ReplayEntry[]` sidecar that replaces the PRIMARY session's derived script. | | `childFiles` | string[] | `$DSH_SNAPSHOT_CHILD_FILES` (path-delimited) | Recorded subagent child-session logs for a nested scenario; empty for a single-session scenario. | | `providers` | `ReplayProviderConfig[]` | — | Optional replay-only provider and model catalog. Each model may publish `contextWindow`; configured routes dispatch through the replay adapter and never perform provider I/O. | +| `paceMs` | number | — (burst) | Optional per-chunk delay in ms so downstream transports (e.g. the web SSE mux observed by a real browser) see genuinely incremental delivery. A realism knob only — tests must not depend on it for correctness. Non-negative integer; abort during a pace wait cancels the stream promptly. | ```yaml - id: llm-replay @@ -43,11 +44,11 @@ Replay keys every call by its calling session id (`GenerateOptions.sessionId`, s ## Exports -- `installLlmReplay(ctx, config)` — install the configured replay adapter or catch-all `llm/stream` listener; returns the disposer (HMR safety). Use this in tests to drive replay without the Loader or env vars. +- `installLlmReplay(ctx, config)` — install the configured replay adapter or catch-all `llm/stream` listener; returns a `ReplayHandle` (`dispose()` for HMR safety plus `assertConsumed()`, the teardown check that every recorded script bound to a live session and every bound cursor drained — turning a scenario that silently drove fewer model calls than recorded into a crisp diagnostic). Use this in tests to drive replay without the Loader or env vars. - `loadSessionScripts(config)` — resolve the ordered `SessionScript[]` (primary + children) for a scenario, ready to bind to live sessions in first-call order. - `loadReplayScript(config)` — resolve the `ReplayEntry[]` for the PRIMARY session only (sidecar override if present, else derived from the JSONL; fail-loud if the fixture is missing). - `deriveReplayScript(events)` / `parseSessionLog(text)` / `parseSessionHeader(text)` — the pure helpers that turn a recorded session log into a script and read its header `id`/`createdAt`. A derived group must end in a `finish` chunk; a group without one is the fingerprint of a thrown `stream()` and must instead be expressed via an override sidecar. -- Types `ReplayEntry` / `SessionScript` / `ReplayConfig` / `ReplayProviderConfig` / `ReplayModelConfig` / `Config`. +- Types `ReplayEntry` / `SessionScript` / `ReplayConfig` / `ReplayProviderConfig` / `ReplayModelConfig` / `ReplayHandle` / `Config`. ## Plugin export shape diff --git a/packages/support/llm-replay/src/index.ts b/packages/support/llm-replay/src/index.ts index ca4511db8a..ecdd5b0c3b 100644 --- a/packages/support/llm-replay/src/index.ts +++ b/packages/support/llm-replay/src/index.ts @@ -74,6 +74,32 @@ export interface ReplayConfig { * by tests that do not need discovery. */ providers?: ReplayProviderConfig[] + /** + * Optional per-chunk pacing delay in milliseconds: each replayed chunk waits + * this long before yielding, so a downstream transport (e.g. the web SSE + * mux observed by a browser) sees genuinely incremental delivery. A realism + * knob only — correctness must never depend on it. Absent or `0` keeps + * today's synchronous burst yield. Must be a non-negative finite integer; + * aborting mid-wait cancels the stream like any other abort. + */ + paceMs?: number +} + +/** + * Handle returned by {@link installLlmReplay}: removal plus the end-of-run + * consumption check that turns silent fixture underruns (a scenario that + * issued fewer calls than recorded, or never bound a recorded child script) + * into a crisp diagnostic at teardown. + */ +export interface ReplayHandle { + /** Remove the registered adapter or waterfall listener (HMR safety). Freestanding closure — safe to destructure. */ + dispose(this: void): void + /** + * Throw unless every recorded script was bound to a live session and every + * bound cursor consumed its full entry list. Call at scenario teardown. + * Freestanding closure — safe to destructure. + */ + assertConsumed(this: void): void } /** @@ -277,12 +303,32 @@ class ReplayAdapter extends LlmAdapter { } } +/** + * Wait `paceMs` between chunk yields, aborting the wait (and the stream) the + * moment the signal fires — a paced replay must cancel as promptly as a burst + * one. + */ +function paceDelay(paceMs: number, signal: AbortSignal | undefined): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + signal?.removeEventListener('abort', onAbort) + resolve() + }, paceMs) + const onAbort = (): void => { + clearTimeout(timer) + reject(new Error('aborted')) + } + signal?.addEventListener('abort', onAbort, { once: true }) + }) +} + /** Yield a recorded stream back, honoring abort like a real adapter. */ -async function* replayEntry(entry: ReplayEntry, signal: AbortSignal | undefined): AsyncIterable { +async function* replayEntry(entry: ReplayEntry, signal: AbortSignal | undefined, paceMs: number): AsyncIterable { switch (entry.kind) { case 'chunks': for (const chunk of entry.chunks) { if (signal?.aborted) throw new Error('aborted') + if (paceMs > 0) await paceDelay(paceMs, signal) yield chunk } return @@ -293,6 +339,7 @@ async function* replayEntry(entry: ReplayEntry, signal: AbortSignal | undefined) // mid-stream STREAM_CLOSED after partial chunks). for (const chunk of entry.chunks) { if (signal?.aborted) throw new Error('aborted') + if (paceMs > 0) await paceDelay(paceMs, signal) yield chunk } throw new LlmError(entry.message, entry.code) @@ -319,14 +366,17 @@ async function* replayEntry(entry: ReplayEntry, signal: AbortSignal | undefined) * next ordered recorded script, then advances its own cursor synchronously at * invocation time; calls without `sessionId` share one anonymous session. A * non-empty provider catalog registers a routed replay adapter; otherwise a - * catch-all waterfall intercepts requests. Returns the effect disposer for - * HMR-safe removal. + * catch-all waterfall intercepts requests. * * @param ctx - the context whose LLM service receives the replay route or waterfall. * @param config - the resolved fixture paths (env-var defaulting is `apply`'s job). - * @returns the disposer that removes the registered adapter or listener. + * @returns the {@link ReplayHandle} carrying the disposer and the teardown consumption check. */ -export function installLlmReplay(ctx: Context, config: ReplayConfig): () => void { +export function installLlmReplay(ctx: Context, config: ReplayConfig): ReplayHandle { + const paceMs = config.paceMs ?? 0 + if (!Number.isInteger(paceMs) || paceMs < 0) { + throw new Error(`llm-replay: paceMs must be a non-negative integer, got ${String(config.paceMs)}`) + } const scripts = loadSessionScripts(config) // Live-session → its bound script + cursor. A new live session id claims the // next not-yet-bound script (scripts are in bind order); `nextScript` is the @@ -370,14 +420,31 @@ export function installLlmReplay(ctx: Context, config: ReplayConfig): () => void + `but its script has only ${boundState.entries.length}; re-record the scenario`, ) } - yield* replayEntry(entry, options.signal) + yield* replayEntry(entry, options.signal, paceMs) })() } const providers = config.providers ?? [] - if (providers.length > 0) { - return ctx.llm.registerAdapter(providers.map(provider => provider.id), new ReplayAdapter(providers, replay)) + const dispose = providers.length > 0 + ? ctx.llm.registerAdapter(providers.map(provider => provider.id), new ReplayAdapter(providers, replay)) + : ctx.on('llm/stream', (options: GenerateOptions, _next) => replay(options)) + return { + dispose, + assertConsumed(): void { + const problems: string[] = [] + if (nextScript < scripts.length) { + problems.push(`${scripts.length - nextScript} recorded script(s) never bound to a live session`) + } + for (const [key, state] of bound) { + if (state.cursor < state.entries.length) { + const who = key === ANON ? 'the anonymous session' : `session ${key}` + problems.push(`${who} consumed ${state.cursor}/${state.entries.length} recorded call(s)`) + } + } + if (problems.length > 0) { + throw new Error(`llm-replay: fixture not fully consumed — ${problems.join('; ')}; the scenario drove fewer model calls than recorded`) + } + }, } - return ctx.on('llm/stream', (options: GenerateOptions, _next) => replay(options)) } export const name = 'llm-replay' @@ -397,6 +464,8 @@ export interface Config { childFiles?: string[] /** Optional replay-only provider catalog; absent or empty selects catch-all waterfall replay. */ providers?: ReplayProviderConfig[] + /** Optional per-chunk pacing delay in ms (see {@link ReplayConfig.paceMs}); absent keeps burst yield. */ + paceMs?: number } export function apply(ctx: Context, config: Config = {}): void { @@ -413,5 +482,6 @@ export function apply(ctx: Context, config: Config = {}): void { ...overrideFile !== undefined && overrideFile.length > 0 ? { overrideFile } : {}, ...childFiles.length > 0 ? { childFiles } : {}, ...config.providers !== undefined ? { providers: config.providers } : {}, + ...config.paceMs !== undefined ? { paceMs: config.paceMs } : {}, }) } diff --git a/packages/support/llm-replay/tests/llm-replay.spec.ts b/packages/support/llm-replay/tests/llm-replay.spec.ts index 14086db27f..b6b03aacbf 100644 --- a/packages/support/llm-replay/tests/llm-replay.spec.ts +++ b/packages/support/llm-replay/tests/llm-replay.spec.ts @@ -234,7 +234,7 @@ describe('installLlmReplay (through the real LlmService)', () => { writeLog(TEXT_CHUNKS) const ctx = new Context() await ctx.plugin(LlmService) - const dispose = installLlmReplay(ctx, { + const { dispose } = installLlmReplay(ctx, { file, providers: [ { @@ -429,6 +429,67 @@ describe('installLlmReplay (through the real LlmService)', () => { await iterator.next() await expect(iterator.next()).rejects.toThrow('aborted') }) + + it('rejects a paceMs that is not a non-negative integer', async () => { + writeLog(TEXT_CHUNKS) + const ctx = new Context() + await ctx.plugin(LlmService) + expect(() => installLlmReplay(ctx, { file, paceMs: -1 })).toThrow(/paceMs/) + expect(() => installLlmReplay(ctx, { file, paceMs: 1.5 })).toThrow(/paceMs/) + }) + + it('paces chunk yields when paceMs is set (each chunk waits at least the pace)', async () => { + writeLog(TEXT_CHUNKS) + const ctx = new Context() + await ctx.plugin(LlmService) + installLlmReplay(ctx, { file, paceMs: 10 }) + const started = performance.now() + const chunks = await drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [] })) + expect(chunks).toEqual(TEXT_CHUNKS) + // N chunks × 10ms; allow generous scheduling slack, assert the floor only. + expect(performance.now() - started).toBeGreaterThanOrEqual(TEXT_CHUNKS.length * 10 - 5) + }) + + it('aborting DURING a pace wait cancels the stream promptly', async () => { + writeLog(TEXT_CHUNKS) + const ctx = new Context() + await ctx.plugin(LlmService) + installLlmReplay(ctx, { file, paceMs: 60_000 }) + const controller = new AbortController() + const pending = drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [], signal: controller.signal })) + // Let the generator park inside the pace timer, then abort — the reject + // must come from the abort listener, not the (distant) timer. + await new Promise(r => setImmediate(r)) + controller.abort() + await expect(pending).rejects.toThrow('aborted') + }) + + it('assertConsumed passes only after every recorded call replayed', async () => { + writeLog(TEXT_CHUNKS, TEXT_CHUNKS) + const ctx = new Context() + await ctx.plugin(LlmService) + const handle = installLlmReplay(ctx, { file }) + await drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [] })) + // One of two recorded calls consumed — the underrun must name the gap. + expect(() => { handle.assertConsumed() }).toThrow(/consumed 1\/2 recorded call/) + await drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [] })) + expect(() => { handle.assertConsumed() }).not.toThrow() + }) + + it('assertConsumed reports recorded scripts no live session ever bound', async () => { + writeLog(TEXT_CHUNKS) + const childFile = join(dir, 'session.1.jsonl') + writeFileSync(childFile, sessionJsonl( + TEXT_CHUNKS.map((chunk, i) => chunkEvent(i + 1, 1, 1, chunk)), + { id: 'child', createdAt: 10 }, + ), 'utf8') + const ctx = new Context() + await ctx.plugin(LlmService) + const handle = installLlmReplay(ctx, { file, childFiles: [childFile] }) + await drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [], sessionId: 'live-parent' as NonNullable })) + // The child script never bound: the scenario drove fewer sessions than recorded. + expect(() => { handle.assertConsumed() }).toThrow(/1 recorded script\(s\) never bound/) + }) }) describe('parseSessionHeader', () => { From 795af3174ed2f06d3adf6d572bcc0945ae04435b Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 19:21:32 +0800 Subject: [PATCH 015/113] fix: cancel session authorization reads --- docs/cordis-catalog/services.md | 6 +- .../cordis/tool-cordis/src/api-catalog.ts | 8 +- .../session-query/session-query/README.md | 4 +- .../session-query/session-query/src/corpus.ts | 8 +- .../session-query/session-query/src/index.ts | 20 ++- .../session-query/tests/session-query.spec.ts | 92 +++++++++++++ .../tool-session-query/package.json | 1 + .../tool-session-query/src/index.ts | 4 +- .../tests/tool-session-query.spec.ts | 123 +++++++++++++++++- pnpm-lock.yaml | 3 + 10 files changed, 250 insertions(+), 19 deletions(-) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index c2669885a4..e31cd66147 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -994,9 +994,10 @@ abstract searchEvents( request: SessionEventSearchRequest, exec?: SessionSearchE /** * List the complete logical corpus using live-preferred records. + * @param signal - optional cancellation for persistence listing. * @returns deterministic newest-first cloned session records. */ -listSessions(): Promise +listSessions(signal?: AbortSignal): Promise /** * Read and replay-validate one complete logical session log without making it live. @@ -1009,9 +1010,10 @@ async readSession(sessionId: SessionId): Promise /** * Filter the complete logical corpus with provider-independent predicates. * @param filters - ANDed session metadata and availability clauses. + * @param signal - optional cancellation for persistence listing. * @returns matching cloned records in deterministic newest-first order. */ -async filterSessions(filters: readonly SessionResultFilter[]): Promise +async filterSessions( filters: readonly SessionResultFilter[], signal?: AbortSignal, ): Promise /** * Fold the latest log-backed title from one live-preferred logical session. diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 72785f4e69..c9e827ff4b 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -495,16 +495,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ jsDoc: '/**\n * Search events within one live-preferred logical session.\n * @param request - target session, query text, filters, page size, and cursor.\n * @param exec - optional cancellation control.\n * @returns matching event hits and their target header from one indexed generation.\n */', }, { - signature: 'listSessions(): Promise', - jsDoc: '/**\n * List the complete logical corpus using live-preferred records.\n * @returns deterministic newest-first cloned session records.\n */', + signature: 'listSessions(signal?: AbortSignal): Promise', + jsDoc: '/**\n * List the complete logical corpus using live-preferred records.\n * @param signal - optional cancellation for persistence listing.\n * @returns deterministic newest-first cloned session records.\n */', }, { signature: 'async readSession(sessionId: SessionId): Promise', jsDoc: '/**\n * Read and replay-validate one complete logical session log without making it live.\n * @param sessionId - live or persisted session id to read.\n * @returns cloned header and complete raw event log from one observation.\n * @throws when persistence, header compatibility, or replay validation fails.\n */', }, { - signature: 'async filterSessions(filters: readonly SessionResultFilter[]): Promise', - jsDoc: '/**\n * Filter the complete logical corpus with provider-independent predicates.\n * @param filters - ANDed session metadata and availability clauses.\n * @returns matching cloned records in deterministic newest-first order.\n */', + signature: 'async filterSessions( filters: readonly SessionResultFilter[], signal?: AbortSignal, ): Promise', + jsDoc: '/**\n * Filter the complete logical corpus with provider-independent predicates.\n * @param filters - ANDed session metadata and availability clauses.\n * @param signal - optional cancellation for persistence listing.\n * @returns matching cloned records in deterministic newest-first order.\n */', }, { signature: 'async readTitle( sessionId: SessionId, signal?: AbortSignal, ): Promise', diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index 8c74f96e3c..6bd0a1990f 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -4,9 +4,9 @@ ## Reads -- `listSessions()` reads current persistence metadata, merges live records with live precedence, and returns cloned records in deterministic newest-first order. +- `listSessions(signal?)` reads current persistence metadata, merges live records with live precedence, and returns cloned records in deterministic newest-first order. - `readSession(sessionId)` returns one complete detached raw log after the same core replay validation used by resume; it never enters the session into the live store. -- `filterSessions(filters)` applies provider-independent session metadata and availability predicates to that same cloned logical corpus. +- `filterSessions(filters, signal?)` applies provider-independent session metadata and availability predicates to that same cloned logical corpus. - `filterEvents(sessionId, filters)` extracts first-party semantic documents and applies provider-independent metadata and literal-text predicates in ascending seq order. - `readTitleSnapshots(sessionIds, signal?)` resolves unique ids from one live-preferred corpus observation, passes cancellation through persisted listing and inspection, and returns ordered per-session settlements so one missing or malformed title source does not discard its peers. Each live source is folded directly, and each persisted worker folds to a detached header/title result and releases the full log before dequeuing another id. Cancellation rejects the whole batch. `readTitleSnapshot(sessionId, signal?)` is the one-observation view; `readTitle(sessionId, signal?)` returns only its optional folded `session/title`. - `listEvents(sessionId)` loads the live-preferred raw log and classifies each event as `current`, `shadowed`, or `log-only` with the shared `dsh-session` surface fold. diff --git a/packages/session-query/session-query/src/corpus.ts b/packages/session-query/session-query/src/corpus.ts index ebf0f40bbc..523b38b3b9 100644 --- a/packages/session-query/session-query/src/corpus.ts +++ b/packages/session-query/session-query/src/corpus.ts @@ -52,11 +52,14 @@ export class SessionCorpus { /** * List the complete logical corpus with live precedence and cloned headers. + * @param signal - optional cancellation for persistence listing. * @returns records in deterministic newest-first order. */ - async listSessions(): Promise { + async listSessions(signal?: AbortSignal): Promise { + signal?.throwIfAborted() const persistence = this._persistence - const persisted = persistence === undefined ? [] : await listPersisted(persistence) + const persisted = persistence === undefined ? [] : await listPersisted(persistence, signal) + signal?.throwIfAborted() const records = new Map() for (const header of persisted) { records.set(header.id, { header: structuredClone(header), live: false, persisted: true }) @@ -239,6 +242,7 @@ async function listPersisted( try { return await persistence.list(signal) } catch (error: unknown) { + if (signal?.aborted) signal.throwIfAborted() throw new SessionQueryError( `session persistence listing failed: ${errorMessage(error)}`, 'SESSION_QUERY_PERSISTENCE_FAILED', diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index 000eb83425..4da71b2a84 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -115,10 +115,11 @@ export abstract class SessionQueryService extends Service { /** * List the complete logical corpus using live-preferred records. + * @param signal - optional cancellation for persistence listing. * @returns deterministic newest-first cloned session records. */ - listSessions(): Promise { - return this._corpus.listSessions() + listSessions(signal?: AbortSignal): Promise { + return this._corpus.listSessions(signal) } /** @@ -139,11 +140,15 @@ export abstract class SessionQueryService extends Service { /** * Filter the complete logical corpus with provider-independent predicates. * @param filters - ANDed session metadata and availability clauses. + * @param signal - optional cancellation for persistence listing. * @returns matching cloned records in deterministic newest-first order. */ - async filterSessions(filters: readonly SessionResultFilter[]): Promise { + async filterSessions( + filters: readonly SessionResultFilter[], + signal?: AbortSignal, + ): Promise { const ownedFilters = materializeSessionResultFilters(filters) - return this._filterSessions(ownedFilters) + return this._filterSessions(ownedFilters, signal) } /** @@ -220,8 +225,11 @@ export abstract class SessionQueryService extends Service { return this._filterEvents(sessionId, ownedFilters) } - private async _filterSessions(filters: readonly SessionResultFilter[]): Promise { - return filterSessionResults(await this._corpus.listSessions(), filters) + private async _filterSessions( + filters: readonly SessionResultFilter[], + signal?: AbortSignal, + ): Promise { + return filterSessionResults(await this._corpus.listSessions(signal), filters) } private async _filterEvents( diff --git a/packages/session-query/session-query/tests/session-query.spec.ts b/packages/session-query/session-query/tests/session-query.spec.ts index f88d8be0f6..dfa209496d 100644 --- a/packages/session-query/session-query/tests/session-query.spec.ts +++ b/packages/session-query/session-query/tests/session-query.spec.ts @@ -130,6 +130,98 @@ function rejectUnknown(reason: unknown): Promise { }) } +const cancellableSessionListings = [ + { + name: 'listSessions', + run: (ctx: Context, signal: AbortSignal) => ctx.sessionQuery.listSessions(signal), + }, + { + name: 'filterSessions', + run: (ctx: Context, signal: AbortSignal) => ctx.sessionQuery.filterSessions([], signal), + }, +] as const + +describe.each(cancellableSessionListings)('$name cancellation', ({ run }) => { + it('preserves an exact pre-abort reason without entering persistence', async () => { + TestPersistence.reset() + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('session listing cancelled before start') + controller.abort(reason) + + await expect(run(ctx, controller.signal)).rejects.toBe(reason) + expect(TestPersistence.listCalls).toBe(0) + expect(TestPersistence.listSignals).toEqual([]) + }) + + it('forwards in-flight cancellation and waits for persistence cleanup before rejecting', async () => { + TestPersistence.reset() + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('session listing cancelled in flight') + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + let active = false + TestPersistence.listOverride = async (signal) => { + if (signal === undefined) throw new Error('expected persistence listing signal') + active = true + const aborted = new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + started.resolve(undefined) + await aborted + abortObserved.resolve(undefined) + await cleanup.promise + active = false + signal.throwIfAborted() + return [] + } + + const pending = run(ctx, controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + controller.abort(reason) + await abortObserved.promise + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(TestPersistence.listSignals).toEqual([controller.signal]) + + cleanup.resolve(undefined) + await expect(pending).rejects.toBe(reason) + expect(active).toBe(false) + }) + + it('preserves cancellation after a persistence implementation ignores the signal', async () => { + TestPersistence.reset() + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('session listing cancelled before persistence returned') + const started = Promise.withResolvers() + const listing = Promise.withResolvers() + TestPersistence.listOverride = (_signal) => { + started.resolve(undefined) + return listing.promise + } + + const pending = run(ctx, controller.signal) + await started.promise + controller.abort(reason) + listing.resolve([]) + + await expect(pending).rejects.toBe(reason) + expect(TestPersistence.listSignals).toEqual([controller.signal]) + }) +}) + describe('session-query exact reads', () => { it('returns a detached replay-valid full log and rejects a corrupt persisted seed', async () => { const valid = header('valid-log', 2) diff --git a/packages/session-query/tool-session-query/package.json b/packages/session-query/tool-session-query/package.json index 9438ddb1de..791a376cec 100644 --- a/packages/session-query/tool-session-query/package.json +++ b/packages/session-query/tool-session-query/package.json @@ -51,6 +51,7 @@ "@deepseek-ai/dsh-session-title": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-timeout": "workspace:^", + "@deepseek-ai/dsh-timeout-policy": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "cordis": "^4.0.0-rc.7" } diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index df1184ffed..f6cebc1376 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -312,7 +312,7 @@ async function authorizeTarget( const records = await ctx.sessionQuery.filterSessions([ { kind: 'id', values: [target] }, { kind: 'cwd', values: [cwd] }, - ]) + ], signal) signal.throwIfAborted() if (records.length !== 1) throw unauthorizedTarget() } @@ -805,7 +805,7 @@ async function authorizeSessionIds( const records = await ctx.sessionQuery.filterSessions([ { kind: 'id', values: other }, { kind: 'cwd', values: [cwd] }, - ]) + ], signal) signal.throwIfAborted() for (const record of records) authorized.add(record.header.id) return authorized diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index 2afb4e9dc7..134430baee 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -2,7 +2,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context, type Fiber } from 'cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { CallId, HarnessError } from '@deepseek-ai/dsh-llm' -import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' +import { MAX_TIMER_DELAY_MS, TimeoutReason } from '@deepseek-ai/dsh-timeout' +import * as TimeoutPolicy from '@deepseek-ai/dsh-timeout-policy' import SessionStore, { SESSION_FORMAT_VERSION, SessionId, @@ -30,6 +31,7 @@ import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query' const activeContexts: Context[] = [] afterEach(async () => { + vi.useRealTimers() vi.restoreAllMocks() for (const ctx of activeContexts.splice(0)) await ctx.fiber.dispose() FakeQuery.reset() @@ -194,12 +196,14 @@ interface Mounted { async function mount( config: ToolSessionQuery.Config = {}, callerCwd: string | null = '/work', + enforceTimeout = false, ): Promise { const ctx = new Context() activeContexts.push(ctx) await ctx.plugin(SessionStore) await ctx.plugin(SystemPrompt) await ctx.plugin(ToolRegistry) + if (enforceTimeout) await ctx.plugin(TimeoutPolicy) await ctx.plugin(FakeQuery) const fiber = await ctx.plugin(ToolSessionQuery, config) const caller = createSession(ctx, 'caller', callerCwd ?? undefined, 10) @@ -1145,6 +1149,123 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => expect(text(result)).not.toContain('title unavailable') }) + it('forwards caller cancellation into direct-target authorization and waits for cleanup', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'stalled-direct-authorization', '/work') + const controller = new AbortController() + const cancellation = new SessionQueryError( + 'direct-target authorization cancelled', + 'SESSION_QUERY_ABORTED', + ) + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + let active = false + const filterSessions = vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions') + .mockImplementation(async (_filters, signal) => { + if (signal === undefined) throw new Error('expected authorization signal') + active = true + const aborted = new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + started.resolve(undefined) + await aborted + abortObserved.resolve(undefined) + await cleanup.promise + active = false + signal.throwIfAborted() + return [] + }) + + const pending = mounted.call( + 'session_event_search', + { session_id: target.id, query: 'needle' }, + { signal: controller.signal }, + ) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + controller.abort(cancellation) + await abortObserved.promise + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(filterSessions.mock.calls[0]?.[1]).toBe(controller.signal) + expect(controller.signal.reason).toBe(cancellation) + expect(FakeQuery.eventRequests).toEqual([]) + + cleanup.resolve(undefined) + const result = await pending + expect(active).toBe(false) + expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') + expect(text(result)).toBe('Error: direct-target authorization cancelled') + expect(FakeQuery.eventRequests).toEqual([]) + }) + + it('forwards the search deadline into parent authorization and times out only after cleanup', async () => { + vi.useFakeTimers() + const timeoutMs = 1_234 + const mounted = await mount({ searchTimeoutMs: timeoutMs }, '/work', true) + const parent = createSession(mounted.ctx, 'stalled-parent-authorization', '/work') + FakeQuery.sessionSearch = () => Promise.resolve({ + items: [sessionHit('authorized-child', '/work', 'needle', parent.id)], + }) + const upstream = new AbortController() + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + let active = false + let deadlineSignal: AbortSignal | undefined + const filterSessions = vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions') + .mockImplementation(async (_filters, signal) => { + if (signal === undefined) throw new Error('expected authorization signal') + deadlineSignal = signal + active = true + const aborted = new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + started.resolve(undefined) + await aborted + abortObserved.resolve(undefined) + await cleanup.promise + active = false + signal.throwIfAborted() + return [] + }) + + const pending = mounted.call( + 'session_search', + { query: 'needle' }, + { signal: upstream.signal }, + ) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + await vi.advanceTimersByTimeAsync(timeoutMs) + await abortObserved.promise + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(deadlineSignal).toBeDefined() + expect(deadlineSignal).not.toBe(upstream.signal) + expect(filterSessions.mock.calls[0]?.[1]).toBe(deadlineSignal) + expect(FakeQuery.searchSignals).toEqual([deadlineSignal]) + expect(deadlineSignal?.reason).toBeInstanceOf(TimeoutReason) + expect(deadlineSignal?.reason).toMatchObject({ code: 'TOOL_TIMEOUT', timeoutMs }) + + cleanup.resolve(undefined) + const result = await pending + expect(active).toBe(false) + expect(errorCode(result)).toBe('TOOL_TIMEOUT') + expect(text(result)).toBe(`Error: tool call timed out after ${timeoutMs}ms`) + }) + it('passes the exact execution signal to every FTS page and stops on cancellation', async () => { const mounted = await mount() const controller = new AbortController() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a48eda1877..89440f48df 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2954,6 +2954,9 @@ importers: '@deepseek-ai/dsh-timeout': specifier: workspace:^ version: link:../../util/timeout + '@deepseek-ai/dsh-timeout-policy': + specifier: workspace:^ + version: link:../../timeout/timeout-policy '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools From 207aab9d8d5c9281444265f699576d99ec031a1c Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 18:59:26 +0800 Subject: [PATCH 016/113] fix(llm): classify empty model completions as retryable EMPTY_RESPONSE A well-formed provider stream that ends with finish_reason stop and zero content blocks previously became a successful empty assistant message: the turn completed silently, and drivers like goal-session counted the no-op round. Both adapters now map that degenerate completion to a finish {kind:'error'} with the new canonical EMPTY_RESPONSE code from dsh-llm, and dsh-llm-retry adds the code to its default retryable set, so the existing closed-step recovery path retries it and fails loud once the budget is exhausted. Covered by adapter unit tests, an llm-retry default-policy test, and a new authored keyless ACP snapshot (empty-response-retry) with a deterministic 1 ms zero-jitter retry overlay. --- ...mpty-model-response-is-retryable.i18n.yaml | 6 +++ ...07-24-empty-model-response-is-retryable.md | 36 +++++++++++++ ...24-empty-model-response-is-retryable.zh.md | 36 +++++++++++++ examples/acp-agent/retry.cordis.snapshot.yml | 41 ++++++++++++++ examples/acp-agent/retry.cordis.yml | 30 +++++++++++ examples/acp-agent/tests/acp.snapshot.ts | 9 ++++ .../snapshots/empty-response-retry/input.json | 7 +++ .../empty-response-retry/session.jsonl | 19 +++++++ .../stdout.expected.jsonl | 7 +++ packages/llm/llm-deepseek/README.md | 2 +- packages/llm/llm-deepseek/src/translate.ts | 15 +++++- .../llm/llm-deepseek/tests/translate.spec.ts | 47 +++++++++++++++- packages/llm/llm-pi-ai/README.md | 2 +- packages/llm/llm-pi-ai/src/stream.ts | 19 +++++-- packages/llm/llm-pi-ai/tests/convert.spec.ts | 23 ++++++-- packages/llm/llm-retry/README.md | 4 +- packages/llm/llm-retry/src/index.ts | 2 +- packages/llm/llm-retry/tests/retry.spec.ts | 54 ++++++++++++++++++- packages/llm/llm/README.md | 1 + packages/llm/llm/src/error.ts | 11 ++++ 20 files changed, 355 insertions(+), 16 deletions(-) create mode 100644 .agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.i18n.yaml create mode 100644 .agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.md create mode 100644 .agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.zh.md create mode 100644 examples/acp-agent/retry.cordis.snapshot.yml create mode 100644 examples/acp-agent/retry.cordis.yml create mode 100644 examples/acp-agent/tests/snapshots/empty-response-retry/input.json create mode 100644 examples/acp-agent/tests/snapshots/empty-response-retry/session.jsonl create mode 100644 examples/acp-agent/tests/snapshots/empty-response-retry/stdout.expected.jsonl diff --git a/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.i18n.yaml new file mode 100644 index 0000000000..d1270e5474 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.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 +2026-07-24-empty-model-response-is-retryable.md: 1c9f6092efe7cc6702117c53ea3f1b7f14445100 +2026-07-24-empty-model-response-is-retryable.zh.md: 8a124d6ac80c751fc2dbc46f1ed4d50ec5e7348f diff --git a/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.md b/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.md new file mode 100644 index 0000000000..1c9f6092ef --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.md @@ -0,0 +1,36 @@ +# Agent Note: Empty model completions are retryable EMPTY_RESPONSE failures + +Status: implemented + +English | [中文](2026-07-24-empty-model-response-is-retryable.zh.md) + +## Problem + +Providers occasionally return a degenerate completion: a well-formed stream that carries a terminal `stop` finish and zero content blocks — no text, no reasoning, no tool calls. Before this change both adapters mapped it to a successful `{kind: 'stop'}` finish, so the loop logged an empty `assistant/message` and ended the turn as `completed`. Nothing retried, nothing failed loud, and a driver like goal-session counted the silent no-op as a consumed round. A live incident showed an openrouter-served model burning three of six goal rounds on empty completions before the goal blocked on its round limit. + +## Decision + +An adapter classifies a completed empty response as a provider-boundary failure, and retry policy treats it as transient: + +- `dsh-llm` exports the canonical code `EMPTY_RESPONSE_CODE` (`'EMPTY_RESPONSE'`) beside `CONTEXT_WINDOW_EXCEEDED_CODE`/`QUOTA_EXCEEDED_CODE`. +- `dsh-llm-pi-ai` (`mapStopReason`): a terminal `stop` whose assistant message has no content blocks becomes a `finish {kind: 'error'}` with that code. Context-overflow detection still wins where it applies (it is checked first and is the more actionable classification). +- `dsh-llm-deepseek` (`translate`): at `[DONE]`, a `stop` (or absent) finish with no opened blocks becomes the same error finish. Reasoning-only streams count as content and stay successful. +- `dsh-llm-retry` adds `EMPTY_RESPONSE` to `DEFAULT_RETRYABLE_CODES`: the attempt produced nothing durable, so repeating it is safe; deployments can still remove it via `retryableCodes`. + +Detection is scoped to `stop` finishes only. `max-tokens` with empty content keeps its existing meaning (pi-ai already normalizes the zero-output overflow case), `tool-calls` cannot be block-empty in practice, and error/aborted finishes already fail. + +The classification rides the existing loop machinery — `finishError` → `agent/request-error` → `dsh-llm-retry` — so no `agent-loop` change was needed, and after the retry budget exhausts, the turn fails loud with `EMPTY_RESPONSE` instead of silently completing empty. + +## Alternatives considered + +**Detect in the loop or `BlockAssembler`.** One shared implementation, but it moves provider-response judgment into the loop, against "plugins, not loop changes", and the assembler is a pure assembly algorithm. The adapter is where wire facts become harness classification, with the overflow reclassification as exact precedent. + +**A stream-transform plugin on the `llm/stream` waterfall.** Provider-neutral and one implementation, but it adds a package plus wiring for what is a boundary fact each adapter can state in a few lines, and default-on behavior would still require touching every bundle. + +**Treat whitespace-only or reasoning-only responses as empty too.** Rejected as overreach: those carry model-produced content, and misclassifying a legitimate (if useless) response as a transport-class failure risks retry loops on models that intentionally stop after reasoning. The scope is exactly "zero content blocks". + +## Consequences + +- A transiently misbehaving provider now costs a bounded retry instead of a silently wasted turn; a persistently empty model surfaces as a loud `EMPTY_RESPONSE` turn failure users can act on. +- A model that genuinely intends to say nothing (rare, but possible after a tool result) is now retried and, if consistently empty, fails the turn. This trade was accepted deliberately: an empty assistant message is indistinguishable from the provider defect and has no value to the user. +- The `empty-response-retry` ACP snapshot (an authored keyless scenario with a deterministic 1 ms zero-jitter retry overlay, `examples/acp-agent/retry.cordis.yml`) pins the product-visible arc: durable `llm/retry` event, the discarded-attempt marker, and a clean completed turn. diff --git a/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.zh.md b/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.zh.md new file mode 100644 index 0000000000..8a124d6ac8 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.zh.md @@ -0,0 +1,36 @@ +# Agent Note: Empty model completions are retryable EMPTY_RESPONSE failures + +Status: implemented + +[English](2026-07-24-empty-model-response-is-retryable.md) | 中文 + +## Problem + +提供方偶尔会返回一种退化的 completion:流本身格式完好,携带一个终止性的 `stop` 结束,却没有任何内容块——没有文本、没有 reasoning(推理)、没有工具调用。本次改动前,两个适配器都会把它映射为成功的 `{kind: 'stop'}` 结束,于是主循环记录了一条空的 `assistant/message`,并把该轮次以 `completed` 结束。没有任何重试,也没有任何显式失败,而像 goal-session 这样的驱动方会把这次静默的空操作计为一次已消耗的 goal 轮数。一次线上事故显示,某个由 openrouter 提供的模型在触及 goal 的轮数上限而被阻塞前,把六轮 goal 中的三轮消耗在了空 completion 上。 + +## Decision + +由适配器把「已完成但为空」的响应归类为一次提供方边界失败,重试策略则将其视为瞬时性问题: + +- `dsh-llm` 在 `CONTEXT_WINDOW_EXCEEDED_CODE`/`QUOTA_EXCEEDED_CODE` 之外,导出规范代码 `EMPTY_RESPONSE_CODE`(`'EMPTY_RESPONSE'`)。 +- `dsh-llm-pi-ai`(`mapStopReason`):当终止性 `stop` 所对应的 assistant 消息没有内容块时,它会变成一个携带该代码的 `finish {kind: 'error'}`。上下文溢出检测在其适用场景中仍然优先(它先被检查,也是更具可操作性的归类)。 +- `dsh-llm-deepseek`(`translate`):在 `[DONE]` 处,若 `stop`(或缺失)结束且没有打开过任何块,则同样变成该错误结束。仅含 reasoning 的流算作有内容,仍视为成功。 +- `dsh-llm-retry` 把 `EMPTY_RESPONSE` 加入 `DEFAULT_RETRYABLE_CODES`:这次尝试没有产生任何持久内容,因此重复它是安全的;部署方仍可通过 `retryableCodes` 将其移除。 + +检测仅限于 `stop` 结束。内容为空的 `max-tokens` 保持其既有含义(pi-ai 已经把零输出的溢出场景归一化处理),`tool-calls` 在实践中不可能是空块,而 error/aborted 结束本身已经算失败。 + +这套归类沿用既有的主循环机制——`finishError` → `agent/request-error` → `dsh-llm-retry`——因此无需改动 `agent-loop`;在重试预算耗尽后,该轮次会以 `EMPTY_RESPONSE` 显式失败,而不再静默地以空内容完成。 + +## Alternatives considered + +**在主循环或 `BlockAssembler` 中检测。** 只需一份共享实现,但这会把对提供方响应的判断挪进主循环,违背「插件优先,而非改动主循环」,且 assembler 是纯粹的组装算法。适配器才是把协议层面的事实转化为 harness 归类的地方,而溢出重归类正是精确的先例。 + +**在 `llm/stream` waterfall(瀑布式事件)上做一个流转换插件。** 这种做法提供方无关且只需一份实现,但它为「每个适配器几行就能声明的边界事实」额外增加了一个包和相应接线,而且默认开启的行为仍需改动每一个 bundle。 + +**把仅含空白或仅含 reasoning 的响应也当作空响应。** 作为过度设计予以否决:这类响应携带了模型产生的内容,把一个合法(哪怕无用)的响应误判为传输类失败,会在那些故意在 reasoning 之后停止的模型上引发重试循环。其范围严格限定为「零内容块」。 + +## Consequences + +- 一个偶发异常的提供方现在只会花费一次有界的重试,而不再是一个被静默浪费的轮次;一个持续返回空内容的模型则会显式暴露为一次用户可据以行动的 `EMPTY_RESPONSE` 轮次失败。 +- 一个确实打算什么都不说的模型(罕见,但在一次工具结果之后有可能出现)现在会被重试,若始终为空,则该轮次失败。这个取舍是经过审慎权衡后接受的:一条空的 assistant 消息与提供方缺陷无法区分,且对用户毫无价值。 +- `empty-response-retry` ACP 快照(一个人工编写的无密钥场景,配有确定性的 1 ms 零抖动重试 overlay,`examples/acp-agent/retry.cordis.yml`)钉住了产品可见的整个过程:持久的 `llm/retry` 事件、被丢弃尝试的标记,以及一次干净的已完成轮次。 diff --git a/examples/acp-agent/retry.cordis.snapshot.yml b/examples/acp-agent/retry.cordis.snapshot.yml new file mode 100644 index 0000000000..4d7010f774 --- /dev/null +++ b/examples/acp-agent/retry.cordis.snapshot.yml @@ -0,0 +1,41 @@ +# Keyless replay for the retry overlay: disable the key-requiring DeepSeek +# adapter, insert `llm-replay`, and restate the app config with the same +# deterministic 1 ms zero-jitter retry policy as the live sibling. A config +# patch replaces the whole app config, so the base fields are restated +# verbatim (raw JSONL persistence so the harness can harvest the log). +- id: base + name: '@cordisjs/plugin-include' + config: + path: ./cordis.yml + patches: + - id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek' + disabled: true + - id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek + model: deepseek-v4-flash + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: none + workspaceContext: + maxBytes: 65536 + llmRetry: + maxTransientRetries: 2 + initialDelayMs: 1 + maxDelayMs: 1 + jitterRatio: 0 + persona: | + You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + + Verify your work by running the code or tests. Keep answers brief and factual. + - insert: + - id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek + name: DeepSeek + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro diff --git a/examples/acp-agent/retry.cordis.yml b/examples/acp-agent/retry.cordis.yml new file mode 100644 index 0000000000..bbb3f81c0d --- /dev/null +++ b/examples/acp-agent/retry.cordis.yml @@ -0,0 +1,30 @@ +# Retry-scenario overlay: pin the bounded transient retry policy to a +# deterministic 1 ms zero-jitter delay so the durable `llm/retry` event +# (`delayMs`) and replay wall time stay reproducible. The overlay changes no +# tool or prompt composition, so its scenarios share the default header class. +# A config patch replaces the whole app config, so the base fields are restated +# verbatim; the model is re-pinned to `deepseek-v4-flash` like the other +# snapshot overlays because the recorded corpus was captured on flash. +- id: base + name: '@cordisjs/plugin-include' + config: + path: ./cordis.yml + patches: + - id: acp-agent + name: '@deepseek-ai/dsh-acp-demo' + config: + provider: deepseek + model: deepseek-v4-flash + persistenceRoot: !!js process.env.DSH_SNAPSHOT_SESSIONS_ROOT ?? './.sessions' + persistenceCompression: !!js "process.env.DSH_SNAPSHOT === undefined ? 'zstd' : 'none'" + workspaceContext: + maxBytes: 65536 + llmRetry: + maxTransientRetries: 2 + initialDelayMs: 1 + maxDelayMs: 1 + jitterRatio: 0 + persona: | + You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + + Verify your work by running the code or tests. Keep answers brief and factual. diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index e35d47cea0..696a747161 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -38,6 +38,7 @@ const PTY_CONFIG = fileURLToPath(new URL('../pty.cordis.yml', import.meta.url)) const DEPTH_TWO_CONFIG = fileURLToPath(new URL('../depth-two.cordis.yml', import.meta.url)) const PACKED_CHUNKS_CONFIG = fileURLToPath(new URL('../packed-chunks.cordis.yml', import.meta.url)) const SESSION_SANDBOX_ROOT_CONFIG = fileURLToPath(new URL('../session-sandbox-root.cordis.yml', import.meta.url)) +const RETRY_CONFIG = fileURLToPath(new URL('../retry.cordis.yml', import.meta.url)) const LSP_CONFIG = fileURLToPath(new URL('./lsp.cordis.yml', import.meta.url)) const SNAPSHOTS_DIR = join(dirname(fileURLToPath(import.meta.url)), 'snapshots') const PACKED_CHUNKS_SOURCE = 'hook-cc-pretool-deny' @@ -137,6 +138,14 @@ const SCENARIOS: Scenario[] = [ headerClass: 'model-switching', }, { name: 'error-finish', hasModelTurn: true, recorded: false, overridden: true }, + // Keyless, authored (like error-finish): a live provider cannot be coaxed + // into a degenerate empty completion, so the fixture scripts the adapters' + // EMPTY_RESPONSE error finish (step 1) followed by the recovered reply + // (step 2), proving the default retry policy end to end: the durable + // llm/retry event, the ACP discarded-attempt marker, and a clean completed + // turn. Its overlay only pins a deterministic 1 ms zero-jitter delay, so it + // shares the default header class. + { name: 'empty-response-retry', hasModelTurn: true, recorded: false, configPath: RETRY_CONFIG }, // Keyless, authored (like error-finish/cancel): deterministically forcing a // LIVE model to repeat one call three times is not a stable recording, so // the fixture scripts five identical todo_write calls and pins BOTH reminder diff --git a/examples/acp-agent/tests/snapshots/empty-response-retry/input.json b/examples/acp-agent/tests/snapshots/empty-response-retry/input.json new file mode 100644 index 0000000000..edc8fdb19f --- /dev/null +++ b/examples/acp-agent/tests/snapshots/empty-response-retry/input.json @@ -0,0 +1,7 @@ +{ + "steps": [ + { "op": "initialize" }, + { "op": "newSession" }, + { "op": "prompt", "text": "This prompt first receives an empty completion, then a retried reply." } + ] +} diff --git a/examples/acp-agent/tests/snapshots/empty-response-retry/session.jsonl b/examples/acp-agent/tests/snapshots/empty-response-retry/session.jsonl new file mode 100644 index 0000000000..f164c7fe62 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/empty-response-retry/session.jsonl @@ -0,0 +1,19 @@ +{"type":"session","version":0,"id":"{{sessionId}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0} +{"type":"turn/start","seq":0,"time":0,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user"}}}} +{"type":"user/message","seq":1,"time":0,"data":{"content":[{"type":"text","text":"This prompt first receives an empty completion, then a retried reply."}],"source":{"kind":"user"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":0,"data":{"title":"This prompt first receives an","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":0,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":0,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}"},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":0,"outputTokens":0}}}} +{"type":"assistant/chunk","seq":6,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"model returned a completed response with no content","code":"EMPTY_RESPONSE"}}}}} +{"type":"step/end","seq":7,"time":0,"data":{"turn":1,"step":1}} +{"type":"llm/retry","seq":8,"time":0,"data":{"turn":1,"step":1,"retry":1,"maxRetries":2,"delayMs":1,"failure":{"message":"model returned a completed response with no content","code":"EMPTY_RESPONSE"}}} +{"type":"step/start","seq":9,"time":0,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":10,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"text"}}} +{"type":"assistant/chunk","seq":11,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":0,"text":"Recovered."}}} +{"type":"assistant/chunk","seq":12,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Recovered."}}}} +{"type":"assistant/chunk","seq":13,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":3}}}} +{"type":"assistant/chunk","seq":14,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":15,"time":0,"data":{"turn":1,"step":2,"content":[{"type":"text","text":"Recovered."}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":12,"outputTokens":3}},"sourceEventSeqs":[10,11,12,13,14],"surfaceOp":"append"} +{"type":"step/end","seq":16,"time":0,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":17,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/examples/acp-agent/tests/snapshots/empty-response-retry/stdout.expected.jsonl b/examples/acp-agent/tests/snapshots/empty-response-retry/stdout.expected.jsonl new file mode 100644 index 0000000000..a420e775d5 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/empty-response-retry/stdout.expected.jsonl @@ -0,0 +1,7 @@ +{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":1,"agentInfo":{"name":"deepseek-harness-acp","version":"0.0.1"},"agentCapabilities":{"loadSession":true,"sessionCapabilities":{"list":{}},"promptCapabilities":{"image":false,"audio":false,"embeddedContext":false}},"authMethods":[]}} +{"jsonrpc":"2.0","id":2,"result":{"sessionId":"{{sessionId}}","modes":{"availableModes":[{"id":"default","name":"default"},{"id":"plan","name":"plan"}],"currentModeId":"default"},"configOptions":[{"id":"model","name":"Model","description":"Sets this session's provider and model.","category":"model","type":"select","currentValue":"[\"deepseek\",\"deepseek-v4-flash\"]","options":[{"value":"[\"deepseek\",\"deepseek-v4-flash\"]","name":"deepseek-v4-flash"},{"value":"[\"deepseek\",\"deepseek-v4-pro\"]","name":"deepseek-v4-pro"}]},{"id":"permission","name":"Permissions","description":"The session permission preset: each choice bundles a sandbox mode and an approval policy.","category":"mode","type":"select","currentValue":"danger-full-access","options":[{"value":"workspace-write","name":"workspace-write","description":"Write inside the workspace and permitted temporary directories; wider retries require approval."},{"value":"danger-full-access","name":"danger-full-access","description":"Full file access without approval prompts."}]}]}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"available_commands_update","availableCommands":[{"name":"goal","description":"set or view the goal for a long-running task","input":{"hint":"[|clear|edit |pause|resume]"}},{"name":"plan","description":"Enter or leave plan mode","input":{"hint":"[off|message]"}}]}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"session_info_update","title":"This prompt first receives an","updatedAt":"{{updatedAt}}"}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"\n\n[Previous model attempt discarded; retrying 1/2 in 1ms: model returned a completed response with no content]\n\n"}}}} +{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"{{sessionId}}","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"Recovered."}}}} +{"jsonrpc":"2.0","id":3,"result":{"stopReason":"end_turn"}} diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 5a9a1bfdbc..6b64fb2fcd 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -49,7 +49,7 @@ Every request carries the shared attribution header from dsh-llm's `attributionH ## Errors -Non-2xx responses throw `LlmError` with stable codes: `AUTH` (401/403), `QUOTA` (a response whose provider details identify exhausted quota, balance, or credits), `RATE_LIMIT` (other 429s), `CONTEXT_WINDOW_EXCEEDED` (a 400 whose provider code, type, or message identifies context overflow), `INVALID_REQUEST` (other 400s), `SERVER` (5xx), `HTTP_` otherwise. Its serializable `failure` retains the HTTP status plus a valid positive `Retry-After` seconds/date delay and `x-request-id` / `x-deepseek-request-id` when present. A pre-response transport failure (DNS, refused connection, TLS, proxy) throws `TRANSPORT` naming the configured endpoint and chaining the original rejection as `cause`; caller aborts throw `ABORTED`, and the loop's cancellation signal remains authoritative. Protocol violations throw `STREAM_CLOSED` (no `[DONE]`) or `MALFORMED_RESPONSE` (bad JSON payload). Unknown wire `finish_reason`s (e.g. `content_filter`, `insufficient_system_resource`) become `finish {kind: 'error', failure}` chunks. +Non-2xx responses throw `LlmError` with stable codes: `AUTH` (401/403), `QUOTA` (a response whose provider details identify exhausted quota, balance, or credits), `RATE_LIMIT` (other 429s), `CONTEXT_WINDOW_EXCEEDED` (a 400 whose provider code, type, or message identifies context overflow), `INVALID_REQUEST` (other 400s), `SERVER` (5xx), `HTTP_` otherwise. Its serializable `failure` retains the HTTP status plus a valid positive `Retry-After` seconds/date delay and `x-request-id` / `x-deepseek-request-id` when present. A pre-response transport failure (DNS, refused connection, TLS, proxy) throws `TRANSPORT` naming the configured endpoint and chaining the original rejection as `cause`; caller aborts throw `ABORTED`, and the loop's cancellation signal remains authoritative. Protocol violations throw `STREAM_CLOSED` (no `[DONE]`) or `MALFORMED_RESPONSE` (bad JSON payload). Unknown wire `finish_reason`s (e.g. `content_filter`, `insufficient_system_resource`) become `finish {kind: 'error', failure}` chunks, and a completed stream whose `stop` (or absent) finish opened no content blocks becomes a `finish {kind: 'error'}` with code `EMPTY_RESPONSE` (retried by default policy). ## Testing diff --git a/packages/llm/llm-deepseek/src/translate.ts b/packages/llm/llm-deepseek/src/translate.ts index f0b5eaf789..f1a6267355 100644 --- a/packages/llm/llm-deepseek/src/translate.ts +++ b/packages/llm/llm-deepseek/src/translate.ts @@ -8,7 +8,7 @@ * @module dsh-llm-deepseek/translate */ -import { CallId, LlmError } from '@deepseek-ai/dsh-llm' +import { CallId, EMPTY_RESPONSE_CODE, LlmError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, FinishReason, StreamChunk, TokenUsage } from '@deepseek-ai/dsh-llm' import { DONE } from './sse.ts' import type { WireChunk, WireUsage } from './types.ts' @@ -80,6 +80,8 @@ function closeBlock(block: OpenBlock): ContentBlock { * Malformed JSON payloads abort the stream with `MALFORMED_RESPONSE`. * @param payloads - SSE data payloads from {@link parseSse}, `[DONE]`-terminated. * @returns deltas as they arrive; `block-end`s, `usage`, and `finish` are all deferred to the `[DONE]` sentinel. + * A `stop` (or absent) finish with no opened blocks is a degenerate provider completion and maps to an + * `EMPTY_RESPONSE` error finish instead of a successful empty message. */ export async function* translate(payloads: AsyncIterable): AsyncGenerator { let nextIndex = 0 @@ -102,7 +104,16 @@ export async function* translate(payloads: AsyncIterable): AsyncGenerato yield { type: 'block-end', index: block.index, block: closeBlock(block) } } if (pendingUsage) yield { type: 'usage', usage: pendingUsage } - yield { type: 'finish', reason: pendingFinish ?? { kind: 'stop' } } + const reason = pendingFinish ?? { kind: 'stop' as const } + yield { + type: 'finish', + reason: reason.kind === 'stop' && order.length === 0 + ? { + kind: 'error', + failure: { message: 'model returned a completed response with no content', code: EMPTY_RESPONSE_CODE }, + } + : reason, + } return } diff --git a/packages/llm/llm-deepseek/tests/translate.spec.ts b/packages/llm/llm-deepseek/tests/translate.spec.ts index 4ae833dc4c..e5a98d1c67 100644 --- a/packages/llm/llm-deepseek/tests/translate.spec.ts +++ b/packages/llm/llm-deepseek/tests/translate.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { BlockAssembler, LlmError } from '@deepseek-ai/dsh-llm' +import { BlockAssembler, EMPTY_RESPONSE_CODE, LlmError } from '@deepseek-ai/dsh-llm' import type { StreamChunk } from '@deepseek-ai/dsh-llm' import { DONE } from '../src/sse.ts' import { mapFinishReason, mapUsage, translate } from '../src/translate.ts' @@ -203,7 +203,50 @@ describe('translate: finish and usage handling', () => { it('handles chunks with no choices at all', async () => { const chunks = await collect(translate(feed({}, DONE))) - expect(chunks).toEqual([{ type: 'finish', reason: { kind: 'stop' } }]) + expect(chunks).toEqual([{ + type: 'finish', + reason: { + kind: 'error', + failure: { message: 'model returned a completed response with no content', code: EMPTY_RESPONSE_CODE }, + }, + }]) + }) + + it('classifies an explicit stop with no opened blocks as EMPTY_RESPONSE, after usage', async () => { + const chunks = await collect(translate(feed( + firstChunk, + { choices: [{ delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 7, completion_tokens: 0 } }, + DONE, + ))) + expect(chunks).toEqual([ + { type: 'usage', usage: { inputTokens: 7, outputTokens: 0 } }, + { + type: 'finish', + reason: { + kind: 'error', + failure: { message: 'model returned a completed response with no content', code: EMPTY_RESPONSE_CODE }, + }, + }, + ]) + }) + + it('keeps a reasoning-only stream a successful stop (any opened block counts)', async () => { + const chunks = await collect(translate(feed( + firstChunk, + { choices: [{ delta: { content: null, reasoning_content: 'mull' } }] }, + { choices: [{ delta: {}, finish_reason: 'stop' }] }, + DONE, + ))) + expect(chunks.at(-1)).toEqual({ type: 'finish', reason: { kind: 'stop' } }) + }) + + it('leaves non-stop finishes unclassified even with no opened blocks', async () => { + const chunks = await collect(translate(feed( + firstChunk, + { choices: [{ delta: {}, finish_reason: 'length' }] }, + DONE, + ))) + expect(chunks.at(-1)).toEqual({ type: 'finish', reason: { kind: 'max-tokens' } }) }) }) diff --git a/packages/llm/llm-pi-ai/README.md b/packages/llm/llm-pi-ai/README.md index 8a6736f112..381026227b 100644 --- a/packages/llm/llm-pi-ai/README.md +++ b/packages/llm/llm-pi-ai/README.md @@ -45,7 +45,7 @@ If a listener rewrites assembled assistant content, the loop drops replay state ## Vocabulary differences - pi-ai tool-call arguments are parsed objects; the harness stores raw JSON strings. The adapter parses input and re-stringifies output. -- pi-ai reports failures as in-stream error events; these map to `finish {kind:'error'|'aborted', failure}` chunks. Provider-specific error text distinguishes terminal `QUOTA` from transient `RATE_LIMIT`, while text and usage signals evaluated against the resolved model's context window normalize overflow to `CONTEXT_WINDOW_EXCEEDED`. +- pi-ai reports failures as in-stream error events; these map to `finish {kind:'error'|'aborted', failure}` chunks. Provider-specific error text distinguishes terminal `QUOTA` from transient `RATE_LIMIT`, while text and usage signals evaluated against the resolved model's context window normalize overflow to `CONTEXT_WINDOW_EXCEEDED`. A terminal `stop` whose message carries no content blocks maps to a `finish {kind:'error'}` with code `EMPTY_RESPONSE` (retried by default policy) instead of a successful empty message. - pi-ai folds reasoning tokens into output usage; there is no separate reasoning count to map. - `GenerateOptions.stop` is rejected with `UNSUPPORTED_OPTION` because pi-ai's common streaming surface cannot guarantee it across providers. diff --git a/packages/llm/llm-pi-ai/src/stream.ts b/packages/llm/llm-pi-ai/src/stream.ts index 37736af716..049b10d930 100644 --- a/packages/llm/llm-pi-ai/src/stream.ts +++ b/packages/llm/llm-pi-ai/src/stream.ts @@ -8,7 +8,7 @@ * @module dsh-llm-pi-ai/stream */ -import { CallId, CONTEXT_WINDOW_EXCEEDED_CODE, isContextWindowExceededError, isQuotaExceededError, LlmError, QUOTA_EXCEEDED_CODE } from '@deepseek-ai/dsh-llm' +import { CallId, CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, isContextWindowExceededError, isQuotaExceededError, LlmError, QUOTA_EXCEEDED_CODE } from '@deepseek-ai/dsh-llm' import type { FinishReason, StreamChunk, TokenUsage } from '@deepseek-ai/dsh-llm' import { isContextOverflow } from '@earendil-works/pi-ai' import type { AssistantMessage, AssistantMessageEvent, Usage as PiUsage } from '@earendil-works/pi-ai' @@ -48,7 +48,8 @@ function classifyPiAiError(message: string): string { * @param contextWindow - resolved catalog capacity for usage-based overflow detection. * @returns the mapped harness reason. Recognized error text, `stop` usage above * `contextWindow`, and zero-output `length` usage that fills the window map - * to `CONTEXT_WINDOW_EXCEEDED`. + * to `CONTEXT_WINDOW_EXCEEDED`; a `stop` with no content blocks maps to an + * `EMPTY_RESPONSE` error. */ export function mapStopReason(message: AssistantMessage, contextWindow?: number): FinishReason { const piAiOverflow = isContextOverflow(message, contextWindow) @@ -66,7 +67,19 @@ export function mapStopReason(message: AssistantMessage, contextWindow?: number) } switch (message.stopReason) { - case 'stop': return { kind: 'stop' } + case 'stop': + // A terminal stop that produced no content blocks is a degenerate + // provider completion, not a successful (empty) assistant message. + if (message.content.length === 0) { + return { + kind: 'error', + failure: { + message: `model "${message.model}" returned a completed response with no content`, + code: EMPTY_RESPONSE_CODE, + }, + } + } + return { kind: 'stop' } case 'length': return { kind: 'max-tokens' } case 'toolUse': return { kind: 'tool-calls' } case 'aborted': return { diff --git a/packages/llm/llm-pi-ai/tests/convert.spec.ts b/packages/llm/llm-pi-ai/tests/convert.spec.ts index 15471875d2..661a930e94 100644 --- a/packages/llm/llm-pi-ai/tests/convert.spec.ts +++ b/packages/llm/llm-pi-ai/tests/convert.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { CallId, CONTEXT_WINDOW_EXCEEDED_CODE, LlmError } from '@deepseek-ai/dsh-llm' +import { CallId, CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, LlmError } from '@deepseek-ai/dsh-llm' import type { ContentBlock, StreamChunk } from '@deepseek-ai/dsh-llm' import type { AssistantMessage, AssistantMessageEvent, Usage } from '@earendil-works/pi-ai' import { toPiContext } from '../src/context.ts' @@ -520,7 +520,22 @@ describe('mapStopReason / mapUsage', () => { ['toolUse', { kind: 'tool-calls' }], ['aborted', { kind: 'aborted', failure: { message: 'pi-ai stream aborted', code: 'ABORTED' } }], ] as const)('maps %s', (stopReason, expected) => { - expect(mapStopReason(assistant({ stopReason }))).toEqual(expected) + expect(mapStopReason(assistant({ stopReason, content: [{ type: 'text', text: 'ok' }] }))).toEqual(expected) + }) + + it('classifies a completed stop with no content as an EMPTY_RESPONSE error', () => { + expect(mapStopReason(assistant({ stopReason: 'stop' }))).toEqual({ + kind: 'error', + failure: { + message: 'model "deepseek-v4-flash" returned a completed response with no content', + code: EMPTY_RESPONSE_CODE, + }, + }) + }) + + it('keeps a thinking-only stop successful (any block counts as content)', () => { + expect(mapStopReason(assistant({ stopReason: 'stop', content: [{ type: 'thinking', thinking: 'mull' }] }))) + .toEqual({ kind: 'stop' }) }) it('defaults the error message when pi-ai omits it', () => { @@ -580,7 +595,9 @@ describe('mapStopReason / mapUsage', () => { }) it('uses the resolved context window for silent and length-stop overflows', () => { - const silent = assistant({ stopReason: 'stop', usage: usage(101, 0) }) + // Non-empty content keeps the no-window branch on the successful stop path + // (an empty stop is EMPTY_RESPONSE, covered above); overflow wins over both. + const silent = assistant({ stopReason: 'stop', usage: usage(101, 0), content: [{ type: 'text', text: 'x' }] }) expect(mapStopReason(silent)).toEqual({ kind: 'stop' }) expect(mapStopReason(silent, 100)).toEqual({ kind: 'error', diff --git a/packages/llm/llm-retry/README.md b/packages/llm/llm-retry/README.md index 699e7e3dad..da1084ba31 100644 --- a/packages/llm/llm-retry/README.md +++ b/packages/llm/llm-retry/README.md @@ -2,7 +2,7 @@ Function plugin that retries selected transient model-request failures on the agent loop's closed-step recovery seam. It does not wrap `ctx.llm.stream()`: every adapter call remains one provider attempt, and every retry opens a fresh numbered step. -The default policy permits two retries for `RATE_LIMIT`, `SERVER`, `TIMEOUT`, and `TRANSPORT`, using bounded exponential backoff from 500 ms to 10 seconds with 10 percent jitter. Delay bounds must fit Node's supported timer range. A valid `providerRetryAfterMs` replaces local backoff when it is within the configured cap; an over-cap instruction delegates to the next recovery policy instead. +The default policy permits two retries for `EMPTY_RESPONSE`, `RATE_LIMIT`, `SERVER`, `TIMEOUT`, and `TRANSPORT`, using bounded exponential backoff from 500 ms to 10 seconds with 10 percent jitter. `EMPTY_RESPONSE` is the adapters' classification of a degenerate provider completion (a terminal stop with zero content blocks); the attempt produced nothing durable, so repeating it is safe. Delay bounds must fit Node's supported timer range. A valid `providerRetryAfterMs` replaces local backoff when it is within the configured cap; an over-cap instruction delegates to the next recovery policy instead. Before waiting, the plugin appends a non-surface `llm/retry` event with the failure and scheduled delay. Cancellation and plugin disposal abort the wait; disposal drains the plugin's active backoffs, and a callback captured before disposal fails closed if invoked afterward. @@ -15,7 +15,7 @@ The separately published `./invariant` companion checks that every retry record initialDelayMs: 500 maxDelayMs: 10000 jitterRatio: 0.1 - retryableCodes: [RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT] + retryableCodes: [EMPTY_RESPONSE, RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT] ``` ## Model Experience diff --git a/packages/llm/llm-retry/src/index.ts b/packages/llm/llm-retry/src/index.ts index 4edf22d6f2..f37cf47e7e 100644 --- a/packages/llm/llm-retry/src/index.ts +++ b/packages/llm/llm-retry/src/index.ts @@ -33,7 +33,7 @@ const DEFAULT_MAX_TRANSIENT_RETRIES = 2 const DEFAULT_INITIAL_DELAY_MS = 500 const DEFAULT_MAX_DELAY_MS = 10_000 const DEFAULT_JITTER_RATIO = 0.1 -const DEFAULT_RETRYABLE_CODES = Object.freeze(['RATE_LIMIT', 'SERVER', 'TIMEOUT', 'TRANSPORT']) +const DEFAULT_RETRYABLE_CODES = Object.freeze(['EMPTY_RESPONSE', 'RATE_LIMIT', 'SERVER', 'TIMEOUT', 'TRANSPORT']) /** Deployment-owned limits and classification for transient request recovery. */ export interface Config { diff --git a/packages/llm/llm-retry/tests/retry.spec.ts b/packages/llm/llm-retry/tests/retry.spec.ts index 4dc1c06bd6..6115724d07 100644 --- a/packages/llm/llm-retry/tests/retry.spec.ts +++ b/packages/llm/llm-retry/tests/retry.spec.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import type { Fiber } from 'cordis' -import LlmService, { CallId, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' +import LlmService, { CallId, EMPTY_RESPONSE_CODE, LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm' import type { GenerateOptions, StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' @@ -51,6 +51,25 @@ function textResponse(text: string): StreamChunk[] { ] } +/** + * A degenerate empty provider completion as an error finish chunk. Both + * adapters emit this shape and the EMPTY_RESPONSE code (the field the policy + * routes on); the message text here is the deepseek adapter's phrasing (pi-ai + * qualifies it with the model name). + */ +function emptyCompletion(): StreamChunk[] { + return [ + { type: 'usage', usage: { inputTokens: 0, outputTokens: 0 } }, + { + type: 'finish', + reason: { + kind: 'error', + failure: { message: 'model returned a completed response with no content', code: EMPTY_RESPONSE_CODE }, + }, + }, + ] +} + async function harness( adapter: LlmAdapter, config: retry.Config = {}, @@ -158,6 +177,39 @@ describe('bounded transient retry policy', () => { }) }) + it('retries an EMPTY_RESPONSE error finish under the default retryable codes', async () => { + vi.useFakeTimers() + const adapter = new ScriptedAdapter([ + emptyCompletion(), + textResponse('recovered'), + ]) + // No retryableCodes override: this proves the default policy covers the + // adapters' empty-completion classification end to end (finish-chunk error + // delivery, not a thrown stream error). + ;({ ctx: context } = await harness(adapter)) + const agent = context.agentLoop.create(SessionId('retry-empty-response'), { provider: 'mock', model: 'mock' }) + const scheduled = waitForRetry(context, agent, 1) + + agent.send([{ type: 'text', text: 'go' }]) + const event = await scheduled + expect(event.data.failure).toEqual({ + message: 'model returned a completed response with no content', + code: EMPTY_RESPONSE_CODE, + }) + + const idle = waitForIdle(context, agent) + await vi.advanceTimersByTimeAsync(500) + await idle + + expect(adapter.requests).toHaveLength(2) + expect(agent.session.events.filter(event => event.type === 'assistant/message').map(event => event.data.step)) + .toEqual([2]) + expect(agent.session.deriveMessages().at(-1)).toMatchObject({ + role: 'assistant', + content: [{ type: 'text', text: 'recovered' }], + }) + }) + it('leaves partial failed chunks on their step without committing a message or tool side effect', async () => { vi.useFakeTimers() const adapter = new ScriptedAdapter([ diff --git a/packages/llm/llm/README.md b/packages/llm/llm/README.md index beac6d5e8e..54306b14d5 100644 --- a/packages/llm/llm/README.md +++ b/packages/llm/llm/README.md @@ -54,6 +54,7 @@ Every product adapter sends application identity on provider HTTP requests. `att - `errorChain(value)` — renders a thrown value with its full `cause` chain and AggregateError members for diagnostic surfaces (UI notices, logger lines, durable `turn/end` messages), so transport wrappers like undici's `TypeError: fetch failed` surface the underlying `ECONNREFUSED`/DNS/TLS detail instead of masking it. Rendering only — route on `code`, never by parsing the result. - `CONTEXT_WINDOW_EXCEEDED_CODE` — the provider-neutral code both DeepSeek adapters use when a request exceeds the model context window, regardless of thrown-HTTP versus in-band finish delivery. `isContextWindowExceededError(detail)` is their shared conservative classifier for OpenAI-compatible provider detail. - `QUOTA_EXCEEDED_CODE` — the non-transient provider-neutral code for exhausted account quota, balance, credits, budget, or usage limits. `isQuotaExceededError(detail)` keeps those failures distinct from request-rate limits. +- `EMPTY_RESPONSE_CODE` — the provider-neutral code both adapters use for a degenerate provider completion: a terminal `stop` that carried no content blocks at all. Classified as an error finish (not a successful empty message) because the attempt produced nothing durable; `dsh-llm-retry` retries it by default. ### Real adapters diff --git a/packages/llm/llm/src/error.ts b/packages/llm/llm/src/error.ts index 758e062895..c4eb816ff6 100644 --- a/packages/llm/llm/src/error.ts +++ b/packages/llm/llm/src/error.ts @@ -27,6 +27,17 @@ export const CONTEXT_WINDOW_EXCEEDED_CODE = 'CONTEXT_WINDOW_EXCEEDED' /** Canonical provider-neutral code for an exhausted account quota or balance. */ export const QUOTA_EXCEEDED_CODE = 'QUOTA' +/** + * Canonical provider-neutral code for a response that completed normally but + * carried no content blocks at all. Providers occasionally emit a degenerate + * completion (a terminal stop with zero output); adapters classify it as this + * failure instead of yielding an empty assistant message, because an empty + * message silently ends the turn with nothing for the user or the loop to act + * on. The attempt produced nothing durable, so retry policy treats it as safe + * to repeat. + */ +export const EMPTY_RESPONSE_CODE = 'EMPTY_RESPONSE' + /** Structured codes and plain phrases that explicitly name a context bound being exceeded. */ const STRUCTURED_CONTEXT_OVERFLOW = new RegExp( String.raw`(?:^|[^a-z0-9])context[\s_-](?:length|window)[\s_-]` From 800bafda3b08cfe0e48b58f7ff1a5478f9b4b2ba Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 19:43:59 +0800 Subject: [PATCH 017/113] refactor(cli): parse dsh argv through one Commander adapter Replace the dsh CLI's three hand-rolled parsing idioms (raw argv[0]/includes dispatch in bin.ts, per-mode node:util parseArgs in headless.ts/web.ts, and the bespoke parseResumeArg scanner in dsh-app-boot) with a single Commander adapter in apps/cli/src/args.ts. parseDshArgs resolves argv into a discriminated DshInvocation union; bin.ts switches on the mode and dynamic-imports the chosen module, which now consumes already-parsed values. - web is a real subcommand; --host uses choices and --port an argParser range check, moving validation into the parser. - --resume rejects empty and repeated forms; --prompt rejects empty; a config positional after --prompt and a root flag placed before web fail loud. - adds --help/--version; removes parseResumeArg from dsh-app-boot. - new apps/cli/tests/args.spec.ts (apps/*/tests added to vitest include, apps/cli/tests to tsconfig.host.json); the tui-agent keyless PTY smoke covers bin.ts dispatch end to end unchanged. --- ...4-dsh-commander-argument-adapter.i18n.yaml | 6 + ...26-07-24-dsh-commander-argument-adapter.md | 37 ++++ ...07-24-dsh-commander-argument-adapter.zh.md | 37 ++++ apps/cli/README.md | 2 + apps/cli/package.json | 3 +- apps/cli/src/args.ts | 183 ++++++++++++++++++ apps/cli/src/bin.ts | 59 ++++-- apps/cli/src/headless.ts | 19 +- apps/cli/src/tui.ts | 13 +- apps/cli/src/web.ts | 34 +--- apps/cli/tests/args.spec.ts | 120 ++++++++++++ packages/ui/app-boot/README.md | 1 - packages/ui/app-boot/src/index.ts | 44 ----- packages/ui/app-boot/tests/app-boot.spec.ts | 27 +-- pnpm-lock.yaml | 3 + tsconfig.host.json | 1 + vitest.config.ts | 1 + 17 files changed, 460 insertions(+), 130 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md create mode 100644 .agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md create mode 100644 apps/cli/src/args.ts create mode 100644 apps/cli/tests/args.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml new file mode 100644 index 0000000000..5dd6055ffe --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.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 +2026-07-24-dsh-commander-argument-adapter.md: dc2830273b245d370feba0df6ed030045b8444ff +2026-07-24-dsh-commander-argument-adapter.zh.md: ea37a1260ebf81e787f02301bc6fc3c9438c4f75 diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md new file mode 100644 index 0000000000..dc2830273b --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md @@ -0,0 +1,37 @@ +# Agent Note: Parse `dsh` argv through one Commander adapter + +Status: implemented + +English | [中文](2026-07-24-dsh-commander-argument-adapter.zh.md) + +## Problem + +The `dsh` CLI entry (`apps/cli`) parsed argv in three hand-rolled idioms that did not compose and gave no `--help`/`--version`. `bin.ts` dispatched by raw inspection — `argv[0] === 'web'`, then `argv.includes('-p') || argv.includes('--prompt')`, else TUI — which is positional-blind: a prompt flag or a config path in the wrong position could misroute the mode, and `argv.includes('-p')` could not tell a real flag from an incidental token. `headless.ts` and `web.ts` each ran their own `node:util` `parseArgs` with inline host/port validation, and `dsh-app-boot` carried `parseResumeArg`, a ~30-line bespoke scanner reimplementing flag/`=`-form/value/repeat handling for `--resume`. Usage was a single hardcoded `usage: dsh -p "task"` line; there was no version flag and no rendered help. + +## Decision + +Argv is parsed once, in `apps/cli/src/args.ts`, through a Commander adapter (the same parser the SDK bins — `create-sdk`, `dsh-scripts` — already standardize on). `parseDshArgs(argv, version)` resolves the invocation into a discriminated `DshInvocation` union: `{ mode: 'tui', config?, resume? }`, `{ mode: 'headless', prompt }`, `{ mode: 'web', host, port }`, `{ mode: 'help' | 'version', text }`, or `{ mode: 'error', message }`. Commander runs under `exitOverride()` with output captured, so it never writes or exits on its own — `--help`, `--version`, and every parse error come back as data. + +`bin.ts` calls the adapter once and switches on `mode` (closed union, `satisfies never` default), dynamic-importing only the chosen mode's module. Each mode module now consumes already-parsed values: `runTui(config, resume)`, `runHeadless(task)`, `runWeb(host, port)` — none re-reads argv. `web` is a real `program.command('web')` subcommand; `--host` is a Commander `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])` and `--port` an `argParser` that range-checks 0–65535, moving both from the inline `runWeb` checks into the parser. `--resume` uses an `argParser` that rejects both an empty id (`--resume=`) and a repeated flag (`--resume a --resume b`), and `--prompt` rejects an empty task, preserving the old "never silently start fresh" invariant (the deleted `parseResumeArg` failed loud on the same cases). The program sets `enablePositionalOptions()`, and the `web` action rejects a root `--prompt`/`--resume` placed before it, so a misplaced flag (`dsh web -p x`, `dsh -p x web`) fails loud instead of silently serving with defaults. `--version` reads this app's `package.json`. + +`parseResumeArg` is deleted from `dsh-app-boot` (its export, its README row, and its unit block); the pre-release stance permits the removal. `dsh-app-boot` keeps its boot/env/config/personal-overlay helpers — only the argv scanner leaves. + +## Package topology + +The argument surface stays inside `apps/cli`, the assembly tier, not a `packages/*` library: it is this one app's routing, not a reusable seam. `dsh-app-boot` shrinks to boot glue with no CLI-parsing responsibility. `commander@^15` is added to `apps/cli/package.json`, matching the SDK bins' pin. + +## Alternatives considered + +**Keep `node:util` `parseArgs` and only unify the dispatch** — rejected: `parseArgs` has no subcommand model, no rendered help, and no version flag, so `web` routing and `--help`/`--version` would stay hand-rolled. The repo already chose Commander for its other CLIs; a second parser idiom for `dsh` alone is the fragmentation this change removes. + +**Keep `parseResumeArg` as a shared helper and feed it Commander's residual args** — rejected: the whole point is to retire the bespoke scanner. Commander parses `--resume` (space and `=` forms, missing-value, position-independence) natively; keeping a parallel hand-written path for the one flag would preserve the duplication the change exists to end. + +**Make the argument surface a `packages/*` seam** — rejected: nothing outside `dsh` consumes it, and capability seams are not split preemptively. The Commander adapter is `apps/cli`'s own concern. + +## Testing + +`apps/cli/tests/args.spec.ts` (new; `apps/*/tests` added to the vitest include and `apps/cli/tests` to `tsconfig.host.json`) drives the adapter directly: TUI defaults, config positional, `--resume` space/inline forms and their position-independence, empty/valueless/repeated `--resume` rejection, `-p`/`--prompt` routing with empty-prompt and stray-positional rejection, `web` host/port defaults and validation with `--host`/`--port` diagnostics, root flags misplaced around `web` failing loud, excess-argument rejection, and `--help`/`web --help`/`--version`/unknown-option outcomes. The `dsh CLI keyless smoke` group in `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` exercises the real `bin.ts` dispatch end to end through a PTY (default boot, personal overlay, invalid config, `--resume` failure, source-path prompt) and stays green unchanged. `packages/ui/app-boot/tests/app-boot.spec.ts` drops its `parseResumeArg` block. + +## Consequences + +`dsh` gains rendered `--help`/`--version` and consistent fail-loud parse errors, and mode routing no longer depends on flag position. Argv parsing lives in one place with one parser idiom shared with the SDK bins, at the cost of a `commander` dependency on `apps/cli` and Commander's parse semantics (its error strings, its `exitOverride` contract) now sitting on the CLI's front door. `dsh-app-boot` no longer owns any CLI-parsing surface; a future consumer needing `--resume`-style parsing composes Commander rather than reviving the deleted scanner. diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md new file mode 100644 index 0000000000..ea37a1260e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 通过单个 Commander 适配器解析 `dsh` 的 argv + +Status: implemented + +[English](2026-07-24-dsh-commander-argument-adapter.md) | 中文 + +## 问题 + +`dsh` 的 CLI(命令行界面)入口(`apps/cli`)以三种手写方式解析 argv,这些方式无法组合,也不提供 `--help`/`--version`。`bin.ts` 通过原始检查进行分发:先判断 `argv[0] === 'web'`,再判断 `argv.includes('-p') || argv.includes('--prompt')`,否则走 TUI。这种方式对位置不敏感:位置错误的 prompt 标志或配置路径可能把模式路由错,而 `argv.includes('-p')` 无法区分真正的标志和偶然出现的 token。`headless.ts` 和 `web.ts` 各自运行自己的 `node:util` `parseArgs`,并内联校验 host/port,而 `dsh-app-boot` 携带 `parseResumeArg`——一个约 30 行的定制扫描器,为 `--resume` 重新实现了标志、`=` 形式、取值和重复的处理。用法说明只有一行硬编码的 `usage: dsh -p "task"`;既没有版本标志,也没有渲染出的帮助信息。 + +## 决策 + +argv 只在 `apps/cli/src/args.ts` 中解析一次,通过一个 Commander 适配器(即 SDK bin,如 `create-sdk`、`dsh-scripts`,已经统一采用的那个解析器)。`parseDshArgs(argv, version)` 将调用解析为一个判别式 `DshInvocation` 联合类型:`{ mode: 'tui', config?, resume? }`、`{ mode: 'headless', prompt }`、`{ mode: 'web', host, port }`、`{ mode: 'help' | 'version', text }` 或 `{ mode: 'error', message }`。Commander 在 `exitOverride()` 下运行并捕获输出,因此它自身从不写出或退出:`--help`、`--version` 和每个解析错误都以数据形式返回。 + +`bin.ts` 调用一次适配器,并对 `mode` 做分支切换(封闭联合类型,默认分支为 `satisfies never`),只动态导入所选模式对应的模块。每个模式模块现在只消费已解析好的值:`runTui(config, resume)`、`runHeadless(task)`、`runWeb(host, port)`,都不会再次读取 argv。`web` 是一个真正的 `program.command('web')` 子命令;`--host` 是 Commander 的 `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])`,`--port` 是一个对 0–65535 做范围检查的 `argParser`,二者都从内联的 `runWeb` 检查移入了解析器。`--resume` 使用一个 `argParser`,同时拒绝空 id(`--resume=`)和重复出现的标志(`--resume a --resume b`),`--prompt` 则拒绝空任务,保留旧有的「绝不静默重新开始」不变式(已删除的 `parseResumeArg` 在相同情形下也会显式报错)。程序设置了 `enablePositionalOptions()`,且 `web` 动作会拒绝置于其前的根级 `--prompt`/`--resume`,因此位置错误的标志(`dsh web -p x`、`dsh -p x web`)会显式报错,而不会静默地以默认值提供服务。`--version` 读取本应用的 `package.json`。 + +`parseResumeArg` 从 `dsh-app-boot` 中删除(包括其导出、README 中的对应行以及单元测试块);预发布阶段的立场允许这次删除。`dsh-app-boot` 保留其 boot/env/config/个人覆盖辅助函数,只有 argv 扫描器被移除。 + +## 包拓扑 + +参数解析留在 `apps/cli`(组装层)内,而不是 `packages/*` 库中:它是这一个应用自身的路由,而非可复用的 seam。`dsh-app-boot` 收缩为纯粹的 boot 胶水代码,不再承担 CLI 解析职责。`commander@^15` 被加入 `apps/cli/package.json`,与 SDK bin 锁定的版本一致。 + +## 考虑过的替代方案 + +**保留 `node:util` `parseArgs`,只统一分发。** 已否决:`parseArgs` 没有子命令模型、没有渲染出的帮助、也没有版本标志,因此 `web` 路由和 `--help`/`--version` 仍将保持手写。本仓库其他 CLI 已经选择了 Commander;单独为 `dsh` 引入第二套解析器方式,正是这次变更要消除的碎片化。 + +**保留 `parseResumeArg` 作为共享辅助函数,并向它喂入 Commander 的残余参数。** 已否决:整件事的核心就是要退役这个定制扫描器。Commander 原生解析 `--resume`(空格和 `=` 形式、缺值、位置无关性);为这一个标志保留一条平行的手写路径,只会保留这次变更要终结的重复。 + +**把参数解析做成 `packages/*` 的 seam。** 已否决:`dsh` 之外没有任何消费方使用它,而能力 seam 不应被提前拆分。这个 Commander 适配器是 `apps/cli` 自身的事务。 + +## 测试 + +`apps/cli/tests/args.spec.ts`(新增;`apps/*/tests` 加入 vitest include,`apps/cli/tests` 加入 `tsconfig.host.json`)直接驱动适配器:TUI 默认值、config 位置参数、`--resume` 的空格/内联形式及其位置无关性、对空值/无值/重复 `--resume` 的拒绝、`-p`/`--prompt` 路由及对空 prompt 和游离位置参数的拒绝、`web` 的 host/port 默认值与校验(含 `--host`/`--port` 诊断信息)、围绕 `web` 位置错误的根级标志会显式报错、对多余参数的拒绝,以及 `--help`/`web --help`/`--version`/未知选项的处理结果。`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 中的 `dsh CLI keyless smoke` 组通过 PTY 端到端地运行真实的 `bin.ts` 分发(默认启动、个人覆盖、无效配置、`--resume` 失败、源路径 prompt),且保持绿色不变。`packages/ui/app-boot/tests/app-boot.spec.ts` 移除其 `parseResumeArg` 测试块。 + +## 影响 + +`dsh` 获得了渲染出的 `--help`/`--version` 以及一致的显式报错式解析错误,模式路由也不再依赖标志位置。argv 解析集中在一处,并与 SDK bin 共用一套解析器方式,代价是 `apps/cli` 新增一项 `commander` 依赖,且 Commander 的解析语义(它的错误字符串、它的 `exitOverride` 契约)如今落在 CLI 的入口处。`dsh-app-boot` 不再拥有任何 CLI 解析职责;未来需要 `--resume` 式解析的消费方应组合 Commander,而不是复活已删除的扫描器。 diff --git a/apps/cli/README.md b/apps/cli/README.md index 87f5e670e3..15765090a0 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -2,6 +2,8 @@ The `dsh` command-line entry follows the `apps/` assembly tier: `apps/*` are product assemblies over `packages/*` libraries. Plain `dsh [config.yml]` boots the interactive TUI coding agent, `dsh -p "task"` runs one headless turn, and `dsh web` serves the browser UI. +Argv is parsed once through a [Commander](https://github.com/tj/commander.js) adapter ([`src/args.ts`](src/args.ts)) that resolves the invocation into a single mode; `src/bin.ts` switches on that mode and dynamic-imports only the chosen mode's module. `dsh --help` and `dsh web --help` render usage, `dsh --version` prints this app's version, and an unknown option or an invalid `--host`/`--port`/`--resume` value fails loud (stderr, exit 1) instead of misrouting. + The TUI surface: - boots the shipped default config (`examples/tui-agent/cordis.yml`) or an explicit config argument, through [`dsh-app-boot`](../../packages/ui/app-boot/README.md); diff --git a/apps/cli/package.json b/apps/cli/package.json index fd744fa02c..791a44f98b 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -19,6 +19,7 @@ "@deepseek-ai/dsh-host-runtime": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-paths": "workspace:^", - "@deepseek-ai/dsh-session": "workspace:^" + "@deepseek-ai/dsh-session": "workspace:^", + "commander": "^15.0.0" } } diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts new file mode 100644 index 0000000000..f549c125c3 --- /dev/null +++ b/apps/cli/src/args.ts @@ -0,0 +1,183 @@ +/** + * Commander adapter for the `dsh` command-line entry: the one place argv is + * parsed and routed to a mode. `bin.ts` switches on the returned discriminant + * and dynamic-imports that mode's module; each mode module then consumes the + * already-parsed values instead of re-reading argv. Output is suppressed and + * `exitOverride` is set so Commander never writes or exits on its own — every + * outcome (including `--help`/`--version` and parse errors) is returned to the + * caller as data. + * @module @deepseek-ai/dsh/args + */ + +import { Command, CommanderError, InvalidArgumentError, Option } from 'commander' + +/** The loopback host `dsh web` binds by default. */ +export const LOOPBACK_HOST = '127.0.0.1' +/** The all-interfaces host `dsh web` accepts to expose the UI on the LAN. */ +export const ALL_INTERFACES_HOST = '0.0.0.0' +const DEFAULT_WEB_PORT = 3080 + +/** Interactive TUI: the default mode. Optional positional config and `--resume `. */ +interface TuiInvocation { + mode: 'tui' + config?: string + resume?: string +} + +/** Headless one-shot: `dsh -p "task"`. */ +interface HeadlessInvocation { + mode: 'headless' + prompt: string +} + +/** Browser UI: `dsh web`. Host constrained to {@link LOOPBACK_HOST}/{@link ALL_INTERFACES_HOST}; port already coerced and range-checked. */ +interface WebInvocation { + mode: 'web' + host: string + port: number +} + +/** `--help` or `--version` requested: `bin.ts` prints `text` to stdout and exits 0. */ +interface InfoInvocation { + mode: 'help' | 'version' + text: string +} + +/** A parse error (unknown option, missing/invalid argument): `bin.ts` prints `message` to stderr and exits 1. */ +interface ErrorInvocation { + mode: 'error' + message: string +} + +/** The resolved `dsh` invocation: exactly one mode, all values parsed and validated. */ +export type DshInvocation = + | TuiInvocation + | HeadlessInvocation + | WebInvocation + | InfoInvocation + | ErrorInvocation + +/** Raw Commander option bag for the root command before it is narrowed to a mode. */ +interface RootOptions { + prompt?: string + resume?: string +} + +/** Commander option bag for the `web` subcommand after `--port` coercion. */ +interface WebOptions { + host: string + port: number +} + +/** + * Coerce `--port` to an integer in 0–65535; a bad value throws + * {@link InvalidArgumentError}, which Commander reports as a parse error the + * adapter returns as an {@link ErrorInvocation}. + */ +function parsePort(raw: string): number { + const port = Number(raw) + if (!Number.isInteger(port) || port < 0 || port > 65535) { + throw new InvalidArgumentError(`invalid --port ${raw}`) + } + return port +} + +/** Reject an empty `--prompt` task; an empty headless prompt has nothing to run. */ +function parsePrompt(raw: string): string { + if (raw === '') throw new InvalidArgumentError("option '-p, --prompt ' must not be empty") + return raw +} + +/** + * Validate a `--resume` value: reject an empty id and a repeated flag. Both are + * mistypes that must fail loud, never silently start a fresh session or keep + * only the last id. `previous` is the value from an earlier `--resume` on the + * same invocation (Commander threads it in), so a second occurrence is caught. + */ +function parseResume(raw: string, previous: string | undefined): string { + if (previous !== undefined) throw new InvalidArgumentError("option '--resume ' may be given only once") + if (raw === '') throw new InvalidArgumentError("option '--resume ' must not be empty") + return raw +} + +/** + * Resolve the raw argv into a single {@link DshInvocation}. Never writes to a + * stream and never exits; `--help`/`--version` and every parse error come back + * as data for `bin.ts` to act on. + * @param argv - the arguments after the node binary and script (`process.argv.slice(2)`). + * @param version - the version string `--version` prints; read from this app's package.json. + * @returns the resolved invocation, discriminated by `mode`. + */ +export function parseDshArgs(argv: readonly string[], version: string): DshInvocation { + let resolved: DshInvocation | undefined + const output: string[] = [] + + const program = new Command() + .name('dsh') + .description('dsh: interactive TUI, headless task, and browser UI') + .version(version, '-V, --version', 'output the version number') + .exitOverride() + .configureOutput({ + writeOut: chunk => void output.push(chunk), + writeErr: chunk => void output.push(chunk), + }) + + // Positional options keep `dsh -p x web` from routing to the `web` + // subcommand: a token after a root option is a positional, not a command. + program + .enablePositionalOptions() + .argument('[config]', 'config to boot instead of the shipped default (TUI mode)') + .addOption(new Option('-p, --prompt ', 'run one headless turn for this task, print the result, and exit').argParser(parsePrompt)) + .addOption(new Option('--resume ', 'resume the persisted session with this id (TUI mode)').argParser(parseResume)) + .action((config: string | undefined, options: RootOptions) => { + if (options.prompt !== undefined) { + // A headless prompt owns the invocation; a config positional is meaningless there. + if (config !== undefined) { + throw new InvalidArgumentError(`error: --prompt takes no config argument (got '${config}')`) + } + resolved = { mode: 'headless', prompt: options.prompt } + return + } + resolved = { + mode: 'tui', + ...config !== undefined ? { config } : {}, + ...options.resume !== undefined ? { resume: options.resume } : {}, + } + }) + + program + .command('web') + .description('serve the browser UI') + .addOption( + new Option('--host ', 'bind host') + .choices([LOOPBACK_HOST, ALL_INTERFACES_HOST]) + .default(LOOPBACK_HOST), + ) + .addOption( + new Option('--port ', 'listen port').default(DEFAULT_WEB_PORT).argParser(parsePort), + ) + .action((options: WebOptions, command: Command) => { + // Root options placed before `web` (`dsh -p x web`) leak onto the parent; + // reject them so a misplaced flag fails loud instead of silently serving. + const leaked = command.parent?.opts() + if (leaked?.prompt !== undefined || leaked?.resume !== undefined) { + throw new InvalidArgumentError('error: web takes no --prompt or --resume; place web first') + } + resolved = { mode: 'web', host: options.host, port: options.port } + }) + + try { + program.parse(argv, { from: 'user' }) + } catch (error) { + /* v8 ignore next -- Commander only throws CommanderError from parse under exitOverride */ + if (!(error instanceof CommanderError)) throw error + if (error.code === 'commander.helpDisplayed') return { mode: 'help', text: output.join('') } + if (error.code === 'commander.version') return { mode: 'version', text: output.join('') } + // Every other CommanderError is a parse failure; its message is the diagnostic. + return { mode: 'error', message: error.message } + } + + /* v8 ignore next -- one action always resolves the invocation or parse throws above */ + if (resolved === undefined) throw new Error('dsh: argument parsing did not resolve a mode') + return resolved +} diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index 1192472b98..5880c68407 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -1,25 +1,58 @@ #!/usr/bin/env node /** - * dsh — command-line entry. Coarse dispatch only; each surface module owns its - * argument handling. Dynamic imports keep unrelated surfaces out of each - * dispatch path; everything except `web` and headless prompts opens the TUI. + * dsh — command-line entry. Parses argv once through the Commander adapter and + * switches on the resolved mode; dynamic imports keep unrelated modes out of + * each dispatch path. `web` and headless prompts run their own module; + * everything else opens the TUI. `--help`/`--version` print and exit 0; a parse + * error prints to stderr and exits 1. * @module @deepseek-ai/dsh/bin */ /* v8 ignore file -- built-bin and PTY tests exercise this self-executing dispatch. */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' import { loadEnv } from '@deepseek-ai/dsh-app-boot' +import { parseDshArgs } from './args.ts' + +// Both the source tree (apps/cli/src) and the bundled bin (apps/cli/lib) sit +// one directory under apps/cli, so the checked-in manifest resolves with the +// same relative hop from either artifact. +/** This app's version, read from its checked-in package.json. */ +function readVersion(): string { + const manifest = JSON.parse( + readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8'), + ) as { version?: unknown } + return typeof manifest.version === 'string' ? manifest.version : '0.0.0' +} loadEnv('dsh') -const argv = process.argv.slice(2) +const invocation = parseDshArgs(process.argv.slice(2), readVersion()) -if (argv[0] === 'web') { - const { runWeb } = await import('./web.ts') - await runWeb(argv.slice(1)) -} else if (argv.includes('-p') || argv.includes('--prompt')) { - const { runHeadless } = await import('./headless.ts') - await runHeadless(argv) -} else { - const { runTui } = await import('./tui.ts') - await runTui(argv) +switch (invocation.mode) { + case 'web': { + const { runWeb } = await import('./web.ts') + await runWeb(invocation.host, invocation.port) + break + } + case 'headless': { + const { runHeadless } = await import('./headless.ts') + await runHeadless(invocation.prompt) + break + } + case 'tui': { + const { runTui } = await import('./tui.ts') + await runTui(invocation.config, invocation.resume) + break + } + case 'help': + case 'version': + process.stdout.write(invocation.text) + process.exit(0) + case 'error': + process.stderr.write(`${invocation.message}\n`) + process.exit(1) + default: + invocation satisfies never + throw new Error(`dsh: unhandled invocation mode ${JSON.stringify(invocation)}`) } diff --git a/apps/cli/src/headless.ts b/apps/cli/src/headless.ts index 303bac61f8..ccfd4c5f8a 100644 --- a/apps/cli/src/headless.ts +++ b/apps/cli/src/headless.ts @@ -7,7 +7,6 @@ * (completed → 0, else 1). */ -import { parseArgs } from 'node:util' import { startHost } from '@deepseek-ai/dsh-host-runtime' import { InProcessApiClient } from '@deepseek-ai/dsh-host-apiproxy' import type { MuxFrame } from '@deepseek-ai/dsh-host-apiproxy/api' @@ -65,17 +64,13 @@ async function consumeUntilTurnEnd(frames: AsyncIterable>, return { text, reason: 'error' } } -export async function runHeadless(argv: string[]): Promise { - const { values } = parseArgs({ - args: argv, - options: { prompt: { type: 'string', short: 'p' } }, - allowPositionals: false, - }) - const task = values.prompt - if (task === undefined || task === '') { - process.stderr.write('usage: dsh -p "task"\n') - process.exit(1) - } +/** + * Run one headless turn for `task` and exit (completed → 0, else 1). The task + * is the non-empty prompt the argument adapter parsed from `-p`/`--prompt` + * (the adapter rejects an empty task, so no guard is needed here). + * @param task - the prompt text for the single turn. + */ +export async function runHeadless(task: string): Promise { // A missing DEEPSEEK_API_KEY throws here (plugin load is fail-loud, uncaught by design). const host = await startHost({ diff --git a/apps/cli/src/tui.ts b/apps/cli/src/tui.ts index 6f97a68ad3..aa8fb9af5f 100644 --- a/apps/cli/src/tui.ts +++ b/apps/cli/src/tui.ts @@ -18,7 +18,6 @@ import { installFailLoud, loadEnv, loadPersonalPatches, - parseResumeArg, resolveConfigPath, } from '@deepseek-ai/dsh-app-boot' import { resolveDshHome } from '@deepseek-ai/dsh-paths' @@ -45,11 +44,12 @@ const SOURCE_ROOT = fileURLToPath(new URL('../../..', import.meta.url)) the tui-agent PTY smoke drives this path end to end, personal overlay included */ /** * Run the interactive TUI from the invoking directory. - * @param argv - arguments after the subcommand dispatch; a `--resume ` flag - * resumes that persisted session, and the first non-flag argument may name a - * config to boot instead of the shipped default. + * @param config - a config path to boot instead of the shipped default, or + * `undefined` for the default; already parsed from the optional positional. + * @param resumeSessionId - a persisted session id to resume, or `undefined`; + * already parsed and non-empty-validated from `--resume`. */ -export async function runTui(argv: string[]): Promise { +export async function runTui(config: string | undefined, resumeSessionId: string | undefined): Promise { // Refuse pipes BEFORE booting: a compose-time throw inside the Loader tree // is logged per-entry rather than rethrown, so a piped launch would // otherwise settle into an idle UI-less process instead of exiting nonzero. @@ -63,9 +63,8 @@ export async function runTui(argv: string[]): Promise { loadEnv(NAME, resolveDshHome()) // An explicit `--resume` flag beats any ambient RESUME_SESSION_ID, so set it // after loadEnv and before boot reads it through the config's `!!js`. - const { resumeSessionId, rest } = parseResumeArg(argv) if (resumeSessionId !== undefined) process.env[RESUME_SESSION_ID_ENV] = resumeSessionId - const ctx = await boot(NAME, resolveConfigPath(rest[0] ?? DEFAULT_CONFIG, undefined), loadPersonalPatches(NAME)) + const ctx = await boot(NAME, resolveConfigPath(config ?? DEFAULT_CONFIG, undefined), loadPersonalPatches(NAME)) addHarnessSourceSection(ctx, SOURCE_ROOT) } /* v8 ignore stop */ diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts index 66a99bb577..106585529f 100644 --- a/apps/cli/src/web.ts +++ b/apps/cli/src/web.ts @@ -4,37 +4,19 @@ * concerns is this app module's job (packages stay single-sided). */ -import { parseArgs } from 'node:util' import { networkInterfaces } from 'node:os' import { createRequire } from 'node:module' import { mountWebPlugins, startHost } from '@deepseek-ai/dsh-host-runtime' import { createHostWebPluginRegistry, startWebServer } from '@deepseek-ai/dsh-host-webserver' +import { ALL_INTERFACES_HOST, LOOPBACK_HOST } from './args.ts' -const LOOPBACK_HOST = '127.0.0.1' -const ALL_INTERFACES_HOST = '0.0.0.0' - -export async function runWeb(argv: string[]): Promise { - const { values } = parseArgs({ - args: argv, - options: { - host: { type: 'string', default: LOOPBACK_HOST }, - port: { type: 'string', default: '3080' }, - }, - allowPositionals: false, - }) - if (values.host !== LOOPBACK_HOST && values.host !== ALL_INTERFACES_HOST) { - process.stderr.write( - `dsh web: invalid --host ${values.host}; expected ${LOOPBACK_HOST} or ${ALL_INTERFACES_HOST}\n`, - ) - process.exit(1) - } - const hostAddress = values.host - const port = Number(values.port) - if (!Number.isInteger(port) || port < 0 || port > 65535) { - process.stderr.write(`dsh web: invalid --port ${values.port}\n`) - process.exit(1) - } - +/** + * Serve the browser UI. Host and port are already validated by the argument + * adapter (host constrained to loopback/all-interfaces, port a 0–65535 integer). + * @param hostAddress - the bind host: {@link LOOPBACK_HOST} or {@link ALL_INTERFACES_HOST}. + * @param port - the listen port; `0` lets the OS choose a free port. + */ +export async function runWeb(hostAddress: string, port: number): Promise { // A missing DEEPSEEK_API_KEY throws here (plugin load is fail-loud, uncaught by design). const host = await startHost({ boot: { diff --git a/apps/cli/tests/args.spec.ts b/apps/cli/tests/args.spec.ts new file mode 100644 index 0000000000..ad6d0266ca --- /dev/null +++ b/apps/cli/tests/args.spec.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from 'vitest' +import { ALL_INTERFACES_HOST, LOOPBACK_HOST, parseDshArgs } from '../src/args.ts' + +const VERSION = '1.2.3' +const parse = (argv: string[]) => parseDshArgs(argv, VERSION) + +/** Assert argv resolves to an error invocation whose message contains `needle`. */ +function expectError(argv: string[], needle: string): void { + const result = parse(argv) + expect(result.mode).toBe('error') + if (result.mode !== 'error') throw new Error('expected error mode') + expect(result.message).toContain(needle) +} + +describe('parseDshArgs — TUI (default mode)', () => { + it('defaults to the TUI with no config and no resume when given no arguments', () => { + expect(parse([])).toEqual({ mode: 'tui' }) + }) + + it('carries a positional config into the TUI mode', () => { + expect(parse(['custom.yml'])).toEqual({ mode: 'tui', config: 'custom.yml' }) + }) + + it('parses --resume in the space and inline forms, independent of a config positional', () => { + expect(parse(['--resume', 'sess-1'])).toEqual({ mode: 'tui', resume: 'sess-1' }) + expect(parse(['--resume=sess-2'])).toEqual({ mode: 'tui', resume: 'sess-2' }) + expect(parse(['--resume', 'sess-3', 'app.yml'])).toEqual({ mode: 'tui', config: 'app.yml', resume: 'sess-3' }) + expect(parse(['app.yml', '--resume', 'sess-4'])).toEqual({ mode: 'tui', config: 'app.yml', resume: 'sess-4' }) + }) + + it('fails loud on a valueless or empty --resume rather than silently starting fresh', () => { + expectError(['--resume'], '--resume') + expectError(['--resume='], 'must not be empty') + }) + + it('rejects a repeated --resume instead of silently keeping the last id', () => { + expectError(['--resume', 'a', '--resume', 'b'], 'may be given only once') + expectError(['--resume=a', '--resume=b'], 'may be given only once') + }) +}) + +describe('parseDshArgs — headless', () => { + it('routes -p / --prompt to the headless mode with the task text', () => { + expect(parse(['-p', 'do the thing'])).toEqual({ mode: 'headless', prompt: 'do the thing' }) + expect(parse(['--prompt', 'do the thing'])).toEqual({ mode: 'headless', prompt: 'do the thing' }) + }) + + it('routes to headless regardless of the prompt flag position', () => { + // Positional-independent: the old `argv.includes('-p')` dispatch could not + // tell a real prompt flag from one buried after other tokens. + expect(parse(['-p', 'task'])).toEqual({ mode: 'headless', prompt: 'task' }) + }) + + it('rejects an empty prompt and a stray config positional', () => { + expectError(['-p', ''], 'must not be empty') + expectError(['-p', 'task', 'app.yml'], 'takes no config') + }) +}) + +describe('parseDshArgs — web', () => { + it('defaults the web mode to loopback and port 3080', () => { + expect(parse(['web'])).toEqual({ mode: 'web', host: LOOPBACK_HOST, port: 3080 }) + }) + + it('accepts an explicit loopback or all-interfaces host and a valid port', () => { + expect(parse(['web', '--host', ALL_INTERFACES_HOST, '--port', '8080'])) + .toEqual({ mode: 'web', host: ALL_INTERFACES_HOST, port: 8080 }) + expect(parse(['web', '--port', '0'])).toEqual({ mode: 'web', host: LOOPBACK_HOST, port: 0 }) + }) + + it('rejects a non-integer or out-of-range port with a --port diagnostic', () => { + expectError(['web', '--port', 'abc'], '--port') + expectError(['web', '--port', '70000'], '--port') + expectError(['web', '--port', '-1'], '--port') + }) + + it('rejects a host outside the allowed choices with a --host diagnostic', () => { + expectError(['web', '--host', '10.0.0.1'], '--host') + }) + + it('rejects an unexpected positional after web', () => { + expectError(['web', 'extra'], 'too many arguments') + }) + + it('fails loud when a root flag is placed before web instead of serving with it dropped', () => { + // `dsh web -p x` and `dsh -p x web` both misrouted or dropped the flag under + // the old `argv[0]==='web'` / `argv.includes('-p')` dispatch. + expectError(['web', '-p', 'x'], "unknown option '-p'") + expectError(['web', '--resume', 'y'], "unknown option '--resume'") + expectError(['-p', 'x', 'web'], 'web takes no') + expectError(['--resume', 'y', 'web'], 'web takes no') + }) + + it('renders web usage for web --help', () => { + const help = parse(['web', '--help']) + expect(help.mode).toBe('help') + if (help.mode !== 'help') throw new Error('expected help mode') + expect(help.text).toContain('Usage: dsh web') + }) +}) + +describe('parseDshArgs — help, version, and errors', () => { + it('returns the rendered usage for --help / -h', () => { + const help = parse(['--help']) + expect(help.mode).toBe('help') + if (help.mode !== 'help') throw new Error('expected help mode') + expect(help.text).toContain('Usage: dsh') + expect(help.text).toContain('web') + expect(parse(['-h']).mode).toBe('help') + }) + + it('returns the version string for --version / -V', () => { + expect(parse(['--version'])).toEqual({ mode: 'version', text: `${VERSION}\n` }) + expect(parse(['-V'])).toEqual({ mode: 'version', text: `${VERSION}\n` }) + }) + + it('reports an unknown option as an error invocation', () => { + expectError(['--nope'], "unknown option '--nope'") + }) +}) diff --git a/packages/ui/app-boot/README.md b/packages/ui/app-boot/README.md index 24840b7fda..68f885608f 100644 --- a/packages/ui/app-boot/README.md +++ b/packages/ui/app-boot/README.md @@ -5,7 +5,6 @@ Shared boot glue for the app bins ([`dsh-tui-demo`](../../examples/tui-demo/READ | Export | Role | |---|---| | `resolveConfigPath(path, snapshotMode, cwd?)` | Absolute config path; `snapshotMode === 'replay'` swaps a `cordis.yml`/`.yaml` basename for its sibling `cordis.snapshot.yml` | -| `parseResumeArg(argv)` | Split the `--resume ` / `--resume=` flag out of the arguments, returning `{ resumeSessionId, rest }`; a valueless, empty, or repeated flag throws so a mistyped resume fails loud instead of silently starting fresh | | `loadEnv(binName, dir?, warn?)` | Load the gitignored `.env` (Node `process.loadEnvFile`); absent file is fine, an unloadable one warns a single labelled line (default: stderr) | | `installFailLoud(binName, proc?)` | Turn a post-`boot()` unhandled Loader rejection into one labelled stderr line + `exit(1)`; returns the uninstaller (for tests) | | `assertEntriesLoaded(ctx, binName)` | Throw when a settled tree holds an enabled entry with no fiber (a plugin module that failed to import) | diff --git a/packages/ui/app-boot/src/index.ts b/packages/ui/app-boot/src/index.ts index 2fd4ba4c05..faeb5a0e0a 100644 --- a/packages/ui/app-boot/src/index.ts +++ b/packages/ui/app-boot/src/index.ts @@ -36,50 +36,6 @@ export function resolveConfigPath( return resolve(dir, replayName) } -/** CLI flag the interactive surface accepts to resume a persisted session by id. */ -const RESUME_FLAG = '--resume' - -/** - * Split a leading `--resume ` / `--resume=` flag out of a CLI argument - * vector, returning the resumed session id (when the flag is present) and the - * remaining arguments with the flag and its value removed — so a positional - * config path stays readable regardless of the flag's position. A `--resume` - * with no following id, an empty id (`--resume=`), or a repeated `--resume` - * throws: a mistyped resume must fail loud, never silently start a fresh - * session. The id is not validated here; an unknown id fails loud downstream - * when the session cannot load. - * @param argv - the CLI arguments after subcommand dispatch. - * @returns the parsed resume id (or `undefined`) and the flag-stripped arguments. - */ -export function parseResumeArg( - argv: readonly string[], -): { resumeSessionId: string | undefined; rest: string[] } { - const rest: string[] = [] - let resumeSessionId: string | undefined - let skipNext = false - for (const [i, arg] of argv.entries()) { - if (skipNext) { - skipNext = false - continue - } - const inlineValue = arg.startsWith(`${RESUME_FLAG}=`) - if (arg === RESUME_FLAG || inlineValue) { - if (resumeSessionId !== undefined) throw new Error(`${RESUME_FLAG} may be given only once`) - const value = inlineValue ? arg.slice(RESUME_FLAG.length + 1) : argv[i + 1] - // A following token that is itself resume syntax (`--resume --resume x`) - // is a missing id, not a session literally named `--resume…`. - if (value === undefined || value === '' || value === RESUME_FLAG || value.startsWith(`${RESUME_FLAG}=`)) { - throw new Error(`${RESUME_FLAG} requires a session id (e.g. ${RESUME_FLAG} )`) - } - resumeSessionId = value - skipNext = !inlineValue // the space form consumed the following token as its value - continue - } - rest.push(arg) - } - return { resumeSessionId, rest } -} - /** * Load the optional gitignored `.env` from `dir`. Missing files fall back to the * ambient environment; other read failures are reported through `warn`. diff --git a/packages/ui/app-boot/tests/app-boot.spec.ts b/packages/ui/app-boot/tests/app-boot.spec.ts index 76e5238db7..d9934cb8bb 100644 --- a/packages/ui/app-boot/tests/app-boot.spec.ts +++ b/packages/ui/app-boot/tests/app-boot.spec.ts @@ -6,7 +6,7 @@ import { Context } from 'cordis' import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' import { addHarnessSourceSection, assertEntriesLoaded, boot, HARNESS_SOURCE_SECTION, - installFailLoud, loadEnv, parseResumeArg, resolveConfigPath, type FailLoudProcess, + installFailLoud, loadEnv, resolveConfigPath, type FailLoudProcess, } from '../src/index.ts' const NAME = 'dsh-test-bin' @@ -30,31 +30,6 @@ describe('resolveConfigPath', () => { }) }) -describe('parseResumeArg', () => { - it('returns no resume id and passes arguments through when the flag is absent', () => { - expect(parseResumeArg([])).toEqual({ resumeSessionId: undefined, rest: [] }) - expect(parseResumeArg(['custom.yml'])).toEqual({ resumeSessionId: undefined, rest: ['custom.yml'] }) - }) - - it('parses the space form, the inline form, and leaves a positional config path in any position', () => { - expect(parseResumeArg(['--resume', 'sess-1'])).toEqual({ resumeSessionId: 'sess-1', rest: [] }) - expect(parseResumeArg(['--resume=sess-2'])).toEqual({ resumeSessionId: 'sess-2', rest: [] }) - expect(parseResumeArg(['--resume', 'sess-3', 'app.yml'])).toEqual({ resumeSessionId: 'sess-3', rest: ['app.yml'] }) - expect(parseResumeArg(['app.yml', '--resume', 'sess-4'])).toEqual({ resumeSessionId: 'sess-4', rest: ['app.yml'] }) - }) - - it('fails loud on a valueless, empty, or repeated flag rather than silently starting fresh', () => { - expect(() => parseResumeArg(['--resume'])).toThrow('--resume requires a session id') - expect(() => parseResumeArg(['--resume='])).toThrow('--resume requires a session id') - expect(() => parseResumeArg(['--resume', 'a', '--resume', 'b'])).toThrow('--resume may be given only once') - }) - - it('rejects resume syntax used as the flag value instead of resuming a session named like the flag', () => { - expect(() => parseResumeArg(['--resume', '--resume', 'sess'])).toThrow('--resume requires a session id') - expect(() => parseResumeArg(['--resume', '--resume=sess'])).toThrow('--resume requires a session id') - }) -}) - describe('loadEnv', () => { it('loads variables from .env in the given dir', () => { const dir = tmp() diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3e28836146..e83b05f35c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -122,6 +122,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../packages/core/session + commander: + specifier: ^15.0.0 + version: 15.0.0 apps/web: dependencies: diff --git a/tsconfig.host.json b/tsconfig.host.json index f340f235da..5419347734 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -8,6 +8,7 @@ "rewriteRelativeImportExtensions": false }, "include": [ + "apps/cli/tests/**/*.ts", "examples/*/src/**/*.ts", "examples/*/start.ts", "examples/*/tests/**/*.ts", diff --git a/vitest.config.ts b/vitest.config.ts index 1177782a8a..fe704797f5 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -30,6 +30,7 @@ const windowsCoverageExclusions = process.platform === 'win32' const testIncludes = [ 'packages/*/*/tests/**/*.spec.{ts,tsx}', + 'apps/*/tests/**/*.spec.ts', 'examples/*/tests/**/*.spec.ts', 'scripts/**/*.spec.ts', ] From 0ffa8f97404baac692bf8f4b597387f0a343139f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 19:45:35 +0800 Subject: [PATCH 018/113] docs: sync canonical retry docs with EMPTY_RESPONSE default Address ds-review-bot: the bounded-request-recovery Agent Note stated the shipped default carried four transient codes, and the llm-streaming contract omitted the new cross-adapter empty-response classification. Update both current-state contract docs to the five-code default and cross-link the empty-response bug-fix note. --- .../architecture/2026-06-21-bounded-llm-request-recovery.md | 4 ++-- docs/core-data-structures/llm-streaming.md | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md index 28de5eb97c..3e144828cf 100644 --- a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md +++ b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md @@ -42,7 +42,7 @@ The agent loop keeps `RequestError` as that exact error object and passes `LlmFa Adapters extract structured facts before falling back to message inspection. They validate HTTP status, parse `Retry-After` seconds or dates into a positive finite millisecond delay, brand the provider request id when exposed, and distinguish their own timeout from the caller's abort. Provider-specific codes and messages may refine a mapping, but no recovery listener parses them. -The initial shared transient-code set is intentionally small: the adapters' existing `RATE_LIMIT` and `SERVER` mappings plus explicit `TIMEOUT` and `TRANSPORT` codes for the two missing remote-failure families. Authentication, quota, invalid request, context overflow, protocol, abort, and unknown failures keep distinct stable codes and are not transient by default. Adding a code requires adapter fixtures and a documented policy decision; it does not require expanding a second failure-class enum. +The initial shared transient-code set is intentionally small: the adapters' existing `RATE_LIMIT` and `SERVER` mappings plus explicit `TIMEOUT` and `TRANSPORT` codes for the two missing remote-failure families. Authentication, quota, invalid request, context overflow, protocol, abort, and unknown failures keep distinct stable codes and are not transient by default. Adding a code requires adapter fixtures and a documented policy decision; it does not require expanding a second failure-class enum. A later decision added `EMPTY_RESPONSE` as a fifth default transient code — a completed provider response with no content blocks, which both adapters now classify as an error finish; see [empty model responses are retryable](../bug-fix/2026-07-24-empty-model-response-is-retryable.md). ### Put retry policy on the existing failed-step seam @@ -62,7 +62,7 @@ interface Config { } ``` -The defaults are two transient retries, a 500 millisecond initial delay, a 10 second delay cap, 10 percent jitter, and the four transient codes above. The count and delay bounds match the conservative edge of the inspected implementations: [OpenCode uses two request retries with 500 ms/10 s bounds](https://github.com/anomalyco/opencode/blob/9976269ab1accfc9f9dc98a4a688c516934de422/%70ackages/llm/src/route/executor.ts#L36-L39), [Pi separates three agent-level retries from provider retries and defaults provider retries to zero](https://github.com/earendil-works/pi/blob/3da591ab74ab9ab407e72ed882600b2c851fae21/%70ackages/coding-agent/docs/settings.md#L139-L147), and [Codex uses finite request/stream budgets plus a five-minute idle timeout](https://github.com/openai/codex/blob/0fb559f0f6e231a88ac02ea002d3ecd248e2b515/codex-rs/model-provider-info/src/lib.rs#L25-L33). Ten percent follows [Codex's bounded jitter](https://github.com/openai/codex/blob/0fb559f0f6e231a88ac02ea002d3ecd248e2b515/codex-rs/codex-client/src/retry.rs#L40-L47). Two retries mean at most three provider requests when no other recovery policy applies. `maxTransientRetries` is a non-negative integer, delays are positive finite numbers with `initialDelayMs <= maxDelayMs`, `jitterRatio` is in `[0, 1]`, and codes are non-empty and unique. These are Cordis config fields rather than hidden constants so deployments can choose different cost and latency budgets. +The defaults are two transient retries, a 500 millisecond initial delay, a 10 second delay cap, 10 percent jitter, and the five transient codes above (`RATE_LIMIT`, `SERVER`, `TIMEOUT`, `TRANSPORT`, and the later `EMPTY_RESPONSE`). The count and delay bounds match the conservative edge of the inspected implementations: [OpenCode uses two request retries with 500 ms/10 s bounds](https://github.com/anomalyco/opencode/blob/9976269ab1accfc9f9dc98a4a688c516934de422/%70ackages/llm/src/route/executor.ts#L36-L39), [Pi separates three agent-level retries from provider retries and defaults provider retries to zero](https://github.com/earendil-works/pi/blob/3da591ab74ab9ab407e72ed882600b2c851fae21/%70ackages/coding-agent/docs/settings.md#L139-L147), and [Codex uses finite request/stream budgets plus a five-minute idle timeout](https://github.com/openai/codex/blob/0fb559f0f6e231a88ac02ea002d3ecd248e2b515/codex-rs/model-provider-info/src/lib.rs#L25-L33). Ten percent follows [Codex's bounded jitter](https://github.com/openai/codex/blob/0fb559f0f6e231a88ac02ea002d3ecd248e2b515/codex-rs/codex-client/src/retry.rs#L40-L47). Two retries mean at most three provider requests when no other recovery policy applies. `maxTransientRetries` is a non-negative integer, delays are positive finite numbers with `initialDelayMs <= maxDelayMs`, `jitterRatio` is in `[0, 1]`, and codes are non-empty and unique. These are Cordis config fields rather than hidden constants so deployments can choose different cost and latency budgets. For an eligible failure with budget remaining, the one-based transient retry count uses bounded exponential backoff. A valid `providerRetryAfterMs` replaces exponential backoff only when it does not exceed `maxDelayMs`; a longer provider delay causes delegation instead of an earlier retry that violates the provider instruction. Local backoff multiplies by an injected random factor in `[1 - jitterRatio, 1 + jitterRatio]` and clamps the final value to `maxDelayMs`; provider delay is not jittered. diff --git a/docs/core-data-structures/llm-streaming.md b/docs/core-data-structures/llm-streaming.md index 257ce90cda..5e82d91faf 100644 --- a/docs/core-data-structures/llm-streaming.md +++ b/docs/core-data-structures/llm-streaming.md @@ -61,6 +61,7 @@ Every adapter MUST obey these, and every consumer may rely on them: - **One adapter call is one provider attempt.** Adapters disable library retries. Agent-level recovery opens another durable numbered step; direct `ctx.llm.stream()` callers remain single-attempt. - **Provider stalls are bounded at the transport.** Both shipping remote adapters expose positive finite `streamIdleTimeoutMs` with a five-minute default. The watchdog arms only while iterator `next()` is outstanding, uses one stable signal for the whole request, maps its own expiry to `TIMEOUT`, and keeps an earlier caller abort as `ABORTED`. - **Context overflow has one canonical code.** Both DeepSeek adapters classify explicit provider detail through `isContextWindowExceededError()` and surface `CONTEXT_WINDOW_EXCEEDED`, whether the failure arrives as a thrown HTTP `LlmError` or an in-band finish error. Consumers route on the code, never provider text. +- **An empty completion is a retryable error, not a silent success.** Both adapters map a terminal `stop` finish that carried no content blocks to `finish {kind:'error'}` with the canonical `EMPTY_RESPONSE` code, and `dsh-llm-retry` retries it by default; see [empty model responses are retryable](../../.agents/notes/implemented/bug-fix/2026-07-24-empty-model-response-is-retryable.md). - **Every provider HTTP request carries the app-attribution header.** Adapters send `attributionHeaders()` (below) - the `User-Agent` baseline - and prove it with a wire-level test (mock server asserting the received header, or the library's header hook for a library-backed adapter). - **Replay state is adapter-owned.** A successful `finish` may carry lossless-JSON state needed to reconstruct a native provider response. The loop stores it with the assembled assistant message unless an `agent/step-result` listener rewrote the content. On a later request, `LlmService` passes the state only when the historical provider and target provider are currently registered to the exact same adapter instance. That adapter validates the state and owns any cross-model or cross-provider conversion; other adapters receive the provider-neutral content and provenance without the private state. From 66585635c860f6b13ebc08a5e717fcd049d89319 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 19:47:23 +0800 Subject: [PATCH 019/113] fix: serialize paginated session searches --- ...model-facing-session-query-tools.i18n.yaml | 4 +-- ...-07-24-model-facing-session-query-tools.md | 8 ++--- ...-24-model-facing-session-query-tools.zh.md | 8 ++--- docs/config-catalog.md | 4 ++- docs/cordis-catalog/services.md | 2 +- .../session-query-sqlite/README.md | 1 + .../session-query-sqlite/src/index.ts | 17 ++++++++++ .../session-query-sqlite/tests/sqlite.spec.ts | 26 ++++++++++++++ .../session-query/session-query/README.md | 3 +- .../session-query/session-query/src/config.ts | 5 +++ .../session-query/session-query/src/corpus.ts | 10 +++--- .../session-query/session-query/src/index.ts | 17 ++++++++-- .../session-query/tests/session-query.spec.ts | 34 +++++++++++++------ .../tool-session-query/README.md | 2 +- .../tool-session-query/src/index.ts | 2 -- .../tests/tool-session-query.spec.ts | 29 +++++++++++++--- 16 files changed, 133 insertions(+), 39 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml index 7425619403..5ec76b0d61 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 -2026-07-24-model-facing-session-query-tools.md: 0551adc431388d6cdd94b8e03c2976020ec90de4 -2026-07-24-model-facing-session-query-tools.zh.md: f82c0fac52d63ac3c11f48ee2769cb9e9590317c +2026-07-24-model-facing-session-query-tools.md: 2f057292acac2c565e6b9dac61ed1e013b998550 +2026-07-24-model-facing-session-query-tools.zh.md: 6ccf60f39afc4021899df5c422ae455259c2ecc3 diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md index 0551adc431..2f057292ac 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -24,11 +24,11 @@ The search tools expose prior work rather than the operation that is performing ## Cursor-free results and spill -Neither search tool exposes a cursor, offset, page size, or model-controlled result limit. One execution follows provider cursors while the observed generation remains valid and collects up to the configured `maxSearchResults`, which defaults to 100. A capped result tells the model to narrow its query or filters; a generation change reports that the whole search must be retried. Search execution carries a configurable `searchTimeoutMs`, defaulting to 30 seconds, through the tool deadline and the service abort signal. +Neither search tool exposes a cursor, offset, page size, or model-controlled result limit. One execution follows provider cursors while the observed generation remains valid and collects up to the configured `maxSearchResults`, which defaults to 100. A capped result tells the model to narrow its query or filters; a generation change reports that the whole search must be retried. Search execution carries a configurable `searchTimeoutMs`, defaulting to 30 seconds, through the tool deadline and the service abort signal. Because internal pages share generation-bound cursors, both search tools are exclusive in the agent-loop scheduler; the exact trace and read tools opt into parallel sibling execution because their observations tolerate intervening commits. Trace and read tools likewise expose no lineage or character pagination. Canonical results are plain text and remain complete within the service's existing event-window and search-count resource bounds. The generic `tools/post-execute` spill policy owns inline byte retention: when a configured deployment receives oversized text, it replaces that text with a bounded preview plus an opaque locator and retrieval hint while preserving the complete result in its spill store. The session-query consumer neither imports `ctx.spillStore` nor implements a second truncation format. -Session-level results include the latest folded title when available. Each tool execution batches its unique title ids through one live-preferred corpus observation with at most four persisted-inspection workers and passes the exact tool-execution signal through persisted listing and inspection. Live sources fold directly; each persisted worker folds its completed source to a detached header/title observation and releases the full log before dequeuing another id, so the batch retains only small projected values. For the search tools, the execution signal carries the configured search deadline. Cancellation starts no queued title inspections and rejects the complete tool execution after already-started inspections settle; a missing, malformed, or operationally failed title remains isolated to that id, preserves the base result, renders an unavailable marker, and logs the underlying error, while an authorization mismatch fails closed. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. +Session-level results include the latest folded title when available. Each tool execution batches its unique title ids through one live-preferred corpus observation with at most the service's configured `persistedInspectConcurrency` workers, which defaults to four, and passes the exact tool-execution signal through persisted listing and inspection. Live sources fold directly; each persisted worker folds its completed source to a detached header/title observation and releases the full log before dequeuing another id, so the batch retains only small projected values. For the search tools, the execution signal carries the configured search deadline. Cancellation starts no queued title inspections and rejects the complete tool execution after already-started inspections settle; a missing, malformed, or operationally failed title remains isolated to that id, preserves the base result, renders an unavailable marker, and logs the underlying error, while an authorization mismatch fails closed. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. ## Host composition @@ -44,8 +44,8 @@ The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.se ## Verification -Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, count caps, cancellation, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, exclusive search and parallel exact-read classification, count caps, cancellation, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. ## Consequences -Models gain provider-independent access to prior session work without receiving storage authority or continuation state. Search has a finite per-call work bound and may require a narrower query to reach matches beyond the first 100; complete traces and event payloads may become spill references instead of inline text. Exact string `cwd` equality favors a conservative security boundary over resolving symlink-equivalent paths. Custom compositions may mount the tool without spill, but then they explicitly accept complete inline trace and read results. +Models gain provider-independent access to prior session work without receiving storage authority or continuation state. Search has a finite per-call work bound and may require a narrower query to reach matches beyond the first 100; search calls cannot overlap siblings, while exact observations retain parallel scheduling. Complete traces and event payloads may become spill references instead of inline text. Exact string `cwd` equality favors a conservative security boundary over resolving symlink-equivalent paths. Custom compositions may mount the tool without spill, but then they explicitly accept complete inline trace and read results. diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md index f82c0fac52..6ccf60f39a 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -24,11 +24,11 @@ Status: implemented ## 无游标结果与 spill -两个搜索工具都不向模型公开游标、偏移量、页大小或模型可控的结果限制。一次执行会在观察到的代保持有效时持续跟随提供方游标,并收集不超过配置项 `maxSearchResults` 的结果,其默认值为 100。达到上限的结果会要求模型缩小查询或过滤范围;代发生变化时会报告必须重试完整搜索。搜索执行通过工具截止时间与服务中止信号传递可配置的 `searchTimeoutMs`,默认值为 30 秒。 +两个搜索工具都不向模型公开游标、偏移量、页大小或模型可控的结果限制。一次执行会在观察到的代保持有效时持续跟随提供方游标,并收集不超过配置项 `maxSearchResults` 的结果,其默认值为 100。达到上限的结果会要求模型缩小查询或过滤范围;代发生变化时会报告必须重试完整搜索。搜索执行通过工具截止时间与服务中止信号传递可配置的 `searchTimeoutMs`,默认值为 30 秒。由于内部页面共享与代绑定的游标,两个搜索工具在 agent loop 调度器中都以独占方式执行;精确追踪与读取工具则允许和兄弟工具并行执行,因为其观测可以容忍期间发生的提交。 追踪与读取工具同样不公开谱系分页或字符分页。规范结果采用纯文本,并在服务已有的事件窗口与搜索数量资源边界内保持完整。通用的 `tools/post-execute` spill 策略负责行内字节保留:当已配置的部署收到过大的文本时,该策略会用有界预览、不可透明推导的定位符与读取提示替换文本,同时在 spill 存储中保留完整结果。会话查询消费者既不导入 `ctx.spillStore`,也不实现第二套截断格式。 -会话级结果在可用时包含最新折叠标题。每次工具执行都会通过一次优先使用实时数据的语料观测批量读取唯一标题 id,最多使用 4 个持久化检查 worker,并将准确的工具执行信号传递给持久化列表与检查操作。实时来源会直接折叠;每个持久化 worker 都会把已完成的来源折叠为分离的会话头/标题观测,并在取出下一个 id 前释放完整日志,因此批次只保留小型投影值。对于搜索工具,该执行信号携带已配置的搜索截止时间。取消不会启动排队中的标题检查,并会在已经启动的检查全部完成后拒绝完整的工具执行;标题缺失、格式错误或发生操作性失败时,错误只影响对应 id,同时保留基础结果、渲染不可用标记并记录底层错误,而授权不匹配则按失败关闭处理。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 +会话级结果在可用时包含最新折叠标题。每次工具执行都会通过一次优先使用实时数据的语料观测批量读取唯一标题 id,最多使用服务通过 `persistedInspectConcurrency` 配置的持久化检查 worker,其默认值为 4,并将准确的工具执行信号传递给持久化列表与检查操作。实时来源会直接折叠;每个持久化 worker 都会把已完成的来源折叠为分离的会话头/标题观测,并在取出下一个 id 前释放完整日志,因此批次只保留小型投影值。对于搜索工具,该执行信号携带已配置的搜索截止时间。取消不会启动排队中的标题检查,并会在已经启动的检查全部完成后拒绝完整的工具执行;标题缺失、格式错误或发生操作性失败时,错误只影响对应 id,同时保留基础结果、渲染不可用标记并记录底层错误,而授权不匹配则按失败关闭处理。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 ## 宿主组合 @@ -44,8 +44,8 @@ Status: implemented ## 验证 -包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、数量上限、取消、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、搜索独占与精确读取并行分类、数量上限、取消、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 ## 后果 -模型无需获得存储权限或继续状态,即可通过与提供方无关的方式访问既往会话工作。搜索具有有限的单次调用工作边界,若要命中前 100 条以后的结果,可能需要缩小查询;完整追踪与事件负载可能表现为 spill 引用而不是行内文本。严格的 `cwd` 字符串相等选择了保守安全边界,而不解析通过符号链接等价的路径。自定义组合可以在不挂载 spill 的情况下使用该工具,但这表示它们明确接受完整追踪与读取结果直接出现在行内。 +模型无需获得存储权限或继续状态,即可通过与提供方无关的方式访问既往会话工作。搜索具有有限的单次调用工作边界,若要命中前 100 条以后的结果,可能需要缩小查询;搜索调用不能与兄弟工具重叠执行,而精确观测仍可并行调度。完整追踪与事件负载可能表现为 spill 引用而不是行内文本。严格的 `cwd` 字符串相等选择了保守安全边界,而不解析通过符号链接等价的路径。自定义组合可以在不挂载 spill 的情况下使用该工具,但这表示它们明确接受完整追踪与读取结果直接出现在行内。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 9f2682c5c3..700cd49e71 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1019,6 +1019,8 @@ export interface Config extends SessionQueryConfig { maxLimit?: number /** Maximum snippet length in Unicode code points. Defaults to 240. */ snippetChars?: number + /** Maximum concurrent persisted-log inspections in one inherited batch read. Defaults to 4. */ + persistedInspectConcurrency?: number } /** Supported SQLite journal modes. */ @@ -1027,7 +1029,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' Depends on: [`SessionQueryConfig`](../packages/session-query/session-query/src/index.ts) -Source: [`packages/session-query/session-query-sqlite/src/index.ts:75`](../packages/session-query/session-query-sqlite/src/index.ts) +Source: [`packages/session-query/session-query-sqlite/src/index.ts:76`](../packages/session-query/session-query-sqlite/src/index.ts) ## `@deepseek-ai/dsh-session-reference` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index e31cd66147..b15fc29ee9 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -1091,7 +1091,7 @@ async readEvent(request: SessionEventReadRequest): Promise Types: [SessionEventReadRequest](../core-data-structures/session-query.md) · [SessionEventRecord](../core-data-structures/session-query.md) · [SessionEventResultFilter](../core-data-structures/session-query.md) · [SessionEventSearchDocument](../core-data-structures/session-query.md) · [SessionEventSearchPage](../core-data-structures/session-query.md) · [SessionEventSearchRequest](../core-data-structures/session-query.md) · [SessionEventTraceObservation](../core-data-structures/session-query.md) · [SessionEventTraceRequest](../core-data-structures/session-query.md) · [SessionEventWindow](../core-data-structures/session-query.md) · [SessionId](../core-data-structures/core.md) · [SessionLineageTrace](../core-data-structures/session-query.md) · [SessionLogSnapshot](../core-data-structures/session-query.md) · [SessionRecord](../core-data-structures/session-query.md) · [SessionResultFilter](../core-data-structures/session-query.md) · [SessionSearchExecContext](../core-data-structures/session-query.md) · [SessionSearchHit](../core-data-structures/session-query.md) · [SessionSearchPage](../core-data-structures/session-query.md) · [SessionSearchRequest](../core-data-structures/session-query.md) · [SessionSurfaceSnapshot](../core-data-structures/session-query.md) · [SessionTitleObservation](../core-data-structures/session-query.md) · [SessionTitleObservationResult](../core-data-structures/session-query.md) · [SessionTitleSnapshot](../core-data-structures/session-title.md) -Source: [`packages/session-query/session-query/src/index.ts:76`](../../packages/session-query/session-query/src/index.ts) +Source: [`packages/session-query/session-query/src/index.ts:81`](../../packages/session-query/session-query/src/index.ts) ## `ctx.sessionReferences` — `SessionReferenceService` diff --git a/packages/session-query/session-query-sqlite/README.md b/packages/session-query/session-query-sqlite/README.md index a2c48a669f..693b1275f2 100644 --- a/packages/session-query/session-query-sqlite/README.md +++ b/packages/session-query/session-query-sqlite/README.md @@ -28,6 +28,7 @@ The database is disposable but reset is guarded: every recognized schema version | `maxLimit` | `100` | Largest accepted request page size; at most `Number.MAX_SAFE_INTEGER - 1`. | | `snippetChars` | `240` | Maximum snippet length in Unicode code points. | | `readWindowMax` | `50` | Maximum `before` or `after` raw-event count for inherited `readEvent()`. | +| `persistedInspectConcurrency` | `4` | Maximum concurrent persisted-log inspections for inherited batch reads; must be a positive safe integer. | ## Tokenizer and limits diff --git a/packages/session-query/session-query-sqlite/src/index.ts b/packages/session-query/session-query-sqlite/src/index.ts index b3ff8feb07..3acf806646 100644 --- a/packages/session-query/session-query-sqlite/src/index.ts +++ b/packages/session-query/session-query-sqlite/src/index.ts @@ -15,6 +15,7 @@ import type { SessionPersistenceSnapshot, } from '@deepseek-ai/dsh-session-persistence' import SessionQueryService, { + SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY, SESSION_QUERY_READ_WINDOW_MAX, SessionQueryError, SessionSearchCursor, @@ -87,6 +88,8 @@ export interface Config extends SessionQueryConfig { maxLimit?: number /** Maximum snippet length in Unicode code points. Defaults to 240. */ snippetChars?: number + /** Maximum concurrent persisted-log inspections in one inherited batch read. Defaults to 4. */ + persistedInspectConcurrency?: number } interface ResolvedConfig { @@ -96,6 +99,7 @@ interface ResolvedConfig { maxLimit: number snippetChars: number readWindowMax: number + persistedInspectConcurrency: number } interface ObservedSession { @@ -176,6 +180,11 @@ export class SessionQuerySqlite extends SessionQueryService { maxLimit: z.number().step(1).min(1).max(SQLITE_MAX_PAGE_LIMIT).default(SESSION_QUERY_SQLITE_MAX_LIMIT), snippetChars: z.number().step(1).min(1).default(SESSION_QUERY_SQLITE_SNIPPET_CHARS), readWindowMax: z.number().step(1).min(0).default(SESSION_QUERY_READ_WINDOW_MAX), + persistedInspectConcurrency: z.number() + .step(1) + .min(1) + .max(Number.MAX_SAFE_INTEGER) + .default(SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY), }) /** Validated and defaulted backend configuration. */ @@ -937,6 +946,8 @@ function resolveConfig(config: Config): ResolvedConfig { maxLimit: config.maxLimit ?? SESSION_QUERY_SQLITE_MAX_LIMIT, snippetChars: config.snippetChars ?? SESSION_QUERY_SQLITE_SNIPPET_CHARS, readWindowMax: config.readWindowMax ?? SESSION_QUERY_READ_WINDOW_MAX, + persistedInspectConcurrency: config.persistedInspectConcurrency + ?? SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY, } if (typeof resolved.path !== 'string' || resolved.path.trim().length === 0) { throw invalidConfig('path must not be blank') @@ -947,6 +958,12 @@ function resolveConfig(config: Config): ResolvedConfig { if (!Number.isInteger(resolved.readWindowMax) || resolved.readWindowMax < 0) { throw invalidConfig('readWindowMax must be a non-negative integer') } + if ( + !Number.isSafeInteger(resolved.persistedInspectConcurrency) + || resolved.persistedInspectConcurrency < 1 + ) { + throw invalidConfig('persistedInspectConcurrency must be a positive safe integer') + } if (resolved.defaultLimit > resolved.maxLimit) { throw invalidConfig('defaultLimit must be less than or equal to maxLimit') } diff --git a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts index 71892159d5..b777ad8455 100644 --- a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts +++ b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts @@ -13,6 +13,7 @@ import SessionQuerySqlite, { SESSION_QUERY_SQLITE_SCHEMA_VERSION, } from '@deepseek-ai/dsh-session-query-sqlite' import { + SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY, SessionQueryError, SessionSearchCursor, type SessionAvailability, @@ -167,6 +168,29 @@ async function liveContext(config: ConstructorParameters { + it('defaults and validates persisted inspection concurrency through its Cordis config', async () => { + const defaultCtx = await liveContext() + expect((defaultCtx.sessionQuery as SessionQuerySqlite).config.persistedInspectConcurrency) + .toBe(SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY) + + const configuredValue = 2 + const configured = new SessionQuerySqlite.Config({ + path: ':memory:', + persistedInspectConcurrency: configuredValue, + }) + expect(configured.persistedInspectConcurrency).toBe(configuredValue) + const configuredCtx = await liveContext(configured) + expect((configuredCtx.sessionQuery as SessionQuerySqlite).config.persistedInspectConcurrency) + .toBe(configuredValue) + + for (const persistedInspectConcurrency of [0, Number.MAX_SAFE_INTEGER + 1]) { + expect(() => new SessionQuerySqlite.Config({ + path: ':memory:', + persistedInspectConcurrency, + })).toThrow() + } + }) + it('searches two-character Unicode61 tokens in live-only sessions', async () => { const ctx = await liveContext({ path: ':memory:', snippetChars: 20 }) const session = ctx.sessions.create(SessionId('live'), { @@ -486,6 +510,8 @@ describe('SQLite session search', () => { { path: ':memory:', maxLimit: 1e100 }, { path: ':memory:', snippetChars: 0 }, { path: ':memory:', readWindowMax: -1 }, + { path: ':memory:', persistedInspectConcurrency: 0 }, + { path: ':memory:', persistedInspectConcurrency: Number.MAX_SAFE_INTEGER + 1 }, { path: ':memory:', defaultLimit: 3, maxLimit: 2 }, { path: ':memory:', journalMode: 'memory' }, ]) { diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index 6bd0a1990f..82d32f5119 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -15,7 +15,7 @@ - `traceSession(sessionId)` reads the corpus once and returns immediate-to-outward ancestors plus deterministic recursive descendant trees. `complete: false` identifies the first missing parent; a target-connected cycle fails with `SESSION_QUERY_INVALID_LINEAGE`. - `traceEvent(request)` loads the logical log once and returns its cloned source header with direct positional replacements and direct logged provenance. `replacementChain` follows positional replacers to the final replacement; provenance links remain non-transitive. -Persistence is optional and may mount or unmount dynamically. Cross-corpus listing and lineage tracing fail with `SESSION_QUERY_PERSISTENCE_FAILED` while mounted persistence is unreadable. A title, event read, or trace targeting a known live session does not consult persistence, so durable backend health cannot make current in-memory state unreadable. Persisted title and event operations list before loading and reject a metadata mismatch rather than combining inconsistent observations. A batch title observation performs one metadata listing, inspects its unique persisted ids with at most four workers, and preserves each title's own observed header for downstream authorization. Cancellation starts no queued inspections and rejects only after already-started workers settle. `listSessions()` remains lightweight and does not load logs or index titles. +Persistence is optional and may mount or unmount dynamically. Cross-corpus listing and lineage tracing fail with `SESSION_QUERY_PERSISTENCE_FAILED` while mounted persistence is unreadable. A title, event read, or trace targeting a known live session does not consult persistence, so durable backend health cannot make current in-memory state unreadable. Persisted title and event operations list before loading and reject a metadata mismatch rather than combining inconsistent observations. A batch title observation performs one metadata listing, inspects its unique persisted ids with at most `persistedInspectConcurrency` workers, and preserves each title's own observed header for downstream authorization. Cancellation starts no queued inspections and rejects only after already-started workers settle. `listSessions()` remains lightweight and does not load logs or index titles. ## Filtering and extraction @@ -38,6 +38,7 @@ The package has no provider coordinator, fallback implementation, or standalone | Key | Default | Contract | |---|---:|---| | `readWindowMax` | `50` | Maximum `before` or `after` raw-event count. | +| `persistedInspectConcurrency` | `4` | Maximum concurrent persisted-log inspections in one batch read; must be a positive safe integer. | ## Model Experience diff --git a/packages/session-query/session-query/src/config.ts b/packages/session-query/session-query/src/config.ts index 5b7ddffd90..714ef937df 100644 --- a/packages/session-query/session-query/src/config.ts +++ b/packages/session-query/session-query/src/config.ts @@ -5,10 +5,15 @@ import { HarnessError } from '@deepseek-ai/dsh-llm' /** Default maximum `before`/`after` raw-event window. */ export const SESSION_QUERY_READ_WINDOW_MAX = 50 +/** Default maximum number of concurrent persisted-log inspections in one batch read. */ +export const SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY = 4 + /** Backend-independent configuration inherited by every session-query implementation. */ export interface Config { /** Maximum accepted raw read context on either side. Defaults to 50. */ readWindowMax?: number + /** Maximum concurrent persisted-log inspections in one batch read. Defaults to 4. */ + persistedInspectConcurrency?: number } /** Stable machine-routable failure taxonomy for session reads, traces, and search. */ diff --git a/packages/session-query/session-query/src/corpus.ts b/packages/session-query/session-query/src/corpus.ts index 523b38b3b9..5ed04a4808 100644 --- a/packages/session-query/session-query/src/corpus.ts +++ b/packages/session-query/session-query/src/corpus.ts @@ -28,15 +28,15 @@ export type LogicalProjectionResult = | { sessionId: SessionId; status: 'fulfilled'; value: Value } | { sessionId: SessionId; status: 'rejected'; reason: unknown } -/** Bound persisted observation fan-out for public batch title reads. */ -const PERSISTED_INSPECT_CONCURRENCY = 4 - /** Resolves a live-preferred corpus against the persistence service mounted now. */ export class SessionCorpus { private _persistence: SessionPersistence | undefined private readonly _optionalPersistenceFiber: Fiber - constructor(private readonly _ctx: Context) { + constructor( + private readonly _ctx: Context, + private readonly _persistedInspectConcurrency: number, + ) { this._optionalPersistenceFiber = _ctx.inject(['sessionPersistence'], (childCtx: Context) => { const service = childCtx.sessionPersistence this._persistence = service @@ -188,7 +188,7 @@ export class SessionCorpus { await resolvePersisted(unresolved[index] as SessionId) } } - const workerCount = Math.min(PERSISTED_INSPECT_CONCURRENCY, unresolved.length) + const workerCount = Math.min(this._persistedInspectConcurrency, unresolved.length) const settlements = await Promise.allSettled( Array.from({ length: workerCount }, () => worker()), ) diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index 4da71b2a84..a16c8e9047 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -31,6 +31,7 @@ import type { SessionTitleObservationResult, } from './types.ts' import { + SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY, SESSION_QUERY_READ_WINDOW_MAX, SessionQueryError, type Config, @@ -48,7 +49,11 @@ import * as tracing from './tracing.ts' export type * from './types.ts' export { SessionSearchCursor } from './cursor.ts' export type { Config, SessionQueryErrorCode } from './config.ts' -export { SESSION_QUERY_READ_WINDOW_MAX, SessionQueryError } from './config.ts' +export { + SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY, + SESSION_QUERY_READ_WINDOW_MAX, + SessionQueryError, +} from './config.ts' export { extractSessionEventText } from './extraction.ts' export { buildSessionEventRecords, buildSessionEventSearchDocuments } from './documents.ts' export { @@ -88,7 +93,15 @@ export abstract class SessionQueryService extends Service { 'SESSION_QUERY_INVALID_CONFIG', ) } - this._corpus = new SessionCorpus(ctx) + const persistedInspectConcurrency = config.persistedInspectConcurrency + ?? SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY + if (!Number.isSafeInteger(persistedInspectConcurrency) || persistedInspectConcurrency < 1) { + throw new SessionQueryError( + 'session-query: persistedInspectConcurrency must be a positive safe integer', + 'SESSION_QUERY_INVALID_CONFIG', + ) + } + this._corpus = new SessionCorpus(ctx, persistedInspectConcurrency) } /** diff --git a/packages/session-query/session-query/tests/session-query.spec.ts b/packages/session-query/session-query/tests/session-query.spec.ts index dfa209496d..4d093360ab 100644 --- a/packages/session-query/session-query/tests/session-query.spec.ts +++ b/packages/session-query/session-query/tests/session-query.spec.ts @@ -4,6 +4,7 @@ import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/ds import type { SessionEvent, SessionHeader, SessionId as SessionIdType } from '@deepseek-ai/dsh-session' import SessionPersistence, { SessionPersistenceRevision } from '@deepseek-ai/dsh-session-persistence' import SessionQueryService, { + SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY, type SessionEventSurface, type SessionQueryErrorCode, } from '@deepseek-ai/dsh-session-query' @@ -372,7 +373,7 @@ describe('session-query exact reads', () => { const results = await ctx.sessionQuery.readTitleSnapshots(entries.map(entry => entry.meta.id)) - expect(maximum).toBe(4) + expect(maximum).toBe(SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY) expect(TestPersistence.listCalls).toBe(1) expect(TestPersistence.inspectCalls).toEqual(entries.map(entry => entry.meta.id)) expect(results.map(result => result.sessionId)).toEqual(entries.map(entry => entry.meta.id)) @@ -466,7 +467,8 @@ describe('session-query exact reads', () => { events: eventLog(`queued-${index}`), })) TestPersistence.reset(entries) - const ctx = await liveContext() + const persistedInspectConcurrency = 2 + const ctx = await liveContext({ persistedInspectConcurrency }) await ctx.plugin(TestPersistence) const controller = new AbortController() const reason = new Error('cancel queued title batch') @@ -490,17 +492,21 @@ describe('session-query exact reads', () => { () => { batchSettled = true }, () => { batchSettled = true }, ) - await vi.waitFor(() => { expect(TestPersistence.inspectCalls).toHaveLength(4) }) + await vi.waitFor(() => { + expect(TestPersistence.inspectCalls).toHaveLength(persistedInspectConcurrency) + }) controller.abort(reason) - await vi.waitFor(() => { expect(abortsObserved).toBe(4) }) + await vi.waitFor(() => { expect(abortsObserved).toBe(persistedInspectConcurrency) }) expect(batchSettled).toBe(false) - expect(TestPersistence.inspectCalls).toEqual(entries.slice(0, 4).map(entry => entry.meta.id)) + expect(TestPersistence.inspectCalls) + .toEqual(entries.slice(0, persistedInspectConcurrency).map(entry => entry.meta.id)) for (const release of releases) release() await expect(pending).rejects.toBe(reason) - expect(inspectionsSettled).toBe(4) - expect(TestPersistence.inspectCalls).toEqual(entries.slice(0, 4).map(entry => entry.meta.id)) + expect(inspectionsSettled).toBe(persistedInspectConcurrency) + expect(TestPersistence.inspectCalls) + .toEqual(entries.slice(0, persistedInspectConcurrency).map(entry => entry.meta.id)) }) it('passes cancellation into a stalled persisted title listing and rejects with its reason', async () => { @@ -907,10 +913,16 @@ describe('session-query exact reads', () => { const direct = new Context() await direct.plugin(SessionStore) expect(new TestSessionQueryService(direct)).toBeInstanceOf(SessionQueryService) - const invalid = new Context() - await invalid.plugin(SessionStore) - expect(() => new TestSessionQueryService(invalid, { readWindowMax: -1 })) - .toThrow(expectCode('SESSION_QUERY_INVALID_CONFIG')) + for (const config of [ + { readWindowMax: -1 }, + { persistedInspectConcurrency: 0 }, + { persistedInspectConcurrency: Number.MAX_SAFE_INTEGER + 1 }, + ]) { + const invalid = new Context() + await invalid.plugin(SessionStore) + expect(() => new TestSessionQueryService(invalid, config)) + .toThrow(expectCode('SESSION_QUERY_INVALID_CONFIG')) + } }) it('leaves the optional persistence dependency optional', async () => { diff --git a/packages/session-query/tool-session-query/README.md b/packages/session-query/tool-session-query/README.md index 2a5ad72f9c..f9e466f4a0 100644 --- a/packages/session-query/tool-session-query/README.md +++ b/packages/session-query/tool-session-query/README.md @@ -9,7 +9,7 @@ Workspace-authorized model tools over `ctx.sessionQuery`. The package depends on | `maxSearchResults` | `100` | Maximum authorized non-self hits collected across internal provider pages | | `searchTimeoutMs` | `30000` | Cooperative deadline attached to both full-text search tools | -The caller comes exclusively from `ToolExecution.exec.agent`. Cross-session access requires exact equality between the target and caller session `cwd` values; a caller without `cwd` can inspect only itself. Search never exposes provider cursors, offsets, page sizes, or a model-controlled limit. Timestamps at the tool boundary require an explicit `Z` or numeric offset and become inclusive epoch-millisecond filters. +The caller comes exclusively from `ToolExecution.exec.agent`. Cross-session access requires exact equality between the target and caller session `cwd` values; a caller without `cwd` can inspect only itself. Search never exposes provider cursors, offsets, page sizes, or a model-controlled limit. Because one search consumes generation-bound provider cursors internally, both search tools execute exclusively with sibling tool calls; the three exact trace/read tools opt into parallel execution. Timestamps at the tool boundary require an explicit `Z` or numeric offset and become inclusive epoch-millisecond filters. `session_search` always omits the caller session. A current-session `session_event_search` stops immediately before the step that invoked it, so the active assistant output and logged tool call cannot match themselves. Direct targets are authorized before trace, event, or title reads. Lineage output replaces unauthorized ancestor and descendant boundaries with markers that contain no hidden session id. diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index f6cebc1376..186e2ca75c 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -211,7 +211,6 @@ export function apply(ctx: Context, config: Config): void { parameters: SESSION_SEARCH_PARAMETERS, output: TEXT_OUTPUT, timeoutMs: resolved.searchTimeoutMs, - isConcurrencySafe: () => true, execute: (args, exec) => executeSessionSearch(ctx, args, exec, resolved.maxSearchResults), presentCall: presentSessionSearchCall, })) @@ -222,7 +221,6 @@ export function apply(ctx: Context, config: Config): void { parameters: EVENT_SEARCH_PARAMETERS, output: TEXT_OUTPUT, timeoutMs: resolved.searchTimeoutMs, - isConcurrencySafe: () => true, execute: (args, exec) => executeEventSearch(ctx, args, exec, resolved.maxSearchResults), presentCall: presentEventSearchCall, })) diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index 134430baee..f403b3f5ba 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -248,15 +248,13 @@ describe('registration and schemas', () => { expect(sessionSchema?.parameters).not.toHaveProperty('properties.cwd') expect(mounted.ctx.tools.get('session_search')?.timeoutMs).toBe(1234) expect(mounted.ctx.tools.get('session_trace')?.timeoutMs).toBeUndefined() - const safeArgs: Record = { - session_search: { query: 'q' }, - session_event_search: { query: 'q' }, + const parallelArgs: Record = { session_trace: {}, session_event_trace: { seq: 0 }, session_event_read: { seq: 0 }, } - for (const name of names) { - expect(mounted.ctx.tools.get(name)?.isConcurrencySafe?.(safeArgs[name])).toBe(true) + for (const [name, args] of Object.entries(parallelArgs)) { + expect(mounted.ctx.tools.get(name)?.isConcurrencySafe?.(args)).toBe(true) } expect(mounted.ctx.tools.get('session_search')?.output.render({}, 'rendered')) .toEqual([{ type: 'text', text: 'rendered' }]) @@ -287,6 +285,27 @@ describe('registration and schemas', () => { .not.toContain('tool:session-query') }) + it('keeps generation-bound searches exclusive while exact observations remain parallel', async () => { + const mounted = await mount() + const classifications = [ + ['session_search', { query: 'q' }, 'exclusive'], + ['session_event_search', { query: 'q' }, 'exclusive'], + ['session_trace', {}, 'parallel'], + ['session_event_trace', { seq: 0 }, 'parallel'], + ['session_event_read', { seq: 0 }, 'parallel'], + ] as const + + for (const [name, args, kind] of classifications) { + expect(mounted.ctx.tools.executionMode({ + name, + arguments: args, + callId: CallId(`mode-${name}`), + signal: new AbortController().signal, + agent: fakeAgent(mounted.caller), + })).toEqual({ kind }) + } + }) + it('fails invalid direct config before registering anything', async () => { const mounted = await mount() for (const maxSearchResults of [0, 1.5, Number.NaN]) { From 46b9a91e556437946b3356d2e5d6eed241cd57ef Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:49:02 +0800 Subject: [PATCH 020/113] =?UTF-8?q?test(web):=20keyless=20browser=20e2e=20?= =?UTF-8?q?lane=20=E2=80=94=20replayed=20round=20trip=20+=20seeded=20cold?= =?UTF-8?q?=20resume?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit apps/web/tests/harness.ts boots the real web assembly in-process (startHost llm:false -> installLlmReplay providers-mode -> mountWebPlugins -> startWebServer) under DSH_SNAPSHOT replay/record/refresh. Barrier stack: in-process turn/end -> agent.whenIdle (covers the persistence flush) -> browser settled-poll. Seeding goes through the real persistence API (semantic-checkpoint precedent); record harvests fixtures from live session memory and tokenizes {{sessionId}}/{{cwd}}; refresh is the sole golden writer. Console tripwires fail scenarios on reconnect/gap-repair self-healing; harness close asserts full replay-fixture consumption. Scenarios, each with fixtures recorded against THIS assembly via a live model run: replay-round-trip (real composer -> real bash echo -> settled markdown + aria golden + world-state event asserts) and seeded-history (cold sidebar list -> implicit resume on open -> history tool cards from the log, zero model calls). apps/web/tests are host-plane programs: excluded from the client-registered apps/web project, included in tsconfig.host.json (one program cannot hold both Context merge sides). --- apps/web/tests/harness.ts | 423 ++++++++++++++++++ apps/web/tests/replay-round-trip.e2e.ts | 109 +++++ apps/web/tests/seeded-history.e2e.ts | 105 +++++ .../snapshots/fresh-round-trip/session.jsonl | 97 ++++ .../snapshots/fresh-round-trip/ui.expected.md | 31 ++ .../tests/snapshots/seeded-history/seed.jsonl | 112 +++++ .../snapshots/seeded-history/ui.expected.md | 36 ++ apps/web/tsconfig.json | 9 + tsconfig.host.json | 4 + 9 files changed, 926 insertions(+) create mode 100644 apps/web/tests/harness.ts create mode 100644 apps/web/tests/replay-round-trip.e2e.ts create mode 100644 apps/web/tests/seeded-history.e2e.ts create mode 100644 apps/web/tests/snapshots/fresh-round-trip/session.jsonl create mode 100644 apps/web/tests/snapshots/fresh-round-trip/ui.expected.md create mode 100644 apps/web/tests/snapshots/seeded-history/seed.jsonl create mode 100644 apps/web/tests/snapshots/seeded-history/ui.expected.md diff --git a/apps/web/tests/harness.ts b/apps/web/tests/harness.ts new file mode 100644 index 0000000000..6f885da0c8 --- /dev/null +++ b/apps/web/tests/harness.ts @@ -0,0 +1,423 @@ +// Shared harness for the keyless browser e2e lane (Agent Note: +// .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md). +// Boots the REAL web assembly in-process from the exported production +// functions — startHost (bootHost spine) + mountWebPlugins + registry + +// startWebServer — so a real chromium exercises the real HTTP/SSE wire, +// apiproxy, agent loop, tools, and persistence. Modes ride $DSH_SNAPSHOT: +// replay (default, keyless: `llm: false` + dsh-llm-replay in providers mode), +// record (real DeepSeek adapter + key, harvests fixtures from live session +// memory), refresh (keyless replay that rewrites the committed goldens). +// +// Assembly divergence from `dsh web` (apps/cli/src/web.ts), deliberate: the +// shipped shell opts into sessionTitleLlm, whose fire-and-forget title call +// shares the session's replay cursor — nondeterministic ordering against the +// loop's own calls — so this lane keeps bootHost's disabled default and +// sidebar titles come from the deterministic fallback service. +import { existsSync, readFileSync } from 'node:fs' +import { mkdtemp, readFile, readdir, rm, utimes, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import type { Page } from 'playwright' +import { expect } from 'vitest' +import { scrubRequestHeaders } from '@deepseek-ai/dsh-acp-snapshot' +import { installLlmReplay, parseSessionLog } from '@deepseek-ai/dsh-llm-replay' +import type { ReplayHandle } from '@deepseek-ai/dsh-llm-replay' +import { startHost, mountWebPlugins } from '@deepseek-ai/dsh-host-runtime' +import type { RunningHost } from '@deepseek-ai/dsh-host-runtime' +import { createHostWebPluginRegistry, startWebServer } from '@deepseek-ai/dsh-host-webserver' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' +import { Context } from 'cordis' +import { DIST_INDEX, REPO_ROOT, requireDist } from './support.ts' + +/** Snapshot mode for the lane, from $DSH_SNAPSHOT (same vocabulary as the ACP/TUI suites). */ +export type WebSnapshotMode = 'replay' | 'record' | 'refresh' + +/** + * Resolve and validate the lane's snapshot mode. + * @returns the active mode; unset/empty selects replay. + */ +export function webSnapshotMode(): WebSnapshotMode { + const value = process.env.DSH_SNAPSHOT + if (value === undefined || value === '' || value === 'replay') return 'replay' + if (value === 'record' || value === 'refresh') return value + throw new Error(`DSH_SNAPSHOT must be replay, record, or refresh; got ${JSON.stringify(value)}`) +} + +// Replay must run in providers mode (never catch-all): with `llm: false` no +// adapter exists, so a catch-all would leave resolveModelContext unroutable +// and compact-basic's post-step pressure check would warn every step. The +// published contextWindow keeps that pressure path provably inert for small +// fixtures. +const PROVIDERS = [{ id: 'deepseek', name: 'DeepSeek', models: [{ id: 'deepseek-v4-flash', contextWindow: 128_000 }] }] + +// The shipped client roster (apps/cli/src/web.ts CLIENT_PACKAGES, sans the +// --dev HMR row). apps/web depends on every entry, so its URL anchors the +// Loader's bare-specifier resolution. +const CLIENT_PACKAGES = [ + '@deepseek-ai/dsh-client-connection', + '@deepseek-ai/dsh-client-runtime', + '@deepseek-ai/dsh-client-ui-theme', + '@deepseek-ai/dsh-client-i18n', + '@deepseek-ai/dsh-client-ui-layout', + '@deepseek-ai/dsh-client-ui-sidebar', + '@deepseek-ai/dsh-client-ui-conversation', + '@deepseek-ai/dsh-client-ui-question', + '@deepseek-ai/dsh-client-ui-trajectory', +] as const + +/** Repo-root .env → process.env for record mode (never overrides set vars); the smoke-real convention. */ +function loadRootEnv(): void { + const envPath = join(REPO_ROOT, '.env') + if (!existsSync(envPath)) return + for (const line of readFileSync(envPath, 'utf8').split('\n')) { + const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line.trim()) + if (m !== null && process.env[m[1]!] === undefined) process.env[m[1]!] = m[2] + } +} + +/** A booted web harness: real assembly, mode-selected model backend, temp world. */ +export interface WebHarness { + /** The active snapshot mode this harness booted under. */ + mode: WebSnapshotMode + /** Browser-facing origin (http://127.0.0.1:). */ + baseUrl: string + /** The running host (ctx is the documented in-process barrier seam). */ + host: RunningHost + /** Temp project directory sessions run in (bash/fs tool cwd). */ + workspaceCwd: string + /** Temp persistence root (seeded sessions land here through the real API). */ + persistenceRoot: string + /** Errors the web server reported asynchronously; assert empty at scenario end. */ + serverErrors: string[] + /** Await a settled turn end: in-process turn/end, then the agent's idle flip (which follows the persistence flush). */ + whenTurnSettled(timeoutMs?: number): Promise + /** Tear everything down; asserts the replay fixture was fully consumed first (replay/refresh). */ + close(): Promise +} + +/** Options for {@link launchWebHarness}. */ +export interface LaunchOptions { + /** + * Replay fixture (session.jsonl) served by dsh-llm-replay in replay/refresh + * modes; ignored in record mode (the real adapter answers). Omit for + * scenarios issuing no model calls — a stray stream then fails loud with + * NO_ADAPTER on the open seam. + */ + replayFixture?: string + /** Per-chunk replay pacing (ms) so the browser observes genuinely incremental SSE; replay/refresh only. */ + paceMs?: number +} + +/** + * Boot the real web assembly under the current snapshot mode. + * @param options - replay fixture selection and pacing. + * @returns the running harness. + */ +export async function launchWebHarness(options: LaunchOptions = {}): Promise { + requireDist() + const mode = webSnapshotMode() + if (mode === 'record') { + loadRootEnv() + if (process.env.DEEPSEEK_API_KEY === undefined || process.env.DEEPSEEK_API_KEY.length === 0) { + throw new Error('web e2e record mode needs DEEPSEEK_API_KEY (env or repo-root .env)') + } + } + const workspaceCwd = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-ws-')) + const persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-web-e2e-sessions-')) + const serverErrors: string[] = [] + let host: RunningHost | undefined + let server: Awaited> | undefined + let replay: ReplayHandle | undefined + try { + host = await startHost({ + boot: { + persistenceRoot, + // Keep the request header free of ambient AGENTS.md content so + // recorded fixtures do not embed this repo's instructions. + workspaceContext: false, + cwd: workspaceCwd, + // Replay/refresh boot keyless with the llm seam open; record mounts + // the real adapter and performs real provider I/O. + ...(mode === 'record' ? {} : { llm: false as const }), + }, + }) + if (mode !== 'record' && options.replayFixture !== undefined) { + replay = installLlmReplay(host.ctx, { + file: options.replayFixture, + providers: PROVIDERS, + ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }), + }) + } + // Anchor at apps/cli exactly as `dsh web` does: that package declares + // every roster entry as a dependency, so the Loader's bare-specifier + // resolution and the registry's package.json resolver both work. + const anchor = pathToFileURL(join(REPO_ROOT, 'apps/cli/src/web.ts')).href + const mounted = await mountWebPlugins(host.ctx, CLIENT_PACKAGES, anchor) + const webPlugins = createHostWebPluginRegistry({ + ctx: host.ctx, + loader: mounted.loader, + resolvePkgJson: mounted.resolvePkgJson, + onError: (err: Error) => { serverErrors.push(String(err)) }, + }) + server = await startWebServer( + { host: '127.0.0.1', port: 0, distIndex: DIST_INDEX, apiHandler: host.handler, webPlugins }, + (err: Error) => { serverErrors.push(String(err)) }, + ) + } catch (error) { + await server?.close().catch(() => undefined) + await host?.dispose().catch(() => undefined) + await rm(workspaceCwd, { recursive: true, force: true }).catch(() => undefined) + await rm(persistenceRoot, { recursive: true, force: true }).catch(() => undefined) + throw error + } + const runningHost = host + const runningServer = server + const replayHandle = replay + + return { + mode, + baseUrl: `http://127.0.0.1:${server.port}`, + host, + workspaceCwd, + persistenceRoot, + serverErrors, + // Barrier stack: the in-process turn/end identifies the session, then + // agent.whenIdle() covers the persistence flush (the idle flip follows + // the flush), and the caller's browser settled-poll comes last because + // host completion strictly precedes render. + whenTurnSettled(timeoutMs = mode === 'record' ? 180_000 : 30_000): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + off() + reject(new Error(`no turn/end within ${timeoutMs}ms`)) + }, timeoutMs) + const off = runningHost.ctx.on('session/event', (session: { id: SessionId }, event: SessionEvent) => { + if (event.type !== 'turn/end') return + clearTimeout(timer) + off() + const agent = runningHost.ctx.agents.get(session.id) + if (agent === undefined) { + reject(new Error(`turn/end for ${session.id} but no live agent`)) + return + } + agent.whenIdle().then(() => { resolve(session.id) }, reject) + }) + }) + }, + async close(): Promise { + const failures: unknown[] = [] + // Fixture-consumption check first, while the run's binding state is + // still authoritative — a scenario that drove fewer model calls than + // recorded fails here instead of drifting green. + try { + replayHandle?.assertConsumed() + } catch (error) { + failures.push(error) + } + await runningServer.close().catch((e: unknown) => failures.push(e)) + await runningHost.dispose().catch((e: unknown) => failures.push(e)) + await rm(workspaceCwd, { recursive: true, force: true }).catch((e: unknown) => failures.push(e)) + await rm(persistenceRoot, { recursive: true, force: true }).catch((e: unknown) => failures.push(e)) + if (failures.length > 0) throw new AggregateError(failures, 'web harness teardown failed') + }, + } +} + +/** + * Serialize a live session back to raw session-JSONL (header + events) — the + * in-memory record-mode harvest, so the on-disk zstd default never matters. + * Mirrors the TUI suite's rawSessionLog. + * @param session - the live session to serialize. + * @returns raw JSONL text ending in one newline. + */ +export function rawSessionLog(session: Session): string { + return [ + JSON.stringify({ type: 'session', ...session.header }), + ...session.events.map(event => JSON.stringify(event)), + '', + ].join('\n') +} + +/** + * Record-mode fixture write-back: harvest the live session, scrub request + * headers to {{system}}/{{tools}} (the web lane pins no header class — a + * deliberate deviation logged in the Agent Note's deferred work), tokenize + * the run-local session id and cwd ({{sessionId}}/{{cwd}}, the committed ACP + * fixture convention — re-records then diff only on real content), and write + * the committed fixture. + * @param harness - the record-mode harness. + * @param sessionId - the driven session. + * @param fixturePath - the committed session.jsonl / seed.jsonl target. + */ +export async function recordFixture(harness: WebHarness, sessionId: SessionId, fixturePath: string): Promise { + const agent = harness.host.ctx.agents.get(sessionId) + if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`) + const tokenized = scrubRequestHeaders(rawSessionLog(agent.session)) + .split(sessionId).join('{{sessionId}}') + .split(harness.workspaceCwd).join('{{cwd}}') + await writeFile(fixturePath, tokenized) +} + +/** + * The user prompts recorded in a fixture, in order — the single source tying + * spec drive steps to recorded reality so script and fixture cannot drift. + * @param fixtureText - raw session.jsonl contents. + * @returns the recorded user prompt texts. + */ +export function fixtureUserPrompts(fixtureText: string): string[] { + return parseSessionLog(fixtureText).flatMap((event) => { + if (event.type !== 'user/message' || event.data.source.kind !== 'user') return [] + const text = event.data.content.filter(block => block.type === 'text').map(block => block.text).join('') + return text.length > 0 ? [text] : [] + }) +} + +/** + * Seed a recorded session fixture into the harness's persistence root through + * the REAL backend API (throwaway Context + SessionStore + JSONL plugin — the + * semantic-checkpoint precedent), never raw file writes: no knowledge of + * bucket hashing, filename encoding, or compression, and malformed shapes + * fail loud at seed time. The fixture's recorded cwd is rewritten to the + * harness workspace so header/path identity and event payload paths agree. + * @param harness - the target harness. + * @param fixtureText - raw recorded session.jsonl contents. + * @param id - the seeded session id (stable for deterministic goldens). + * @returns the seeded id. + */ +export async function seedSession(harness: WebHarness, fixtureText: string, id: string): Promise { + // Committed fixtures tokenize run-local identity ({{sessionId}}/{{cwd}}, + // written by recordFixture); realize both for this world before parsing. + const realized = fixtureText + .split('{{sessionId}}').join(id) + .split('{{cwd}}').join(harness.workspaceCwd) + const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd + const rewritten = fixtureCwd === undefined + ? realized + : realized.split(fixtureCwd).join(harness.workspaceCwd) + const events = parseSessionLog(rewritten) + if (events.length === 0) throw new Error('seed fixture has no events') + const last = events[events.length - 1]! + // An open final turn would be mutated by resume's crash repair on first + // open; a committed seed must be a closed recording. + if (last.type !== 'turn/end') throw new Error(`seed fixture must end in turn/end, got ${last.type}`) + const meta: SessionHeader = { + version: SESSION_FORMAT_VERSION, + id: SessionId(id), + createdAt: Date.now() - 60_000, + cwd: harness.workspaceCwd, + delegationDepth: 0, + } + const ctx = new Context() + try { + await ctx.plugin(SessionStore) + // Same root as the host with the plugin's own default compression, so the + // host's directory-scan list() sees one consistent encoding. + await ctx.plugin(SessionPersistenceJsonl, { root: harness.persistenceRoot }) + await ctx.sessionPersistence.create(meta) + await ctx.sessionPersistence.append(meta.id, events) + // Deterministic sidebar order: cold summaries take updatedAt from mtime. + const located = ctx.sessionPersistence.locate(meta) + if (located !== undefined) { + const backdated = new Date(meta.createdAt) + await utimes(located.path, backdated, backdated) + } + } finally { + await ctx.fiber.dispose() + } + return meta.id +} + +/** + * Normalize an aria snapshot: uuid, cwd, workspace-basename, and duration + * volatility collapse to stable tokens. + * @param snapshot - raw ariaSnapshot text. + * @param workspaceCwd - the harness workspace (basename doubles as the header breadcrumb). + * @returns tokenized snapshot text. + */ +export function normalizeAria(snapshot: string, workspaceCwd: string): string { + // The header breadcrumb renders the workspace's basename, not the full + // path, so both spellings must collapse to the token. + const base = workspaceCwd.split('/').pop()! + return snapshot + .split(workspaceCwd).join('{{cwd}}') + .split(base).join('{{workspace}}') + .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '{{uuid}}') + .replace(/\b\d+(?:\.\d+)?(?:ms|s|秒)\b/g, '{{duration}}') +} + +/** + * Capture the region's aria snapshot at a settled milestone: poll until two + * consecutive normalized captures are equal — a single-shot capture races the + * last React commits. + * @param page - the page under test. + * @param selector - the region locator selector. + * @param workspaceCwd - normalization input. + * @returns the stable normalized snapshot. + */ +export async function captureStableAria(page: Page, selector: string, workspaceCwd: string): Promise { + const region = page.locator(selector).first() + let previous = normalizeAria(await region.ariaSnapshot(), workspaceCwd) + await expect.poll(async () => { + const current = normalizeAria(await region.ariaSnapshot(), workspaceCwd) + const stable = current === previous + previous = current + return stable + }, { timeout: 5_000, message: 'aria snapshot did not stabilize' }).toBe(true) + return previous +} + +/** + * Compare a normalized golden, or rewrite it under refresh. Refresh is the + * ONLY writer: a missing golden in replay mode fails with the healing command + * instead of silently self-bootstrapping. + * @param goldenPath - the committed ui.expected.md path. + * @param actual - the stable normalized snapshot. + * @param mode - the active snapshot mode. + */ +export async function compareOrRefreshGolden(goldenPath: string, actual: string, mode: WebSnapshotMode): Promise { + const payload = `${actual}\n` + if (mode === 'refresh') { + await writeFile(goldenPath, payload) + return + } + if (!existsSync(goldenPath)) { + throw new Error(`missing golden ${goldenPath} — run DSH_SNAPSHOT=refresh pnpm run test:web to generate it`) + } + expect(payload).toBe(await readFile(goldenPath, 'utf8')) +} + +/** + * Fixture-inventory guard (the TUI afterAll shape): the scenario directory + * holds exactly the expected files and every committed JSONL is a scrub + * fixed-point (no request-header bulk escaped the record write-back). + * @param dir - the scenario snapshot directory. + * @param expected - the exact expected file inventory. + */ +export async function assertFixtureInventory(dir: string, expected: string[]): Promise { + const entries = (await readdir(dir)).sort() + expect(entries).toEqual([...expected].sort()) + for (const entry of entries.filter(name => name.endsWith('.jsonl'))) { + const content = await readFile(join(dir, entry), 'utf8') + expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content) + } +} + +/** + * Console tripwires: reconnect/gap-repair self-healing or a pageerror must + * fail the scenario, not mask a dead wire behind eventual consistency. + * @param page - the page under test. + * @returns live warning/pageerror collectors to assert empty at scenario end. + */ +export function watchConsole(page: Page): { warnings: string[]; pageErrors: string[] } { + const warnings: string[] = [] + const pageErrors: string[] = [] + page.on('console', (message) => { + const text = message.text() + if (/connection lost|gap repair|discontinuous/i.test(text)) warnings.push(text) + }) + page.on('pageerror', (error) => { pageErrors.push(String(error)) }) + return { warnings, pageErrors } +} diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts new file mode 100644 index 0000000000..faf1a1f6a8 --- /dev/null +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -0,0 +1,109 @@ +// Web e2e scenario: fresh round trip. A real chromium types a prompt into the +// real composer; the wire, apiproxy, agent loop, and the REAL bash tool (echo +// in the temp workspace) all run; the model seam is dsh-llm-replay (keyless) +// or the live adapter (record). Drive steps run in every mode and wait only +// on generic completion (whenTurnSettled — never model-content selectors, so +// record cannot hang on a live model answering differently); assertion steps +// run in replay/refresh only. Settled states only — streaming incrementality +// is asserted from the persisted assistant/chunk events, not transient DOM. +// Record: DSH_SNAPSHOT=record rewrites session.jsonl, then a keyless +// DSH_SNAPSHOT=refresh regenerates ui.expected.md. +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + launchWebHarness, recordFixture, watchConsole, webSnapshotMode, type WebHarness, +} from './harness.ts' +import { saveFailureShot } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/fresh-round-trip', import.meta.url)) +const FIXTURE = fileURLToPath(new URL('./snapshots/fresh-round-trip/session.jsonl', import.meta.url)) +const UI_EXPECTED = fileURLToPath(new URL('./snapshots/fresh-round-trip/ui.expected.md', import.meta.url)) +const MODE = webSnapshotMode() + +// The scenario's one drive prompt. Record sends it; replay asserts the +// committed fixture recorded exactly it, so drive script and fixture cannot +// drift apart. +const PROMPT = 'Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop.' + +describe('web e2e: fresh round trip through the real assembly', () => { + let harness: WebHarness + let browser: Browser + let page: Page + let tripwire: ReturnType + const sessionEvents: SessionEvent[] = [] + + beforeAll(async () => { + harness = await launchWebHarness({ + ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }), + }) + harness.host.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) }) + browser = await chromium.launch() + page = await browser.newPage({ viewport: { width: 1680, height: 1000 } }) + tripwire = watchConsole(page) + await page.goto(harness.baseUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await harness?.close() + }) + + it('drives the recorded prompt to a settled turn (all modes)', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip')) + if (MODE !== 'record') { + // Drift guard: the committed fixture must carry exactly the drive prompt. + expect(fixtureUserPrompts(await readFile(FIXTURE, 'utf8'))).toEqual([PROMPT]) + } + const input = page.locator('textarea').first() + await input.waitFor({ timeout: 10_000 }) + // Arm the host-side settled barrier BEFORE the send click. + const settled = harness.whenTurnSettled() + await input.fill(PROMPT) + await input.press('Enter') + const sessionId = await settled + if (MODE === 'record') { + await recordFixture(harness, sessionId, FIXTURE) + } + }, 200_000) + + it.skipIf(MODE === 'record')('rendered the settled turn: markdown, tool row, composer restore', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-settled')) + // Browser settled-poll after host completion (host strictly precedes render). + await page.locator('[data-streaming="true"]').waitFor({ state: 'detached', timeout: 15_000 }).catch(() => { + // Chunks may coalesce into one commit; a never-mounted streaming node is + // legal — the chunk-event assertions below carry incrementality. + }) + await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) + // World state, not self-report: bash really ran and the turn closed clean. + const toolCalls = sessionEvents.filter(e => e.type === 'tool/call') + expect(toolCalls.map(e => (e as SessionEvent & { data: { name: string } }).data.name)).toContain('bash') + const turnEnds = sessionEvents.filter(e => e.type === 'turn/end') + expect(turnEnds.length).toBe(1) + expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed') + // The persisted chunk events are the authoritative incrementality proof. + expect(sessionEvents.filter(e => e.type === 'assistant/chunk').length).toBeGreaterThan(10) + }, 60_000) + + it.skipIf(MODE === 'record')('matches the conversation aria golden with stable anchors', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-aria')) + // Anchor assertions survive a semantics-preserving component rewrite even + // while the whole-region golden churns. + await expect(page.getByRole('textbox').first().isVisible()).resolves.toBe(true) + expect(await page.getByText('WEB_E2E_OK', { exact: false }).count()).toBeGreaterThanOrEqual(1) + const snapshot = await captureStableAria(page, '[class*="centerCol"]', harness.workspaceCwd) + await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) + }) + + it.skipIf(MODE === 'record')('stayed clean: no pageerrors, no reconnect self-healing, no server errors', async () => { + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + expect(harness.serverErrors).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'ui.expected.md']) + }) +}) diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts new file mode 100644 index 0000000000..734c0848c4 --- /dev/null +++ b/apps/web/tests/seeded-history.e2e.ts @@ -0,0 +1,105 @@ +// Web e2e scenario: seeded history. A recorded session seeded cold through +// the REAL persistence API renders purely from the log — the surface nothing +// else covers: sidebar cold listing, the implicit resume/attach inside the +// history RPC, history-page tool views, and the client fold of historical +// events — with ZERO model calls in replay (no replay fixture; a stray stream +// fails loud on the open llm seam). The seed is a recorded fixture under the +// same record discipline as every other: DSH_SNAPSHOT=record drives the turn +// live through the composer (real read tool against seeded workspace files) +// and harvests seed.jsonl; replay/refresh seed it cold and only render. +import { readFile, writeFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { join } from 'node:path' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + launchWebHarness, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebHarness, +} from './harness.ts' +import { saveFailureShot } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/seeded-history', import.meta.url)) +const SEED = fileURLToPath(new URL('./snapshots/seeded-history/seed.jsonl', import.meta.url)) +const UI_EXPECTED = fileURLToPath(new URL('./snapshots/seeded-history/ui.expected.md', import.meta.url)) +const MODE = webSnapshotMode() +const SEED_ID = 'seeded-history-web-e2e' + +const PROMPT = 'Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop.' + +describe('web e2e: seeded history renders through cold resume', () => { + let harness: WebHarness + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + harness = await launchWebHarness({}) + // The read-tool targets exist in both modes: record needs them for the + // live turn; replay's seeded log carries their recorded contents but the + // workspace stays consistent for any user poking the harness. + await writeFile(join(harness.workspaceCwd, 'a.txt'), 'alpha\n') + await writeFile(join(harness.workspaceCwd, 'b.txt'), 'beta\n') + if (MODE !== 'record') { + const raw = await readFile(SEED, 'utf8') + expect(fixtureUserPrompts(raw), 'seed fixture must carry exactly the drive prompt').toEqual([PROMPT]) + await seedSession(harness, raw, SEED_ID) + } + browser = await chromium.launch() + page = await browser.newPage({ viewport: { width: 1680, height: 1000 } }) + tripwire = watchConsole(page) + await page.goto(harness.baseUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await harness?.close() + }) + + it.skipIf(MODE !== 'record')('records the seed turn live through the composer', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-record')) + const input = page.locator('textarea').first() + await input.waitFor({ timeout: 10_000 }) + const settled = harness.whenTurnSettled() + await input.fill(PROMPT) + await input.press('Enter') + const sessionId = await settled + await recordFixture(harness, sessionId, SEED) + }, 200_000) + + it.skipIf(MODE === 'record')('lists the seeded session cold and renders its history from the log', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-history')) + // The sidebar tree collapses workspace groups by default: click the group + // row (treeitem 0) to expand, then the revealed session row. + const groupRow = page.locator('[role="treeitem"]').first() + await groupRow.waitFor({ timeout: 15_000 }) + await groupRow.click() + const sessionRow = page.locator('[role="treeitem"]').nth(1) + await sessionRow.waitFor({ timeout: 10_000 }) + await sessionRow.click() + // Settled barrier for history: the recorded final assistant text renders. + await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBe(1) + // Tool cards render from logged tool/call + tool/result alone (views are + // host-recomputed per page; the generic card is the documented default). + const toolRows = page.locator('[data-variant], [data-sample]') + await expect.poll(() => toolRows.count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(2) + expect(await page.getByText('a.txt', { exact: false }).count()).toBeGreaterThan(0) + }, 60_000) + + it.skipIf(MODE === 'record')('matches the historical conversation aria golden', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-aria')) + const snapshot = (await captureStableAria(page, '[class*="centerCol"]', harness.workspaceCwd)) + .split(SEED_ID).join('{{seededId}}') + await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) + }) + + it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => { + // No replay fixture was installed and the llm seam is open — any stray + // stream would have failed the turn loudly. Cleanliness pins the wire. + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + expect(harness.serverErrors).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, ['seed.jsonl', 'ui.expected.md']) + }) +}) diff --git a/apps/web/tests/snapshots/fresh-round-trip/session.jsonl b/apps/web/tests/snapshots/fresh-round-trip/session.jsonl new file mode 100644 index 0000000000..d9cc109c60 --- /dev/null +++ b/apps/web/tests/snapshots/fresh-round-trip/session.jsonl @@ -0,0 +1,97 @@ +{"type":"session","version":0,"id":"{{sessionId}}","createdAt":1784893539564,"cwd":"{{cwd}}"} +{"type":"turn/start","seq":0,"time":1784893539588,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user","rpcId":"4962b8d4-0422-4f81-8187-642e3e6bab78"}}}} +{"type":"user/message","seq":1,"time":1784893539589,"data":{"content":[{"type":"text","text":"Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"4962b8d4-0422-4f81-8187-642e3e6bab78"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1784893539592,"data":{"title":"Use the bash tool to","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1784893539657,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1784893539658,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}","messagePrefix":["{{messagePrefix}}"]},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":1784893540271,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":6,"time":1784893540271,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":7,"time":1784893540366,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":8,"time":1784893540396,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} +{"type":"assistant/chunk","seq":9,"time":1784893540396,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":10,"time":1784893540396,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":11,"time":1784893540396,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" run"}}} +{"type":"assistant/chunk","seq":12,"time":1784893540397,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} +{"type":"assistant/chunk","seq":13,"time":1784893540421,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" simple"}}} +{"type":"assistant/chunk","seq":14,"time":1784893540447,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" bash"}}} +{"type":"assistant/chunk","seq":15,"time":1784893540447,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} +{"type":"assistant/chunk","seq":16,"time":1784893540448,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":17,"time":1784893540448,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":18,"time":1784893540475,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":19,"time":1784893540476,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":20,"time":1784893540476,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"D"}}} +{"type":"assistant/chunk","seq":21,"time":1784893540476,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} +{"type":"assistant/chunk","seq":22,"time":1784893540476,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} +{"type":"assistant/chunk","seq":23,"time":1784893540565,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":24,"time":1784893540566,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":""}}} +{"type":"assistant/chunk","seq":25,"time":1784893540591,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"{"}}} +{"type":"assistant/chunk","seq":26,"time":1784893540592,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":27,"time":1784893540592,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"command"}}} +{"type":"assistant/chunk","seq":28,"time":1784893540592,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":29,"time":1784893540592,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":30,"time":1784893540621,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":31,"time":1784893540621,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"echo"}}} +{"type":"assistant/chunk","seq":32,"time":1784893540621,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":" WEB"}}} +{"type":"assistant/chunk","seq":33,"time":1784893540621,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"_E"}}} +{"type":"assistant/chunk","seq":34,"time":1784893540651,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"2"}}} +{"type":"assistant/chunk","seq":35,"time":1784893540651,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"E"}}} +{"type":"assistant/chunk","seq":36,"time":1784893540652,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"_OK"}}} +{"type":"assistant/chunk","seq":37,"time":1784893540652,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":38,"time":1784893540680,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":", "}}} +{"type":"assistant/chunk","seq":39,"time":1784893540680,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":40,"time":1784893540709,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"description"}}} +{"type":"assistant/chunk","seq":41,"time":1784893540710,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":42,"time":1784893540710,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":43,"time":1784893540710,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":44,"time":1784893540738,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"Print"}}} +{"type":"assistant/chunk","seq":45,"time":1784893540738,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":" WEB"}}} +{"type":"assistant/chunk","seq":46,"time":1784893540768,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"_E"}}} +{"type":"assistant/chunk","seq":47,"time":1784893540768,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"2"}}} +{"type":"assistant/chunk","seq":48,"time":1784893540768,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"E"}}} +{"type":"assistant/chunk","seq":49,"time":1784893540768,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"_OK"}}} +{"type":"assistant/chunk","seq":50,"time":1784893540769,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":" to"}}} +{"type":"assistant/chunk","seq":51,"time":1784893540797,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":" stdout"}}} +{"type":"assistant/chunk","seq":52,"time":1784893540801,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":53,"time":1784893540826,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","argumentsDelta":"}"}}} +{"type":"assistant/chunk","seq":54,"time":1784893540859,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to run a simple bash command and reply with \"DONE\"."}}}} +{"type":"assistant/chunk","seq":55,"time":1784893540859,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","arguments":"{\"command\": \"echo WEB_E2E_OK\", \"description\": \"Print WEB_E2E_OK to stdout\"}"}}}} +{"type":"assistant/chunk","seq":56,"time":1784893540859,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":7802,"outputTokens":88,"cacheReadTokens":0,"reasoningTokens":17}}}} +{"type":"assistant/chunk","seq":57,"time":1784893540860,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":58,"time":1784893540863,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to run a simple bash command and reply with \"DONE\"."},{"type":"tool-call","id":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","arguments":"{\"command\": \"echo WEB_E2E_OK\", \"description\": \"Print WEB_E2E_OK to stdout\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":7802,"outputTokens":88,"cacheReadTokens":0,"reasoningTokens":17}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57],"surfaceOp":"append"} +{"type":"tool/call","seq":59,"time":1784893540864,"data":{"turn":1,"step":1,"callId":"call_00_yxp0l3itFAMPCLKhz7EU1205","name":"bash","arguments":"{\"command\": \"echo WEB_E2E_OK\", \"description\": \"Print WEB_E2E_OK to stdout\"}"}} +{"type":"tool/result","seq":60,"time":1784893540878,"data":{"turn":1,"step":1,"callId":"call_00_yxp0l3itFAMPCLKhz7EU1205","content":[{"type":"text","text":"WEB_E2E_OK\n"}],"isError":false},"sourceEventSeqs":[59],"surfaceOp":"append"} +{"type":"step/end","seq":61,"time":1784893540881,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":62,"time":1784893540881,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":63,"time":1784893541457,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":64,"time":1784893541457,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":65,"time":1784893541545,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" command"}}} +{"type":"assistant/chunk","seq":66,"time":1784893541574,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" executed"}}} +{"type":"assistant/chunk","seq":67,"time":1784893541574,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" successfully"}}} +{"type":"assistant/chunk","seq":68,"time":1784893541574,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":69,"time":1784893541574,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" printed"}}} +{"type":"assistant/chunk","seq":70,"time":1784893541603,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":71,"time":1784893541604,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"WEB"}}} +{"type":"assistant/chunk","seq":72,"time":1784893541604,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"_E"}}} +{"type":"assistant/chunk","seq":73,"time":1784893541604,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"2"}}} +{"type":"assistant/chunk","seq":74,"time":1784893541604,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"E"}}} +{"type":"assistant/chunk","seq":75,"time":1784893541604,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"_OK"}}} +{"type":"assistant/chunk","seq":76,"time":1784893541633,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} +{"type":"assistant/chunk","seq":77,"time":1784893541633,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} +{"type":"assistant/chunk","seq":78,"time":1784893541675,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" should"}}} +{"type":"assistant/chunk","seq":79,"time":1784893541676,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" now"}}} +{"type":"assistant/chunk","seq":80,"time":1784893541676,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":81,"time":1784893541676,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":82,"time":1784893541694,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":83,"time":1784893541694,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"D"}}} +{"type":"assistant/chunk","seq":84,"time":1784893541694,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} +{"type":"assistant/chunk","seq":85,"time":1784893541695,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} +{"type":"assistant/chunk","seq":86,"time":1784893541718,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":87,"time":1784893541718,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} +{"type":"assistant/chunk","seq":88,"time":1784893541718,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} +{"type":"assistant/chunk","seq":89,"time":1784893541719,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The command executed successfully and printed \"WEB_E2E_OK\". I should now reply with \"DONE\"."}}}} +{"type":"assistant/chunk","seq":90,"time":1784893541719,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":91,"time":1784893541719,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":228,"outputTokens":25,"cacheReadTokens":7680,"reasoningTokens":22}}}} +{"type":"assistant/chunk","seq":92,"time":1784893541719,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":93,"time":1784893541720,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"The command executed successfully and printed \"WEB_E2E_OK\". I should now reply with \"DONE\"."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":228,"outputTokens":25,"cacheReadTokens":7680,"reasoningTokens":22}},"sourceEventSeqs":[63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92],"surfaceOp":"append"} +{"type":"step/end","seq":94,"time":1784893541720,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":95,"time":1784893541721,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md new file mode 100644 index 0000000000..4464843ce6 --- /dev/null +++ b/apps/web/tests/snapshots/fresh-round-trip/ui.expected.md @@ -0,0 +1,31 @@ +- banner: + - navigation "会话层级": + - button "Use the bash tool to" [disabled] + - text: · 1 turns + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" + - tab "Waterfall" +- text: "Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop." +- button "Think The user wants me to run a simple bash command and reply with \"DONE\".": + - img + - text: Think The user wants me to run a simple bash command and reply with "DONE". +- text: Print WEB_E2E_OK to stdout +- button "Think The command executed successfully and printed \"WEB_E2E_OK\". I should now reply with \"DONE\".": + - img + - text: Think The command executed successfully and printed "WEB_E2E_OK". I should now reply with "DONE". +- paragraph: DONE +- text: cache hit 49% · 15,823 tokens · 1 turns · 2 steps +- textbox "输入消息,Enter 发送,Shift+Enter 换行" +- button "添加": + - img +- combobox "Plan mode": + - option "Plan" [selected] + - option "Agent" +- combobox "Access mode": + - option "Read-only" [selected] + - option "Read-write" +- combobox "Model": + - option "DeepSeek-V4-Pro High" [selected] + - option "DeepSeek-V4-Pro" +- button "发送" [disabled] diff --git a/apps/web/tests/snapshots/seeded-history/seed.jsonl b/apps/web/tests/snapshots/seeded-history/seed.jsonl new file mode 100644 index 0000000000..a27f182e32 --- /dev/null +++ b/apps/web/tests/snapshots/seeded-history/seed.jsonl @@ -0,0 +1,112 @@ +{"type":"session","version":0,"id":"{{sessionId}}","createdAt":1784893580342,"cwd":"{{cwd}}"} +{"type":"turn/start","seq":0,"time":1784893580362,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user","rpcId":"ab867856-cd1a-4270-8cee-c240076c58e9"}}}} +{"type":"user/message","seq":1,"time":1784893580363,"data":{"content":[{"type":"text","text":"Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"ab867856-cd1a-4270-8cee-c240076c58e9"}},"surfaceOp":"append"} +{"type":"session/title","seq":2,"time":1784893580365,"data":{"title":"Use the read tool twice","messageSeqs":[1],"source":{"kind":"fallback"}}} +{"type":"step/start","seq":3,"time":1784893580420,"data":{"turn":1,"step":1}} +{"type":"request/header","seq":4,"time":1784893580421,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}","messagePrefix":["{{messagePrefix}}"]},"reason":"initial"}} +{"type":"assistant/chunk","seq":5,"time":1784893581003,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":6,"time":1784893581003,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"The"}}} +{"type":"assistant/chunk","seq":7,"time":1784893581092,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" user"}}} +{"type":"assistant/chunk","seq":8,"time":1784893581107,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" wants"}}} +{"type":"assistant/chunk","seq":9,"time":1784893581108,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":10,"time":1784893581108,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":11,"time":1784893581108,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} +{"type":"assistant/chunk","seq":12,"time":1784893581135,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} +{"type":"assistant/chunk","seq":13,"time":1784893581135,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} +{"type":"assistant/chunk","seq":14,"time":1784893581136,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":15,"time":1784893581161,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" b"}}} +{"type":"assistant/chunk","seq":16,"time":1784893581162,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} +{"type":"assistant/chunk","seq":17,"time":1784893581162,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":","}}} +{"type":"assistant/chunk","seq":18,"time":1784893581189,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" then"}}} +{"type":"assistant/chunk","seq":19,"time":1784893581190,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":20,"time":1784893581190,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":21,"time":1784893581190,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" D"}}} +{"type":"assistant/chunk","seq":22,"time":1784893581217,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} +{"type":"assistant/chunk","seq":23,"time":1784893581217,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":24,"time":1784893581217,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" Let"}}} +{"type":"assistant/chunk","seq":25,"time":1784893581217,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" me"}}} +{"type":"assistant/chunk","seq":26,"time":1784893581217,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} +{"type":"assistant/chunk","seq":27,"time":1784893581258,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" both"}}} +{"type":"assistant/chunk","seq":28,"time":1784893581259,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":" files"}}} +{"type":"assistant/chunk","seq":29,"time":1784893581259,"data":{"turn":1,"step":1,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":30,"time":1784893581324,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":31,"time":1784893581325,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":""}}} +{"type":"assistant/chunk","seq":32,"time":1784893581325,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"{"}}} +{"type":"assistant/chunk","seq":33,"time":1784893581325,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":34,"time":1784893581351,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"file"}}} +{"type":"assistant/chunk","seq":35,"time":1784893581351,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"_path"}}} +{"type":"assistant/chunk","seq":36,"time":1784893581351,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":37,"time":1784893581351,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":38,"time":1784893581378,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":39,"time":1784893581378,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"a"}}} +{"type":"assistant/chunk","seq":40,"time":1784893581378,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":41,"time":1784893581378,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":42,"time":1784893581404,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":1,"id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","argumentsDelta":"}"}}} +{"type":"assistant/chunk","seq":43,"time":1784893581462,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}}} +{"type":"assistant/chunk","seq":44,"time":1784893581462,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":""}}} +{"type":"assistant/chunk","seq":45,"time":1784893581486,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"{"}}} +{"type":"assistant/chunk","seq":46,"time":1784893581486,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":47,"time":1784893581486,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"file"}}} +{"type":"assistant/chunk","seq":48,"time":1784893581486,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"_path"}}} +{"type":"assistant/chunk","seq":49,"time":1784893581486,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":50,"time":1784893581486,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":": "}}} +{"type":"assistant/chunk","seq":51,"time":1784893581513,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":52,"time":1784893581513,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"b"}}} +{"type":"assistant/chunk","seq":53,"time":1784893581514,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":".txt"}}} +{"type":"assistant/chunk","seq":54,"time":1784893581514,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"\""}}} +{"type":"assistant/chunk","seq":55,"time":1784893581539,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":2,"id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","argumentsDelta":"}"}}} +{"type":"assistant/chunk","seq":56,"time":1784893581597,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to read a.txt and b.txt, then reply with DONE. Let me read both files."}}}} +{"type":"assistant/chunk","seq":57,"time":1784893581597,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","arguments":"{\"file_path\": \"a.txt\"}"}}}} +{"type":"assistant/chunk","seq":58,"time":1784893581597,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","arguments":"{\"file_path\": \"b.txt\"}"}}}} +{"type":"assistant/chunk","seq":59,"time":1784893581597,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":124,"outputTokens":100,"cacheReadTokens":7680,"reasoningTokens":24}}}} +{"type":"assistant/chunk","seq":60,"time":1784893581597,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} +{"type":"assistant/message","seq":61,"time":1784893581601,"data":{"turn":1,"step":1,"content":[{"type":"reasoning","text":"The user wants me to read a.txt and b.txt, then reply with DONE. Let me read both files."},{"type":"tool-call","id":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","arguments":"{\"file_path\": \"a.txt\"}"},{"type":"tool-call","id":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","arguments":"{\"file_path\": \"b.txt\"}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":124,"outputTokens":100,"cacheReadTokens":7680,"reasoningTokens":24}},"sourceEventSeqs":[5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60],"surfaceOp":"append"} +{"type":"tool/call","seq":62,"time":1784893581602,"data":{"turn":1,"step":1,"callId":"call_00_8bQPkq98ZAzRTEJA6XM38538","name":"read","arguments":"{\"file_path\": \"a.txt\"}"}} +{"type":"tool/call","seq":63,"time":1784893581604,"data":{"turn":1,"step":1,"callId":"call_01_5FMIBJA9HHyktFY8KSlk9459","name":"read","arguments":"{\"file_path\": \"b.txt\"}"}} +{"type":"tool/result","seq":64,"time":1784893581608,"data":{"turn":1,"step":1,"callId":"call_00_8bQPkq98ZAzRTEJA6XM38538","content":[{"type":"text","text":"{{cwd}}/a.txt\nfile\n\n1: alpha\n\n(End of file - total 1 lines)\n"}],"isError":false},"sourceEventSeqs":[62],"surfaceOp":"append"} +{"type":"tool/result","seq":65,"time":1784893581609,"data":{"turn":1,"step":1,"callId":"call_01_5FMIBJA9HHyktFY8KSlk9459","content":[{"type":"text","text":"{{cwd}}/b.txt\nfile\n\n1: beta\n\n(End of file - total 1 lines)\n"}],"isError":false},"sourceEventSeqs":[63],"surfaceOp":"append"} +{"type":"step/end","seq":66,"time":1784893581611,"data":{"turn":1,"step":1}} +{"type":"step/start","seq":67,"time":1784893581611,"data":{"turn":1,"step":2}} +{"type":"assistant/chunk","seq":68,"time":1784893582137,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}}} +{"type":"assistant/chunk","seq":69,"time":1784893582137,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"Both"}}} +{"type":"assistant/chunk","seq":70,"time":1784893582257,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" files"}}} +{"type":"assistant/chunk","seq":71,"time":1784893582259,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" have"}}} +{"type":"assistant/chunk","seq":72,"time":1784893582260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" been"}}} +{"type":"assistant/chunk","seq":73,"time":1784893582260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" read"}}} +{"type":"assistant/chunk","seq":74,"time":1784893582260,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":75,"time":1784893582277,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" a"}}} +{"type":"assistant/chunk","seq":76,"time":1784893582303,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} +{"type":"assistant/chunk","seq":77,"time":1784893582303,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" contains"}}} +{"type":"assistant/chunk","seq":78,"time":1784893582304,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":79,"time":1784893582304,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"alpha"}}} +{"type":"assistant/chunk","seq":80,"time":1784893582304,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\""}}} +{"type":"assistant/chunk","seq":81,"time":1784893582330,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" and"}}} +{"type":"assistant/chunk","seq":82,"time":1784893582330,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" b"}}} +{"type":"assistant/chunk","seq":83,"time":1784893582330,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":".txt"}}} +{"type":"assistant/chunk","seq":84,"time":1784893582330,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" contains"}}} +{"type":"assistant/chunk","seq":85,"time":1784893582331,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" \""}}} +{"type":"assistant/chunk","seq":86,"time":1784893582331,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"beta"}}} +{"type":"assistant/chunk","seq":87,"time":1784893582356,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"\"."}}} +{"type":"assistant/chunk","seq":88,"time":1784893582357,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" Now"}}} +{"type":"assistant/chunk","seq":89,"time":1784893582384,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" I"}}} +{"type":"assistant/chunk","seq":90,"time":1784893582384,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" just"}}} +{"type":"assistant/chunk","seq":91,"time":1784893582384,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" need"}}} +{"type":"assistant/chunk","seq":92,"time":1784893582384,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" to"}}} +{"type":"assistant/chunk","seq":93,"time":1784893582385,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" reply"}}} +{"type":"assistant/chunk","seq":94,"time":1784893582411,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" with"}}} +{"type":"assistant/chunk","seq":95,"time":1784893582411,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" the"}}} +{"type":"assistant/chunk","seq":96,"time":1784893582438,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" single"}}} +{"type":"assistant/chunk","seq":97,"time":1784893582438,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" word"}}} +{"type":"assistant/chunk","seq":98,"time":1784893582438,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":" D"}}} +{"type":"assistant/chunk","seq":99,"time":1784893582438,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"ONE"}}} +{"type":"assistant/chunk","seq":100,"time":1784893582438,"data":{"turn":1,"step":2,"chunk":{"type":"reasoning-delta","index":0,"text":"."}}} +{"type":"assistant/chunk","seq":101,"time":1784893582467,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":1,"blockType":"text"}}} +{"type":"assistant/chunk","seq":102,"time":1784893582468,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"D"}}} +{"type":"assistant/chunk","seq":103,"time":1784893582468,"data":{"turn":1,"step":2,"chunk":{"type":"text-delta","index":1,"text":"ONE"}}} +{"type":"assistant/chunk","seq":104,"time":1784893582468,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". Now I just need to reply with the single word DONE."}}}} +{"type":"assistant/chunk","seq":105,"time":1784893582468,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}}} +{"type":"assistant/chunk","seq":106,"time":1784893582468,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":340,"outputTokens":35,"cacheReadTokens":7680,"reasoningTokens":32}}}} +{"type":"assistant/chunk","seq":107,"time":1784893582468,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"stop"}}}} +{"type":"assistant/message","seq":108,"time":1784893582469,"data":{"turn":1,"step":2,"content":[{"type":"reasoning","text":"Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". Now I just need to reply with the single word DONE."},{"type":"text","text":"DONE"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":340,"outputTokens":35,"cacheReadTokens":7680,"reasoningTokens":32}},"sourceEventSeqs":[68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107],"surfaceOp":"append"} +{"type":"step/end","seq":109,"time":1784893582470,"data":{"turn":1,"step":2}} +{"type":"turn/end","seq":110,"time":1784893582470,"data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/apps/web/tests/snapshots/seeded-history/ui.expected.md b/apps/web/tests/snapshots/seeded-history/ui.expected.md new file mode 100644 index 0000000000..07f5b15b2d --- /dev/null +++ b/apps/web/tests/snapshots/seeded-history/ui.expected.md @@ -0,0 +1,36 @@ +- banner: + - navigation "会话层级": + - button "Use the read tool twice" [disabled] + - text: · 1 turns + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" + - tab "Waterfall" +- text: "Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop." +- button "Think The user wants me to read a.txt and b.txt, then reply with DONE. Let me read both files.": + - img + - text: Think The user wants me to read a.txt and b.txt, then reply with DONE. Let me read both files. +- button: + - img +- text: Read a.txt +- button: + - img +- text: Read b.txt +- button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". Now I just need to reply with the single word DONE.": + - img + - text: Think Both files have been read. a.txt contains "alpha" and b.txt contains "beta". Now I just need to reply with the single word DONE. +- paragraph: DONE +- text: cache hit 97% · 15,959 tokens · 1 turns · 2 steps +- textbox "输入消息,Enter 发送,Shift+Enter 换行" +- button "添加": + - img +- combobox "Plan mode": + - option "Plan" [selected] + - option "Agent" +- combobox "Access mode": + - option "Read-only" [selected] + - option "Read-write" +- combobox "Model": + - option "DeepSeek-V4-Pro High" [selected] + - option "DeepSeek-V4-Pro" +- button "发送" [disabled] diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 998996304e..514cbe4d57 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -17,6 +17,15 @@ "src", "tests" ], + // The web e2e lane (harness + replay specs) boots the host spine and reads + // its Context merges — host-plane programs, checked in tsconfig.host.json; + // this client-registered project must not also hold them (one program + // cannot see both sides of the cordis Context merges). + "exclude": [ + "tests/harness.ts", + "tests/replay-round-trip.e2e.ts", + "tests/seeded-history.e2e.ts" + ], "references": [ { "path": "../../packages/client/web" diff --git a/tsconfig.host.json b/tsconfig.host.json index a13bcf35e3..a5f48ed22d 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -8,6 +8,10 @@ "rewriteRelativeImportExtensions": false }, "include": [ + "apps/web/tests/harness.ts", + "apps/web/tests/support.ts", + "apps/web/tests/replay-round-trip.e2e.ts", + "apps/web/tests/seeded-history.e2e.ts", "examples/*/src/**/*.ts", "examples/*/start.ts", "examples/*/tests/**/*.ts", From 4e295221f352b4ca507e813a2c410269d5a6e29a Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 19:52:47 +0800 Subject: [PATCH 021/113] refactor(persistence): group sessions in project directories --- ...7-24-project-session-directories.i18n.yaml | 6 + .../2026-07-24-project-session-directories.md | 48 +++++++ ...26-07-24-project-session-directories.zh.md | 48 +++++++ docs/core-data-structures/persistence.md | 2 +- .../session-persistence-jsonl/README.md | 17 ++- .../session-persistence-jsonl/src/format.ts | 67 ++++++++-- .../session-persistence-jsonl/src/index.ts | 90 ++++++++----- .../tests/jsonl.spec.ts | 122 +++++++++++++----- .../tests/zstd.spec.ts | 29 +++-- packages/support/acp-snapshot/src/harness.ts | 42 +++--- .../tests/fixtures/fake-acp-agent.ts | 6 +- .../record-suite/rec-child/behavior.json | 4 +- .../record-suite/rec-pin/behavior.json | 2 +- .../suite/authored-error/behavior.json | 2 +- .../fixtures/suite/blocked-log/behavior.json | 2 +- .../fixtures/suite/pin-turn/behavior.json | 2 +- .../fixtures/suite/plain-turn/behavior.json | 4 +- .../acp-snapshot/tests/harness.spec.ts | 16 +-- 18 files changed, 366 insertions(+), 143 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-24-project-session-directories.md create mode 100644 .agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml new file mode 100644 index 0000000000..f6cd03ddfd --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.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 +2026-07-24-project-session-directories.md: f65045419d5c749525ebdefcd1875dfc8ea69182 +2026-07-24-project-session-directories.zh.md: 1b4320d925c85b9b42a6c3ec9ee4ec52f4600786 diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md new file mode 100644 index 0000000000..f65045419d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md @@ -0,0 +1,48 @@ +# Agent Note: Project-grouped session directories + +Status: implemented + +English | [中文](2026-07-24-project-session-directories.zh.md) + +## Problem + +A persistence root may be local to one project, shared by several projects, temporary, or centralized. The hashed cwd buckets kept all deployments functional but made a shared root difficult to navigate because a developer could not recognize a project from its directory name. + +Each JSONL session also occupied one file directly inside the project bucket. That shape had no ownership directory for additional session artifacts such as metadata, attachments, spill files, or coordination state. + +## Decision + +The JSONL backend stores sessions under a readable project key and gives every session its own directory: + +```text +/ + ----/ + / + session.jsonl.zstd +``` + +Raw mode uses `session.jsonl`, and sessions without a cwd use `_no-cwd`. Filesystem and drive separators become `-`, unsafe code units use `~XXXX`, and the readable prefix is bounded to keep the component within filesystem limits. A short SHA-256 suffix distinguishes project paths whose readable forms collide or truncate alike. + +The configured root remains a deployment choice. The layout neither selects a global root nor requires projects to share one. When a deployment does centralize storage, project paths remain recognizable; a project-local root uses the same deterministic structure. + +The encoded session id names an ownership directory rather than the transcript itself. `SessionPersistence.locate()` continues to return the fixed transcript path, preserving hook `transcript_path` and `DSH_SESSION_JSONL` semantics. Discovery ignores other entries inside the session directory so the backend can add session-owned artifacts without another layout change. + +Lazy materialization remains tied to the transcript: `create()` performs no filesystem I/O, and the first append creates the project/session directories before collision-safe transcript publication. Empty directories are not listed as sessions. The backend rejects flat `/.jsonl*` artifacts with an explicit layout error; the pre-release format provides no automatic data migration. + +## Alternatives considered + +**Keep opaque cwd hashes.** This preserved short names but defeated the requested navigation by project path when several projects share a persistence root. + +**Put session files directly in each project directory.** This matched Claude Code and pi's basic file organization but left no session-level ownership boundary for future artifacts. + +**Replace separators without a collision suffix.** This is readable but lossy: paths containing literal `-` can collide with paths where `-` represents a separator. Retaining a short hash suffix preserves readable navigation without merging distinct projects. + +**Mandate a centralized root.** Rejected because storage placement belongs to deployment configuration. Project grouping is useful when roots are shared and harmless when they are not. + +**Load both flat and directory layouts.** Rejected under the pre-release no-compatibility stance. One accepted layout keeps identity checks and discovery deterministic. + +## Consequences + +Shared stores can be navigated by recognizable project names, while local and custom roots keep their existing configuration freedom. Every session has a directory available for future backend-owned artifacts, and existing transcript consumers still receive a file path. + +Project directory names are longer than the former 12-hex cwd hashes. Very long paths show only a bounded prefix plus their distinguishing hash, and moving a project still selects a different directory because the absolute cwd remains part of storage identity. diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md new file mode 100644 index 0000000000..1b4320d925 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md @@ -0,0 +1,48 @@ +# Agent Note: 按项目分组的会话目录 + +Status: implemented + +[English](2026-07-24-project-session-directories.md) | 中文 + +## 问题 + +持久化根目录可以只供一个项目使用,也可以由多个项目共享,还可以是临时目录或集中式目录。对 cwd 进行哈希得到的分桶目录能适用于所有这些部署方式,但开发者无法从目录名辨认项目,因此共享根目录难以浏览。 + +每个 JSONL 会话也直接以单个文件的形式放在项目分桶目录中。这种布局没有为元数据、附件、溢写文件或协调状态等其他会话产物提供归属目录。 + +## 决策 + +JSONL 后端按可读的项目键存储会话,并为每个会话提供独立目录: + +```text +/ + ----/ + / + session.jsonl.zstd +``` + +原始模式使用 `session.jsonl`,没有 cwd 的会话使用 `_no-cwd`。文件系统路径分隔符和驱动器分隔符会转换为 `-`,不安全的代码单元使用 `~XXXX`,可读前缀则限制长度,以确保目录项不超过文件系统限制。短 SHA-256 后缀用于区分可读形式发生冲突或被截断成相同形式的项目路径。 + +根目录由部署配置决定。这种布局既不选择全局根目录,也不要求项目共享根目录。部署选择集中存储时,目录名仍能让项目路径易于辨认;使用项目本地根目录时,也采用同样的确定性结构。 + +编码后的会话 id 用于命名归属目录,而不是 transcript(文本记录)文件本身。`SessionPersistence.locate()` 仍返回固定的 transcript 路径,从而保持钩子 `transcript_path` 和 `DSH_SESSION_JSONL` 的语义不变。发现过程会忽略会话目录中的其他条目,因此后端以后添加会话自有产物时无需再次改变布局。 + +延迟物化仍以 transcript 为界:`create()` 不执行文件系统 I/O,首次追加会先创建项目目录和会话目录,再以无冲突方式发布 transcript。空目录不会被列为会话。后端会显式报告布局错误并拒绝扁平的 `/.jsonl*` 产物;预发布格式不提供自动数据迁移。 + +## 考虑过的替代方案 + +**保留不透明的 cwd 哈希。** 这可以保持目录名简短,但当多个项目共享一个持久化根目录时,无法满足按项目路径浏览的需求。 + +**把会话文件直接放入各项目目录。** 这与 Claude Code 和 pi 的基本文件组织一致,但没有为未来产物提供会话级归属边界。 + +**替换分隔符但不添加冲突后缀。** 这种方式可读但有损:路径中的字面 `-` 可能与用 `-` 表示分隔符的路径发生冲突。保留短哈希后缀,既能让不同项目保持区分,又不会牺牲可读的浏览体验。 + +**强制使用集中式根目录。** 不予采纳,因为存储位置属于部署配置。项目分组在根目录共享时有用,在不共享时也没有负面影响。 + +**同时加载扁平布局和目录布局。** 按照预发布阶段不提供兼容性的原则,不予采纳。只接受一种布局,可以让身份检查和发现过程保持确定性。 + +## 后果 + +共享存储可以通过易于辨认的项目名进行浏览,本地根目录和自定义根目录则继续保有现有的配置自由。每个会话都有一个可供后端未来存放自有产物的目录,而现有 transcript 消费方仍会收到文件路径。 + +项目目录名比原先由 12 个十六进制字符组成的 cwd 哈希更长。路径很长时,目录名只显示长度受限的前缀和用于区分的哈希;移动项目仍会选择不同的目录,因为绝对 cwd 仍是存储身份的一部分。 diff --git a/docs/core-data-structures/persistence.md b/docs/core-data-structures/persistence.md index f45eb0417a..12cfc31125 100644 --- a/docs/core-data-structures/persistence.md +++ b/docs/core-data-structures/persistence.md @@ -18,7 +18,7 @@ Repair applies only to cold sessions. For a live id, `SessionPersistence.load(id ## `SessionLocation` — optional per-session artifact target -`SessionPersistence.locate(meta)` synchronously resolves a backend-owned independent artifact without reading, creating, or flushing it. JSONL returns its absolute target path; SQLite returns `undefined` because sessions share one database. A returned path can therefore name a file that does not yet exist or lacks the current unflushed turn; it is a location hint, not authorization or a freshness guarantee. +`SessionPersistence.locate(meta)` synchronously resolves a backend-owned independent artifact without reading, creating, or flushing it. JSONL returns the absolute transcript path inside its project/session directory; SQLite returns `undefined` because sessions share one database. A returned path can therefore name a file that does not yet exist or lacks the current unflushed turn; it is a location hint, not authorization or a freshness guarantee. ```ts type-equiv /** diff --git a/packages/session-persistence/session-persistence-jsonl/README.md b/packages/session-persistence/session-persistence-jsonl/README.md index bf86bf8633..8bd704f1e2 100644 --- a/packages/session-persistence/session-persistence-jsonl/README.md +++ b/packages/session-persistence/session-persistence-jsonl/README.md @@ -6,14 +6,16 @@ The JSONL durable session-persistence backend — a concrete `SessionPersistence ``` / - cwd-/ # per-project bucket (or _no-cwd/ when no cwd) - .jsonl.zstd # default: checksummed header frame + append frames - .jsonl # only with compression: 'none' + ----/ # readable project directory (or _no-cwd/) + / # session-owned directory + session.jsonl.zstd # default: checksummed header frame + append frames + session.jsonl # only with compression: 'none' ``` - The first logical line is the immutable `SessionHeader` tagged `{ type: 'session', version, id, cwd?, createdAt, parentSession?, seedLength?, delegationDepth }`. `delegationDepth` is required on disk and is `0` for a top-level session; a missing or invalid value rejects the log. Every subsequent logical line is one storage record; `assistant/chunk` events are never dropped, and `seq` stays contiguous across the decoded log (`events[i].seq === i`). - A storage record is a `SessionEvent` JSON verbatim, or — written only under `packChunks` — a **packed chunk row** (`text-chunks` / `reasoning-chunks` / `tool-call-chunks`; bare slash-less tags like the header's `session`, so row tags cannot be confused with event types): one line holding a run of ≥3 consecutive same-block `assistant/chunk` delta events, `seq0`/`time0` plus per-member `dt` gaps reconstructing every member's `seq`/`time` exactly. The lossless codec lives in `@deepseek-ai/dsh-session` (`packChunkRuns`/`decodeStorageRecord`) and whitelists exact shapes — anything unrecognized stores verbatim. Reading is layout-blind: `load` always decodes rows, so packed, unpacked, and mixed files load identically. -- Session ids are unvalidated branded strings, so they are injectively escaped to a single safe path segment before use (no traversal, no collision). +- The project directory keeps the normalized cwd readable for navigation and adds a short SHA-256 suffix so paths that normalize alike remain distinct. Its readable prefix is bounded for filesystem component limits. The configured root remains deployment-controlled: it may be project-local, shared, temporary, or centralized. +- Session ids are unvalidated branded strings, so they are injectively escaped to a single safe path segment before use (no traversal, no collision). The resulting directory is reserved for additional session-owned artifacts; discovery reads only the fixed transcript filename. ## Config @@ -23,17 +25,17 @@ The JSONL durable session-persistence backend — a concrete `SessionPersistence | `packChunks` | `boolean` (default `false`) | Write delta-chunk runs as packed rows (~60% smaller logical logs measured on a real coding session). Off, the written logical layout is byte-identical to the pre-packing format; reading packed rows works regardless of this switch. Off by default while the snapshot goldens stay one-event-per-line — recording with packing on rewrites every fixture `session.jsonl`. | | `compression` | `'zstd' \| 'none'` | Defaults to `'zstd'`; `'none'` retains newline-delimited UTF-8 text. | -`locate(meta)` returns `{ kind: 'jsonl', path }` using the resolved absolute root and the same cwd-bucket/id encoding as materialization. It performs no filesystem I/O: the target can be returned before the file exists, and an existing file contains only the last flushed prefix. +`locate(meta)` returns `{ kind: 'jsonl', path }` for the fixed transcript inside the resolved project/session directories. It performs no filesystem I/O: the target can be returned before the directory or file exists, and an existing file contains only the last flushed prefix. ## Physical encoding The default artifact is a standard concatenation of independent [Zstandard frames](../../../.agents/notes/implemented/architecture/2026-07-19-zstandard-jsonl-session-logs.md): one checksummed frame containing only the header line, followed by one checksummed frame per durable append batch. The backend uses Node's built-in Zstandard API with its default compression level and exposes no level knob. Listing reads and validates only the header frame. `compression: 'none'` keeps the same logical lines in the original raw representation. -A root belongs to one encoding. Startup discovery and targeted lookup reject the opposite suffix with an error naming the incompatible artifact and instructing the caller to select the matching mode or a separate root. There is no migration, mixed-root fallback, or dual write. +A root belongs to one encoding. Startup discovery and targeted lookup reject the opposite suffix with an error naming the incompatible artifact and instructing the caller to select the matching mode or a separate root. Flat `/.jsonl*` artifacts are also rejected instead of ignored. There is no migration, mixed-root fallback, or dual write. ## Durability and crash semantics -- **Bound storage identity.** Lookup requires one matching encoded filename across the cwd buckets, then verifies that the header id equals the requested id and that the header's id/cwd derive the selected path. Listing applies the same path check and rejects duplicate ids. Identity failures occur before repair or append. +- **Bound storage identity.** Lookup requires one matching session directory across the readable project directories, then verifies that the header id equals the requested id and that the header's id/cwd derive the selected transcript path. Listing applies the same path check and rejects duplicate ids. Identity failures occur before repair or append. - **Lazy materialization.** `create(meta)` writes nothing; on the first `append`, the backend writes and `fsync`s the encoded header and first batch in a temporary file. POSIX publishes it without overwrite via a hard link and `fsync`s the parent directory. Windows publishes it without overwrite via `MoveFileExW(..., MOVEFILE_WRITE_THROUGH)` and creates missing directories through the same write-through pattern. A created-but-never-appended session leaves nothing on disk and is absent from `list`. - **Append-only.** Flushed events are never rewritten. Subsequent raw batches append lines; compressed batches append one frame. Both paths `fsync`, and a caught write or sync failure rolls the file back to its prior byte length. - **Crash recovery — preserve valid tail work.** `load` validates every complete compressed frame and scans their decompressed JSONL. If the last frame is structurally incomplete, the reader keeps its complete decoded records, truncates from that frame's start, and re-encodes those records with the synthetic tool, step, and turn closers required by the shared [persistence contract](../../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md). Raw mode truncates from its first incomplete line. A checksum/decompression failure in a complete frame, or a defect at or before the last committed `turn/end`, is corruption and rejects. @@ -64,6 +66,7 @@ JSONL storage does not mutate live request prefixes. A resumed loop can reuse pr ## Known Limitations and Deferred Work - **Only the configured encoding and current `SESSION_FORMAT_VERSION` (v0) load** — changing compression requires a separate/fresh root or selecting the legacy raw mode; the pre-release format has no migration. +- **The flat-file storage layout does not load** — use a separate root or move pre-release artifacts into the project/session directory layout before loading. - **Compressed files are not directly line-readable** — use the backend to load them, or select `compression: 'none'` before writing a fresh root when text fixtures or external line readers are required. - **Nothing deletes session files** — logs accumulate under `root` until removed externally (the seam has no deletion surface). - **One live writer per session** — append and repair are coordinated only inside the owning backend instance. Another backend instance or process must not write the same session until that owner reaches quiescent disposal; initial same-id publication remains collision-safe through the POSIX no-overwrite hard link or Windows write-through rename without replacement. diff --git a/packages/session-persistence/session-persistence-jsonl/src/format.ts b/packages/session-persistence/session-persistence-jsonl/src/format.ts index 2a34a1ce80..bb55f5e00d 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/format.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/format.ts @@ -2,7 +2,7 @@ * On-disk format helpers for the JSONL session-persistence backend: path * sanitization (a {@link SessionId} is an unvalidated branded string, so it * MUST be encoded before use in a path — no traversal, no collision), the - * per-cwd directory layout, header-line (de)serialization, and the + * per-project/session directory layout, header-line (de)serialization, and the * truncation-repair offset computation. * * @module dsh-session-persistence-jsonl/format @@ -120,24 +120,65 @@ export function encodeSegment(raw: string): string { } /** - * The directory a session's files live in: the configured root, then a per-cwd - * subdirectory so sessions group by project. The cwd subdir is a stable hash of - * the cwd (short, collision-resistant, filesystem-safe); sessions without a - * cwd go in a shared `_no-cwd` bucket. - * @param root - the backend's session root directory. - * @param cwd - the session's project directory; `undefined` selects the shared `_no-cwd` bucket. - * @returns the per-cwd bucket directory path under `root`. + * Build the readable, collision-resistant directory key for a project path. + * Filesystem separators and drive separators become `-`; unsafe code units use + * the same `~XXXX` escape as session ids. The readable prefix is bounded for + * filesystem component limits, and the hash suffix keeps distinct or truncated + * paths separate. + * @param cwd - the session's project directory. + * @returns a single filesystem-safe project directory name. */ -export function sessionDir(root: string, cwd: string | undefined): string { - if (cwd === undefined) return join(root, '_no-cwd') +export function projectKey(cwd: string): string { + if (cwd.length === 0) throw new Error('cannot encode an empty project path') + let readable = '' + let separatorRun = false + for (let i = 0; i < cwd.length; i++) { + const code = cwd.charCodeAt(i) + const ch = String.fromCharCode(code) + if (ch === '/' || ch === '\\' || ch === ':') { + if (!separatorRun) readable += '-' + separatorRun = true + } else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) { + readable += ch + separatorRun = false + } else { + readable += '~' + code.toString(16).toUpperCase().padStart(4, '0') + separatorRun = false + } + } const hash = createHash('sha256').update(cwd).digest('hex').slice(0, 12) - return join(root, `cwd-${hash}`) + const slug = readable.replace(/^-+/, '') || 'root' + return `--${slug.slice(0, 200)}--${hash}` +} + +/** + * The configured root's human-navigable project directory. A configured root + * may be local or shared; this grouping does not prescribe its deployment. + * @param root - the backend's session root directory. + * @param cwd - the session's project directory; `undefined` selects `_no-cwd`. + * @returns the project directory path under `root`. + */ +export function projectDir(root: string, cwd: string | undefined): string { + if (cwd === undefined) return join(root, '_no-cwd') + return join(root, projectKey(cwd)) +} + +/** + * The directory owned by one session and available for future session-local + * artifacts. + * @param root - the backend's session root directory. + * @param cwd - the session's project directory. + * @param id - the session id, encoded to one safe path segment. + * @returns the session directory beneath its project directory. + */ +export function sessionDir(root: string, cwd: string | undefined, id: SessionId): string { + return join(projectDir(root, cwd), encodeSegment(id)) } /** * The append-only event-log file path for a session. * @param root - the backend's session root directory. - * @param cwd - the session's project directory (picks the per-cwd bucket; `undefined` → `_no-cwd`). + * @param cwd - the session's project directory (`undefined` → `_no-cwd`). * @param id - the session id, path-encoded via {@link encodeSegment} before filesystem use. * @param compression - physical artifact encoding and filename suffix. * @returns the session's configured JSONL artifact path. @@ -148,7 +189,7 @@ export function logPath( id: SessionId, compression: JsonlCompression, ): string { - return join(sessionDir(root, cwd), `${encodeSegment(id)}${logSuffix(compression)}`) + return join(sessionDir(root, cwd, id), `session${logSuffix(compression)}`) } /** diff --git a/packages/session-persistence/session-persistence-jsonl/src/index.ts b/packages/session-persistence/session-persistence-jsonl/src/index.ts index 629c0e3ff1..ad58cfe145 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/index.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/index.ts @@ -19,7 +19,7 @@ import { } from '@deepseek-ai/dsh-session-persistence' import type { SessionEvent, SessionId, SessionHeader } from '@deepseek-ai/dsh-session' import { - encodeSegment, eventLines, logPath, logSuffix, parseHeaderMeta, scanLog, sessionDir, toHeaderLine, + encodeSegment, eventLines, logPath, logSuffix, parseHeaderMeta, projectDir, scanLog, sessionDir, toHeaderLine, type JsonlCompression, } from './format.ts' import { compressZstdFrame, decompressZstdFrame, scanZstdFrames } from './zstd.ts' @@ -141,7 +141,7 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi /* jscpd:ignore-end */ // --- PersistenceBackend hooks (the file-bytes storage primitives) --- - /** Read a stored prefix by id across all cwd buckets when cwd is unknown. */ + /** Read a stored prefix by id across all project directories when cwd is unknown. */ async loadStored(id: SessionId): Promise | undefined> { await this.ensureRootEncoding() const path = await this.findLog(id) @@ -278,9 +278,12 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi await this.ensureRootEncoding() const artifacts: Array<{ header: SessionHeader; path: string }> = [] const ids = new Set() - for (const dir of await this.listCwdDirs()) { - for (const name of await this.listArtifactNames(dir)) { - const path = join(dir, name) + for (const project of await this.listProjectDirs()) { + for (const dir of await this.listSessionDirs(project)) { + const opposite = join(dir, `session${logSuffix(this.oppositeCompression())}`) + if (await this.exists(opposite)) throw this.encodingMismatch(opposite) + const path = join(dir, `session${logSuffix(this.compression)}`) + if (!await this.exists(path)) continue // Read only headers so listing scales with session count, not log size. const first = this.compression === 'zstd' ? await this.readFirstZstdLine(path) @@ -290,7 +293,7 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi if (meta === undefined) continue // not a session header this.assertStoredIdentity(path, meta) if (ids.has(meta.id)) { - throw new Error(`duplicate JSONL session id "${meta.id}" appears in multiple cwd buckets`) + throw new Error(`duplicate JSONL session id "${meta.id}" appears in multiple project directories`) } ids.add(meta.id) artifacts.push({ header: meta, path }) @@ -303,20 +306,22 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi /** Atomically write the header line + first batch (temp-write, fsync, publish). */ private async materialize(meta: SessionHeader, events: readonly SessionEvent[]): Promise { - const dir = sessionDir(this.root, meta.cwd) + const project = projectDir(this.root, meta.cwd) + const dir = sessionDir(this.root, meta.cwd, meta.id) const finalPath = logPath(this.root, meta.cwd, meta.id, this.compression) await this.rejectOppositeArtifact(meta.cwd, meta.id) const content = await this.encodeMaterialization(meta, events) /* v8 ignore next -- native Windows coverage exercises this platform dispatch; Linux covers the POSIX peer */ if (process.platform === 'win32') { - await this.materializeWin32(dir, finalPath, meta.id, content) + await this.materializeWin32(project, dir, finalPath, meta.id, content) } else { - await this.materializePosix(dir, finalPath, meta.id, content) + await this.materializePosix(project, dir, finalPath, meta.id, content) } } /* v8 ignore start -- Windows uses the Win32 durable-publish path; POSIX coverage exercises this peer. */ private async materializePosix( + project: string, dir: string, finalPath: string, id: SessionId, @@ -324,8 +329,10 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi ): Promise { await mkdir(this.root, { recursive: true, mode: 0o700 }) await this.syncDirPosix(dirname(this.root)) - await mkdir(dir, { recursive: true, mode: 0o700 }) + await mkdir(project, { recursive: true, mode: 0o700 }) await this.syncDirPosix(this.root) + await mkdir(dir, { recursive: true, mode: 0o700 }) + await this.syncDirPosix(project) await this.rejectExistingLog(finalPath, id) const tmp = await this.writeSyncedTempFile(finalPath, content) // Publish via link()+unlink(), NOT rename(): link fails with EEXIST if the @@ -358,12 +365,14 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi /* v8 ignore start -- native Windows coverage exercises this integration path */ private async materializeWin32( + project: string, dir: string, finalPath: string, id: SessionId, content: Buffer | string, ): Promise { await ensureDurableDirectoryWin32(this.root) + await ensureDurableDirectoryWin32(project) await ensureDurableDirectoryWin32(dir) await this.rejectExistingLog(finalPath, id) const tmp = await this.writeSyncedTempFile(finalPath, content) @@ -541,19 +550,19 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } } - /** Find the unique physical log for an id across every cwd bucket. */ + /** Find the unique physical log for an id across every project directory. */ private async findLog(id: SessionId): Promise { - const target = encodeSegment(id) + logSuffix(this.compression) - const oppositeTarget = encodeSegment(id) + logSuffix(this.oppositeCompression()) const matches: string[] = [] - for (const dir of await this.listCwdDirs()) { - const path = join(dir, target) - const opposite = join(dir, oppositeTarget) + for (const project of await this.listProjectDirs()) { + await this.rejectLegacyFlatArtifact(project, id) + const dir = join(project, encodeSegment(id)) + const path = join(dir, `session${logSuffix(this.compression)}`) + const opposite = join(dir, `session${logSuffix(this.oppositeCompression())}`) if (await this.exists(opposite)) throw this.encodingMismatch(opposite) if (await this.exists(path)) matches.push(path) } if (matches.length > 1) { - throw new Error(`duplicate JSONL session id "${id}" appears in multiple cwd buckets`) + throw new Error(`duplicate JSONL session id "${id}" appears in multiple project directories`) } return matches[0] } @@ -580,12 +589,12 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi throw new Error(`corrupt session log "${path}": header id cannot name a storage path`, { cause: error }) } if (path !== expectedPath) { - throw new Error(`corrupt session log "${path}": header id "${meta.id}" and cwd belong at "${expectedPath}"`) + throw new Error(`corrupt session log "${path}": header id "${meta.id}" and cwd identify "${expectedPath}"`) } } - /** The cwd-bucket directories under the root (absolute paths). */ - private async listCwdDirs(): Promise { + /** The human-readable project directories under the configured root. */ + private async listProjectDirs(): Promise { try { const entries = await readdir(this.root, { withFileTypes: true }) return entries.filter(e => e.isDirectory()).map(e => join(this.root, e.name)) @@ -596,13 +605,13 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } } - private async listArtifactNames(dir: string): Promise { - const entries = await readdir(dir) - const oppositeSuffix = logSuffix(this.oppositeCompression()) - const incompatible = entries.find(name => name.endsWith(oppositeSuffix)) - if (incompatible !== undefined) throw this.encodingMismatch(`${dir}/${incompatible}`) - const suffix = logSuffix(this.compression) - return entries.filter(name => name.endsWith(suffix)) + /** List session-owned directories and reject the obsolete flat-file layout. */ + private async listSessionDirs(project: string): Promise { + const entries = await readdir(project, { withFileTypes: true }) + const legacy = entries.find(entry => + entry.isFile() && (entry.name.endsWith('.jsonl') || entry.name.endsWith('.jsonl.zstd'))) + if (legacy !== undefined) throw this.legacyLayout(join(project, legacy.name)) + return entries.filter(entry => entry.isDirectory()).map(entry => join(project, entry.name)) } /** Reject a root that already belongs to the other physical encoding. */ @@ -612,11 +621,19 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } private async checkRootEncoding(): Promise { - const oppositeSuffix = logSuffix(this.oppositeCompression()) - for (const dir of await this.listCwdDirs()) { - const entries = await readdir(dir) - const incompatible = entries.find(name => name.endsWith(oppositeSuffix)) - if (incompatible !== undefined) throw this.encodingMismatch(`${dir}/${incompatible}`) + for (const project of await this.listProjectDirs()) { + for (const dir of await this.listSessionDirs(project)) { + const incompatible = join(dir, `session${logSuffix(this.oppositeCompression())}`) + if (await this.exists(incompatible)) throw this.encodingMismatch(incompatible) + } + } + } + + private async rejectLegacyFlatArtifact(project: string, id: SessionId): Promise { + const encoded = encodeSegment(id) + for (const compression of ['zstd', 'none'] as const) { + const path = join(project, encoded + logSuffix(compression)) + if (await this.exists(path)) throw this.legacyLayout(path) } } @@ -637,6 +654,13 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi ) } + private legacyLayout(path: string): Error { + return new Error( + `session artifact ${JSON.stringify(path)} uses the unsupported flat-file layout; ` + + 'use a separate root or move it into a project/session directory before loading', + ) + } + private async exists(path: string): Promise { try { const handle = await open(path, 'r') @@ -646,7 +670,7 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi // Only ENOENT means absent. A permission/I/O error must surface rather // than letting load or collision checks proceed under false absence. // Windows reports ENOENT, not ENOTDIR, for `regular-file/child`; verify - // the immediate parent so a blocked cwd bucket remains a storage fault. + // the immediate parent so a blocked session directory remains a storage fault. /* v8 ignore else -- Windows reports file-valued parents as ENOENT; POSIX covers direct ENOTDIR. */ if (isENOENT(error)) { await this.assertLogParentAllowsAbsence(path) diff --git a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts index 2b49b7d55b..0c46afc6b8 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts @@ -6,7 +6,9 @@ import { isAbsolute, join, relative, resolve } from 'node:path' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' -import { encodeSegment, eventLines, logPath, scanLog, sessionDir, toHeaderLine } from '../src/format.ts' +import { + encodeSegment, eventLines, logPath, projectDir, projectKey, scanLog, sessionDir, toHeaderLine, +} from '../src/format.ts' import { runPersistenceContract, meta, oneTurnLog, appendLog } from '../../session-persistence/tests/contract.ts' import { runCoordinatorContract, type CoordinatorFixture } from '../../session-persistence/tests/coordinator-contract.ts' @@ -125,6 +127,18 @@ describe('SessionPersistenceJsonl: format helpers', () => { expect(() => encodeSegment('')).toThrow(/empty/) }) + it('projectKey keeps the path readable and disambiguates normalized collisions', () => { + expect(projectKey('/Users/qyj/work/deepseek-harness')).toMatch( + /^--Users-qyj-work-deepseek-harness--[a-f0-9]{12}$/, + ) + expect(projectKey('/a/b-c')).not.toBe(projectKey('/a-b/c')) + expect(projectKey('C:\\work\\agent')).toMatch(/^--C-work-agent--[a-f0-9]{12}$/) + expect(projectKey('/开发/~agent')).toMatch(/^--~5F00~53D1-~007Eagent--[a-f0-9]{12}$/) + expect(projectKey('/')).toMatch(/^--root--[a-f0-9]{12}$/) + expect(projectKey('/' + 'x'.repeat(1_000))).toHaveLength(216) + expect(() => projectKey('')).toThrow(/empty project path/) + }) + it('resolves a relative custom root before locating a session', async () => { const absoluteRoot = await freshRoot() const ctx = new Context() @@ -161,15 +175,15 @@ describe('SessionPersistenceJsonl: durability and crash semantics', () => { await ctx.sessionPersistence.create(m) // locate() is a pure target-path calculation: neither it nor create() // materializes a file before the first append. - const dir = sessionDir(root, '/work') + const dir = sessionDir(root, '/work', m.id) await expect(stat(rawLogPath(root, '/work', m.id))).rejects.toThrow() expect((await ctx.sessionPersistence.list()).map(h => h.id)).not.toContain(m.id) await ctx.sessionPersistence.append(m.id, oneTurnLog()) // now materialized + expect((await stat(dir)).isDirectory()).toBe(true) expect((await stat(rawLogPath(root, '/work', m.id))).isFile()).toBe(true) expect((await ctx.sessionPersistence.list()).map(h => h.id)).toContain(m.id) - void dir }) it('keeps the same location on resume and gives a fork its own location', async () => { @@ -268,7 +282,7 @@ describe('SessionPersistenceJsonl: durability and crash semantics', () => { it('rejects a stored v0 log containing a legacy request/header-delta event', async () => { const m = meta('legacy-header-delta', '/legacy') const path = rawLogPath(root, m.cwd, m.id) - await mkdir(sessionDir(root, m.cwd), { recursive: true }) + await mkdir(sessionDir(root, m.cwd, m.id), { recursive: true }) await writeFile(path, [ JSON.stringify(toHeaderLine(m)), JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }), @@ -283,7 +297,7 @@ describe('SessionPersistenceJsonl: durability and crash semantics', () => { it('rejects a stored v0 full header carrying the legacy fallback reason', async () => { const m = meta('legacy-header-fallback', '/legacy') const path = rawLogPath(root, m.cwd, m.id) - await mkdir(sessionDir(root, m.cwd), { recursive: true }) + await mkdir(sessionDir(root, m.cwd, m.id), { recursive: true }) await writeFile(path, [ JSON.stringify(toHeaderLine(m)), JSON.stringify({ @@ -693,7 +707,7 @@ describe('SessionPersistenceJsonl: packed chunk rows (packChunks: true)', () => const log = chunkRunLog() // First turn written line-per-event by an unpacked-config writer (an old // file, hand-planted so this packed-config backend adopts it on load). - await mkdir(sessionDir(root, '/work'), { recursive: true }) + await mkdir(sessionDir(root, '/work', m.id), { recursive: true }) await writeFile(rawLogPath(root, '/work', m.id), [ JSON.stringify({ type: 'session', version: 0, id: 'mixed', createdAt: 1000, cwd: '/work', delegationDepth: 0 }), ...log.map(e => JSON.stringify(e)), @@ -789,12 +803,12 @@ describe('SessionPersistenceJsonl: edge cases', () => { await expect(stat(rawLogPath(root, '/mutated', SessionId('create-snap')))).rejects.toThrow() }) - it('list discovers sessions across multiple cwd buckets', async () => { + it('list discovers sessions across multiple project directories', async () => { await ctx.sessionPersistence.create(meta('p1', '/projA')) await ctx.sessionPersistence.append(SessionId('p1'), oneTurnLog()) await ctx.sessionPersistence.create(meta('p2', '/projB')) await ctx.sessionPersistence.append(SessionId('p2'), oneTurnLog()) - await ctx.sessionPersistence.create(meta('p3')) // no cwd → _no-cwd bucket + await ctx.sessionPersistence.create(meta('p3')) // no cwd → _no-cwd project directory await ctx.sessionPersistence.append(SessionId('p3'), oneTurnLog()) const ids = (await ctx.sessionPersistence.list()).map(x => x.id).sort() @@ -805,18 +819,60 @@ describe('SessionPersistenceJsonl: edge cases', () => { expect(await ctx.sessionPersistence.list()).toEqual([]) }) - it('list skips empty and non-header .jsonl files (metadata-only read)', async () => { + it('keeps the transcript in an extensible session-owned directory', async () => { + const m = meta('owned-directory', '/project') + await ctx.sessionPersistence.create(m) + await ctx.sessionPersistence.append(m.id, oneTurnLog()) + const dir = sessionDir(root, m.cwd, m.id) + await writeFile(join(dir, 'metadata.json'), '{}\n') + await writeFile(join(projectDir(root, m.cwd), 'README'), 'project metadata\n') + await mkdir(join(projectDir(root, m.cwd), 'reserved-session'), { recursive: true }) + + expect(await readdir(dir)).toEqual(expect.arrayContaining(['metadata.json', 'session.jsonl'])) + expect((await ctx.sessionPersistence.list()).map(header => header.id)).toContain(m.id) + expect((await ctx.sessionPersistence.load(m.id)).events).toEqual(oneTurnLog()) + }) + + it('rejects the obsolete flat-file layout instead of ignoring stored sessions', async () => { + const m = meta('legacy-flat', '/legacy') + const project = projectDir(root, m.cwd) + const path = join(project, `${encodeSegment(m.id)}.jsonl`) + await mkdir(project, { recursive: true }) + await writeFile(path, [ + JSON.stringify(toHeaderLine(m)), + ...oneTurnLog().map(event => JSON.stringify(event)), + '', + ].join('\n')) + + await expect(ctx.sessionPersistence.load(m.id)).rejects.toThrow(/unsupported flat-file layout/) + await expect(ctx.sessionPersistence.list()).rejects.toThrow(/unsupported flat-file layout/) + }) + + it('rejects a compressed obsolete flat-file artifact during targeted lookup', async () => { + const m = meta('legacy-compressed-flat', '/legacy') + const project = projectDir(root, m.cwd) + expect(await ctx.sessionPersistence.list()).toEqual([]) + await mkdir(project, { recursive: true }) + await writeFile(join(project, `${encodeSegment(m.id)}.jsonl.zstd`), 'legacy') + + await expect(ctx.sessionPersistence.load(m.id)).rejects.toThrow(/unsupported flat-file layout/) + }) + + it('list skips empty and non-header session logs (metadata-only read)', async () => { // A real session… await ctx.sessionPersistence.create(meta('real', '/p')) await ctx.sessionPersistence.append(SessionId('real'), oneTurnLog()) - // …alongside two junk files in the _no-cwd bucket: an EMPTY file (readFirstLine - // returns undefined) and a file whose first line is not a session header - // (parseHeaderMeta returns undefined). Both are skipped, not listed. - const bucket = join(root, '_no-cwd') - await mkdir(bucket, { recursive: true }) - await writeFile(join(bucket, 'empty.jsonl'), '') - await writeFile(join(bucket, 'notheader.jsonl'), '{"type":"turn/start"}\n') - await writeFile(join(bucket, 'badjson.jsonl'), 'not json at all\n') + // …alongside junk session directories whose fixed transcript is empty or + // lacks a header. Both remain unmaterialized and are skipped. + for (const [id, content] of [ + ['empty', ''], + ['notheader', '{"type":"turn/start"}\n'], + ['badjson', 'not json at all\n'], + ] as const) { + const path = rawLogPath(root, undefined, SessionId(id)) + await mkdir(sessionDir(root, undefined, SessionId(id)), { recursive: true }) + await writeFile(path, content) + } const ids = (await ctx.sessionPersistence.list()).map(x => x.id).sort() expect(ids).toEqual(['real']) @@ -825,10 +881,10 @@ describe('SessionPersistenceJsonl: edge cases', () => { it('list reads a header line longer than the 8KB read chunk', async () => { // A tolerated extra field makes this valid header exceed the 8192-byte read buffer, proving // `readFirstLine` accumulates chunks before `list()` parses it. - const bucket = join(root, '_no-cwd') - await mkdir(bucket, { recursive: true }) + const id = SessionId('big') + await mkdir(sessionDir(root, undefined, id), { recursive: true }) const bigHeader = JSON.stringify({ type: 'session', version: 0, id: 'big', createdAt: 1, delegationDepth: 0, pad: 'x'.repeat(9000) }) - await writeFile(join(bucket, 'big.jsonl'), bigHeader + '\n') + await writeFile(rawLogPath(root, undefined, id), bigHeader + '\n') const ids = (await ctx.sessionPersistence.list()).map(x => x.id) expect(ids).toContain('big') }) @@ -839,30 +895,30 @@ describe('SessionPersistenceJsonl: edge cases', () => { await ctx.sessionPersistence.append(m.id, oneTurnLog()) await rewriteHeader(rawLogPath(root, m.cwd, m.id), (header) => { header.cwd = '/elsewhere' }) - await expect(ctx.sessionPersistence.list()).rejects.toThrow(/and cwd belong at/) + await expect(ctx.sessionPersistence.list()).rejects.toThrow(/and cwd identify/) }) it('list rejects a session header whose id cannot name a storage path', async () => { - const bucket = sessionDir(root, undefined) - await mkdir(bucket, { recursive: true }) - await writeFile(join(bucket, 'invalid-id.jsonl'), JSON.stringify({ + const dir = join(projectDir(root, undefined), 'invalid-id') + await mkdir(dir, { recursive: true }) + await writeFile(join(dir, 'session.jsonl'), JSON.stringify({ type: 'session', version: 0, id: '', createdAt: 1, delegationDepth: 0, }) + '\n') await expect(ctx.sessionPersistence.list()).rejects.toThrow(/header id cannot name a storage path/) }) - it('load and list reject one id materialized in multiple cwd buckets', async () => { + it('load and list reject one id materialized in multiple project directories', async () => { const id = SessionId('duplicate') for (const cwd of ['/a', '/b']) { const m = meta(id, cwd) - await mkdir(sessionDir(root, cwd), { recursive: true }) + await mkdir(sessionDir(root, cwd, id), { recursive: true }) const content = [JSON.stringify(toHeaderLine(m)), ...oneTurnLog().map(event => JSON.stringify(event))].join('\n') + '\n' await writeFile(rawLogPath(root, cwd, id), content) } - await expect(ctx.sessionPersistence.load(id)).rejects.toThrow(/appears in multiple cwd buckets/) - await expect(ctx.sessionPersistence.list()).rejects.toThrow(/appears in multiple cwd buckets/) + await expect(ctx.sessionPersistence.load(id)).rejects.toThrow(/appears in multiple project directories/) + await expect(ctx.sessionPersistence.list()).rejects.toThrow(/appears in multiple project directories/) }) it('a DIFFERENT live session object reusing a disposed id gets its own init (no stale cache)', async () => { @@ -985,12 +1041,12 @@ describe('SessionPersistenceJsonl: edge cases', () => { await expect(backend.exists(join(blocker, 'child.jsonl'))).rejects.toThrow(/ENOTDIR/) }) - it('materialization surfaces a cwd-bucket storage fault', async () => { + it('materialization surfaces a project-directory storage fault', async () => { const cwd = '/x' const ctx2 = new Context() await ctx2.plugin(SessionStore) await ctx2.plugin(SessionPersistenceJsonl, { root, compression: 'none' }) - await writeFile(sessionDir(root, cwd), 'x') // bucket path is now a FILE + await writeFile(projectDir(root, cwd), 'x') // project path is now a file let s!: Session await ctx2.plugin(Object.assign((inner: Context) => { s = inner.sessions.create(SessionId('exists-fault'), { meta: { cwd } }) @@ -1038,14 +1094,14 @@ describe('SessionPersistenceJsonl: edge cases', () => { }) - it('createCore rejects an id already on disk under a DIFFERENT cwd bucket', async () => { + it('createCore rejects an id already on disk under a different project directory', async () => { // Persist the id under cwd A. const a = meta('dup-id', '/projA') await ctx.sessionPersistence.create(a) await ctx.sessionPersistence.append(a.id, oneTurnLog()) // A fresh backend creating the SAME id under cwd B must still refuse: load - // identifies by id across all buckets, so a second log would make resume - // nondeterministic. create scans every bucket, not just meta.cwd's. + // identifies by id across all projects, so a second log would make resume + // nondeterministic. create scans every project, not just meta.cwd's. const ctx2 = new Context() await ctx2.plugin(SessionStore) await ctx2.plugin(SessionPersistenceJsonl, { root, compression: 'none' }) diff --git a/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts index fcadac1f04..a91b51ec9d 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/zstd.spec.ts @@ -391,15 +391,21 @@ describe('SessionPersistenceJsonl: default Zstandard encoding', () => { it('skips empty, incomplete, and non-header compressed artifacts while rejecting malformed header frames', async () => { const root = await freshRoot() - const bucket = sessionDir(root, undefined) - await mkdir(bucket, { recursive: true }) - await writeFile(join(bucket, 'empty.jsonl.zstd'), '') - await writeFile(join(bucket, 'partial.jsonl.zstd'), MAGIC) - await writeFile(join(bucket, 'not-header.jsonl.zstd'), await compressZstdFrame('{"type":"turn/start"}\n')) + for (const [id, content] of [ + ['empty', Buffer.alloc(0)], + ['partial', MAGIC], + ['not-header', await compressZstdFrame('{"type":"turn/start"}\n')], + ] as const) { + const sessionId = SessionId(id) + await mkdir(sessionDir(root, undefined, sessionId), { recursive: true }) + await writeFile(logPath(root, undefined, sessionId, 'zstd'), content) + } const ctx = await mount(root) expect(await ctx.sessionPersistence.list()).toEqual([]) - await writeFile(join(bucket, 'two-lines.jsonl.zstd'), await compressZstdFrame([ + const twoLinesId = SessionId('two-lines') + await mkdir(sessionDir(root, undefined, twoLinesId), { recursive: true }) + await writeFile(logPath(root, undefined, twoLinesId, 'zstd'), await compressZstdFrame([ JSON.stringify(toHeaderLine(meta('two-lines'))), JSON.stringify({ type: 'turn/start' }), '', @@ -411,8 +417,9 @@ describe('SessionPersistenceJsonl: default Zstandard encoding', () => { it('rejects missing, empty, and checksum-corrupt header frames on targeted reads', async () => { const root = await freshRoot() - const bucket = sessionDir(root, undefined) - await mkdir(bucket, { recursive: true }) + for (const id of ['partial-only', 'empty-header', 'bad-checksum']) { + await mkdir(sessionDir(root, undefined, SessionId(id)), { recursive: true }) + } await writeFile(logPath(root, undefined, SessionId('partial-only'), 'zstd'), MAGIC) await writeFile(logPath(root, undefined, SessionId('empty-header'), 'zstd'), await compressZstdFrame('')) const corruptHeader = Buffer.from(await compressZstdFrame(`${JSON.stringify(toHeaderLine(meta('bad-checksum')))}\n`)) @@ -453,7 +460,7 @@ describe('SessionPersistenceJsonl: encoding selection', () => { expect(await ctx.sessionPersistence.list()).toEqual([]) const loadHeader = meta('late-raw-load', '/late') - await mkdir(sessionDir(root, loadHeader.cwd), { recursive: true }) + await mkdir(sessionDir(root, loadHeader.cwd, loadHeader.id), { recursive: true }) await writeFile(logPath(root, loadHeader.cwd, loadHeader.id, 'none'), [ JSON.stringify(toHeaderLine(loadHeader)), ...oneTurnLog().map(e => JSON.stringify(e)), @@ -471,13 +478,13 @@ describe('SessionPersistenceJsonl: encoding selection', () => { await ctx.sessionPersistence.list() const header = meta('late-raw-materialize', '/late') await ctx.sessionPersistence.create(header) - await mkdir(sessionDir(root, header.cwd), { recursive: true }) + await mkdir(sessionDir(root, header.cwd, header.id), { recursive: true }) await writeFile(logPath(root, header.cwd, header.id, 'none'), [ JSON.stringify(toHeaderLine(header)), ...oneTurnLog().map(e => JSON.stringify(e)), '', ].join('\n')) await expect(ctx.sessionPersistence.append(header.id, oneTurnLog())).rejects.toThrow(/uses \.jsonl/) - expect((await readdir(sessionDir(root, header.cwd))).some(name => name.endsWith('.jsonl.zstd'))).toBe(false) + expect((await readdir(sessionDir(root, header.cwd, header.id))).some(name => name.endsWith('.jsonl.zstd'))).toBe(false) }) }) diff --git a/packages/support/acp-snapshot/src/harness.ts b/packages/support/acp-snapshot/src/harness.ts index 2821969457..d2d861ed1a 100644 --- a/packages/support/acp-snapshot/src/harness.ts +++ b/packages/support/acp-snapshot/src/harness.ts @@ -563,39 +563,29 @@ function latestTurnIsClosed(content: string): boolean { * `parentSession`) leads, then each subagent child by ascending `createdAt`. * * Snapshot configs select the JSONL backend's raw mode, which lays sessions - * out as `//.jsonl` (one bucket per cwd). A - * parent and its same-cwd in-process child land in the SAME bucket, so - * collecting all files across all buckets catches both. Returns `[]` if no log - * was produced (a no-session scenario). + * out as `///session.jsonl`. Recursive collection + * catches the primary and every child session. Returns `[]` if no log was + * produced (a no-session scenario). */ async function harvestSessionLogs(root: string): Promise { - let cwdDirs: string[] + let files: string[] try { - cwdDirs = await readdir(root) + files = await readdir(root, { recursive: true }) } catch { return [] } const logs: HarvestedLog[] = [] - for (const dir of cwdDirs) { - const sub = join(root, dir) - let files: string[] - try { - files = await readdir(sub) - } catch { - continue - } - for (const f of files) { - if (!f.endsWith('.jsonl')) continue - const content = await readFile(join(sub, f), 'utf8') - const firstLine = content.split('\n').find(line => line.trim().length > 0) ?? '{}' - const header = JSON.parse(firstLine) as { id?: unknown; createdAt?: unknown; parentSession?: unknown } - logs.push({ - id: typeof header.id === 'string' ? header.id : '', - createdAt: typeof header.createdAt === 'number' ? header.createdAt : 0, - ...typeof header.parentSession === 'string' ? { parentSession: header.parentSession } : {}, - content, - }) - } + for (const file of files) { + if (basename(file) !== 'session.jsonl') continue + const content = await readFile(join(root, file), 'utf8') + const firstLine = content.split('\n').find(line => line.trim().length > 0) ?? '{}' + const header = JSON.parse(firstLine) as { id?: unknown; createdAt?: unknown; parentSession?: unknown } + logs.push({ + id: typeof header.id === 'string' ? header.id : '', + createdAt: typeof header.createdAt === 'number' ? header.createdAt : 0, + ...typeof header.parentSession === 'string' ? { parentSession: header.parentSession } : {}, + content, + }) } // Primary (no parentSession) first, then children by ascending createdAt. A // scenario has exactly one top-level session. In the synchronous cut sibling diff --git a/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts b/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts index df3bb0b970..570a783a13 100644 --- a/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts +++ b/packages/support/acp-snapshot/tests/fixtures/fake-acp-agent.ts @@ -23,9 +23,9 @@ import { dirname, join } from 'node:path' import { randomUUID } from 'node:crypto' import { createInterface } from 'node:readline' -/** One scripted session log: a file path under the sessions root plus its JSONL lines. */ +/** One scripted session log: a transcript path under the sessions root plus its JSONL lines. */ interface ScriptedLog { - /** Path relative to `$DSH_SNAPSHOT_SESSIONS_ROOT`, e.g. `bucket/a.jsonl` (an empty dir segment is invalid). */ + /** Path relative to `$DSH_SNAPSHOT_SESSIONS_ROOT`, e.g. `project/session/session.jsonl`. */ file: string /** * The JSONL records. String templates `{{CWD}}` and `{{SID}}` are replaced @@ -69,7 +69,7 @@ interface Behavior { logs?: ScriptedLog[] /** Leave a stray FILE directly under the sessions root (harvest must skip it). */ strayRootFile?: boolean - /** Leave a stray non-`.jsonl` file inside a bucket (harvest must skip it). */ + /** Leave a stray non-transcript file inside a project directory (harvest must skip it). */ strayBucketFile?: boolean /** Delete the sessions root entirely (harvest must yield no logs). */ deleteSessionsRoot?: boolean diff --git a/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-child/behavior.json b/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-child/behavior.json index fd06978be1..d98afb4865 100644 --- a/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-child/behavior.json +++ b/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-child/behavior.json @@ -1,11 +1,11 @@ { "prompt": "respond", "logs": [ - { "file": "b/parent.jsonl", "lines": [ + { "file": "b/parent/session.jsonl", "lines": [ { "type": "session", "id": "{{SID}}", "createdAt": 700, "cwd": "{{CWD}}", "delegationDepth": 0 }, { "type": "request/header", "seq": 0, "time": 3, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "initial" } } ]}, - { "file": "b/child.jsonl", "lines": [ + { "file": "b/child/session.jsonl", "lines": [ { "type": "session", "id": "abababab-cdcd-4efe-8ada-badabadabada", "createdAt": 800, "cwd": "{{CWD}}", "parentSession": "{{SID}}", "delegationDepth": 1 }, { "type": "request/header", "seq": 0, "time": 2, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "initial" } } ]} diff --git a/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-pin/behavior.json b/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-pin/behavior.json index b0ed5f1a3f..7fffecf747 100644 --- a/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-pin/behavior.json +++ b/packages/support/acp-snapshot/tests/fixtures/record-suite/rec-pin/behavior.json @@ -1,7 +1,7 @@ { "prompt": "respond", "logs": [{ - "file": "b/main.jsonl", + "file": "b/main/session.jsonl", "lines": [ { "type": "session", "id": "{{SID}}", "createdAt": 600, "cwd": "{{CWD}}", "delegationDepth": 0 }, { "type": "request/header", "seq": 0, "time": 4, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "initial" } } diff --git a/packages/support/acp-snapshot/tests/fixtures/suite/authored-error/behavior.json b/packages/support/acp-snapshot/tests/fixtures/suite/authored-error/behavior.json index 991de99fd6..fd843a3a08 100644 --- a/packages/support/acp-snapshot/tests/fixtures/suite/authored-error/behavior.json +++ b/packages/support/acp-snapshot/tests/fixtures/suite/authored-error/behavior.json @@ -1,7 +1,7 @@ { "prompt": "error", "logs": [{ - "file": "b/main.jsonl", + "file": "b/main/session.jsonl", "lines": [ { "type": "session", "id": "{{SID}}", "createdAt": 500, "cwd": "{{CWD}}", "delegationDepth": 0 }, { "type": "turn/end", "seq": 1, "time": 9, "data": { "error": "model exploded" } } diff --git a/packages/support/acp-snapshot/tests/fixtures/suite/blocked-log/behavior.json b/packages/support/acp-snapshot/tests/fixtures/suite/blocked-log/behavior.json index 209159da7d..3c8ffc0b86 100644 --- a/packages/support/acp-snapshot/tests/fixtures/suite/blocked-log/behavior.json +++ b/packages/support/acp-snapshot/tests/fixtures/suite/blocked-log/behavior.json @@ -1,7 +1,7 @@ { "prompt": "error", "logs": [{ - "file": "b/main.jsonl", + "file": "b/main/session.jsonl", "lines": [ { "type": "session", "id": "{{SID}}", "createdAt": 400, "cwd": "{{CWD}}", "delegationDepth": 0 }, { "type": "hook/result", "seq": 1, "time": 8, "data": { "decision": "block", "durationMs": 37 } } diff --git a/packages/support/acp-snapshot/tests/fixtures/suite/pin-turn/behavior.json b/packages/support/acp-snapshot/tests/fixtures/suite/pin-turn/behavior.json index ad4c368e49..4de8f25b7e 100644 --- a/packages/support/acp-snapshot/tests/fixtures/suite/pin-turn/behavior.json +++ b/packages/support/acp-snapshot/tests/fixtures/suite/pin-turn/behavior.json @@ -1,7 +1,7 @@ { "prompt": "respond", "logs": [{ - "file": "b/main.jsonl", + "file": "b/main/session.jsonl", "lines": [ { "type": "session", "id": "{{SID}}", "createdAt": 100, "cwd": "{{CWD}}", "delegationDepth": 0 }, { "type": "request/header", "seq": 0, "time": 100, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "initial" } }, diff --git a/packages/support/acp-snapshot/tests/fixtures/suite/plain-turn/behavior.json b/packages/support/acp-snapshot/tests/fixtures/suite/plain-turn/behavior.json index 8903d0360e..e00ca3ff28 100644 --- a/packages/support/acp-snapshot/tests/fixtures/suite/plain-turn/behavior.json +++ b/packages/support/acp-snapshot/tests/fixtures/suite/plain-turn/behavior.json @@ -2,12 +2,12 @@ "prompt": "respond", "echoWorkspace": true, "logs": [ - { "file": "b/parent.jsonl", "lines": [ + { "file": "b/parent/session.jsonl", "lines": [ { "type": "session", "id": "{{SID}}", "createdAt": 200, "cwd": "{{CWD}}", "delegationDepth": 0 }, { "type": "request/header", "seq": 0, "time": 5, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "initial" } }, { "type": "assistant/chunk", "seq": 1, "time": 5, "data": { "turn": 1, "step": 1, "chunk": { "type": "text-delta", "index": 0, "text": "hi" } } } ]}, - { "file": "b/child.jsonl", "lines": [ + { "file": "b/child/session.jsonl", "lines": [ { "type": "session", "id": "eeeeeeee-1111-4222-8333-444444444444", "createdAt": 300, "cwd": "{{CWD}}", "parentSession": "{{SID}}", "delegationDepth": 1 }, { "type": "request/header", "seq": 0, "time": 6, "data": { "header": { "config": { "model": "fake" }, "system": "SYS PROMPT", "tools": [{ "name": "t1", "description": "D1", "parameters": { "type": "object" } }] }, "reason": "initial" } } ]} diff --git a/packages/support/acp-snapshot/tests/harness.spec.ts b/packages/support/acp-snapshot/tests/harness.spec.ts index a87e72d3d4..b1981abc9d 100644 --- a/packages/support/acp-snapshot/tests/harness.spec.ts +++ b/packages/support/acp-snapshot/tests/harness.spec.ts @@ -378,7 +378,7 @@ describe('runScenario', () => { const { fixtureFile } = await scenario({ permissionProbe: true, logs: [{ - file: 'bucket/main.jsonl', + file: 'project/main/session.jsonl', lines: [ { type: 'session', id: '{{SID}}', createdAt: 42, cwd: '{{CWD}}' }, { type: 'turn/start', seq: 1, time: 9, data: { turn: 1 } }, @@ -566,7 +566,7 @@ describe('runScenario', () => { prompt: 'hang-until-cancel', persistLogsOnCancel: true, logs: [{ - file: 'bucket/session.jsonl', + file: 'project/main/session.jsonl', lines: [ { type: 'session', version: 0, id: '{{SID}}', createdAt: 1, delegationDepth: 0 }, { type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'aborted' } } }, @@ -591,7 +591,7 @@ describe('runScenario', () => { prompt: 'hang-until-cancel', persistLogsOnCancel: true, logs: [{ - file: 'bucket/session.jsonl', + file: 'project/main/session.jsonl', lines: [ { type: 'session', version: 0, id: '{{SID}}', createdAt: 1, delegationDepth: 0 }, { type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }, @@ -776,11 +776,11 @@ describe('runScenario', () => { // File names chosen so readdir feeds the sort children-first AND // parent-in-the-middle: the comparator then sees a parent on both // sides of a pair, plus the same-createdAt (localeCompare) tiebreak. - { file: 'b1/aa-child-c.jsonl', lines: [{ type: 'session', id: 'cccccccc-0000-4000-8000-000000000000', createdAt: 500, parentSession: '{{SID}}' }] }, - { file: 'b1/bb-parent.jsonl', lines: [{ type: 'session', id: '{{SID}}', createdAt: 900 }] }, - { file: 'b1/cc-child-a.jsonl', lines: [{ type: 'session', id: 'aaaaaaaa-0000-4000-8000-000000000000', createdAt: 500, parentSession: '{{SID}}' }] }, + { file: 'b1/aa-child-c/session.jsonl', lines: [{ type: 'session', id: 'cccccccc-0000-4000-8000-000000000000', createdAt: 500, parentSession: '{{SID}}' }] }, + { file: 'b1/bb-parent/session.jsonl', lines: [{ type: 'session', id: '{{SID}}', createdAt: 900 }] }, + { file: 'b1/cc-child-a/session.jsonl', lines: [{ type: 'session', id: 'aaaaaaaa-0000-4000-8000-000000000000', createdAt: 500, parentSession: '{{SID}}' }] }, // Missing id/createdAt fall back to ''/0; earliest child by createdAt. - { file: 'b2/orphan-fields.jsonl', lines: [{ type: 'session', parentSession: '{{SID}}' }] }, + { file: 'b2/orphan/session.jsonl', lines: [{ type: 'session', parentSession: '{{SID}}' }] }, ], }) const result = await runScenario( @@ -797,7 +797,7 @@ describe('runScenario', () => { }) it('treats an empty log file as a header-less primary with default fields', { timeout: 20_000 }, async () => { - const { fixtureFile } = await scenario({ logs: [{ file: 'b/empty.jsonl', lines: [] }] }) + const { fixtureFile } = await scenario({ logs: [{ file: 'b/empty/session.jsonl', lines: [] }] }) const result = await runScenario( { steps: boot }, { agent: AGENT, mode: 'replay', fixtureFile }, From 2cd37e276518ef04489f5ddc0e08574827a9f3f8 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 19:57:27 +0800 Subject: [PATCH 022/113] docs(testing): web e2e lane docs + Agent Note to implemented MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit testing.md gains the web browser snapshot tier entry (divergent DSH_SNAPSHOT=... test:web commands) and names apps/web/tests/snapshots/ as the web surface's snapshot home. The GUI testing note's tier map and lane map gain the e2e scenarios (both languages, pair re-recorded) and drop the stale verify-session-real references (those scripts left with the missions/ tree). packages/client/AGENTS.md check ladder covers the wire-carriage trigger and refresh/record commands. acp-snapshot README stops claiming the whole package is ACP-specific — its normalizers are transport-neutral with three consumers now. vitest.web.config.ts header carries TODO(ci-browser) with the staged-reversal pointer. The design-study Agent Note moves proposed/ -> implemented/ rewritten in present tense: all review decisions recorded (llm:false seam over the placeholder-key hack, providers-mode replay, whenIdle barrier stack, single aria golden + anchors, TUI-style inline modes over a suite factory, scrub-only header stance, CI deferral) with re-entry triggers under Deferred. --- .../2026-07-20-gui-testing-system.i18n.yaml | 4 +- .../process/2026-07-20-gui-testing-system.md | 8 +- .../2026-07-20-gui-testing-system.zh.md | 8 +- .../2026-07-24-web-gui-browser-e2e-lane.md | 88 ++++++++++++++++++ .../2026-07-24-web-gui-browser-e2e-lane.md | 92 ------------------- apps/web/tests/harness.ts | 10 +- docs/testing.md | 3 +- packages/client/AGENTS.md | 2 +- packages/support/acp-snapshot/README.md | 2 +- vitest.web.config.ts | 11 ++- 10 files changed, 114 insertions(+), 114 deletions(-) create mode 100644 .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md delete mode 100644 .agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md diff --git a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.i18n.yaml b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.i18n.yaml index b21353698c..ca443d7a16 100644 --- a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.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 -2026-07-20-gui-testing-system.md: e42dafcdf37e48475e7d420eaad9600e6c20891c -2026-07-20-gui-testing-system.zh.md: e4ef6246e59e0ad6c0a3070a38c546f964e347fa +2026-07-20-gui-testing-system.md: b261bd2c84a628ab6fcdc29c59cf36a7b2428a76 +2026-07-20-gui-testing-system.zh.md: ecb8634695bd05359e6b590a825a4ad3604003b1 diff --git a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md index e42dafcdf3..b261bd2c84 100644 --- a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md +++ b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md @@ -20,7 +20,7 @@ Cut along the architecture's natural test seams into three tiers, bottom-up: |---|---|---|---| | 1 Protocol isomorphism | `AbstractApiClient` + `toFetchHandler` (bidirectional data / rpcId / zod types / SSE streams / batching / timeouts) | **The full chain at the isomorphic point**: `InProcessApiClient(toFetchHandler(脚本化 impl))` skips the network but genuinely runs the wire serialization — zero browser, pure node env | `packages/host/apiproxy/tests/client-handler.spec.ts` | | 2 Object-layer orchestration | `Session`/`SessionManager`/`ConnectionController` (state machines and timing: stitching / dedup / paging / optimistic draft clearing / pendingBuffers / reconnect / backoff) | **The "event sequence in → snapshot out" golden path**: programmable fakes + deferreds controlling timing + fake timers controlling backoff | `packages/client/{runtime,connection}/tests/` | -| 3 Assembled presentation | Built artifacts × the real client loader and plugin composition | App-owned semantic snapshots boot all eight built client plugins under jsdom for deterministic cross-plugin state changes; bare Playwright smoke separately proves the real browser/carrier boundary, with real-host cases self-skipping without a key | `apps/web/tests/*.snapshot.ts`, `apps/web/tests/smoke-{fixture,real}.e2e.ts` | +| 3 Assembled presentation | Built artifacts × the real client loader and plugin composition | App-owned semantic snapshots boot all eight built client plugins under jsdom for deterministic cross-plugin state changes; bare Playwright smoke separately proves the real browser/carrier boundary, with real-host cases self-skipping without a key; the keyless browser e2e lane replays recorded session fixtures through the real in-process web assembly (`llm: false` + dsh-llm-replay) against conversation aria goldens ([web e2e lane](../testing/2026-07-24-web-gui-browser-e2e-lane.md)) | `apps/web/tests/*.snapshot.ts`, `apps/web/tests/smoke-{fixture,real}.e2e.ts`, `apps/web/tests/{replay-round-trip,seeded-history}.e2e.ts` | Inter-tier discipline: **each tier tests its own layer, upper tiers never re-test lower ones** — an app semantic snapshot pins only user-visible projection across the assembled plugin boundary, while Playwright smoke proves browser and carrier liveness; wire semantics belong to tier 1 and data semantics to tier 2. Pure-function layers (lineage/partial/notifier/fold-adapter) are tested directly with zero fakes in the same package's tests/ alongside tier 2. @@ -33,15 +33,15 @@ Inter-tier discipline: **each tier tests its own layer, upper tiers never re-tes |---|---|---|---| | Baseline | `pnpm run test:gui` | Tier 1+2 vitest (`packages/client packages/host`), seconds-fast, no browser, no server | Casually, after touching any GUI source | | Semantic snapshot | `DSH_EXAMPLE_MODE=lib pnpm run test:snapshot` | Keyless assembled-application semantics plus the repo's transport-specific expected outputs | After a human-visible GUI change; before delivery | -| Browser end-to-end | `pnpm run test:web` | Rebuilds the front-end dist first, then runs the tier-3 two-level smoke (fixture level + real-host level self-skip) | After touching the build surface/boot/carriage; before delivery | +| Browser end-to-end | `pnpm run test:web` | Rebuilds the front-end dist first, then runs the tier-3 browser set: the two-level smoke (fixture level + real-host level self-skip) plus the keyless replayed e2e scenarios (`DSH_SNAPSHOT=record`/`refresh` re-record fixtures / rewrite goldens) | After touching the build surface/boot/carriage; before delivery | | Gate | `pnpm run test:coverage` | The repo-wide gate (host and client GUI packages included, except annotated browser-grade exclusions) | The PR window | **Division of labor between the browser scripts and vitest**: Playwright owns browser/carrier black-box regression and long sequential user journeys; ordinary vitest owns data-layer semantics such as reference stability, timing, and wire shapes; snapshot vitest owns stable app-level semantic output through the built composition. These lanes complement each other rather than duplicating assertions. ## Anti-regression discipline -- **Every bug fix pins an assertion**: a browser-visible bug is pinned into the regression section of its owning verify script (one pin = one report line); a data-layer bug is pinned into the matching spec (precedent: the res-close misjudgment pinned in the webserver bridge suite — pure Node, reproduces in seconds, no longer needs the 12s browser sentinel as the only defense). -- **All-green on fixture is not done, the real host must pass too**: what the fixture short-circuits is exactly the wire carriage chain (node:http bridge close semantics, real network timing); both empirically confirmed bugs hid there. Changes touching connection/bridge/handler/SSE must run `verify-session-real`. +- **Every bug fix pins an assertion**: a browser-visible bug is pinned into its owning browser spec (smoke or e2e scenario); a data-layer bug is pinned into the matching spec (precedent: the res-close misjudgment pinned in the webserver bridge suite — pure Node, reproduces in seconds, no longer needs the 12s browser sentinel as the only defense). +- **All-green on fixture is not done, the real wire must pass too**: what the fixture short-circuits is exactly the wire carriage chain (node:http bridge close semantics, real network timing); both empirically confirmed bugs hid there. Changes touching connection/bridge/handler/SSE must run the browser lane (`pnpm run test:web`) — its keyless e2e scenarios drive the real HTTP/SSE carriage, and the with-key real-host smoke remains the live-model complement. - The code-on-disk-is-the-answer reconciliation workflow: when a behavior change lands and turns existing cases red, reconcile on the spot (fix the test or fix the code, with the RFC/contract as arbiter); no red left hanging. ## Consequences diff --git a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md index e4ef6246e5..ecb8634695 100644 --- a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md +++ b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md @@ -20,7 +20,7 @@ GUI 栈需要考虑多种应用形态,同应用形态内的不同运行环境 |---|---|---|---| | 1 协议同构层 | `AbstractApiClient` + `toFetchHandler`(双向数据/rpcId/ZOD类型/SSE 流/合批/超时) | **同构点全链**:`InProcessApiClient(toFetchHandler(脚本化 impl))` 不过网络但真跑 wire 序列化——零浏览器、纯 node env | `packages/host/apiproxy/tests/client-handler.spec.ts` | | 2 对象层编排 | `Session`/`SessionManager`/`ConnectionController`(状态机与时序:缝合/去重/翻页/乐观清稿/pendingBuffers/重连/退避) | **「事件序列进→快照出」黄金路径**:可编程假体 + deferred 控时序 + fake timers 控退避 | `packages/client/{runtime,connection}/tests/` | -| 3 组装呈现层 | 构建产物 × 真实 client loader 与插件组合 | 归应用所有的语义快照会在 jsdom 下启动全部 8 个已构建的 client 插件,以固定确定性的跨插件状态变化;独立使用 Playwright 裸库的冒烟测试负责验证真实浏览器/承载层边界,真 host 用例在无密钥时自行跳过 | `apps/web/tests/*.snapshot.ts`、`apps/web/tests/smoke-{fixture,real}.e2e.ts` | +| 3 组装呈现层 | 构建产物 × 真实 client loader 与插件组合 | 归应用所有的语义快照会在 jsdom 下启动全部 8 个已构建的 client 插件,以固定确定性的跨插件状态变化;独立使用 Playwright 裸库的冒烟测试负责验证真实浏览器/承载层边界,真 host 用例在无密钥时自行跳过;无密钥浏览器 e2e 车道把录制的会话 fixture 通过真实进程内 web 组装(`llm: false` + dsh-llm-replay)回放,与会话区 aria 期望输出比对([web e2e 车道](../testing/2026-07-24-web-gui-browser-e2e-lane.md)) | `apps/web/tests/*.snapshot.ts`、`apps/web/tests/smoke-{fixture,real}.e2e.ts`、`apps/web/tests/{replay-round-trip,seeded-history}.e2e.ts` | 层间纪律:**下层各测各的,上层不重测下层**:应用语义快照只固定组装后插件边界上的用户可见投影,Playwright 冒烟测试负责验证浏览器与承载层是否存活;wire 语义归 1 层,数据语义归 2 层。纯函数层(lineage/partial/notifier/fold-adapter)随 2 层同包 tests/ 零假体直测。 @@ -33,15 +33,15 @@ GUI 栈需要考虑多种应用形态,同应用形态内的不同运行环境 |---|---|---|---| | 基础 | `pnpm run test:gui` | 1+2 层 vitest(`packages/client packages/host`),秒级、无浏览器无 server | 改 GUI 任意源码后随手跑 | | 语义快照 | `DSH_EXAMPLE_MODE=lib pnpm run test:snapshot` | 无需密钥的组装应用语义,以及仓库按传输形态划分的预期输出 | 用户可见的 GUI 变更后;交付前 | -| 浏览器端到端 | `pnpm run test:web` | 先重建前端 dist,再跑 3 层双级 smoke(fixture 级 + 真 host 级 self-skip) | 改构建面/boot/承载后;交付前 | +| 浏览器端到端 | `pnpm run test:web` | 先重建前端 dist,再跑 3 层浏览器全集:双级 smoke(fixture 级 + 真 host 级 self-skip)加上无密钥回放 e2e 场景(`DSH_SNAPSHOT=record`/`refresh` 重录 fixture / 重写期望输出) | 改构建面/boot/承载后;交付前 | | 门禁 | `pnpm run test:coverage` | 全仓 gate(host 与 client GUI 包均纳入,仅排除带注释的浏览器级例外) | PR 窗口 | **浏览器脚本与 vitest 的分工**:Playwright 负责浏览器/承载层黑盒回归和较长的连续用户操作流程;普通 vitest 负责引用稳定性、时序和 wire 结构等数据层语义;快照 vitest 通过构建后的组合负责稳定的应用层语义输出。这些车道彼此互补,而不重复断言。 ## 防回归纪律 -- **修一个 bug 钉一条断言**:浏览器可见的 bug 钉进所属 verify 脚本的回归节(一钉一行 report);数据层 bug 钉进对应 spec(先例:res-close 误判钉在 webserver 桥 suite——纯 Node 秒级复现,不再需要 12s 浏览器哨兵作唯一防线)。 -- **fixture 全绿不算完,真 host 也要过**:fixture 短路的恰是 wire 承载链(node:http 桥 close 语义、真网络时序),两次实证 bug 都藏在那里。改动触及连接/桥/handler/SSE 的,`verify-session-real` 必跑。 +- **修一个 bug 钉一条断言**:浏览器可见的 bug 钉进所属浏览器 spec(smoke 或 e2e 场景);数据层 bug 钉进对应 spec(先例:res-close 误判钉在 webserver 桥 suite——纯 Node 秒级复现,不再需要 12s 浏览器哨兵作唯一防线)。 +- **fixture 全绿不算完,真 wire 也要过**:fixture 短路的恰是 wire 承载链(node:http 桥 close 语义、真网络时序),两次实证 bug 都藏在那里。改动触及连接/桥/handler/SSE 的,浏览器车道(`pnpm run test:web`)必跑——其无密钥 e2e 场景驱动真实 HTTP/SSE 承载,带密钥的真 host smoke 仍是真模型侧的补充。 - 落盘代码即答案的对表工作流:行为改动落盘打红既有用例时,当场对表校准(改测试还是改代码以 RFC/契约为裁),不留悬红。 ## Consequences diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md new file mode 100644 index 0000000000..fddd1e9a0c --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md @@ -0,0 +1,88 @@ +# Agent Note: Keyless browser e2e lane for the web GUI + +Status: implemented + +## Problem + +The web GUI ships as a real assembled chain — chromium page → client plugin bundles → HTTP unary RPC + two SSE streams → `toFetchHandler`/apiproxy → `bootHost`'s agent loop, tools, and JSONL persistence — and no test exercised that chain keylessly and deterministically. The [GUI testing system](../process/2026-07-20-gui-testing-system.md) covers tier 1 (wire isomorphism in node), tier 2 (object-layer state machines), and tier-3 smokes, but the keyless smoke drives `FixtureApiClient` — no host, no wire, no agent loop — while the full-chain smoke needs `DEEPSEEK_API_KEY` and a live model, so it is nondeterministic and self-skips in keyless CI. The snapshot philosophy of [docs/testing.md](../../../../docs/testing.md) — record once with a key, replay forever keyless, refresh on format churn — already covers the ACP, headless `stream-json`, and TUI transcript surfaces; the web surface was the one assembled product shape without it. The gap is exactly where the two confirmed GUI P0s hid: the wire carriage chain the fixture client short-circuits. + +## Decision + +`pnpm run test:web` carries a keyless, deterministic browser e2e lane under `apps/web/tests/`: recorded session-log fixtures replayed through `@deepseek-ai/dsh-llm-replay` against the real in-process web assembly, asserting a normalized conversation aria golden plus in-process world state. No new package; the product deltas are the `BootHostOptions.llm` seam and two additive `dsh-llm-replay` surfaces. + +### Harness: `apps/web/tests/harness.ts` + +A plain shared-fixture module (the [testing-policy sanctioned shape](../../../../docs/testing.md)), not a package: the gate-worthy logic — replay derivation, session parsing, log scrubbing, persistence — lives in the gated packages `dsh-llm-replay`, `dsh-acp-snapshot`, and `dsh-session-persistence-jsonl`; what remains is boot wiring and browser glue, and chromium-driving code cannot hold per-file 100% coverage on the browserless coverage runners. + +`launchWebHarness()` boots the real web assembly in-process from the exported production functions — `startHost({ boot: { …, llm: false } })`, `installLlmReplay(host.ctx, { file, providers, paceMs })`, `mountWebPlugins(host.ctx, roster, anchor)`, `createHostWebPluginRegistry`, `startWebServer({ port: 0, … })`. This is the web analog of the TUI suite mounting the production bundle in-process ([TUI snapshots](2026-07-18-tui-terminal-state-snapshots.md)): the real entry boundary (`dsh web` bin arg-parsing, dist resolution) stays held by the keyless CLI smokes in `smoke-real.e2e.ts`, and the web surface has no `cordis.yml` to bypass — assembly is written in the app per the [GUI layering decision](../architecture/2026-07-19-gui-layering-and-rpc-protocol.md), a ruling this lane's design review explicitly reaffirmed (Loader-izing `dsh web` was declined; it would be its own proposal). Two deliberate assembly divergences from the `dsh web` shell, noted in the harness header: `workspaceContext: false` (recorded fixtures must not embed this repo's AGENTS.md) and `sessionTitleLlm` left at bootHost's disabled default (its fire-and-forget title call would share the session's replay cursor nondeterministically). + +The `llm: false` seam is the reviewed resolution of the keyless-boot question: `'deepseek' | false` on `BootHostOptions`, matching the `workspaceContext: Config | false` shape, with `RunningHost.ctx` JSDoc naming "filling a deliberately-open capability seam" as its third sanctioned use. Replay runs in providers-catalog mode with a published `contextWindow` (the TUI `PROVIDERS` shape), never catch-all: with no adapter registered, catch-all would leave `resolveModelContext` unroutable and `compact-basic`'s post-step pressure check would warn every step instead of being provably inert. + +`seedSession()` seeds cold sessions through the real persistence API — a throwaway `Context` mounting `SessionStore` + `SessionPersistenceJsonl` against the host's root, `create()` + `append()`, one `utimes` backdate for deterministic sidebar order (the `semantic-checkpoint.snapshot.ts` precedent) — never raw file writes, so the seeder knows nothing of bucket hashing, filename encoding, or compression, and the host's zstd default needs no boot knob. Seeds are validated at seed time (parseable, ending in `turn/end` — an open final turn would be mutated by resume's crash repair). + +### Determinism rules + +The barrier stack for a prompted turn, in order: (1) host-side `await agent.whenIdle()` under a timeout, keyed off the in-process `turn/end` — the idle flip follows the persistence flush, so one await covers turn completion and durability; (2) browser settled poll (streaming detached, final text visible); (3) any log harvest after `host.dispose()`. An in-process `turn/end` listener alone is a wrong barrier (it fires before the SSE frame reaches the browser and before the fsync); file polling is banned (slow on NFS, superseded by `whenIdle`); `networkidle` is banned outright (never resolves while an SSE stream is open). + +No single-shot transient-DOM assertions: every hop from replay yield to React commit can coalesce chunks, so sampling `[data-streaming]` is a race by construction. Streaming incrementality is asserted from the persisted `assistant/chunk` events (model-visible ⟺ logged makes the log the authoritative proof). `dsh-llm-replay`'s opt-in `paceMs` (default absent = burst) is a realism knob so the browser observes genuinely incremental SSE; correctness never leans on it, and abort during a pace wait cancels promptly. + +Every scenario fails on any pageerror and on the client's connection-loss/gap-repair console warnings: the reconnect machine plus history resync would otherwise self-heal a dead SSE path and the suite would certify a broken wire. Harness `close()` calls the `ReplayHandle.assertConsumed()` teardown check (every recorded script bound, every cursor drained), converting silent underruns and shifted bindings into crisp diagnostics. No vitest retry on the lane; one chromium per file, fresh context per scenario, one host per scenario; viewport pinned; selectors anchor on roles, `data-*` attributes, and visible text. + +### Expected outputs + +One committed golden per scenario: a normalized `ariaSnapshot()` of the conversation region (`ui.expected.md`) — uuid/cwd/workspace-basename/duration tokens normalized, captured poll-until-equal at the settled milestone — plus a few role/text anchor assertions that stay green under a semantics-preserving component rewrite while the golden churns reviewably. The aria tree is the mechanization of the client rule "assert what the user would see, never class names". World-state assertions ride `host.ctx` session events inline (which tools ran, `turn/end` completed) instead of a second committed log golden: the persisted-log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence, and re-pinning it here would double refresh cost against the tier discipline. `refresh` is the sole golden writer — a missing golden in replay mode fails with the healing command rather than self-bootstrapping. + +The typecheck plane split is structural: `apps/web/tests/{harness,support,replay-round-trip.e2e,seeded-history.e2e}.ts` are host-plane programs (they boot the host spine), so they are excluded from the client-registered `apps/web` project and included file-by-file in `tsconfig.host.json` — one program cannot hold both sides of the cordis `Context` merges. + +### Modes and fixtures + +`DSH_SNAPSHOT` selects replay (default, keyless), record (with key), or refresh (keyless) as inline spec branches — the TUI shape, not a suite factory: at two scenarios the acp-snapshot factory machinery has no owner, and the genuinely shared parts are already exported (`scrubRequestHeaders`, `parseSessionLog`, `installLlmReplay`). Each spec splits into drive steps (type, send, `whenTurnSettled` — run in all modes, never waiting on model-content selectors, so record cannot hang on a live model answering differently) and assertion steps (replay/refresh only). Record = drive live through the real composer + harvest the in-memory `session.header`/`session.events` (the TUI `rawSessionLog` shape — no file decompression) + `scrubRequestHeaders` + `{{sessionId}}`/`{{cwd}}` tokenization; a follow-up keyless refresh regenerates `ui.expected.md`. Both scenarios' fixtures were recorded against this assembly through this flow. A drift guard ties each spec's drive prompt to the fixture's recorded `user/message`. A fixture-inventory guard holds each scenario directory closed (exact file set, every JSONL a scrub fixed-point). Web fixtures scrub headers everywhere and pin no header class, following the TUI precedent over the strict [pinned-header](2026-07-06-pin-request-header-content-in-one-scenario.md) reading — see Deferred. + +### Scenarios + +1. **`replay-round-trip`** — new session, prompt through the real composer, replay streams reasoning + a `bash` tool call that really executes in the temp workspace + final text (paced 15ms). Asserts settled markdown, the aria golden, and inline world state (bash `tool/call`, completed `turn/end`, >10 chunk events). +2. **`seeded-history`** — a recorded session seeded cold; the sidebar lists it (group row → session row, collapsed by default), opening renders tool cards and text purely from the log through the implicit cold-resume attach inside `session.history` — zero model calls in replay, so no binding constraints; record mode drives the same turn live (real `read` tool against seeded workspace files) to produce the seed. + +### CI stance + +The lane ships gate-exempt inside `pnpm run test:web`, exactly as that config's header records. Adding chromium to CI would reverse the "no browser infrastructure in CI" premise in the [GUI testing note](../process/2026-07-20-gui-testing-system.md) and therefore requires its own Agent Note cross-linked from there, staged as a non-required job first with measured promotion criteria (consecutive green runs, wall time, zero-retry flake budget, runner browser-cache strategy). `TODO(ci-browser)` marks the seam. Scenarios are POSIX-oriented (the lane is not in the Windows matrix). + +## Prior art + +Surveyed AI-chat/agent web UIs and mocking layers (LibreChat, vercel/ai-chatbot + AI SDK, lobe-chat, open-webui, OpenHands, Chainlit, continue, cline, langfuse, gradio/streamlit; Playwright HAR/route, MSW, Polly/nock, WireMock, aimock). The dominant proven architecture for apps that own their backend is an in-process fake/replay model behind the real backend seam with everything downstream real (LibreChat's `LIBRECHAT_TEST_RUN_HOOK` fake model; ai-chatbot's `MockLanguageModelV3` + `simulateReadableStream`; continue's scripted mock provider classes) — which is what `dsh-llm-replay` already is. Browser-level SSE interception cannot exercise incremental rendering (`route.fulfill` delivers the whole body at once; playwright#33564) and leaves the server SSE stack untested, so projects use it only for edge cases. Chunk pacing as a fixture parameter recurs everywhere (LibreChat 10ms default with slow profiles; ai-chatbot 500ms); real models in CI rot (open-webui's suite grew 120-second timeouts, was disabled, then deleted); sessions are seeded at the persistence layer with controlled timestamps (LibreChat inserts backdated Mongo documents; langfuse seeds its DB). No surveyed project replays a recorded agent-event log through the real backend for UI tests — the closest are provider-level recorded fixtures (aimock) and frontend-level socket history emission (OpenHands MSW) — so the session-log-as-fixture design goes one step beyond prior art along the axis this repo's model-visible ⟺ logged invariant makes natural. + +## Alternatives considered + +**Browser-network SSE interception (`page.route`).** Rejected: `route.fulfill` cannot stream, so incremental token rendering is unexercisable and the server-side SSE/backpressure/close path — where both confirmed P0s hid — goes untested. + +**Mock HTTP provider at `DEEPSEEK_BASE_URL`.** Rejected as the lane's mechanism (kept for the one existing workspace-probe smoke): fixtures become hand-authored OpenAI SSE byte scripts, a second fixture format that drifts from the session-log format the rest of the repo records and replays; the adapter's real HTTP path is with-key e2e's job. + +**Growing the `?fixture` client.** Rejected: tier separation — `FixtureApiClient` exists to test the client shell without a server; everything below the client API seam stays untested by construction. + +**Placeholder `DEEPSEEK_API_KEY` + replay interception instead of the `llm: false` seam.** Rejected despite zero product change and two in-tree precedents: it satisfies `llm-deepseek`'s fail-loud key check with a lie and leaves a dead adapter mounted-but-intercepted; the seam matches an existing option shape and fails loud at the earliest resolvable point. + +**A `packages/support/web-snapshot` package with a `defineWebSnapshotSuite` factory.** Rejected: chromium-driving source cannot honestly hold per-file 100% coverage on browserless coverage runners, and at two scenarios a factory generalizes from one consumer while the genuinely shared logic is already exported from gated packages. Re-entry trigger: a second web-shaped consumer or ≥6 scenarios with demonstrably drifting inline branches; the package boundary would then be drawn browser-free. + +**A committed normalized-session-log golden as a second expected surface.** Rejected: the log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence; here it would double refresh cost and re-test lower tiers. Inline world-state assertions on `host.ctx` events keep the world-verification duty. + +**Spawning the `dsh web` bin with a `DSH_SNAPSHOT` replay branch.** Rejected: it needs a test-mode branch plus env plumbing in the product bin where the in-process route uses exported production functions; the bin's thin glue is covered by the keyless CLI smokes. Becomes free only if the web host is ever Loader-ized — declined in review, with the app-assembly ruling reaffirmed. + +**Changing the wire protocol for testability.** Rejected: the contract already has a first-class keyless isomorphic seam (`InProcessApiClient(toFetchHandler(api))`), the per-event unbatched SSE is exactly what makes replay observable in a browser, and testing a wire we no longer ship would invert the tier's purpose. + +**Real-model browser tests as the keyless lane.** Rejected: nondeterministic by construction; the surveyed cautionary case (open-webui) grew unbounded timeouts and was deleted. The with-key W5 smoke stays as the live-model complement. + +**A client `data-dsh-busy` settled signal.** Deferred: the multi-condition settled polls proved sufficient at two scenarios and the host-side `whenIdle` barrier does the heavy lifting. Re-entry trigger: the first settled-poll flake, or a scenario needing a state the DOM does not expose. + +## Testing + +The lane itself: `pnpm run test:web` runs both scenarios keylessly alongside the existing smoke pair; `DSH_SNAPSHOT=record pnpm exec vitest run --config vitest.web.config.ts apps/web/tests/` re-records a scenario's fixture against the live model; `DSH_SNAPSHOT=refresh` rewrites both aria goldens keylessly. The `llm: false` seam is pinned by `packages/host/runtime/tests/host-runtime.spec.ts` (keyless boot, NO_ADAPTER at first stream, embedder fill through ctx); `paceMs` validation, pacing floor, abort-during-pace, and both `assertConsumed` failure shapes are pinned in `packages/support/llm-replay/tests/llm-replay.spec.ts`. + +## Deferred + +- **Web header-class pin**: web fixtures tokenize `{{system}}`/`{{tools}}` everywhere and no scenario pins bootHost's composed prompt/tool schemas (`TODO(web-header-pin)` — the harness `recordFixture` JSDoc marks it). Following the TUI scrub-everywhere precedent; revisit when the web assembly's header diverges from the repl composition it mirrors. +- **CI browser provisioning**: reversal of the no-browser-in-CI ruling, staged criteria above (`TODO(ci-browser)`). +- **Follow-up-prompt-after-resume scenario**: the history/live stitch path over the real wire; add as its own scenario when that code changes or regresses. + +## Consequences + +The web surface gains its record-once/replay-forever tier: the real chromium → SSE → apiproxy → loop → tools → persistence chain runs keylessly in ~10-30s, deterministic across repeat runs, with fixtures owned and re-recordable by the lane itself. Costs accepted: every intentional conversation-UI change ends with a keyless `DSH_SNAPSHOT=refresh` (golden churn is reviewed diff, anchors keep semantic green); the aria format is Playwright-owned — the one committed snapshot format the repo does not control — so playwright version bumps must be deliberate bump-and-refresh commits (the dependency floats `^1.49.0` in `apps/web/package.json`; pin exactly if churn bites); replay's first-call-order binding constrains scenarios to one prompting session each, with the consumption assertion as the tripwire; `compact-basic` shares the session's replay cursor and stays inert only under the published 128k catalog window; and the lane guards regressions only where it runs (locally, `test:web`) until the CI reversal is separately decided. diff --git a/.agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md deleted file mode 100644 index cc7504dae7..0000000000 --- a/.agents/notes/proposed/testing/2026-07-24-web-gui-browser-e2e-lane.md +++ /dev/null @@ -1,92 +0,0 @@ -# Agent Note: Keyless browser e2e lane for the web GUI - -Status: proposed - -## Problem - -The web GUI ships as a real assembled chain — chromium page → nine client plugin bundles → HTTP unary RPC + two SSE streams → `toFetchHandler`/apiproxy → `bootHost`'s agent loop, tools, and JSONL persistence — and no test exercises that chain keylessly and deterministically. The [GUI testing system](../../implemented/process/2026-07-20-gui-testing-system.md) covers tier 1 (wire isomorphism in node), tier 2 (object-layer state machines), and a tier-3 smoke pair, but the keyless smoke (`apps/web/tests/smoke-fixture.e2e.ts`) drives `FixtureApiClient` behind `?fixture` — no host, no wire, no agent loop — while the full-chain smoke (`smoke-real.e2e.ts`) needs `DEEPSEEK_API_KEY` and a live model, so it is nondeterministic and self-skips in keyless CI. The snapshot philosophy of [docs/testing.md](../../../../docs/testing.md) — record once with a key, replay forever keyless, refresh on format churn — already covers the ACP, headless `stream-json`, and TUI transcript surfaces; the web surface is the one assembled product shape without it. The gap is exactly where the two confirmed GUI P0s hid: the wire carriage chain the fixture client short-circuits. - -## Proposal - -Add a keyless, deterministic browser e2e lane under `apps/web/tests/`, driven by recorded session-log fixtures replayed through `@deepseek-ai/dsh-llm-replay`, asserting the rendered accessibility tree plus in-process world state. No new package; no product-code change except (open question 1) an LLM composition knob. - -### Harness: `apps/web/tests/harness.ts` - -A plain shared-fixture module (the [testing-policy sanctioned shape](../../../../docs/testing.md)), not a package: the gate-worthy logic this lane needs — replay derivation, session parsing, log scrubbing, persistence — already lives in gated packages (`dsh-llm-replay`, `dsh-acp-snapshot`, `dsh-session-persistence-jsonl`); what remains is boot wiring and browser glue, and chromium-driving code cannot hold per-file 100% coverage on the browserless coverage runners. - -`launchWebHarness()` boots the real web assembly in-process from the exported production functions — `startHost({ boot: { persistenceRoot: , workspaceContext: false, cwd: } })`, `installLlmReplay(host.ctx, { file, childFiles, providers })`, `mountWebPlugins(host.ctx)`, `createHostWebPluginRegistry`, `startWebServer({ port: 0, distIndex, apiHandler: host.handler, webPlugins })` — and returns `{ baseUrl, host, workspaceCwd, close }`. This is the web analog of the TUI suite mounting the production bundle in-process ([TUI snapshots](../../implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)): the real entry boundary (`dsh web` bin arg-parsing and dist resolution) stays held by the existing keyless CLI smokes in `smoke-real.e2e.ts`, and the web surface has no `cordis.yml` to bypass — assembly is written in the app per the [GUI layering decision](../../implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md). Replay runs in providers-catalog mode with a `contextWindow` (the TUI suite's `PROVIDERS` shape), never catch-all: with no adapter registered, catch-all mode would make `compact-basic`'s `resolveModelContext` throw into its post-step catch every step, spamming warnings and silently disabling the pressure path instead of proving it inert. - -`seedSession(host, fixtureText)` seeds cold sessions through the real persistence API — a throwaway `Context` mounting `SessionStore` + `SessionPersistenceJsonl` against the host's root, `create()` + `append()`, one `utimes` for deterministic sidebar order (the precedent is `examples/acp-agent/tests/semantic-checkpoint.snapshot.ts`) — never raw file writes, so the seeder needs no knowledge of bucket hashing, filename encoding, or compression. Seeds are validated at seed time (parseable, `seq`-contiguous, ending in `turn/end`) so fixture drift fails loud at the earliest resolvable point rather than as silently dropped frames in the client; a seed not ending in `turn/end` would be mutated by resume's crash repair. - -### Determinism rules - -The barrier stack, in order, for a prompted turn: (1) host-side `await agent.whenIdle()` under a timeout — the idle flip happens after both the `turn/end` append and the persistence flush, so one await covers turn completion and durability; (2) browser settled poll — streaming node detached, composer restored, final text visible; (3) log harvest only after `host.dispose()`. An in-process `turn/end` listener alone is a wrong barrier (it fires before the SSE frame reaches the browser and before the fsync), and file polling is banned (slow on NFS, superseded by `whenIdle`). For history-open scenarios the barrier is a poll for the last expected message's text, then a poll-until-equal aria capture. `networkidle` is banned outright — it never resolves while an SSE stream is open. - -No single-shot transient-DOM assertions: every hop from replay yield to React commit can coalesce chunks, so sampling `[data-streaming]` is a race by construction. Streaming incrementality is asserted from the persisted `assistant/chunk` events (model-visible ⟺ logged makes the log the authoritative proof), optionally corroborated by an in-page MutationObserver latch armed before send — observers cannot miss a commit; polls can. `dsh-llm-replay` gains an opt-in `paceMs` config field (default absent = today's instant yield) as a realism knob so the browser observes genuinely incremental SSE; correctness never leans on the pace. - -Every scenario fails on any pageerror and on the client's connection-loss/gap-repair console warnings: the reconnect machine plus history resync would otherwise self-heal a dead SSE path and the suite would certify a broken wire. Harness `close()` asserts every replay script was fully consumed (all scripts bound, every cursor at end), converting silent underruns and shifted bindings into crisp diagnostics; this is a small additive stats handle on `installLlmReplay`. No vitest retry on the lane — a retried-green race is a flake deferred, and only the chromium launch itself may retry inside the harness, logged. One chromium per file, fresh browser context per scenario, one host per scenario; viewport pinned; selectors anchor on roles, `data-*` attributes, and visible text only. - -### Expected outputs - -One committed golden per scenario: a normalized `ariaSnapshot()` of the conversation region only (`ui.expected.md`) — uuid/cwd/duration tokens normalized, sidebar and other time-bearing chrome structurally excluded, captured poll-until-equal at the settled milestone. The accessibility tree is the mechanization of the client rule "assert what the user would see, never class names": it survives CSS-module hash churn, styling rewrites, and DOM restructuring, and a wholesale component rewrite refreshes it keylessly. Alongside the golden, three or four targeted role/text anchor assertions (heading level, `pre code` content, tool-row accessible name) keep green anchors under a semantics-preserving rewrite so a churned golden diff is reviewable against surviving anchors. World-state assertions ride `host.ctx` session events inline (which tools ran, `turn/end` completed, no error) instead of a second committed log golden: the persisted-log surface is already pinned by the ACP/headless/TUI suites through the same loop and persistence plugins, and re-pinning it here would double refresh cost for no new regression class. `playwright` gets pinned exactly in `apps/web/package.json` — the aria format is Playwright-owned, the one snapshot format in this repo we do not own, so version bumps must be deliberate bump-and-refresh commits. - -### Modes and fixtures - -`DSH_SNAPSHOT` selects replay (default, keyless), record (with key), or refresh (keyless), as inline branches in the specs — the TUI suite's shape, not a suite-factory: at two scenarios the acp-snapshot factory machinery (scenario tables, pinning classes, Windows sidecars, packed-row stabilization) has no owner, and the genuinely shared parts are already exported (`scrubRequestHeaders`, `normalizeSessionLog`, `parseSessionLog`, `installLlmReplay`). Each scenario script splits into drive steps (type, send, `whenIdle`-generic waits — run in all modes, never waiting on model-content selectors) and interaction/assertion steps (expand reasoning, aria capture — replay/refresh only), so record mode cannot hang on a live model answering with a different tool count. Record = drive + harvest the in-memory `session.header` + `session.events` (the TUI `rawSessionLog` shape — no file decompression, so `bootHost` needs no compression knob) + scrub via `scrubRequestHeaders` + a mandatory keyless refresh to regenerate `ui.expected.md`. Web fixtures scrub headers everywhere and pin nowhere, matching the TUI precedent; whether the web surface must instead own a header-class pin per the [pinned-header discipline](../../implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md) is open question 3. Seeds are recorded fixtures under the same inventory and refresh discipline as replay fixtures, never hand-authored one-offs, so `DSH_SNAPSHOT=refresh` heals every committed surface after intentional shape churn and only `assistant/chunk`-shape churn escalates to re-record. A TUI-style `afterAll` fixture guard holds the inventory closed (expected files present, every fixture scrub-fixed-point, no orphan directories). - -### Demo scenarios - -1. **`fresh-round-trip`** — new session, prompt, replay streams reasoning + markdown + a `bash` tool call that really executes (`echo` in the temp workspace) + final text. Asserts settled markdown semantics (heading, code block), the tool card row, composer restore, the aria golden, and inline world state (bash `tool/call` + completed `turn/end` in the session events). The keyless version of the with-key W5 flows. -2. **`seeded-history`** — a recorded session seeded cold; the sidebar lists it, opening it renders tool cards and collapsible reasoning purely from the log. This exercises the implicit cold-resume attach (`session.history` resumes via `agentFor`), cold summaries, history pagination views, and the client fold of historical events — the surface nothing else covers — with zero model calls, so no replay-binding constraints at all. A follow-up-prompt-after-resume scenario is deliberately deferred until the history/live stitch path changes or regresses. - -### Lane wiring and CI stance - -The lane rides `vitest.web.config.ts` (`pnpm run test:web`, serial), which stays gate-exempt exactly as its header comment records. Adding chromium to CI would reverse the "no browser infrastructure in CI" premise recorded in the [GUI testing system note](../../implemented/process/2026-07-20-gui-testing-system.md) and therefore requires its own Agent Note cross-linked from that note, staged as: non-required CI job first, promotion criteria measured (consecutive green runs, wall time, zero-retry flake budget, browser cache strategy on the enterprise runners, whether the runner images carry the chromium system libraries). Deferred out of this proposal; a `TODO(ci-browser)` marks the seam. Scenarios are `posixOnly` initially. Docs updated in the same implementation PR: the [testing policy](../../../../docs/testing.md) names `apps/web/tests/snapshots/` as the web surface's snapshot home with its divergent `DSH_SNAPSHOT=… pnpm run test:web` commands, the GUI testing note's tier map gains the lane (and drops its stale references to the deleted `missions/scripts/verify-*` files), `packages/client/AGENTS.md`'s check ladder mentions it, and the `dsh-acp-snapshot` README's "ACP-specific by design" sentence is corrected — this lane is the third consumer of its normalizers. - -### Open questions - -1. **LLM seam.** Two viable shapes. (a) `BootHostOptions.llm?: 'deepseek' | false` — an assembly toggle in the one module that owns assembly, matching the existing `workspaceContext: Config | false` shape and the reserved-knob sentence in `start.ts`; `llm: false` mounts no adapter, the harness fills the open seam on `host.ctx`, misuse fails loud at the first stream with `NO_ADAPTER`, and keyless boots stop needing any key. (b) Zero product change — a placeholder `DEEPSEEK_API_KEY` env var satisfies `llm-deepseek`'s load-time presence check (twice-precedented in-tree) and replay intercepts ahead of the mounted adapter. (a) is cleaner semantics and honest keylessness at the cost of a test-motivated product field; (b) is free but satisfies a fail-loud check with a lie and leaves a dead adapter mounted. Recommendation: (a), shaped minimal. -2. **Loader-izing `dsh web`.** Making the web host `cordis.yml`-driven like every example would give the ACP-style `cordis.snapshot.yml` replay overlay for free and align with "everything is a plugin", but it reverses the settled "assembly is written in the app" ruling and is a product-architecture decision on its own merits — its own proposal if wanted; this lane does not need it. -3. **Header-class pin.** Strict reading of the pinned-header discipline wants one web scenario pinning `bootHost`'s composed prompt + tool schemas (a header class no ACP scenario covers); the TUI precedent scrubs everywhere and pins nowhere. Cheap middle: pin sidecars on `fresh-round-trip` at record time. Recommendation: follow TUI now (scrub-only), revisit when the web assembly's header diverges further from the repl composition it mirrors. -4. **Golden breadth.** Full conversation-region aria golden (adopted above) versus targeted assertions only. The golden is the "assembled transcript" duty for user-visible changes; the cost is a keyless refresh on every component rewrite. Recommendation: keep the golden + anchors. -5. **Client settled signal.** A `data-dsh-busy` attribute derived from the object layer's pending-RPC/active-stream state would replace multi-condition settled polls with one selector. Presentation-plane observability, no session-log leak — but the current polls suffice for two scenarios. Recommendation: defer until a settled-poll flake actually appears. - -## Prior art - -Surveyed AI-chat/agent web UIs and mocking layers (LibreChat, vercel/ai-chatbot + AI SDK, lobe-chat, open-webui, OpenHands, Chainlit, continue, cline, langfuse, gradio/streamlit; Playwright HAR/route, MSW, Polly/nock, WireMock, aimock). The dominant proven architecture for apps that own their backend is an in-process fake/replay model behind the real backend seam with everything downstream real (LibreChat's `LIBRECHAT_TEST_RUN_HOOK` fake model; ai-chatbot's `MockLanguageModelV3` + `simulateReadableStream`; continue's scripted mock provider classes) — which is what `dsh-llm-replay` already is. Browser-level SSE interception cannot exercise incremental rendering (`route.fulfill` delivers the whole body at once; playwright#33564) and leaves the server SSE stack untested, so projects use it only for edge cases. Chunk pacing as a fixture parameter recurs everywhere (LibreChat 10ms default with slow profiles; ai-chatbot 500ms); real models in CI rot (open-webui's suite grew 120-second timeouts, was disabled, then deleted); sessions are seeded at the persistence layer with controlled timestamps (LibreChat inserts backdated Mongo documents; langfuse seeds its DB). No surveyed project replays a recorded agent-event log through the real backend for UI tests — the closest are provider-level recorded fixtures (aimock) and frontend-level socket history emission (OpenHands MSW) — so the session-log-as-fixture design goes one step beyond prior art along the axis this repo's model-visible ⟺ logged invariant makes natural. - -## Alternatives considered - -**Browser-network SSE interception (`page.route`).** Rejected: `route.fulfill` cannot stream, so incremental token rendering is unexercisable and the server-side SSE/backpressure/close path — where both confirmed P0s hid — goes untested. - -**Mock HTTP provider at `DEEPSEEK_BASE_URL`.** Rejected as the lane's mechanism (kept for the one existing workspace-probe smoke): fixtures become hand-authored OpenAI SSE byte scripts, a second fixture format that drifts from the session-log format the rest of the repo records and replays; the adapter's real HTTP path is with-key e2e's job. - -**Growing the `?fixture` client.** Rejected: tier separation — `FixtureApiClient` exists to test the client shell without a server; everything below the client API seam stays untested by construction. - -**A `packages/support/web-snapshot` package with a `defineWebSnapshotSuite` factory.** Rejected for now: chromium-driving source cannot honestly hold per-file 100% coverage on browserless coverage runners, and at two scenarios the factory generalizes from one consumer while the genuinely shared logic already lives exported in `dsh-llm-replay`/`dsh-acp-snapshot`. Re-entry trigger: a second web-shaped consumer or ≥6 scenarios with demonstrably drifting inline branches; the package boundary would then be drawn browser-free. - -**A committed normalized-session-log golden as a second expected surface.** Rejected: the log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence; here it would double refresh cost and re-test lower tiers, against the tier discipline. Inline world-state assertions on `host.ctx` events keep the world-verification duty. - -**Spawning the `dsh web` bin with a `DSH_SNAPSHOT` replay branch.** Rejected for now: it needs a test-mode branch plus env plumbing in the product bin where the in-process route uses exported production functions with zero product change; the bin's thin glue is covered by the keyless CLI smokes. Becomes free if the web host is ever Loader-ized (open question 2). - -**Changing the wire protocol for testability.** Rejected: the contract already has a first-class keyless isomorphic seam (`InProcessApiClient(toFetchHandler(api))`), the per-event unbatched SSE is exactly what makes replay observable in a browser, and testing a wire we no longer ship would invert the tier's purpose. - -**Real-model browser tests as the keyless lane.** Rejected: nondeterministic by construction; the surveyed cautionary case (open-webui) grew unbounded timeouts and was deleted. The with-key W5 smoke stays as the live-model complement. - -## Acceptance criteria - -- `pnpm run test:web` keyless passes the two scenarios deterministically (no vitest retry), alongside the existing smoke pair, on a checkout with built client bundles and the frontend dist. -- Replay asserts: aria golden equality at the settled milestone, anchor role/text assertions, inline world-state event assertions, zero pageerrors, zero connection-loss/gap-repair console warnings, all replay scripts fully consumed at teardown. -- `DSH_SNAPSHOT=record` with a key re-records `fresh-round-trip` (drive steps only), rewrites its `session.jsonl` scrubbed, and a follow-up `DSH_SNAPSHOT=refresh` regenerates `ui.expected.md` keylessly; `refresh` alone heals goldens after intentional non-chunk shape churn. -- The seeded scenario renders history through the real cold-resume path with zero model calls and leaves the seed fixture byte-identical (closedness validated at seed time). -- Fixture guard holds the snapshot inventory closed; failure produces a bundle under `.artifacts/` (screenshot, console, pageerrors, persistence copy, actual-vs-expected aria). -- Docs land in the same PR: testing.md web-lane entry, GUI testing note tier map + stale verify-script cleanup, client AGENTS.md ladder, acp-snapshot README correction, this note moved to `implemented/` rewritten in present tense. - -## Risks - -- **The aria format is Playwright-owned** — the one committed snapshot format the repo does not control; a version bump can churn every golden. Mitigated by an exact version pin in `apps/web` and a documented bump-and-refresh procedure; residual risk accepted. -- **Replay's first-call-order binding** stays fragile under concurrent browser-driven sessions; the lane constrains scenarios to one prompting session each (the seeded scenario prompts none), and the teardown consumption assertion turns violations into diagnostics rather than surreal transcripts. -- **`compact-basic` shares the session's replay cursor** — a pressure-triggered summarize would consume a script entry; inert for small fixtures under the 128k catalog window, and the consumption assertion catches it if a fixture ever grows past the threshold. -- **CI remains browserless for now**, so the lane guards regressions only where it is run (locally and in any future non-required job) until the CI reversal is separately decided; the runner images' chromium-library situation is unverified. -- **Record-mode nondeterminism** is contained but not eliminated by the drive/assert split: a live model may still produce a transcript whose replay violates a scenario's assertions, requiring prompt tuning at record time (bounded by terse prompts and a chunk-count warning in record mode). -- **jsdom-lane overlap**: component-level rendering is already covered per-plugin; this lane must stay at assembled-transcript altitude (whole-region golden + anchors) or it starts re-testing tier 2 and paying double maintenance. diff --git a/apps/web/tests/harness.ts b/apps/web/tests/harness.ts index 6f885da0c8..71c3ac9344 100644 --- a/apps/web/tests/harness.ts +++ b/apps/web/tests/harness.ts @@ -243,11 +243,11 @@ export function rawSessionLog(session: Session): string { /** * Record-mode fixture write-back: harvest the live session, scrub request - * headers to {{system}}/{{tools}} (the web lane pins no header class — a - * deliberate deviation logged in the Agent Note's deferred work), tokenize - * the run-local session id and cwd ({{sessionId}}/{{cwd}}, the committed ACP - * fixture convention — re-records then diff only on real content), and write - * the committed fixture. + * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no + * header class — a deliberate deviation logged in the Agent Note's deferred + * work), tokenize the run-local session id and cwd ({{sessionId}}/{{cwd}}, + * the committed ACP fixture convention — re-records then diff only on real + * content), and write the committed fixture. * @param harness - the record-mode harness. * @param sessionId - the driven session. * @param fixturePath - the committed session.jsonl / seed.jsonl target. diff --git a/docs/testing.md b/docs/testing.md index 85798cee3e..5841cd5f29 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -8,6 +8,7 @@ How this repo tests, tier by tier, and the rules that keep a green suite meaning - **Coverage gate** (`pnpm run test:coverage`): the gating run, per-file 100% on `packages/*/*/src`. An uncovered line is often dead code the gate is correctly flagging for deletion, not a missing test to bolt on. Line coverage is necessary, never sufficient — it proves lines ran, not that the feature works as shipped. - **Real-API e2e** (`pnpm run test:e2e`): with-key tests against live provider APIs — the DeepSeek model plus provider-specific smokes that gate on their own keys (`EXA_API_KEY`, `PERPLEXITY_API_KEY`, …); each suite self-skips without its key so keyless CI stays green ([real-API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md)). - **Snapshot** (`pnpm run test:snapshot`): transport-specific keyless expected outputs cover external presentation. ACP suites boot the real example subprocess, replay a recorded session, and diff normalized JSON-RPC plus the re-persisted log ([ACP snapshot Agent Note](../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md)); the headless suite independently pins `stream-json` through its real one-shot subprocess. TUI completed journeys replay recorded primary/child JSONL through the real agent loop and tools before projecting ANSI into semantic terminal-state expected outputs; package-local snapshots retain transient renderer states, and a real PTY conversation covers the process boundary ([TUI snapshot Agent Note](../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)). Use `pnpm run test:snapshot:record` when a model transcript must change and `pnpm run test:snapshot:refresh` when committed replay input remains correct; review every JSONL and expected-output diff. System-prompt/tool-schema content is pinned by one ACP scenario (`text-turn`) and tokenized in every other fixture, so a prompt or schema edit churns one committed line ([pinned-header Agent Note](../.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)). +- **Web browser snapshot** (inside `pnpm run test:web`, gate-exempt like the rest of that lane): the web GUI's keyless assembled-transcript tier — a real chromium over the real in-process web assembly (`llm: false` + `dsh-llm-replay`), scenario fixtures and normalized conversation aria goldens under `apps/web/tests/snapshots/`. Its record/refresh commands diverge from `test:snapshot` (`DSH_SNAPSHOT=record pnpm run test:web` re-records against the live model; `DSH_SNAPSHOT=refresh` rewrites goldens keylessly); the [web e2e lane Agent Note](../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md) owns the design, and CI browser provisioning is deferred there. ## The with-key policy: inference is cheap here @@ -41,4 +42,4 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword ## When a snapshot test is required -Every non-trivial model- or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP surfaces use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. Completed interactive-terminal journeys use JSONL-driven scenarios under `examples/tui-agent/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness can express it before implementation. +Every non-trivial model- or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP surfaces use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. Completed interactive-terminal journeys use JSONL-driven scenarios under `examples/tui-agent/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. Browser-rendered web GUI journeys use `apps/web/tests/snapshots/` through the web e2e lane's harness. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness can express it before implementation. diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index 5bde15dc2c..3c96ac1e85 100644 --- a/packages/client/AGENTS.md +++ b/packages/client/AGENTS.md @@ -65,7 +65,7 @@ The GUI test structure (three tiers, lane map) is settled in the [GUI testing sy Run the narrowest rung that covers what you touched; escalate only when the change surface demands it. 1. **Every GUI code change** — `pnpm run test:gui` (seconds; no browser, no server): the client suites plus the host-side GUI packages. This is the inner loop; run it as freely as a typecheck. -2. **Changes to the build surface, boot wiring, or static serving** (`apps/web`, vite config, `dsh-host-webserver`) — additionally `pnpm run test:web`: rebuilds the frontend dist, then runs the browser smoke pair (the real-host case self-skips without `DEEPSEEK_API_KEY`). +2. **Changes to the build surface, boot wiring, static serving, or the wire carriage** (`apps/web`, vite config, `dsh-host-webserver`, connection/handler/SSE) — additionally `pnpm run test:web`: rebuilds the frontend dist, then runs the browser smoke pair (the real-host case self-skips without `DEEPSEEK_API_KEY`) plus the keyless replayed e2e scenarios (`DSH_SNAPSHOT=refresh` rewrites their aria goldens after an intentional conversation-UI change; `DSH_SNAPSHOT=record` re-records fixtures with a key). 3. **Before a PR** — `pnpm run check:pre-push` (the repo-wide gate ladder). Between PR windows this rung is not expected on every commit. If `test:gui` is red on code you did not touch, neither silently fix nor ignore it: note it in your handoff so it lands in the next PR window's sweep. diff --git a/packages/support/acp-snapshot/README.md b/packages/support/acp-snapshot/README.md index 05a4974c19..1243cd5026 100644 --- a/packages/support/acp-snapshot/README.md +++ b/packages/support/acp-snapshot/README.md @@ -42,7 +42,7 @@ Every scenario compares `stdout.expected.jsonl` with cwd-rooted separators canon The example also ships a `cordis.snapshot.yml` replay overlay next to its `cordis.yml` (the bin swaps them under `DSH_SNAPSHOT=replay` — [single-source replay config Agent Note](../../../.agents/notes/implemented/testing/2026-07-04-single-source-acp-replay-config.md)); replay fixtures are served by [`dsh-llm-replay`](../llm-replay/README.md), which this package points at via the `DSH_SNAPSHOT_*` env vars it sets on the child. `pnpm run test:snapshot:record` calls the live LLM and rewrites the recorded scenarios' model fixtures; `pnpm run test:snapshot:refresh` stays keyless, runs the replay overlay, and rewrites stdout, comparable session-log expected outputs, and each pin's prompt and tool-schema sidecars from the committed model scripts. Fixture roles, record/replay/refresh semantics, and scenario-table fields are documented on `Scenario` and in the [snapshot Agent Note](../../../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md). -Constraints: `suite.ts` imports vitest, so the package entry is importable only inside a vitest run (the launcher, harness, and normalizers have no such dependency but ship from the same entry). ACP-specific by design — the launcher speaks the SDK's `ClientSideConnection`. Permission round-trips are scriptable: `InputScript.permissionAnswers` is a FIFO queue of option-kind selections (`allow_once`, `reject_once`, …) the client maps to the agent-issued `optionId` at answer time; an absent or exhausted queue answers `cancelled`, and a kind the request never offered rejects the run (the agent is answered `cancelled`, so a tolerant agent cannot absorb the scenario bug). Session config options are scriptable too: the `setConfigOption` step switches a knob over `session/set_config_option`, and `setConfigOptionExpectError` asserts the bridge rejects an unknown id or out-of-vocabulary value (the error frame stays in the transcript). +Constraints: `suite.ts` imports vitest, so the package entry is importable only inside a vitest run (the launcher, harness, and normalizers have no such dependency but ship from the same entry). The launcher and suite factory are ACP-specific by design — the launcher speaks the SDK's `ClientSideConnection` — while the normalizers are transport-neutral session-log/text helpers also consumed by the TUI snapshot suite and the web browser e2e lane. Permission round-trips are scriptable: `InputScript.permissionAnswers` is a FIFO queue of option-kind selections (`allow_once`, `reject_once`, …) the client maps to the agent-issued `optionId` at answer time; an absent or exhausted queue answers `cancelled`, and a kind the request never offered rejects the run (the agent is answered `cancelled`, so a tolerant agent cannot absorb the scenario bug). Session config options are scriptable too: the `setConfigOption` step switches a knob over `session/set_config_option`, and `setConfigOptionExpectError` asserts the bridge rejects an unknown id or out-of-vocabulary value (the error frame stays in the transcript). ## Model Experience diff --git a/vitest.web.config.ts b/vitest.web.config.ts index de220c9f12..bcca93e5dd 100644 --- a/vitest.web.config.ts +++ b/vitest.web.config.ts @@ -1,10 +1,13 @@ import tsconfigPaths from 'vite-tsconfig-paths' import { defineConfig } from 'vitest/config' -// Web smoke lane (GUI, gate-exempt — not part of the CI sequence yet): built -// page + real chromium, so it lives outside the unit/e2e includes. The -// real-host test self-skips without DEEPSEEK_API_KEY; the fixture test is -// keyless and deterministic. +// Web browser lane (GUI, gate-exempt — not part of the CI sequence yet): +// built page + real chromium, so it lives outside the unit/e2e includes. The +// real-host smoke self-skips without DEEPSEEK_API_KEY; the fixture smoke and +// the replayed e2e scenarios are keyless and deterministic. +// TODO(ci-browser): running this lane in CI requires chromium provisioning +// and reverses the no-browser-in-CI ruling — staged criteria in +// .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md. try { // Node >= 21.7 native; throws when the file does not exist. process.loadEnvFile(new URL('.env', import.meta.url).pathname) From ee5132c1e190759c10daa6c0dd8fa47e08b27c28 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 20:01:38 +0800 Subject: [PATCH 023/113] refactor(cli): dispatch web as a reserved token, drop parse machinery Simplify the Commander adapter now that behavior can change: dispatch a leading `web` token to its own parser instead of a subcommand of the root program, and read opts()/processedArgs after parse() instead of action closures with a mutable holder. This removes enablePositionalOptions(), the parent-option leak guard, both action closures, and the --resume/--prompt argParser threading. Behavior changes: `dsh -p x web` is a headless prompt (extra positional dropped), `dsh web -p x` fails loud (web has no -p), and a repeated --resume is natural last-wins. The two real fail-loud invariants stay as post-parse checks: an empty --resume= id (agent-loop treats '' as no-resume) and an empty -p task. Trims args.spec.ts to the routing/fail-loud/help behavior that matters; the tui-agent keyless PTY smoke still covers bin.ts dispatch end to end. Net ~114 fewer lines across adapter and tests. --- ...4-dsh-commander-argument-adapter.i18n.yaml | 4 +- ...26-07-24-dsh-commander-argument-adapter.md | 6 +- ...07-24-dsh-commander-argument-adapter.zh.md | 6 +- apps/cli/src/args.ts | 177 ++++++++---------- apps/cli/tests/args.spec.ts | 119 ++---------- 5 files changed, 101 insertions(+), 211 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml index 5dd6055ffe..03b3c8e6f7 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.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 -2026-07-24-dsh-commander-argument-adapter.md: dc2830273b245d370feba0df6ed030045b8444ff -2026-07-24-dsh-commander-argument-adapter.zh.md: ea37a1260ebf81e787f02301bc6fc3c9438c4f75 +2026-07-24-dsh-commander-argument-adapter.md: 4decd926c7fffc8f7d24200f8b91044eaa1d00f1 +2026-07-24-dsh-commander-argument-adapter.zh.md: eaccc221d362804b0aa3081d0593e9dee8af1d4c diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md index dc2830273b..4decd926c7 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md @@ -12,7 +12,7 @@ The `dsh` CLI entry (`apps/cli`) parsed argv in three hand-rolled idioms that di Argv is parsed once, in `apps/cli/src/args.ts`, through a Commander adapter (the same parser the SDK bins — `create-sdk`, `dsh-scripts` — already standardize on). `parseDshArgs(argv, version)` resolves the invocation into a discriminated `DshInvocation` union: `{ mode: 'tui', config?, resume? }`, `{ mode: 'headless', prompt }`, `{ mode: 'web', host, port }`, `{ mode: 'help' | 'version', text }`, or `{ mode: 'error', message }`. Commander runs under `exitOverride()` with output captured, so it never writes or exits on its own — `--help`, `--version`, and every parse error come back as data. -`bin.ts` calls the adapter once and switches on `mode` (closed union, `satisfies never` default), dynamic-importing only the chosen mode's module. Each mode module now consumes already-parsed values: `runTui(config, resume)`, `runHeadless(task)`, `runWeb(host, port)` — none re-reads argv. `web` is a real `program.command('web')` subcommand; `--host` is a Commander `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])` and `--port` an `argParser` that range-checks 0–65535, moving both from the inline `runWeb` checks into the parser. `--resume` uses an `argParser` that rejects both an empty id (`--resume=`) and a repeated flag (`--resume a --resume b`), and `--prompt` rejects an empty task, preserving the old "never silently start fresh" invariant (the deleted `parseResumeArg` failed loud on the same cases). The program sets `enablePositionalOptions()`, and the `web` action rejects a root `--prompt`/`--resume` placed before it, so a misplaced flag (`dsh web -p x`, `dsh -p x web`) fails loud instead of silently serving with defaults. `--version` reads this app's `package.json`. +`bin.ts` calls the adapter once and switches on `mode` (closed union, `satisfies never` default), dynamic-importing only the chosen mode's module. Each mode module now consumes already-parsed values: `runTui(config, resume)`, `runHeadless(task)`, `runWeb(host, port)` — none re-reads argv. `web` is a **reserved first token**: `parseDshArgs` dispatches a leading `web` to its own Commander parser and everything else to the default TUI/headless parser, so root flags and `web` flags never share a grammar — `dsh web -p x` fails loud (`web` has no `-p`) and `dsh -p x web` is just a headless prompt whose second positional is dropped, with no cross-command leakage to guard against. Each parser reads Commander's `opts()`/`processedArgs` after `parse()` rather than through action closures. `--host` is a `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])` and `--port` an `argParser` that range-checks 0–65535, moving both from the inline `runWeb` checks into the parser. Two post-parse checks preserve the "never silently start fresh" invariant: an empty `--resume=` id and an empty `-p` task each become a `mode: 'error'`, because agent-loop treats an empty resume id as no-resume and an empty prompt has nothing to run. A repeated `--resume` is Commander's natural last-wins (the old bespoke scanner rejected it; last-wins is the standard CLI behavior and needs no special case). `--version` reads this app's `package.json`. `parseResumeArg` is deleted from `dsh-app-boot` (its export, its README row, and its unit block); the pre-release stance permits the removal. `dsh-app-boot` keeps its boot/env/config/personal-overlay helpers — only the argv scanner leaves. @@ -26,11 +26,13 @@ The argument surface stays inside `apps/cli`, the assembly tier, not a `packages **Keep `parseResumeArg` as a shared helper and feed it Commander's residual args** — rejected: the whole point is to retire the bespoke scanner. Commander parses `--resume` (space and `=` forms, missing-value, position-independence) natively; keeping a parallel hand-written path for the one flag would preserve the duplication the change exists to end. +**Make `web` a Commander subcommand of one root program** — rejected: a single program mixing a root `-p`/`--resume` grammar with a `web` subcommand leaks the root options onto `web` unless `enablePositionalOptions()` plus a parent-option guard are bolted on, which is exactly the kind of special-case machinery this change removes. Dispatching `web` as a reserved first token to a second parser is smaller and keeps the two grammars fully independent. + **Make the argument surface a `packages/*` seam** — rejected: nothing outside `dsh` consumes it, and capability seams are not split preemptively. The Commander adapter is `apps/cli`'s own concern. ## Testing -`apps/cli/tests/args.spec.ts` (new; `apps/*/tests` added to the vitest include and `apps/cli/tests` to `tsconfig.host.json`) drives the adapter directly: TUI defaults, config positional, `--resume` space/inline forms and their position-independence, empty/valueless/repeated `--resume` rejection, `-p`/`--prompt` routing with empty-prompt and stray-positional rejection, `web` host/port defaults and validation with `--host`/`--port` diagnostics, root flags misplaced around `web` failing loud, excess-argument rejection, and `--help`/`web --help`/`--version`/unknown-option outcomes. The `dsh CLI keyless smoke` group in `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` exercises the real `bin.ts` dispatch end to end through a PTY (default boot, personal overlay, invalid config, `--resume` failure, source-path prompt) and stays green unchanged. `packages/ui/app-boot/tests/app-boot.spec.ts` drops its `parseResumeArg` block. +`apps/cli/tests/args.spec.ts` (new; `apps/*/tests` added to the vitest include and `apps/cli/tests` to `tsconfig.host.json`) covers the adapter at the level that matters: mode routing by shape, the fail-loud checks (empty resume/prompt, bad host/port, unknown option), and `--help`/`--version` surfacing as data. The `dsh CLI keyless smoke` group in `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` exercises the real `bin.ts` dispatch end to end through a PTY (default boot, personal overlay, invalid config, `--resume` failure, source-path prompt) and stays green unchanged. `packages/ui/app-boot/tests/app-boot.spec.ts` drops its `parseResumeArg` block. ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md index ea37a1260e..eaccc221d3 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md @@ -12,7 +12,7 @@ Status: implemented argv 只在 `apps/cli/src/args.ts` 中解析一次,通过一个 Commander 适配器(即 SDK bin,如 `create-sdk`、`dsh-scripts`,已经统一采用的那个解析器)。`parseDshArgs(argv, version)` 将调用解析为一个判别式 `DshInvocation` 联合类型:`{ mode: 'tui', config?, resume? }`、`{ mode: 'headless', prompt }`、`{ mode: 'web', host, port }`、`{ mode: 'help' | 'version', text }` 或 `{ mode: 'error', message }`。Commander 在 `exitOverride()` 下运行并捕获输出,因此它自身从不写出或退出:`--help`、`--version` 和每个解析错误都以数据形式返回。 -`bin.ts` 调用一次适配器,并对 `mode` 做分支切换(封闭联合类型,默认分支为 `satisfies never`),只动态导入所选模式对应的模块。每个模式模块现在只消费已解析好的值:`runTui(config, resume)`、`runHeadless(task)`、`runWeb(host, port)`,都不会再次读取 argv。`web` 是一个真正的 `program.command('web')` 子命令;`--host` 是 Commander 的 `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])`,`--port` 是一个对 0–65535 做范围检查的 `argParser`,二者都从内联的 `runWeb` 检查移入了解析器。`--resume` 使用一个 `argParser`,同时拒绝空 id(`--resume=`)和重复出现的标志(`--resume a --resume b`),`--prompt` 则拒绝空任务,保留旧有的「绝不静默重新开始」不变式(已删除的 `parseResumeArg` 在相同情形下也会显式报错)。程序设置了 `enablePositionalOptions()`,且 `web` 动作会拒绝置于其前的根级 `--prompt`/`--resume`,因此位置错误的标志(`dsh web -p x`、`dsh -p x web`)会显式报错,而不会静默地以默认值提供服务。`--version` 读取本应用的 `package.json`。 +`bin.ts` 调用一次适配器,并对 `mode` 做分支切换(封闭联合类型,默认分支为 `satisfies never`),只动态导入所选模式对应的模块。每个模式模块现在只消费已解析好的值:`runTui(config, resume)`、`runHeadless(task)`、`runWeb(host, port)`,都不会再次读取 argv。`web` 是一个**保留的首个 token**:`parseDshArgs` 将开头的 `web` 分发给它自己的 Commander 解析器,其余一切分发给默认的 TUI/headless 解析器,因此根级标志与 `web` 标志从不共用同一套语法——`dsh web -p x` 会显式报错(`web` 没有 `-p`),而 `dsh -p x web` 只是一个 headless prompt,其第二个位置参数被丢弃,无需防范任何跨命令泄漏。每个解析器都在 `parse()` 之后读取 Commander 的 `opts()`/`processedArgs`,而不是通过 action 闭包。`--host` 是一个 `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])`,`--port` 是一个对 0–65535 做范围检查的 `argParser`,二者都从内联的 `runWeb` 检查移入了解析器。两处解析后的检查保留了「绝不静默重新开始」不变式:空的 `--resume=` id 和空的 `-p` 任务各自变为 `mode: 'error'`,因为 agent-loop 把空的 resume id 视为不恢复,而空的 prompt 没有任何内容可运行。重复出现的 `--resume` 采用 Commander 天然的后者胜出(旧的定制扫描器会拒绝它;后者胜出是标准的 CLI 行为,无需特殊处理)。`--version` 读取本应用的 `package.json`。 `parseResumeArg` 从 `dsh-app-boot` 中删除(包括其导出、README 中的对应行以及单元测试块);预发布阶段的立场允许这次删除。`dsh-app-boot` 保留其 boot/env/config/个人覆盖辅助函数,只有 argv 扫描器被移除。 @@ -26,11 +26,13 @@ argv 只在 `apps/cli/src/args.ts` 中解析一次,通过一个 Commander 适 **保留 `parseResumeArg` 作为共享辅助函数,并向它喂入 Commander 的残余参数。** 已否决:整件事的核心就是要退役这个定制扫描器。Commander 原生解析 `--resume`(空格和 `=` 形式、缺值、位置无关性);为这一个标志保留一条平行的手写路径,只会保留这次变更要终结的重复。 +**把 `web` 做成单个根程序的 Commander 子命令。** 已否决:一个程序若把根级 `-p`/`--resume` 语法与 `web` 子命令混在一起,除非再加上 `enablePositionalOptions()` 和一个父级选项守卫,否则根级选项会泄漏到 `web` 上——而这正是这次变更要移除的那类特殊处理机制。把 `web` 作为保留的首个 token 分发给第二个解析器更小巧,且让两套语法完全独立。 + **把参数解析做成 `packages/*` 的 seam。** 已否决:`dsh` 之外没有任何消费方使用它,而能力 seam 不应被提前拆分。这个 Commander 适配器是 `apps/cli` 自身的事务。 ## 测试 -`apps/cli/tests/args.spec.ts`(新增;`apps/*/tests` 加入 vitest include,`apps/cli/tests` 加入 `tsconfig.host.json`)直接驱动适配器:TUI 默认值、config 位置参数、`--resume` 的空格/内联形式及其位置无关性、对空值/无值/重复 `--resume` 的拒绝、`-p`/`--prompt` 路由及对空 prompt 和游离位置参数的拒绝、`web` 的 host/port 默认值与校验(含 `--host`/`--port` 诊断信息)、围绕 `web` 位置错误的根级标志会显式报错、对多余参数的拒绝,以及 `--help`/`web --help`/`--version`/未知选项的处理结果。`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 中的 `dsh CLI keyless smoke` 组通过 PTY 端到端地运行真实的 `bin.ts` 分发(默认启动、个人覆盖、无效配置、`--resume` 失败、源路径 prompt),且保持绿色不变。`packages/ui/app-boot/tests/app-boot.spec.ts` 移除其 `parseResumeArg` 测试块。 +`apps/cli/tests/args.spec.ts`(新增;`apps/*/tests` 加入 vitest include,`apps/cli/tests` 加入 `tsconfig.host.json`)在关键层面覆盖适配器:按形态进行的模式路由、显式报错检查(空 resume/prompt、错误的 host/port、未知选项),以及 `--help`/`--version` 以数据形式呈现。`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 中的 `dsh CLI keyless smoke` 组通过 PTY 端到端地运行真实的 `bin.ts` 分发(默认启动、个人覆盖、无效配置、`--resume` 失败、源路径 prompt),且保持绿色不变。`packages/ui/app-boot/tests/app-boot.spec.ts` 移除其 `parseResumeArg` 测试块。 ## 影响 diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts index f549c125c3..e45393e8c6 100644 --- a/apps/cli/src/args.ts +++ b/apps/cli/src/args.ts @@ -5,7 +5,8 @@ * already-parsed values instead of re-reading argv. Output is suppressed and * `exitOverride` is set so Commander never writes or exits on its own — every * outcome (including `--help`/`--version` and parse errors) is returned to the - * caller as data. + * caller as data. The `web` subcommand is a reserved first token dispatched to + * its own parser, so root flags and `web` flags never share a grammar. * @module @deepseek-ai/dsh/args */ @@ -57,23 +58,7 @@ export type DshInvocation = | InfoInvocation | ErrorInvocation -/** Raw Commander option bag for the root command before it is narrowed to a mode. */ -interface RootOptions { - prompt?: string - resume?: string -} - -/** Commander option bag for the `web` subcommand after `--port` coercion. */ -interface WebOptions { - host: string - port: number -} - -/** - * Coerce `--port` to an integer in 0–65535; a bad value throws - * {@link InvalidArgumentError}, which Commander reports as a parse error the - * adapter returns as an {@link ErrorInvocation}. - */ +/** Coerce `--port` to an integer in 0–65535; a bad value fails loud as a parse error. */ function parsePort(raw: string): number { const port = Number(raw) if (!Number.isInteger(port) || port < 0 || port > 65535) { @@ -82,102 +67,90 @@ function parsePort(raw: string): number { return port } -/** Reject an empty `--prompt` task; an empty headless prompt has nothing to run. */ -function parsePrompt(raw: string): string { - if (raw === '') throw new InvalidArgumentError("option '-p, --prompt ' must not be empty") - return raw +/** + * A configured `Command` under `exitOverride` with output captured into `sink`, + * so `--help`, `--version`, and parse errors surface as thrown `CommanderError`s + * (see {@link settle}) rather than writing to a stream or exiting. + */ +function program(name: string, version: string, sink: string[]): Command { + return new Command() + .name(name) + .version(version, '-V, --version', 'output the version number') + .exitOverride() + .configureOutput({ + writeOut: chunk => void sink.push(chunk), + writeErr: chunk => void sink.push(chunk), + }) } /** - * Validate a `--resume` value: reject an empty id and a repeated flag. Both are - * mistypes that must fail loud, never silently start a fresh session or keep - * only the last id. `previous` is the value from an earlier `--resume` on the - * same invocation (Commander threads it in), so a second occurrence is caught. + * Run `command.parse` and map its thrown `CommanderError` to an info/error + * invocation, or `undefined` when the parse succeeded (the caller then reads the + * parsed options). */ -function parseResume(raw: string, previous: string | undefined): string { - if (previous !== undefined) throw new InvalidArgumentError("option '--resume ' may be given only once") - if (raw === '') throw new InvalidArgumentError("option '--resume ' must not be empty") - return raw +function settle(command: Command, argv: readonly string[], sink: string[]): InfoInvocation | ErrorInvocation | undefined { + try { + command.parse(argv, { from: 'user' }) + return undefined + } catch (error) { + /* v8 ignore next -- Commander only throws CommanderError from parse under exitOverride */ + if (!(error instanceof CommanderError)) throw error + if (error.code === 'commander.helpDisplayed') return { mode: 'help', text: sink.join('') } + if (error.code === 'commander.version') return { mode: 'version', text: sink.join('') } + return { mode: 'error', message: error.message } + } +} + +/** Parse `dsh web` arguments (everything after the `web` token). */ +function parseWeb(argv: readonly string[], version: string): DshInvocation { + const sink: string[] = [] + const web = program('dsh web', version, sink) + .description('serve the browser UI') + .addOption(new Option('--host ', 'bind host').choices([LOOPBACK_HOST, ALL_INTERFACES_HOST]).default(LOOPBACK_HOST)) + .addOption(new Option('--port ', 'listen port').default(DEFAULT_WEB_PORT).argParser(parsePort)) + const settled = settle(web, argv, sink) + if (settled !== undefined) return settled + const { host, port } = web.opts<{ host: string; port: number }>() + return { mode: 'web', host, port } +} + +/** Parse the default (TUI / headless) arguments: `[config]`, `-p/--prompt`, `--resume`. */ +function parseRoot(argv: readonly string[], version: string): DshInvocation { + const sink: string[] = [] + const root = program('dsh', version, sink) + .description('dsh: interactive TUI, headless task, and browser UI') + .argument('[config]', 'config to boot instead of the shipped default (TUI mode)') + .option('-p, --prompt ', 'run one headless turn for this task, print the result, and exit') + .option('--resume ', 'resume the persisted session with this id (TUI mode)') + const settled = settle(root, argv, sink) + if (settled !== undefined) return settled + const { prompt, resume } = root.opts<{ prompt?: string; resume?: string }>() + const config = root.processedArgs[0] as string | undefined + + if (prompt !== undefined) { + // A headless prompt owns the invocation; an empty task has nothing to run. + if (prompt === '') return { mode: 'error', message: "error: option '-p, --prompt ' must not be empty" } + return { mode: 'headless', prompt } + } + // An empty `--resume=` id would silently start a fresh session downstream + // (agent-loop treats '' as no-resume), so a mistyped resume must fail loud. + if (resume === '') return { mode: 'error', message: "error: option '--resume ' must not be empty" } + return { + mode: 'tui', + ...config !== undefined ? { config } : {}, + ...resume !== undefined ? { resume } : {}, + } } /** * Resolve the raw argv into a single {@link DshInvocation}. Never writes to a * stream and never exits; `--help`/`--version` and every parse error come back - * as data for `bin.ts` to act on. + * as data for `bin.ts` to act on. A leading `web` token dispatches to the web + * parser; everything else is the default TUI/headless grammar. * @param argv - the arguments after the node binary and script (`process.argv.slice(2)`). * @param version - the version string `--version` prints; read from this app's package.json. * @returns the resolved invocation, discriminated by `mode`. */ export function parseDshArgs(argv: readonly string[], version: string): DshInvocation { - let resolved: DshInvocation | undefined - const output: string[] = [] - - const program = new Command() - .name('dsh') - .description('dsh: interactive TUI, headless task, and browser UI') - .version(version, '-V, --version', 'output the version number') - .exitOverride() - .configureOutput({ - writeOut: chunk => void output.push(chunk), - writeErr: chunk => void output.push(chunk), - }) - - // Positional options keep `dsh -p x web` from routing to the `web` - // subcommand: a token after a root option is a positional, not a command. - program - .enablePositionalOptions() - .argument('[config]', 'config to boot instead of the shipped default (TUI mode)') - .addOption(new Option('-p, --prompt ', 'run one headless turn for this task, print the result, and exit').argParser(parsePrompt)) - .addOption(new Option('--resume ', 'resume the persisted session with this id (TUI mode)').argParser(parseResume)) - .action((config: string | undefined, options: RootOptions) => { - if (options.prompt !== undefined) { - // A headless prompt owns the invocation; a config positional is meaningless there. - if (config !== undefined) { - throw new InvalidArgumentError(`error: --prompt takes no config argument (got '${config}')`) - } - resolved = { mode: 'headless', prompt: options.prompt } - return - } - resolved = { - mode: 'tui', - ...config !== undefined ? { config } : {}, - ...options.resume !== undefined ? { resume: options.resume } : {}, - } - }) - - program - .command('web') - .description('serve the browser UI') - .addOption( - new Option('--host ', 'bind host') - .choices([LOOPBACK_HOST, ALL_INTERFACES_HOST]) - .default(LOOPBACK_HOST), - ) - .addOption( - new Option('--port ', 'listen port').default(DEFAULT_WEB_PORT).argParser(parsePort), - ) - .action((options: WebOptions, command: Command) => { - // Root options placed before `web` (`dsh -p x web`) leak onto the parent; - // reject them so a misplaced flag fails loud instead of silently serving. - const leaked = command.parent?.opts() - if (leaked?.prompt !== undefined || leaked?.resume !== undefined) { - throw new InvalidArgumentError('error: web takes no --prompt or --resume; place web first') - } - resolved = { mode: 'web', host: options.host, port: options.port } - }) - - try { - program.parse(argv, { from: 'user' }) - } catch (error) { - /* v8 ignore next -- Commander only throws CommanderError from parse under exitOverride */ - if (!(error instanceof CommanderError)) throw error - if (error.code === 'commander.helpDisplayed') return { mode: 'help', text: output.join('') } - if (error.code === 'commander.version') return { mode: 'version', text: output.join('') } - // Every other CommanderError is a parse failure; its message is the diagnostic. - return { mode: 'error', message: error.message } - } - - /* v8 ignore next -- one action always resolves the invocation or parse throws above */ - if (resolved === undefined) throw new Error('dsh: argument parsing did not resolve a mode') - return resolved + return argv[0] === 'web' ? parseWeb(argv.slice(1), version) : parseRoot(argv, version) } diff --git a/apps/cli/tests/args.spec.ts b/apps/cli/tests/args.spec.ts index ad6d0266ca..c9d3c236ad 100644 --- a/apps/cli/tests/args.spec.ts +++ b/apps/cli/tests/args.spec.ts @@ -1,120 +1,33 @@ import { describe, expect, it } from 'vitest' import { ALL_INTERFACES_HOST, LOOPBACK_HOST, parseDshArgs } from '../src/args.ts' -const VERSION = '1.2.3' -const parse = (argv: string[]) => parseDshArgs(argv, VERSION) +const parse = (argv: string[]) => parseDshArgs(argv, '1.2.3') -/** Assert argv resolves to an error invocation whose message contains `needle`. */ -function expectError(argv: string[], needle: string): void { - const result = parse(argv) - expect(result.mode).toBe('error') - if (result.mode !== 'error') throw new Error('expected error mode') - expect(result.message).toContain(needle) -} - -describe('parseDshArgs — TUI (default mode)', () => { - it('defaults to the TUI with no config and no resume when given no arguments', () => { +describe('parseDshArgs', () => { + it('routes each mode by its shape: default TUI, -p headless, web subcommand', () => { expect(parse([])).toEqual({ mode: 'tui' }) - }) - - it('carries a positional config into the TUI mode', () => { expect(parse(['custom.yml'])).toEqual({ mode: 'tui', config: 'custom.yml' }) - }) - - it('parses --resume in the space and inline forms, independent of a config positional', () => { - expect(parse(['--resume', 'sess-1'])).toEqual({ mode: 'tui', resume: 'sess-1' }) - expect(parse(['--resume=sess-2'])).toEqual({ mode: 'tui', resume: 'sess-2' }) - expect(parse(['--resume', 'sess-3', 'app.yml'])).toEqual({ mode: 'tui', config: 'app.yml', resume: 'sess-3' }) - expect(parse(['app.yml', '--resume', 'sess-4'])).toEqual({ mode: 'tui', config: 'app.yml', resume: 'sess-4' }) - }) - - it('fails loud on a valueless or empty --resume rather than silently starting fresh', () => { - expectError(['--resume'], '--resume') - expectError(['--resume='], 'must not be empty') - }) - - it('rejects a repeated --resume instead of silently keeping the last id', () => { - expectError(['--resume', 'a', '--resume', 'b'], 'may be given only once') - expectError(['--resume=a', '--resume=b'], 'may be given only once') - }) -}) - -describe('parseDshArgs — headless', () => { - it('routes -p / --prompt to the headless mode with the task text', () => { + expect(parse(['--resume', 'sess', 'app.yml'])).toEqual({ mode: 'tui', config: 'app.yml', resume: 'sess' }) expect(parse(['-p', 'do the thing'])).toEqual({ mode: 'headless', prompt: 'do the thing' }) - expect(parse(['--prompt', 'do the thing'])).toEqual({ mode: 'headless', prompt: 'do the thing' }) - }) - - it('routes to headless regardless of the prompt flag position', () => { - // Positional-independent: the old `argv.includes('-p')` dispatch could not - // tell a real prompt flag from one buried after other tokens. - expect(parse(['-p', 'task'])).toEqual({ mode: 'headless', prompt: 'task' }) - }) - - it('rejects an empty prompt and a stray config positional', () => { - expectError(['-p', ''], 'must not be empty') - expectError(['-p', 'task', 'app.yml'], 'takes no config') - }) -}) - -describe('parseDshArgs — web', () => { - it('defaults the web mode to loopback and port 3080', () => { expect(parse(['web'])).toEqual({ mode: 'web', host: LOOPBACK_HOST, port: 3080 }) - }) - - it('accepts an explicit loopback or all-interfaces host and a valid port', () => { expect(parse(['web', '--host', ALL_INTERFACES_HOST, '--port', '8080'])) .toEqual({ mode: 'web', host: ALL_INTERFACES_HOST, port: 8080 }) - expect(parse(['web', '--port', '0'])).toEqual({ mode: 'web', host: LOOPBACK_HOST, port: 0 }) }) - it('rejects a non-integer or out-of-range port with a --port diagnostic', () => { - expectError(['web', '--port', 'abc'], '--port') - expectError(['web', '--port', '70000'], '--port') - expectError(['web', '--port', '-1'], '--port') + it('fails loud instead of silently starting fresh or serving on bad input', () => { + // An empty resume/prompt would otherwise be swallowed (agent-loop treats an + // empty resume id as no-resume); a bad host/port must not reach the listener. + expect(parse(['--resume=']).mode).toBe('error') + expect(parse(['-p', '']).mode).toBe('error') + expect(parse(['web', '--host', '10.0.0.1']).mode).toBe('error') + expect(parse(['web', '--port', 'abc']).mode).toBe('error') + expect(parse(['--bogus']).mode).toBe('error') }) - it('rejects a host outside the allowed choices with a --host diagnostic', () => { - expectError(['web', '--host', '10.0.0.1'], '--host') - }) - - it('rejects an unexpected positional after web', () => { - expectError(['web', 'extra'], 'too many arguments') - }) - - it('fails loud when a root flag is placed before web instead of serving with it dropped', () => { - // `dsh web -p x` and `dsh -p x web` both misrouted or dropped the flag under - // the old `argv[0]==='web'` / `argv.includes('-p')` dispatch. - expectError(['web', '-p', 'x'], "unknown option '-p'") - expectError(['web', '--resume', 'y'], "unknown option '--resume'") - expectError(['-p', 'x', 'web'], 'web takes no') - expectError(['--resume', 'y', 'web'], 'web takes no') - }) - - it('renders web usage for web --help', () => { - const help = parse(['web', '--help']) - expect(help.mode).toBe('help') - if (help.mode !== 'help') throw new Error('expected help mode') - expect(help.text).toContain('Usage: dsh web') - }) -}) - -describe('parseDshArgs — help, version, and errors', () => { - it('returns the rendered usage for --help / -h', () => { + it('surfaces --help and --version as printable data, not a process exit', () => { const help = parse(['--help']) - expect(help.mode).toBe('help') - if (help.mode !== 'help') throw new Error('expected help mode') - expect(help.text).toContain('Usage: dsh') - expect(help.text).toContain('web') - expect(parse(['-h']).mode).toBe('help') - }) - - it('returns the version string for --version / -V', () => { - expect(parse(['--version'])).toEqual({ mode: 'version', text: `${VERSION}\n` }) - expect(parse(['-V'])).toEqual({ mode: 'version', text: `${VERSION}\n` }) - }) - - it('reports an unknown option as an error invocation', () => { - expectError(['--nope'], "unknown option '--nope'") + expect(help).toMatchObject({ mode: 'help' }) + if (help.mode === 'help') expect(help.text).toContain('Usage: dsh') + expect(parse(['--version'])).toEqual({ mode: 'version', text: '1.2.3\n' }) }) }) From 04c8a17de5e48cd3b5f4c3d485baf86323625733 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 20:08:38 +0800 Subject: [PATCH 024/113] fix: cancel exact session observations --- ...model-facing-session-query-tools.i18n.yaml | 4 +- ...-07-24-model-facing-session-query-tools.md | 4 +- ...-24-model-facing-session-query-tools.zh.md | 4 +- docs/cordis-catalog/services.md | 9 +- .../cordis/tool-cordis/src/api-catalog.ts | 12 +- .../session-query/session-query/README.md | 8 +- .../session-query/session-query/src/corpus.ts | 26 ++- .../session-query/session-query/src/index.ts | 21 +- .../session-query/tests/session-query.spec.ts | 197 +++++++++++++++++- .../tool-session-query/README.md | 2 +- .../tool-session-query/src/index.ts | 6 +- .../tests/tool-session-query.spec.ts | 72 +++++++ 12 files changed, 328 insertions(+), 37 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml index 5ec76b0d61..cc975b746d 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 -2026-07-24-model-facing-session-query-tools.md: 2f057292acac2c565e6b9dac61ed1e013b998550 -2026-07-24-model-facing-session-query-tools.zh.md: 6ccf60f39afc4021899df5c422ae455259c2ecc3 +2026-07-24-model-facing-session-query-tools.md: 75aa8eef1b27ca64b49710ba055b33d091f514ad +2026-07-24-model-facing-session-query-tools.zh.md: a59f88b38ac88b9a88cb55e799847c283145205a diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md index 2f057292ac..75aa8eef1b 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -26,7 +26,7 @@ The search tools expose prior work rather than the operation that is performing Neither search tool exposes a cursor, offset, page size, or model-controlled result limit. One execution follows provider cursors while the observed generation remains valid and collects up to the configured `maxSearchResults`, which defaults to 100. A capped result tells the model to narrow its query or filters; a generation change reports that the whole search must be retried. Search execution carries a configurable `searchTimeoutMs`, defaulting to 30 seconds, through the tool deadline and the service abort signal. Because internal pages share generation-bound cursors, both search tools are exclusive in the agent-loop scheduler; the exact trace and read tools opt into parallel sibling execution because their observations tolerate intervening commits. -Trace and read tools likewise expose no lineage or character pagination. Canonical results are plain text and remain complete within the service's existing event-window and search-count resource bounds. The generic `tools/post-execute` spill policy owns inline byte retention: when a configured deployment receives oversized text, it replaces that text with a bounded preview plus an opaque locator and retrieval hint while preserving the complete result in its spill store. The session-query consumer neither imports `ctx.spillStore` nor implements a second truncation format. +Trace and read tools likewise expose no lineage or character pagination. Canonical results are plain text and remain complete within the service's existing event-window and search-count resource bounds. Each exact executor passes its unchanged tool-execution signal through target authorization and the service trace or read. Within service resolution, known-live event traces, event reads, and title reads remain persistence-free while honoring pre-abort. Session lineage tracing passes the signal to whole-corpus persistence listing; persisted event tracing and reading pass it to target listing and inspection. Each started backend call is awaited for cleanup before the exact abort reason is preserved, even when that backend ignored cancellation. The generic `tools/post-execute` spill policy owns inline byte retention: when a configured deployment receives oversized text, it replaces that text with a bounded preview plus an opaque locator and retrieval hint while preserving the complete result in its spill store. The session-query consumer neither imports `ctx.spillStore` nor implements a second truncation format. Session-level results include the latest folded title when available. Each tool execution batches its unique title ids through one live-preferred corpus observation with at most the service's configured `persistedInspectConcurrency` workers, which defaults to four, and passes the exact tool-execution signal through persisted listing and inspection. Live sources fold directly; each persisted worker folds its completed source to a detached header/title observation and releases the full log before dequeuing another id, so the batch retains only small projected values. For the search tools, the execution signal carries the configured search deadline. Cancellation starts no queued title inspections and rejects the complete tool execution after already-started inspections settle; a missing, malformed, or operationally failed title remains isolated to that id, preserves the base result, renders an unavailable marker, and logs the underlying error, while an authorization mismatch fails closed. Search results include the strongest matching event and provider excerpt, traces include complete authorized relationships, and event reads keep neighbor presentation readable while reserving exact JSON for the requested target. @@ -44,7 +44,7 @@ The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.se ## Verification -Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, exclusive search and parallel exact-read classification, count caps, cancellation, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, exclusive search and parallel exact-read classification, count caps, exact-signal forwarding, abort-reason preservation, persistence cleanup quiescence, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md index 6ccf60f39a..a59f88b38a 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -26,7 +26,7 @@ Status: implemented 两个搜索工具都不向模型公开游标、偏移量、页大小或模型可控的结果限制。一次执行会在观察到的代保持有效时持续跟随提供方游标,并收集不超过配置项 `maxSearchResults` 的结果,其默认值为 100。达到上限的结果会要求模型缩小查询或过滤范围;代发生变化时会报告必须重试完整搜索。搜索执行通过工具截止时间与服务中止信号传递可配置的 `searchTimeoutMs`,默认值为 30 秒。由于内部页面共享与代绑定的游标,两个搜索工具在 agent loop 调度器中都以独占方式执行;精确追踪与读取工具则允许和兄弟工具并行执行,因为其观测可以容忍期间发生的提交。 -追踪与读取工具同样不公开谱系分页或字符分页。规范结果采用纯文本,并在服务已有的事件窗口与搜索数量资源边界内保持完整。通用的 `tools/post-execute` spill 策略负责行内字节保留:当已配置的部署收到过大的文本时,该策略会用有界预览、不可透明推导的定位符与读取提示替换文本,同时在 spill 存储中保留完整结果。会话查询消费者既不导入 `ctx.spillStore`,也不实现第二套截断格式。 +追踪与读取工具同样不公开谱系分页或字符分页。规范结果采用纯文本,并在服务已有的事件窗口与搜索数量资源边界内保持完整。每个精确执行器都会将未经替换的工具执行信号传递给目标授权与服务追踪或读取。在服务解析过程中,已知实时事件追踪、事件读取与标题读取在遵循预中止的同时仍不访问持久化。会话谱系追踪会将该信号传递给全语料持久化列表;持久化事件追踪与读取则将其传递给目标列表和检查。每个已启动的后端调用都会等待清理完成后再保留准确的中止原因,即使该后端忽略了取消也不例外。通用的 `tools/post-execute` spill 策略负责行内字节保留:当已配置的部署收到过大的文本时,该策略会用有界预览、不可透明推导的定位符与读取提示替换文本,同时在 spill 存储中保留完整结果。会话查询消费者既不导入 `ctx.spillStore`,也不实现第二套截断格式。 会话级结果在可用时包含最新折叠标题。每次工具执行都会通过一次优先使用实时数据的语料观测批量读取唯一标题 id,最多使用服务通过 `persistedInspectConcurrency` 配置的持久化检查 worker,其默认值为 4,并将准确的工具执行信号传递给持久化列表与检查操作。实时来源会直接折叠;每个持久化 worker 都会把已完成的来源折叠为分离的会话头/标题观测,并在取出下一个 id 前释放完整日志,因此批次只保留小型投影值。对于搜索工具,该执行信号携带已配置的搜索截止时间。取消不会启动排队中的标题检查,并会在已经启动的检查全部完成后拒绝完整的工具执行;标题缺失、格式错误或发生操作性失败时,错误只影响对应 id,同时保留基础结果、渲染不可用标记并记录底层错误,而授权不匹配则按失败关闭处理。搜索结果包含最强匹配事件与提供方摘录,追踪包含完整的已授权关系,事件读取保持邻近事件表现易读,同时只为被请求的目标保留精确 JSON。 @@ -44,7 +44,7 @@ Status: implemented ## 验证 -包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、搜索独占与精确读取并行分类、数量上限、取消、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、搜索独占与精确读取并行分类、数量上限、精确信号传递、中止原因保留、持久化清理静止、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 ## 后果 diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index b15fc29ee9..4348fb4d39 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -1068,25 +1068,28 @@ async readSurface(sessionId: SessionId): Promise /** * Trace known ancestry and descendants from one corpus observation. * @param sessionId - logical session id to trace. + * @param signal - optional cancellation for persistence listing. * @returns a complete lineage or an explicit unresolved parent boundary. * @throws when corpus resolution fails, the target is absent, or its known ancestry cycles. */ -async traceSession(sessionId: SessionId): Promise +async traceSession(sessionId: SessionId, signal?: AbortSignal): Promise /** * Trace one event's direct positional and provenance relationships. * @param request - target session id and event seq. + * @param signal - optional cancellation for persisted source resolution. * @returns source header, direct links, and the target's positional replacement chain. * @throws when source resolution fails, the target is absent, or surface/provenance validation fails. */ -async traceEvent(request: SessionEventTraceRequest): Promise +async traceEvent(request: SessionEventTraceRequest, signal?: AbortSignal): Promise /** * Read one full event plus a bounded raw-log context window. * @param request - target session/seq and context sizes. + * @param signal - optional cancellation for persisted source resolution. * @returns cloned target and neighboring events. */ -async readEvent(request: SessionEventReadRequest): Promise +async readEvent(request: SessionEventReadRequest, signal?: AbortSignal): Promise ``` Types: [SessionEventReadRequest](../core-data-structures/session-query.md) · [SessionEventRecord](../core-data-structures/session-query.md) · [SessionEventResultFilter](../core-data-structures/session-query.md) · [SessionEventSearchDocument](../core-data-structures/session-query.md) · [SessionEventSearchPage](../core-data-structures/session-query.md) · [SessionEventSearchRequest](../core-data-structures/session-query.md) · [SessionEventTraceObservation](../core-data-structures/session-query.md) · [SessionEventTraceRequest](../core-data-structures/session-query.md) · [SessionEventWindow](../core-data-structures/session-query.md) · [SessionId](../core-data-structures/core.md) · [SessionLineageTrace](../core-data-structures/session-query.md) · [SessionLogSnapshot](../core-data-structures/session-query.md) · [SessionRecord](../core-data-structures/session-query.md) · [SessionResultFilter](../core-data-structures/session-query.md) · [SessionSearchExecContext](../core-data-structures/session-query.md) · [SessionSearchHit](../core-data-structures/session-query.md) · [SessionSearchPage](../core-data-structures/session-query.md) · [SessionSearchRequest](../core-data-structures/session-query.md) · [SessionSurfaceSnapshot](../core-data-structures/session-query.md) · [SessionTitleObservation](../core-data-structures/session-query.md) · [SessionTitleObservationResult](../core-data-structures/session-query.md) · [SessionTitleSnapshot](../core-data-structures/session-title.md) diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index c9e827ff4b..4c0dce90cf 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -531,16 +531,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ jsDoc: '/**\n * Read one session\'s complete current model surface from one corpus observation.\n * @param sessionId - live-preferred session id to read.\n * @returns cloned header, current surface, and raw-log capture boundary.\n * @throws when source resolution fails or the session surface is invalid.\n */', }, { - signature: 'async traceSession(sessionId: SessionId): Promise', - jsDoc: '/**\n * Trace known ancestry and descendants from one corpus observation.\n * @param sessionId - logical session id to trace.\n * @returns a complete lineage or an explicit unresolved parent boundary.\n * @throws when corpus resolution fails, the target is absent, or its known ancestry cycles.\n */', + signature: 'async traceSession(sessionId: SessionId, signal?: AbortSignal): Promise', + jsDoc: '/**\n * Trace known ancestry and descendants from one corpus observation.\n * @param sessionId - logical session id to trace.\n * @param signal - optional cancellation for persistence listing.\n * @returns a complete lineage or an explicit unresolved parent boundary.\n * @throws when corpus resolution fails, the target is absent, or its known ancestry cycles.\n */', }, { - signature: 'async traceEvent(request: SessionEventTraceRequest): Promise', - jsDoc: '/**\n * Trace one event\'s direct positional and provenance relationships.\n * @param request - target session id and event seq.\n * @returns source header, direct links, and the target\'s positional replacement chain.\n * @throws when source resolution fails, the target is absent, or surface/provenance validation fails.\n */', + signature: 'async traceEvent(request: SessionEventTraceRequest, signal?: AbortSignal): Promise', + jsDoc: '/**\n * Trace one event\'s direct positional and provenance relationships.\n * @param request - target session id and event seq.\n * @param signal - optional cancellation for persisted source resolution.\n * @returns source header, direct links, and the target\'s positional replacement chain.\n * @throws when source resolution fails, the target is absent, or surface/provenance validation fails.\n */', }, { - signature: 'async readEvent(request: SessionEventReadRequest): Promise', - jsDoc: '/**\n * Read one full event plus a bounded raw-log context window.\n * @param request - target session/seq and context sizes.\n * @returns cloned target and neighboring events.\n */', + signature: 'async readEvent(request: SessionEventReadRequest, signal?: AbortSignal): Promise', + jsDoc: '/**\n * Read one full event plus a bounded raw-log context window.\n * @param request - target session/seq and context sizes.\n * @param signal - optional cancellation for persisted source resolution.\n * @returns cloned target and neighboring events.\n */', }, ], }, diff --git a/packages/session-query/session-query/README.md b/packages/session-query/session-query/README.md index 82d32f5119..27191c3e5f 100644 --- a/packages/session-query/session-query/README.md +++ b/packages/session-query/session-query/README.md @@ -11,11 +11,11 @@ - `readTitleSnapshots(sessionIds, signal?)` resolves unique ids from one live-preferred corpus observation, passes cancellation through persisted listing and inspection, and returns ordered per-session settlements so one missing or malformed title source does not discard its peers. Each live source is folded directly, and each persisted worker folds to a detached header/title result and releases the full log before dequeuing another id. Cancellation rejects the whole batch. `readTitleSnapshot(sessionId, signal?)` is the one-observation view; `readTitle(sessionId, signal?)` returns only its optional folded `session/title`. - `listEvents(sessionId)` loads the live-preferred raw log and classifies each event as `current`, `shadowed`, or `log-only` with the shared `dsh-session` surface fold. - `readSurface(sessionId)` returns one cloned header, raw-log capture boundary, and the complete folded current surface in model-history order. A live session wins over persistence; compaction is observed before or after its replacement append, never as a synthetic mixture. -- `readEvent(request)` returns a cloned header, the full target event, and a bounded raw-seq window. `before` and `after` default to zero and may not exceed `readWindowMax`. -- `traceSession(sessionId)` reads the corpus once and returns immediate-to-outward ancestors plus deterministic recursive descendant trees. `complete: false` identifies the first missing parent; a target-connected cycle fails with `SESSION_QUERY_INVALID_LINEAGE`. -- `traceEvent(request)` loads the logical log once and returns its cloned source header with direct positional replacements and direct logged provenance. `replacementChain` follows positional replacers to the final replacement; provenance links remain non-transitive. +- `readEvent(request, signal?)` returns a cloned header, the full target event, and a bounded raw-seq window. `before` and `after` default to zero and may not exceed `readWindowMax`. +- `traceSession(sessionId, signal?)` reads the corpus once and returns immediate-to-outward ancestors plus deterministic recursive descendant trees. `complete: false` identifies the first missing parent; a target-connected cycle fails with `SESSION_QUERY_INVALID_LINEAGE`. +- `traceEvent(request, signal?)` loads the logical log once and returns its cloned source header with direct positional replacements and direct logged provenance. `replacementChain` follows positional replacers to the final replacement; provenance links remain non-transitive. -Persistence is optional and may mount or unmount dynamically. Cross-corpus listing and lineage tracing fail with `SESSION_QUERY_PERSISTENCE_FAILED` while mounted persistence is unreadable. A title, event read, or trace targeting a known live session does not consult persistence, so durable backend health cannot make current in-memory state unreadable. Persisted title and event operations list before loading and reject a metadata mismatch rather than combining inconsistent observations. A batch title observation performs one metadata listing, inspects its unique persisted ids with at most `persistedInspectConcurrency` workers, and preserves each title's own observed header for downstream authorization. Cancellation starts no queued inspections and rejects only after already-started workers settle. `listSessions()` remains lightweight and does not load logs or index titles. +Persistence is optional and may mount or unmount dynamically. Cross-corpus listing and lineage tracing fail with `SESSION_QUERY_PERSISTENCE_FAILED` while mounted persistence is unreadable. A title read, event trace, or event read targeting a known live session does not consult persistence, so durable backend health cannot make current in-memory state unreadable. Persisted title and event operations list before loading and reject a metadata mismatch rather than combining inconsistent observations. Lineage-trace cancellation is passed to persisted listing; event-trace and event-read cancellation is passed to persisted listing and inspection. Each waits for the started backend call to settle, then rejects with the signal's exact reason even when the backend ignored that signal. A pre-aborted known-live title read, event trace, or event read rejects before folding or snapshotting without consulting persistence. A batch title observation performs one metadata listing, inspects its unique persisted ids with at most `persistedInspectConcurrency` workers, and preserves each title's own observed header for downstream authorization. Cancellation starts no queued inspections and rejects only after already-started workers settle. `listSessions()` remains lightweight and does not load logs or index titles. ## Filtering and extraction diff --git a/packages/session-query/session-query/src/corpus.ts b/packages/session-query/session-query/src/corpus.ts index 5ed04a4808..649a80965a 100644 --- a/packages/session-query/session-query/src/corpus.ts +++ b/packages/session-query/session-query/src/corpus.ts @@ -82,23 +82,37 @@ export class SessionCorpus { * A known live target never consults persistence, so an optional backend's * failure cannot make current in-memory history unreadable. * @param sessionId - session to resolve. + * @param signal - optional cancellation for persisted source resolution. * @returns detached live-preferred header and events. */ - async load(sessionId: SessionId): Promise { + async load(sessionId: SessionId, signal?: AbortSignal): Promise { + signal?.throwIfAborted() const live = this._ctx.sessions.get(sessionId) - if (live !== undefined) return snapshotLive(live) + if (live !== undefined) { + const snapshot = snapshotLive(live) + signal?.throwIfAborted() + return snapshot + } const persistence = this._persistence if (persistence === undefined) throw notFound(sessionId) - const listed = (await listPersisted(persistence)).find(header => header.id === sessionId) + const listed = (await listPersisted(persistence, signal)).find(header => header.id === sessionId) + signal?.throwIfAborted() if (listed === undefined) throw notFound(sessionId) - const loaded = await inspectPersisted(persistence, sessionId) + const loaded = await inspectPersisted(persistence, sessionId, signal) + signal?.throwIfAborted() const attached = this._ctx.sessions.get(sessionId) - if (attached !== undefined) return snapshotLive(attached) + if (attached !== undefined) { + const snapshot = snapshotLive(attached) + signal?.throwIfAborted() + return snapshot + } assertSessionHeadersCompatible(loaded.meta, listed) - return { + const snapshot = { header: structuredClone(loaded.meta), events: loaded.events.map(event => structuredClone(event)), } + signal?.throwIfAborted() + return snapshot } /** diff --git a/packages/session-query/session-query/src/index.ts b/packages/session-query/session-query/src/index.ts index a16c8e9047..4dc982f8f3 100644 --- a/packages/session-query/session-query/src/index.ts +++ b/packages/session-query/session-query/src/index.ts @@ -272,22 +272,26 @@ export abstract class SessionQueryService extends Service { /** * Trace known ancestry and descendants from one corpus observation. * @param sessionId - logical session id to trace. + * @param signal - optional cancellation for persistence listing. * @returns a complete lineage or an explicit unresolved parent boundary. * @throws when corpus resolution fails, the target is absent, or its known ancestry cycles. */ - async traceSession(sessionId: SessionId): Promise { - const records = await this._corpus.listSessions() + async traceSession(sessionId: SessionId, signal?: AbortSignal): Promise { + const records = await this._corpus.listSessions(signal) + signal?.throwIfAborted() return tracing.traceSession(records, sessionId) } /** * Trace one event's direct positional and provenance relationships. * @param request - target session id and event seq. + * @param signal - optional cancellation for persisted source resolution. * @returns source header, direct links, and the target's positional replacement chain. * @throws when source resolution fails, the target is absent, or surface/provenance validation fails. */ - async traceEvent(request: SessionEventTraceRequest): Promise { - const loaded = await this._corpus.load(request.sessionId) + async traceEvent(request: SessionEventTraceRequest, signal?: AbortSignal): Promise { + const loaded = await this._corpus.load(request.sessionId, signal) + signal?.throwIfAborted() return { session: loaded.header, ...tracing.traceEvent(request.sessionId, loaded.events, request.seq), @@ -297,14 +301,15 @@ export abstract class SessionQueryService extends Service { /** * Read one full event plus a bounded raw-log context window. * @param request - target session/seq and context sizes. + * @param signal - optional cancellation for persisted source resolution. * @returns cloned target and neighboring events. */ - async readEvent(request: SessionEventReadRequest): Promise { + async readEvent(request: SessionEventReadRequest, signal?: AbortSignal): Promise { const before = this._readWindow('before', request.before) const after = this._readWindow('after', request.after) const sessionId = request.sessionId const seq = request.seq - return this._readEvent(sessionId, seq, before, after) + return this._readEvent(sessionId, seq, before, after, signal) } private async _readEvent( @@ -312,8 +317,10 @@ export abstract class SessionQueryService extends Service { seq: number, before: number, after: number, + signal?: AbortSignal, ): Promise { - const loaded = await this._corpus.load(sessionId) + const loaded = await this._corpus.load(sessionId, signal) + signal?.throwIfAborted() const target = loaded.events[seq] if (target === undefined || target.seq !== seq) { throw new SessionQueryError( diff --git a/packages/session-query/session-query/tests/session-query.spec.ts b/packages/session-query/session-query/tests/session-query.spec.ts index 4d093360ab..b830158be7 100644 --- a/packages/session-query/session-query/tests/session-query.spec.ts +++ b/packages/session-query/session-query/tests/session-query.spec.ts @@ -142,6 +142,34 @@ const cancellableSessionListings = [ }, ] as const +interface CancellableExactRead { + readonly name: 'traceSession' | 'traceEvent' | 'readEvent' + readonly inspects: boolean + readonly run: ( + ctx: Context, + sessionId: SessionIdType, + signal: AbortSignal, + ) => Promise +} + +const cancellableExactReads: readonly CancellableExactRead[] = [ + { + name: 'traceSession', + inspects: false, + run: (ctx, sessionId, signal) => ctx.sessionQuery.traceSession(sessionId, signal), + }, + { + name: 'traceEvent', + inspects: true, + run: (ctx, sessionId, signal) => ctx.sessionQuery.traceEvent({ sessionId, seq: 0 }, signal), + }, + { + name: 'readEvent', + inspects: true, + run: (ctx, sessionId, signal) => ctx.sessionQuery.readEvent({ sessionId, seq: 0 }, signal), + }, +] as const + describe.each(cancellableSessionListings)('$name cancellation', ({ run }) => { it('preserves an exact pre-abort reason without entering persistence', async () => { TestPersistence.reset() @@ -223,6 +251,167 @@ describe.each(cancellableSessionListings)('$name cancellation', ({ run }) => { }) }) +describe.each(cancellableExactReads)('$name cancellation', ({ inspects, run }) => { + it('preserves an exact pre-abort reason without entering persistence', async () => { + const persisted = header('pre-aborted-exact-read') + TestPersistence.reset([{ meta: persisted, events: eventLog() }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('exact read cancelled before start') + controller.abort(reason) + + await expect(run(ctx, persisted.id, controller.signal)).rejects.toBe(reason) + expect(TestPersistence.listCalls).toBe(0) + expect(TestPersistence.inspectCalls).toEqual([]) + }) + + it('forwards in-flight list cancellation and waits for cleanup before rejecting', async () => { + const persisted = header('cancelled-exact-list') + TestPersistence.reset([{ meta: persisted, events: eventLog() }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('exact read list cancelled in flight') + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + let active = false + TestPersistence.listOverride = async (signal) => { + if (signal === undefined) throw new Error('expected exact-read listing signal') + active = true + const aborted = new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + started.resolve(undefined) + await aborted + abortObserved.resolve(undefined) + await cleanup.promise + active = false + signal.throwIfAborted() + return [] + } + + const pending = run(ctx, persisted.id, controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + controller.abort(reason) + await abortObserved.promise + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(TestPersistence.listSignals).toEqual([controller.signal]) + expect(TestPersistence.inspectCalls).toEqual([]) + + cleanup.resolve(undefined) + await expect(pending).rejects.toBe(reason) + expect(active).toBe(false) + }) + + it('waits for an ignoring backend to return before preserving the abort reason', async () => { + const persisted = header('ignored-exact-signal') + const entry = { meta: persisted, events: eventLog() } + TestPersistence.reset([entry]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('exact read cancelled while backend ignored signal') + const started = Promise.withResolvers() + const release = Promise.withResolvers() + let active = false + if (inspects) { + TestPersistence.inspectOverride = async () => { + active = true + started.resolve(undefined) + await release.promise + active = false + return structuredClone(entry) + } + } else { + TestPersistence.listOverride = async () => { + active = true + started.resolve(undefined) + await release.promise + active = false + return [structuredClone(persisted)] + } + } + + const pending = run(ctx, persisted.id, controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + controller.abort(reason) + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(TestPersistence.listSignals).toEqual([controller.signal]) + expect(TestPersistence.inspectSignals).toEqual(inspects ? [controller.signal] : []) + + release.resolve(undefined) + await expect(pending).rejects.toBe(reason) + expect(active).toBe(false) + }) +}) + +describe.each(cancellableExactReads.filter(read => read.inspects))( + '$name persisted inspection cancellation', + ({ run }) => { + it('forwards cancellation and waits for inspection cleanup before rejecting', async () => { + const persisted = header('cancelled-exact-inspect') + TestPersistence.reset([{ meta: persisted, events: eventLog() }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + const reason = new Error('exact read inspection cancelled in flight') + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + let active = false + TestPersistence.inspectOverride = async (_sessionId, signal) => { + if (signal === undefined) throw new Error('expected exact-read inspection signal') + active = true + const aborted = new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + started.resolve(undefined) + await aborted + abortObserved.resolve(undefined) + await cleanup.promise + active = false + signal.throwIfAborted() + throw new Error('unreachable after exact-read cancellation') + } + + const pending = run(ctx, persisted.id, controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + controller.abort(reason) + await abortObserved.promise + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(TestPersistence.listSignals).toEqual([controller.signal]) + expect(TestPersistence.inspectSignals).toEqual([controller.signal]) + + cleanup.resolve(undefined) + await expect(pending).rejects.toBe(reason) + expect(active).toBe(false) + }) + }, +) + describe('session-query exact reads', () => { it('returns a detached replay-valid full log and rejects a corrupt persisted seed', async () => { const valid = header('valid-log', 2) @@ -862,9 +1051,15 @@ describe('session-query exact reads', () => { await ctx.plugin(TestPersistence) TestPersistence.listFailure = new Error('list unavailable') TestPersistence.inspectFailure = new Error('inspect unavailable') + const signal = new AbortController().signal await expect(ctx.sessionQuery.listEvents(live.id)).resolves.toHaveLength(2) - await expect(ctx.sessionQuery.readEvent({ sessionId: live.id, seq: 1 })).resolves.toMatchObject({ target: { seq: 1 } }) + await expect(ctx.sessionQuery.traceEvent({ sessionId: live.id, seq: 1 }, signal)) + .resolves.toMatchObject({ session: { id: live.id }, target: { seq: 1 } }) + await expect(ctx.sessionQuery.readEvent({ sessionId: live.id, seq: 1 }, signal)) + .resolves.toMatchObject({ target: { seq: 1 } }) + expect(TestPersistence.listSignals).toEqual([]) + expect(TestPersistence.inspectSignals).toEqual([]) await expect(ctx.sessionQuery.listSessions()).rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED')) await expect(ctx.sessionQuery.listEvents(SessionId('durable'))).rejects.toThrow(expectCode('SESSION_QUERY_PERSISTENCE_FAILED')) }) diff --git a/packages/session-query/tool-session-query/README.md b/packages/session-query/tool-session-query/README.md index f9e466f4a0..7b40527f62 100644 --- a/packages/session-query/tool-session-query/README.md +++ b/packages/session-query/tool-session-query/README.md @@ -9,7 +9,7 @@ Workspace-authorized model tools over `ctx.sessionQuery`. The package depends on | `maxSearchResults` | `100` | Maximum authorized non-self hits collected across internal provider pages | | `searchTimeoutMs` | `30000` | Cooperative deadline attached to both full-text search tools | -The caller comes exclusively from `ToolExecution.exec.agent`. Cross-session access requires exact equality between the target and caller session `cwd` values; a caller without `cwd` can inspect only itself. Search never exposes provider cursors, offsets, page sizes, or a model-controlled limit. Because one search consumes generation-bound provider cursors internally, both search tools execute exclusively with sibling tool calls; the three exact trace/read tools opt into parallel execution. Timestamps at the tool boundary require an explicit `Z` or numeric offset and become inclusive epoch-millisecond filters. +The caller comes exclusively from `ToolExecution.exec.agent`. Cross-session access requires exact equality between the target and caller session `cwd` values; a caller without `cwd` can inspect only itself. Search never exposes provider cursors, offsets, page sizes, or a model-controlled limit. Because one search consumes generation-bound provider cursors internally, both search tools execute exclusively with sibling tool calls; the three exact trace/read tools opt into parallel execution. Every exact executor passes its unchanged execution signal through authorization and the service trace/read, so cancellation waits for cooperative persistence cleanup and retains the signal's exact reason. Timestamps at the tool boundary require an explicit `Z` or numeric offset and become inclusive epoch-millisecond filters. `session_search` always omits the caller session. A current-session `session_event_search` stops immediately before the step that invoked it, so the active assistant output and logged tool call cannot match themselves. Direct targets are authorized before trace, event, or title reads. Lineage output replaces unauthorized ancestor and descendant boundaries with markers that contain no hidden session id. diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index 186e2ca75c..0ffbeeb836 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -428,7 +428,7 @@ async function executeSessionTrace( await authorizeTarget(ctx, caller, sessionId, exec.signal) let trace: SessionLineageTrace try { - trace = await ctx.sessionQuery.traceSession(sessionId) + trace = await ctx.sessionQuery.traceSession(sessionId, exec.signal) } catch (error: unknown) { exec.signal.throwIfAborted() if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_INVALID_LINEAGE') { @@ -471,7 +471,7 @@ async function executeEventTrace( const caller = callerOf(exec) const sessionId = targetId(args, caller) await authorizeTarget(ctx, caller, sessionId, exec.signal) - const trace = await ctx.sessionQuery.traceEvent({ sessionId, seq: args.seq }) + const trace = await ctx.sessionQuery.traceEvent({ sessionId, seq: args.seq }, exec.signal) exec.signal.throwIfAborted() assertObservedTargetAuthorized(caller, sessionId, trace.session) const title = await readTitle(ctx, caller, sessionId, exec.signal) @@ -494,7 +494,7 @@ async function executeEventRead( seq: args.seq, ...args.before === undefined ? {} : { before: args.before }, ...args.after === undefined ? {} : { after: args.after }, - }) + }, exec.signal) exec.signal.throwIfAborted() assertObservedTargetAuthorized(caller, sessionId, window.session) const title = await readTitle(ctx, caller, sessionId, exec.signal) diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index f403b3f5ba..d52a4d48aa 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -661,6 +661,78 @@ describe('workspace authority and lineage redaction', () => { expect(text(result)).toBe(`Error: ${message}`) }) + it.each([ + 'session_trace', + 'session_event_trace', + 'session_event_read', + ] as const)('forwards the exact signal to %s and waits for service cleanup', async (toolName) => { + const mounted = await mount() + const target = createSession(mounted.ctx, `cancelled-${toolName}`, '/work') + target.append( + 'user/message', + { content: [{ type: 'text', text: 'pending exact read' }], source: { kind: 'user' } }, + { surfaceOp: 'append' }, + ) + const controller = new AbortController() + const cancellation = new SessionQueryError( + `${toolName} cancelled`, + 'SESSION_QUERY_ABORTED', + ) + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + let observedSignal: AbortSignal | undefined + let active = false + const holdExactRead = async (signal?: AbortSignal): Promise => { + if (signal === undefined) throw new Error('expected exact tool execution signal') + observedSignal = signal + active = true + const aborted = new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + started.resolve(undefined) + await aborted + abortObserved.resolve(undefined) + await cleanup.promise + active = false + signal.throwIfAborted() + throw new Error('unreachable after exact tool cancellation') + } + if (toolName === 'session_trace') { + vi.spyOn(mounted.ctx.sessionQuery, 'traceSession') + .mockImplementation((_sessionId, signal) => holdExactRead(signal)) + } else if (toolName === 'session_event_trace') { + vi.spyOn(mounted.ctx.sessionQuery, 'traceEvent') + .mockImplementation((_request, signal) => holdExactRead(signal)) + } else { + vi.spyOn(mounted.ctx.sessionQuery, 'readEvent') + .mockImplementation((_request, signal) => holdExactRead(signal)) + } + const args = toolName === 'session_trace' + ? { session_id: target.id } + : { session_id: target.id, seq: 0 } + + const pending = mounted.call(toolName, args, { signal: controller.signal }) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + controller.abort(cancellation) + await abortObserved.promise + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(observedSignal).toBe(controller.signal) + + cleanup.resolve(undefined) + const result = await pending + expect(active).toBe(false) + expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') + expect(text(result)).toBe(`Error: ${toolName} cancelled`) + }) + it('preserves caller cancellation while a lineage trace is pending', async () => { const mounted = await mount() const target = createSession(mounted.ctx, 'cancelled-trace-target', '/work') From d08050ab69256cdc5f4183dd0b56dbad475fac59 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 20:30:33 +0800 Subject: [PATCH 025/113] =?UTF-8?q?chore(web-e2e):=20gate=20fixes=20?= =?UTF-8?q?=E2=80=94=20catalog,=20budgets,=20knip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regenerate config-catalog for the llm-replay paceMs row; condense the testing.md web-lane entry to pointer form and raise its ceiling 1020->1060 (the two-sentence tier entry for a genuinely new surface does not fit the old ceiling after relocation-first trims); internalize two harness helpers knip flagged (rawSessionLog/normalizeAria are module-internal). --- apps/web/tests/harness.ts | 9 ++----- docs/config-catalog.md | 2 +- docs/testing.md | 4 +-- .../llm-replay/tests/llm-replay.spec.ts | 27 ++++++++++++++++++- scripts/doc-budgets.manifest.json | 2 +- 5 files changed, 32 insertions(+), 12 deletions(-) diff --git a/apps/web/tests/harness.ts b/apps/web/tests/harness.ts index 71c3ac9344..b2941c62e0 100644 --- a/apps/web/tests/harness.ts +++ b/apps/web/tests/harness.ts @@ -230,10 +230,8 @@ export async function launchWebHarness(options: LaunchOptions = {}): Promise JSON.stringify(event)), @@ -333,11 +331,8 @@ export async function seedSession(harness: WebHarness, fixtureText: string, id: /** * Normalize an aria snapshot: uuid, cwd, workspace-basename, and duration * volatility collapse to stable tokens. - * @param snapshot - raw ariaSnapshot text. - * @param workspaceCwd - the harness workspace (basename doubles as the header breadcrumb). - * @returns tokenized snapshot text. */ -export function normalizeAria(snapshot: string, workspaceCwd: string): string { +function normalizeAria(snapshot: string, workspaceCwd: string): string { // The header breadcrumb renders the workspace's basename, not the full // path, so both spellings must collapse to the token. const base = workspaceCwd.split('/').pop()! diff --git a/docs/config-catalog.md b/docs/config-catalog.md index c06fef3d4d..1b546be67d 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -643,7 +643,7 @@ export interface ReplayModelConfig { } ``` -Source: [`packages/support/llm-replay/src/index.ts:453`](../packages/support/llm-replay/src/index.ts) +Source: [`packages/support/llm-replay/src/index.ts:454`](../packages/support/llm-replay/src/index.ts) ## `@deepseek-ai/dsh-llm-retry` diff --git a/docs/testing.md b/docs/testing.md index 5841cd5f29..78ce3c2856 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -8,7 +8,7 @@ How this repo tests, tier by tier, and the rules that keep a green suite meaning - **Coverage gate** (`pnpm run test:coverage`): the gating run, per-file 100% on `packages/*/*/src`. An uncovered line is often dead code the gate is correctly flagging for deletion, not a missing test to bolt on. Line coverage is necessary, never sufficient — it proves lines ran, not that the feature works as shipped. - **Real-API e2e** (`pnpm run test:e2e`): with-key tests against live provider APIs — the DeepSeek model plus provider-specific smokes that gate on their own keys (`EXA_API_KEY`, `PERPLEXITY_API_KEY`, …); each suite self-skips without its key so keyless CI stays green ([real-API e2e Agent Note](../.agents/notes/implemented/testing/2026-06-19-real-api-e2e-ci.md)). - **Snapshot** (`pnpm run test:snapshot`): transport-specific keyless expected outputs cover external presentation. ACP suites boot the real example subprocess, replay a recorded session, and diff normalized JSON-RPC plus the re-persisted log ([ACP snapshot Agent Note](../.agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md)); the headless suite independently pins `stream-json` through its real one-shot subprocess. TUI completed journeys replay recorded primary/child JSONL through the real agent loop and tools before projecting ANSI into semantic terminal-state expected outputs; package-local snapshots retain transient renderer states, and a real PTY conversation covers the process boundary ([TUI snapshot Agent Note](../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md)). Use `pnpm run test:snapshot:record` when a model transcript must change and `pnpm run test:snapshot:refresh` when committed replay input remains correct; review every JSONL and expected-output diff. System-prompt/tool-schema content is pinned by one ACP scenario (`text-turn`) and tokenized in every other fixture, so a prompt or schema edit churns one committed line ([pinned-header Agent Note](../.agents/notes/implemented/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)). -- **Web browser snapshot** (inside `pnpm run test:web`, gate-exempt like the rest of that lane): the web GUI's keyless assembled-transcript tier — a real chromium over the real in-process web assembly (`llm: false` + `dsh-llm-replay`), scenario fixtures and normalized conversation aria goldens under `apps/web/tests/snapshots/`. Its record/refresh commands diverge from `test:snapshot` (`DSH_SNAPSHOT=record pnpm run test:web` re-records against the live model; `DSH_SNAPSHOT=refresh` rewrites goldens keylessly); the [web e2e lane Agent Note](../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md) owns the design, and CI browser provisioning is deferred there. +- **Web browser snapshot** (gate-exempt `pnpm run test:web`): real chromium over the in-process web assembly replays recorded fixtures against conversation aria goldens (`apps/web/tests/snapshots/`); `DSH_SNAPSHOT=record`/`refresh` semantics and the deferred CI browser decision live in the [web e2e lane Agent Note](../.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md). ## The with-key policy: inference is cheap here @@ -42,4 +42,4 @@ An e2e assertion re-runs the command or re-reads the file externally; a keyword ## When a snapshot test is required -Every non-trivial model- or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP surfaces use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. Completed interactive-terminal journeys use JSONL-driven scenarios under `examples/tui-agent/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. Browser-rendered web GUI journeys use `apps/web/tests/snapshots/` through the web e2e lane's harness. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness can express it before implementation. +Every non-trivial model- or human-visible change adds or updates a keyless scenario in the same PR through a runnable example's owning snapshot suite. Package tests, e2e assertions, mock/test-only compositions, and PR rationale do not replace the assembled transcript; extend the harness when needed. ACP surfaces use `examples//tests/snapshots/`, a scenario table over the [`dsh-acp-snapshot`](../packages/support/acp-snapshot/README.md) suite factory (`examples/acp-agent` is primary); `examples/headless-agent` owns the `stream-json` snapshot and replay fixtures. Completed interactive-terminal journeys use JSONL-driven scenarios under `examples/tui-agent/tests/snapshots/`; transient presentation uses the package-local semantic matrix, with a PTY case when input, Loader selection, or terminal teardown changes. Browser-rendered web GUI journeys use `apps/web/tests/snapshots/`. New capability seams, lifecycle shapes, or transcript surfaces name every coverage tier at plan time and verify the harness can express it before implementation. diff --git a/packages/support/llm-replay/tests/llm-replay.spec.ts b/packages/support/llm-replay/tests/llm-replay.spec.ts index b6b03aacbf..d42626bedd 100644 --- a/packages/support/llm-replay/tests/llm-replay.spec.ts +++ b/packages/support/llm-replay/tests/llm-replay.spec.ts @@ -476,6 +476,31 @@ describe('installLlmReplay (through the real LlmService)', () => { expect(() => { handle.assertConsumed() }).not.toThrow() }) + it('paces a throw-entry prefix too (the recorded partial streams at the same cadence)', async () => { + writeFileSync(file, sessionJsonl([]), 'utf8') + const overrideFile = join(dir, 'replay.override.json') + const partial: StreamChunk[] = [{ type: 'block-start', index: 0, blockType: 'text' }] + writeFileSync(overrideFile, JSON.stringify([ + { kind: 'throw', chunks: partial, message: 'boom', code: 'STREAM_CLOSED' }, + ]), 'utf8') + const ctx = new Context() + await ctx.plugin(LlmService) + installLlmReplay(ctx, { file, overrideFile, paceMs: 10 }) + const started = performance.now() + await expect(drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [] }))).rejects.toThrow('boom') + expect(performance.now() - started).toBeGreaterThanOrEqual(5) + }) + + it('assertConsumed names an underrunning identified session by its id', async () => { + writeLog(TEXT_CHUNKS, TEXT_CHUNKS) + const ctx = new Context() + await ctx.plugin(LlmService) + const handle = installLlmReplay(ctx, { file }) + const sessionId = 'live-underrun' as NonNullable + await drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [], sessionId })) + expect(() => { handle.assertConsumed() }).toThrow(/session live-underrun consumed 1\/2/) + }) + it('assertConsumed reports recorded scripts no live session ever bound', async () => { writeLog(TEXT_CHUNKS) const childFile = join(dir, 'session.1.jsonl') @@ -690,7 +715,7 @@ describe('apply (the plugin entry)', () => { writeFileSync(file, sessionJsonl(TEXT_CHUNKS.map((c, i) => chunkEvent(i + 1, 1, 1, c))), 'utf8') const ctx = new Context() await ctx.plugin(LlmService) - apply(ctx, { file, providers: [{ id: 'm', models: [{ id: 'm' }] }] }) + apply(ctx, { file, providers: [{ id: 'm', models: [{ id: 'm' }] }], paceMs: 1 }) expect(ctx.llm.listProviders()).toEqual([{ id: 'm', name: 'm' }]) expect(await drain(ctx.llm.stream({ provider: 'm', model: 'm', messages: [] }))).toEqual(TEXT_CHUNKS) }) diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 7e4d154174..fe61bfa69d 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -4,7 +4,7 @@ "docs/architecture.md": 1800, "docs/cordis-primer.md": 600, "docs/defensive-patterns.md": 550, - "docs/testing.md": 1020, + "docs/testing.md": 1060, "examples/AGENTS.md": 310, "packages/AGENTS.md": 660, "packages/README.md": 760 From ba6fc1cfa3a17d0bfe92e214d8ddfd953ce94355 Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 20:50:53 +0800 Subject: [PATCH 026/113] fix: harden session query authorization --- ...model-facing-session-query-tools.i18n.yaml | 4 +- ...-07-24-model-facing-session-query-tools.md | 6 +- ...-24-model-facing-session-query-tools.zh.md | 6 +- docs/config-catalog.md | 2 +- .../tool-session-query/README.md | 4 +- .../tool-session-query/src/index.ts | 296 +++++++--- .../tests/tool-session-query.spec.ts | 539 +++++++++++++++++- 7 files changed, 758 insertions(+), 99 deletions(-) diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml index cc975b746d..88363d0aca 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 -2026-07-24-model-facing-session-query-tools.md: 75aa8eef1b27ca64b49710ba055b33d091f514ad -2026-07-24-model-facing-session-query-tools.zh.md: a59f88b38ac88b9a88cb55e799847c283145205a +2026-07-24-model-facing-session-query-tools.md: aea490f3569dd95bffb6ebbaae5a130e6440c281 +2026-07-24-model-facing-session-query-tools.zh.md: eae100375fe7abf91ba3e503808a6d98b540255e diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md index 75aa8eef1b..aea490f356 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -14,12 +14,14 @@ The unified `ctx.sessionQuery` service exposes exact reads, filters, relationshi `session_search` groups full-text matches by session and exposes typed session and event metadata filters. `session_event_search` searches one session, defaulting to the caller's current session. `session_trace` returns the complete authorized ancestor chain and recursive descendant trees. `session_event_trace` returns every known positional replacement and direct provenance relationship for one event. `session_event_read` returns the exact target event as unabridged JSON and optionally summarizes a bounded raw-event window; omitted `before` and `after` values mean target-only. -Model-facing filters use flat snake-case fields. Timestamps are timezone-qualified ISO 8601 strings at the tool boundary, convert to inclusive epoch-millisecond ranges for the service, and render as UTC ISO 8601. List values are ORed inside one filter while separate filters are ANDed. Parent ids and the root-session marker share one parent clause. Event type strings remain open because `SessionEventMap` is merge-extensible; availability and event surface use closed values. +Model-facing filters use flat snake-case fields. Timestamps are timezone-qualified ISO 8601 strings at the tool boundary, convert to inclusive epoch-millisecond ranges for the service, and render as UTC ISO 8601. List values are ORed inside one filter while separate filters are ANDed. Requested parent ids are deduplicated and authority-filtered before FTS, so only parents in the caller workspace enter the provider clause; missing and cross-workspace guesses behave identically, while the root-session marker remains independently ORed into that clause. Event type strings remain open because `SessionEventMap` is merge-extensible; availability and event surface use closed values. ## Workspace authority Every executor derives its caller from immutable `ToolExecution.exec.agent` identity and never accepts a model-supplied workspace. A target is authorized only when its observed `cwd` exactly equals the caller session's `cwd`. Cross-session search always adds that workspace filter. Direct operations preflight the target and then validate the header returned from the same service observation as every event-search page, event trace, event read, lineage target, or folded title before rendering its payload. This prevents a live or persisted target replacement between the check and use from crossing the workspace boundary. Lineage rendering stops at an unauthorized ancestor or descendant subtree without revealing the hidden session id. A caller whose session has no `cwd` can inspect only its own session; missing agent identity fails closed. +Every trusted `ctx.sessionQuery` call crosses one model-boundary sanitizer. It checks the execution signal first, preserving caller cancellation exactly. For other failures it records the available corpus or provider diagnostic chain in the internal log on a best-effort basis, substituting a fixed placeholder when the value cannot be safely inspected. Diagnostic formatting and error classification are independently guarded, so an unprintable nested cause cannot escape or prevent a safely classified outer error, while unsafe classification or logging returns the fixed generic `SESSION_QUERY_TOOL_FAILED` code and message. Per-title failures use the same sanitizer before becoming unavailable markers. Tool-owned input-validation and authorization errors remain precise because they are created outside this service boundary. + The search tools expose prior work rather than the operation that is performing the search. `session_search` omits the caller's session. When `session_event_search` targets the caller's session, it intersects the requested sequence range with the event immediately before the current `step/start`, excluding the current assistant message and tool call as well as the query arguments indexed from that call. ## Cursor-free results and spill @@ -44,7 +46,7 @@ The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.se ## Verification -Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, changed-observation rejection, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, exclusive search and parallel exact-read classification, count caps, exact-signal forwarding, abort-reason preservation, persistence cleanup quiescence, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, parent-filter preauthorization and oracle resistance, changed-observation rejection, service-diagnostic redaction for ordinary and adversarial unknown values, best-effort cyclic-cause logging, logger-failure containment, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, exclusive search and parallel exact-read classification, count caps, exact-signal forwarding, abort-reason preservation, persistence cleanup quiescence, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md index a59f88b38a..eae100375f 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -14,12 +14,14 @@ Status: implemented `session_search` 按会话聚合全文匹配,并公开带类型的会话与事件元数据过滤条件。`session_event_search` 搜索一个会话,默认目标为调用者的当前会话。`session_trace` 返回完整的已授权祖先链与递归后代树。`session_event_trace` 返回一个事件所有已知的位置替换关系与直接来源关系。`session_event_read` 以未删节 JSON 返回准确的目标事件,并可选择汇总一个有界的原始事件窗口;省略 `before` 与 `after` 时只返回目标。 -面向模型的过滤条件使用扁平的 snake-case 字段。工具边界上的时间戳采用带时区的 ISO 8601 字符串,转换为服务使用的闭区间毫秒时间戳,并以 UTC ISO 8601 渲染。同一个过滤条件中的列表值按 OR 组合,不同过滤条件按 AND 组合。父会话 id 与根会话标记共用一个父级条件。由于 `SessionEventMap` 可通过声明合并扩展,事件类型字符串保持开放;可用状态与事件表层使用封闭取值。 +面向模型的过滤条件使用扁平的 snake-case 字段。工具边界上的时间戳采用带时区的 ISO 8601 字符串,转换为服务使用的闭区间毫秒时间戳,并以 UTC ISO 8601 渲染。同一个过滤条件中的列表值按 OR 组合,不同过滤条件按 AND 组合。请求的父会话 id 会在 FTS 之前去重并按权限过滤,因此只有调用者工作区中的父会话会进入提供方条件;缺失与跨工作区的猜测具有相同行为,而根会话标记仍会独立按 OR 加入该条件。由于 `SessionEventMap` 可通过声明合并扩展,事件类型字符串保持开放;可用状态与事件表层使用封闭取值。 ## 工作区权限 每个执行器都从不可变的 `ToolExecution.exec.agent` 身份推导调用者,绝不接受模型提供的工作区。只有当目标观测中的 `cwd` 与调用者会话的 `cwd` 完全相同时,目标才获授权。跨会话搜索始终附加该工作区过滤条件。直接操作先预检目标,然后在渲染负载前,校验与每一页事件搜索结果、事件追踪、事件读取、谱系目标或折叠标题来自同一服务观测的会话头。这样,即使实时或持久化目标在检查与使用之间被替换,也无法跨越工作区边界。谱系渲染在遇到未授权的祖先或后代子树时停止,且不泄露被隐藏的会话 id。调用者会话没有 `cwd` 时只能检查自身会话;缺少 agent 身份时按失败关闭处理。 +每个受信任的 `ctx.sessionQuery` 调用都会经过同一个模型边界净化器。它首先检查执行信号,准确保留调用者取消。对于其他失败,它会尽力把可获得的语料或提供方诊断链写入内部日志;当值无法安全检查时,则改用固定占位符。诊断格式化与错误分类各自受到保护,因此无法打印的嵌套 cause 既不会逃逸,也不会阻止对外层错误进行安全分类;分类不安全或日志记录失败时,则返回固定的通用错误码 `SESSION_QUERY_TOOL_FAILED` 及其消息。逐标题失败也会先经过同一个净化器,再转为不可用标记。工具自身的输入校验与授权错误在该服务边界之外创建,因此仍保留精确消息。 + 搜索工具公开的是既往工作,而不是正在执行搜索的操作本身。`session_search` 排除调用者会话。`session_event_search` 以调用者会话为目标时,会把请求的序号范围与当前 `step/start` 之前的最后一个事件取交集,从而排除当前 assistant 消息、工具调用,以及从该次调用中建立索引的查询参数。 ## 无游标结果与 spill @@ -44,7 +46,7 @@ Status: implemented ## 验证 -包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、变更观测拒绝、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、搜索独占与精确读取并行分类、数量上限、精确信号传递、中止原因保留、持久化清理静止、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、父级过滤预授权与抵御预言机探测、变更观测拒绝、普通值与对抗性未知值的服务诊断脱敏、尽力记录循环 cause、日志失败隔离、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、搜索独占与精确读取并行分类、数量上限、精确信号传递、中止原因保留、持久化清理静止、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 ## 后果 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 700cd49e71..88d8f1bbaa 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1439,7 +1439,7 @@ export interface Config { } ``` -Source: [`packages/session-query/tool-session-query/src/index.ts:51`](../packages/session-query/tool-session-query/src/index.ts) +Source: [`packages/session-query/tool-session-query/src/index.ts:52`](../packages/session-query/tool-session-query/src/index.ts) ## `@deepseek-ai/dsh-tool-skill` diff --git a/packages/session-query/tool-session-query/README.md b/packages/session-query/tool-session-query/README.md index 7b40527f62..504405d698 100644 --- a/packages/session-query/tool-session-query/README.md +++ b/packages/session-query/tool-session-query/README.md @@ -11,7 +11,9 @@ Workspace-authorized model tools over `ctx.sessionQuery`. The package depends on The caller comes exclusively from `ToolExecution.exec.agent`. Cross-session access requires exact equality between the target and caller session `cwd` values; a caller without `cwd` can inspect only itself. Search never exposes provider cursors, offsets, page sizes, or a model-controlled limit. Because one search consumes generation-bound provider cursors internally, both search tools execute exclusively with sibling tool calls; the three exact trace/read tools opt into parallel execution. Every exact executor passes its unchanged execution signal through authorization and the service trace/read, so cancellation waits for cooperative persistence cleanup and retains the signal's exact reason. Timestamps at the tool boundary require an explicit `Z` or numeric offset and become inclusive epoch-millisecond filters. -`session_search` always omits the caller session. A current-session `session_event_search` stops immediately before the step that invoked it, so the active assistant output and logged tool call cannot match themselves. Direct targets are authorized before trace, event, or title reads. Lineage output replaces unauthorized ancestor and descendant boundaries with markers that contain no hidden session id. +`session_search` always omits the caller session. Requested parent ids are deduplicated and checked against caller-workspace authority before FTS; only authorized ids reach the provider, while missing and cross-workspace guesses behave identically and the root marker remains independently ORed. A current-session `session_event_search` stops immediately before the step that invoked it, so the active assistant output and logged tool call cannot match themselves. Direct targets are authorized before trace, event, or title reads. Lineage output replaces unauthorized ancestor and descendant boundaries with markers that contain no hidden session id. + +Every trusted `ctx.sessionQuery` call crosses one model-boundary sanitizer. Caller cancellation is checked first and preserved exactly. Available corpus and provider diagnostics, including safely inspectable nested causes, are logged internally on a best-effort basis; unprintable failures use a fixed log placeholder. Diagnostic formatting and error classification are independently guarded, so an unprintable cause cannot escape or prevent a safely classified outer error, while unsafe classification or logging falls back to the fixed `SESSION_QUERY_TOOL_FAILED` code and message. Local argument-validation and authorization errors retain their precise tool-owned messages. The package deliberately performs no byte or character truncation and does not import a spill backend. Deployments that need bounded inline output mount `@deepseek-ai/dsh-spill-policy`, which can replace the rendered text after execution while retaining the complete result. diff --git a/packages/session-query/tool-session-query/src/index.ts b/packages/session-query/tool-session-query/src/index.ts index 0ffbeeb836..e05ab89218 100644 --- a/packages/session-query/tool-session-query/src/index.ts +++ b/packages/session-query/tool-session-query/src/index.ts @@ -29,6 +29,7 @@ import { type SessionLineageTrace, type SessionRecord, type SessionResultFilter, + type SessionQueryErrorCode, type SessionSearchCursor, type SessionSearchHit, } from '@deepseek-ai/dsh-session-query' @@ -196,6 +197,76 @@ const PROMPT_TEXT = + 'events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with ' + 'session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data.' +interface ModelSafeServiceFailure { + readonly code: SessionQueryErrorCode | 'SESSION_QUERY_TOOL_FAILED' + readonly message: string +} + +const UNPRINTABLE_SERVICE_ERROR = '[unprintable session query failure]' + +const SAFE_SESSION_QUERY_FAILURES = { + SESSION_QUERY_ABORTED: { + code: 'SESSION_QUERY_ABORTED', + message: 'session query was cancelled', + }, + SESSION_QUERY_EVENT_NOT_FOUND: { + code: 'SESSION_QUERY_EVENT_NOT_FOUND', + message: 'session event was not found', + }, + SESSION_QUERY_INDEX_FAILED: { + code: 'SESSION_QUERY_INDEX_FAILED', + message: 'session search index is unavailable', + }, + SESSION_QUERY_INVALID_CONFIG: { + code: 'SESSION_QUERY_TOOL_FAILED', + message: 'session query operation failed', + }, + SESSION_QUERY_INVALID_CURSOR: { + code: 'SESSION_QUERY_INVALID_CURSOR', + message: 'session search continuation is invalid', + }, + SESSION_QUERY_INVALID_FILTER: { + code: 'SESSION_QUERY_INVALID_FILTER', + message: 'session query filters were rejected', + }, + SESSION_QUERY_INVALID_LIMIT: { + code: 'SESSION_QUERY_INVALID_LIMIT', + message: 'session query result limit was rejected', + }, + SESSION_QUERY_INVALID_QUERY: { + code: 'SESSION_QUERY_INVALID_QUERY', + message: 'session query was rejected', + }, + SESSION_QUERY_INVALID_LINEAGE: { + code: 'SESSION_QUERY_INVALID_LINEAGE', + message: 'session lineage is invalid', + }, + SESSION_QUERY_INVALID_SURFACE: { + code: 'SESSION_QUERY_INVALID_SURFACE', + message: 'session event history is invalid', + }, + SESSION_QUERY_INVALID_WINDOW: { + code: 'SESSION_QUERY_INVALID_WINDOW', + message: 'session event window is invalid', + }, + SESSION_QUERY_PERSISTENCE_FAILED: { + code: 'SESSION_QUERY_PERSISTENCE_FAILED', + message: 'session history storage is unavailable', + }, + SESSION_QUERY_SESSION_NOT_FOUND: { + code: 'SESSION_QUERY_SESSION_NOT_FOUND', + message: 'session was not found', + }, + SESSION_QUERY_STALE_CURSOR: { + code: 'SESSION_QUERY_STALE_CURSOR', + message: 'session history changed while paging; retry the complete search call', + }, + SESSION_QUERY_SOURCE_CONFLICT: { + code: 'SESSION_QUERY_TOOL_FAILED', + message: 'session query operation failed', + }, +} satisfies Record + /** Register all five tools and their shared model guidance. */ export function apply(ctx: Context, config: Config): void { const resolved = resolveConfig(config) @@ -306,12 +377,11 @@ async function authorizeTarget( if (target === caller.id) return const cwd = caller.header.cwd if (cwd === undefined) throw unauthorizedTarget() - signal.throwIfAborted() - const records = await ctx.sessionQuery.filterSessions([ - { kind: 'id', values: [target] }, - { kind: 'cwd', values: [cwd] }, - ], signal) - signal.throwIfAborted() + const records = await sessionQueryCall(ctx, signal, 'target authorization', () => + ctx.sessionQuery.filterSessions([ + { kind: 'id', values: [target] }, + { kind: 'cwd', values: [cwd] }, + ], signal)) if (records.length !== 1) throw unauthorizedTarget() } @@ -322,6 +392,57 @@ function unauthorizedTarget(): HarnessError { ) } +async function sessionQueryCall( + ctx: Context, + signal: AbortSignal, + operation: string, + call: () => Promise, +): Promise { + signal.throwIfAborted() + try { + const value = await call() + signal.throwIfAborted() + return value + } catch (error: unknown) { + signal.throwIfAborted() + throw sanitizeSessionQueryError(ctx, operation, error) + } +} + +function sanitizeSessionQueryError( + ctx: Context, + operation: string, + error: unknown, +): HarnessError { + const generic = genericSessionQueryFailure() + const diagnostic = fullError(error) + try { + ctx.logger.warn(`tool-session-query: ${operation} failed: ${diagnostic}`) + if (error instanceof SessionQueryError) { + const code: unknown = error.code + const failure = typeof code === 'string' && Object.hasOwn(SAFE_SESSION_QUERY_FAILURES, code) + ? SAFE_SESSION_QUERY_FAILURES[code as SessionQueryErrorCode] + : undefined + if (failure !== undefined && failure.code !== 'SESSION_QUERY_TOOL_FAILED') { + return new SessionQueryError(failure.message, failure.code) + } + } + if (error instanceof HarnessError && error.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') { + return unauthorizedTarget() + } + } catch { + return generic + } + return generic +} + +function genericSessionQueryFailure(): HarnessError { + return new HarnessError( + 'session query operation failed', + 'SESSION_QUERY_TOOL_FAILED', + ) +} + async function executeSessionSearch( ctx: Context, args: SessionSearchArgs, @@ -338,7 +459,6 @@ async function executeSessionSearch( } const query = normalizeQuery(args.query) const sessionFilters = buildSessionFilters(args) - sessionFilters.push({ kind: 'cwd', values: [cwd] }) const eventFilters = buildEventFilters({ seqFrom: args.event_seq_from, seqTo: args.event_seq_to, @@ -347,15 +467,28 @@ async function executeSessionSearch( eventTypes: args.event_types, surfaces: args.event_surfaces, }) + const requestedParentIds = materializeParentSessionIds(args.parent_session_ids) + if (requestedParentIds !== undefined || args.include_root_sessions === true) { + const authorizedParentIds = requestedParentIds === undefined + ? new Set() + : await authorizeSessionIds(ctx, caller, requestedParentIds, exec.signal) + const parentValues: Array = requestedParentIds + ?.filter(id => authorizedParentIds.has(id)) ?? [] + if (args.include_root_sessions === true) parentValues.push(null) + if (parentValues.length === 0) return formatEmptySessionSearch() + sessionFilters.push({ kind: 'parent', values: parentValues }) + } + sessionFilters.push({ kind: 'cwd', values: [cwd] }) const collected = await collectPages( maxResults, exec.signal, - cursor => ctx.sessionQuery.searchSessions({ - query, - sessionFilters, - eventFilters, - ...cursor === undefined ? {} : { cursor }, - }, { signal: exec.signal }), + cursor => sessionQueryCall(ctx, exec.signal, 'session search', () => + ctx.sessionQuery.searchSessions({ + query, + sessionFilters, + eventFilters, + ...cursor === undefined ? {} : { cursor }, + }, { signal: exec.signal })), hit => hit.header.id !== caller.id && recordAuthorized(hit, caller), ) @@ -404,12 +537,13 @@ async function executeEventSearch( maxResults, exec.signal, async (cursor): Promise => { - const page = await ctx.sessionQuery.searchEvents({ - sessionId, - query, - filters, - ...cursor === undefined ? {} : { cursor }, - }, { signal: exec.signal }) + const page = await sessionQueryCall(ctx, exec.signal, 'event search', () => + ctx.sessionQuery.searchEvents({ + sessionId, + query, + filters, + ...cursor === undefined ? {} : { cursor }, + }, { signal: exec.signal })) assertObservedTargetAuthorized(caller, sessionId, page.session) return page }, @@ -426,20 +560,8 @@ async function executeSessionTrace( const caller = callerOf(exec) const sessionId = targetId(args, caller) await authorizeTarget(ctx, caller, sessionId, exec.signal) - let trace: SessionLineageTrace - try { - trace = await ctx.sessionQuery.traceSession(sessionId, exec.signal) - } catch (error: unknown) { - exec.signal.throwIfAborted() - if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_INVALID_LINEAGE') { - throw new SessionQueryError( - 'session lineage is invalid', - 'SESSION_QUERY_INVALID_LINEAGE', - ) - } - throw error - } - exec.signal.throwIfAborted() + const trace = await sessionQueryCall(ctx, exec.signal, 'session lineage trace', () => + ctx.sessionQuery.traceSession(sessionId, exec.signal)) assertObservedTargetAuthorized(caller, sessionId, trace.target.header) const ancestors: SessionRecord[] = [] @@ -471,8 +593,8 @@ async function executeEventTrace( const caller = callerOf(exec) const sessionId = targetId(args, caller) await authorizeTarget(ctx, caller, sessionId, exec.signal) - const trace = await ctx.sessionQuery.traceEvent({ sessionId, seq: args.seq }, exec.signal) - exec.signal.throwIfAborted() + const trace = await sessionQueryCall(ctx, exec.signal, 'event trace', () => + ctx.sessionQuery.traceEvent({ sessionId, seq: args.seq }, exec.signal)) assertObservedTargetAuthorized(caller, sessionId, trace.session) const title = await readTitle(ctx, caller, sessionId, exec.signal) return formatEventTrace(sessionId, title, trace) @@ -489,13 +611,13 @@ async function executeEventRead( const caller = callerOf(exec) const sessionId = targetId(args, caller) await authorizeTarget(ctx, caller, sessionId, exec.signal) - const window = await ctx.sessionQuery.readEvent({ - sessionId, - seq: args.seq, - ...args.before === undefined ? {} : { before: args.before }, - ...args.after === undefined ? {} : { after: args.after }, - }, exec.signal) - exec.signal.throwIfAborted() + const window = await sessionQueryCall(ctx, exec.signal, 'event read', () => + ctx.sessionQuery.readEvent({ + sessionId, + seq: args.seq, + ...args.before === undefined ? {} : { before: args.before }, + ...args.after === undefined ? {} : { after: args.after }, + }, exec.signal)) assertObservedTargetAuthorized(caller, sessionId, window.session) const title = await readTitle(ctx, caller, sessionId, exec.signal) return formatEventRead(sessionId, title, window) @@ -509,15 +631,6 @@ function buildSessionFilters(args: SessionSearchArgs): SessionResultFilter[] { } const created = timestampRange('created_at', args.created_at_from, args.created_at_to) if (created !== undefined) filters.push({ kind: 'created-at', ...created }) - if (args.parent_session_ids !== undefined || args.include_root_sessions === true) { - const values: Array = [] - if (args.parent_session_ids !== undefined) { - assertNonEmptyArray('parent_session_ids', args.parent_session_ids) - values.push(...args.parent_session_ids.map(SessionId)) - } - if (args.include_root_sessions === true) values.push(null) - filters.push({ kind: 'parent', values }) - } if (args.availability !== undefined) { assertNonEmptyArray('availability', args.availability) filters.push({ kind: 'availability', values: args.availability }) @@ -525,6 +638,12 @@ function buildSessionFilters(args: SessionSearchArgs): SessionResultFilter[] { return filters } +function materializeParentSessionIds(values: readonly string[] | undefined): SessionIdValue[] | undefined { + if (values === undefined) return undefined + assertNonEmptyArray('parent_session_ids', values) + return [...new Set(values.map(SessionId))] +} + interface EventFilterInput { readonly seqFrom?: number | undefined readonly seqTo?: number | undefined @@ -737,19 +856,7 @@ async function collectPages( let cursor: SessionSearchCursor | undefined while (true) { signal.throwIfAborted() - let page: Awaited> - try { - page = await request(cursor) - } catch (error: unknown) { - if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_STALE_CURSOR') { - throw new SessionQueryError( - 'session history changed while paging; retry the complete search call', - 'SESSION_QUERY_STALE_CURSOR', - { cause: error }, - ) - } - throw error - } + const page = await request(cursor) signal.throwIfAborted() for (const item of page.items) { if (!accept(item)) continue @@ -799,13 +906,17 @@ async function authorizeSessionIds( const cwd = caller.header.cwd const other = unique.filter(id => id !== caller.id) if (cwd === undefined || other.length === 0) return authorized - signal.throwIfAborted() - const records = await ctx.sessionQuery.filterSessions([ - { kind: 'id', values: other }, - { kind: 'cwd', values: [cwd] }, - ], signal) - signal.throwIfAborted() - for (const record of records) authorized.add(record.header.id) + const records = await sessionQueryCall(ctx, signal, 'session-id authorization', () => + ctx.sessionQuery.filterSessions([ + { kind: 'id', values: other }, + { kind: 'cwd', values: [cwd] }, + ], signal)) + const requested = new Set(other) + for (const record of records) { + if (requested.has(record.header.id) && recordAuthorized(record, caller)) { + authorized.add(record.header.id) + } + } return authorized } @@ -816,12 +927,11 @@ async function readTitles( signal: AbortSignal, ): Promise { const result = new Map() - signal.throwIfAborted() - const observations = await ctx.sessionQuery.readTitleSnapshots(ids, signal) - signal.throwIfAborted() + const observations = await sessionQueryCall(ctx, signal, 'title observation', () => + ctx.sessionQuery.readTitleSnapshots(ids, signal)) for (const observation of observations) { if (observation.status === 'rejected') { - result.set(observation.sessionId, unavailableTitle(ctx, observation.sessionId, observation.reason)) + result.set(observation.sessionId, unavailableTitle(ctx, observation.reason)) continue } assertObservedTargetAuthorized(caller, observation.sessionId, observation.value.session) @@ -841,17 +951,35 @@ async function readTitle( function unavailableTitle( ctx: Context, - id: SessionIdValue, error: unknown, ): TitleView { - if (error instanceof HarnessError && error.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') throw error - const code = error instanceof HarnessError ? error.code : 'UNKNOWN' - ctx.logger.warn(`tool-session-query: title read failed for session "${id}": ${fullError(error)}`) - return { text: 'untitled', unavailableCode: code } + const sanitized = sanitizeSessionQueryError(ctx, 'title observation item', error) + if (sanitized.code === 'SESSION_QUERY_TOOL_UNAUTHORIZED') throw sanitized + return { text: 'untitled', unavailableCode: sanitized.code } } function fullError(error: unknown): string { - return error instanceof Error ? error.stack ?? String(error) : String(error) + try { + return renderFullError(error) + } catch { + return UNPRINTABLE_SERVICE_ERROR + } +} + +function renderFullError(error: unknown): string { + if (!(error instanceof Error)) return String(error) + const diagnostics: string[] = [] + const seen = new Set() + let current: unknown = error + while (current instanceof Error && !seen.has(current)) { + seen.add(current) + diagnostics.push(current.stack ?? String(current)) + current = current.cause + } + /* v8 ignore next -- defensive containment for a cyclic Error.cause graph */ + if (current instanceof Error) diagnostics.push('[circular error cause]') + else if (current !== undefined) diagnostics.push(renderFullError(current)) + return diagnostics.join('\nCaused by: ') } function authorizeDescendants( @@ -927,7 +1055,7 @@ function formatSessionSearch( titles: CompleteTitleMap, authorizedParents: ReadonlySet, ): string { - if (collected.items.length === 0) return 'No prior session matches found.' + if (collected.items.length === 0) return formatEmptySessionSearch() const lines = [`Session search results (${collected.items.length}):`] for (const [index, hit] of collected.items.entries()) { const parent = hit.header.parentSession === undefined @@ -955,6 +1083,10 @@ function formatSessionSearch( return lines.join('\n') } +function formatEmptySessionSearch(): string { + return 'No prior session matches found.' +} + function formatEventSearch( sessionId: SessionIdValue, title: TitleView, diff --git a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts index d52a4d48aa..35ab1fa408 100644 --- a/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts +++ b/packages/session-query/tool-session-query/tests/tool-session-query.spec.ts @@ -363,6 +363,7 @@ describe('input validation and translation', () => { it('normalizes the query and compiles inclusive session/event filters with one parent OR clause', async () => { const mounted = await mount() + createSession(mounted.ctx, 'parent', '/work') await mounted.call('session_search', { query: ' alpha beta ', session_ids: ['a', 'b'], @@ -388,8 +389,8 @@ describe('input validation and translation', () => { from: Date.parse('2026-07-24T00:00:00+08:00'), to: Date.parse('2026-07-24T01:00:00+08:00'), }, - { kind: 'parent', values: ['parent', null] }, { kind: 'availability', values: ['live'] }, + { kind: 'parent', values: ['parent', null] }, { kind: 'cwd', values: ['/work'] }, ], eventFilters: [ @@ -538,6 +539,7 @@ describe('input validation and translation', () => { it('compiles one-sided timestamps and independent root/parent clauses', async () => { const mounted = await mount() + createSession(mounted.ctx, 'parent', '/work') await mounted.call('session_search', { query: 'q', created_at_from: '2024-02-29T00:00Z', @@ -596,6 +598,191 @@ describe('workspace authority and lineage redaction', () => { .toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') }) + it('makes hidden and nonexistent parent guesses indistinguishable without calling search', async () => { + const mounted = await mount() + const hiddenParent = createSession(mounted.ctx, 'guessed-hidden-parent-secret', '/outside') + const visibleChild = createSession( + mounted.ctx, + 'visible-child-of-hidden-parent', + '/work', + 20, + hiddenParent.id, + ) + FakeQuery.sessionSearch = () => Promise.resolve({ + items: [sessionHit(visibleChild.id, '/work', 'must not be discoverable', hiddenParent.id)], + }) + + const hidden = await mounted.call('session_search', { + query: 'needle', + parent_session_ids: [hiddenParent.id], + }) + const missing = await mounted.call('session_search', { + query: 'needle', + parent_session_ids: ['guessed-missing-parent'], + }) + + expect(hidden).toEqual(missing) + expect(text(hidden)).toBe('No prior session matches found.') + expect(JSON.stringify(hidden)).not.toContain(visibleChild.id) + expect(FakeQuery.sessionRequests).toEqual([]) + }) + + it('deduplicates parent guesses and sends only authorized parents plus the root marker', async () => { + const mounted = await mount() + const visible = createSession(mounted.ctx, 'visible-parent', '/work') + const hidden = createSession(mounted.ctx, 'hidden-parent-filter-secret', '/outside') + + await mounted.call('session_search', { + query: 'needle', + parent_session_ids: [visible.id, hidden.id, visible.id, 'missing-parent'], + include_root_sessions: true, + }) + await mounted.call('session_search', { + query: 'needle', + parent_session_ids: [hidden.id], + include_root_sessions: true, + }) + await mounted.call('session_search', { + query: 'needle', + parent_session_ids: ['missing-parent'], + include_root_sessions: true, + }) + + const parentValues = FakeQuery.sessionRequests.map(request => + request.sessionFilters?.find(filter => filter.kind === 'parent')) + expect(parentValues).toEqual([ + { kind: 'parent', values: [visible.id, null] }, + { kind: 'parent', values: [null] }, + { kind: 'parent', values: [null] }, + ]) + }) + + it('rejects unrequested or unauthorized records returned during parent preauthorization', async () => { + const mounted = await mount() + const requested = SessionId('requested-parent') + vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions').mockResolvedValueOnce([ + { header: header('unrequested-parent', '/work'), live: true, persisted: false }, + { header: header(requested, '/outside'), live: true, persisted: false }, + ]) + + const result = await mounted.call('session_search', { + query: 'needle', + parent_session_ids: [requested], + }) + + expect(text(result)).toBe('No prior session matches found.') + expect(FakeQuery.sessionRequests).toEqual([]) + }) + + it('validates every other search filter before parent preauthorization', async () => { + const mounted = await mount() + const filterSessions = vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions') + + const result = await mounted.call('session_search', { + query: 'needle', + parent_session_ids: ['guessed-parent'], + event_seq_from: -1, + }) + + expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_FILTER') + expect(filterSessions).not.toHaveBeenCalled() + expect(FakeQuery.sessionRequests).toEqual([]) + }) + + it('sanitizes parent preauthorization failures without calling search', async () => { + const mounted = await mount() + const secret = 'conflict at hidden-parent-preauthorization-secret' + vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions').mockRejectedValueOnce( + new SessionQueryError(secret, 'SESSION_QUERY_SOURCE_CONFLICT'), + ) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call('session_search', { + query: 'needle', + parent_session_ids: ['guessed-parent'], + }) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED') + expect(text(result)).toBe('Error: session query operation failed') + expect(JSON.stringify(result)).not.toContain(secret) + expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret)) + expect(FakeQuery.sessionRequests).toEqual([]) + }) + + it('sanitizes direct-target authorization failures before event search', async () => { + const mounted = await mount() + const target = createSession(mounted.ctx, 'authorization-failure-target', '/work') + const secret = 'conflict with hidden-authorization-session-secret' + vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions').mockRejectedValueOnce( + new SessionQueryError(secret, 'SESSION_QUERY_SOURCE_CONFLICT'), + ) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call('session_event_search', { + session_id: target.id, + query: 'needle', + }) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED') + expect(text(result)).toBe('Error: session query operation failed') + expect(JSON.stringify(result)).not.toContain(secret) + expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret)) + expect(FakeQuery.eventRequests).toEqual([]) + }) + + it('preserves parent-preauthorization cancellation and waits for cleanup without logging it', async () => { + const mounted = await mount() + const controller = new AbortController() + const cancellation = new SessionQueryError( + 'parent preauthorization cancelled', + 'SESSION_QUERY_ABORTED', + ) + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + let active = false + vi.spyOn(mounted.ctx.sessionQuery, 'filterSessions') + .mockImplementation(async (_filters, signal) => { + if (signal === undefined) throw new Error('expected parent-authorization signal') + active = true + const aborted = new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + started.resolve(undefined) + await aborted + abortObserved.resolve(undefined) + await cleanup.promise + active = false + signal.throwIfAborted() + return [] + }) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const pending = mounted.call('session_search', { + query: 'needle', + parent_session_ids: ['guessed-parent'], + }, { signal: controller.signal }) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + await started.promise + controller.abort(cancellation) + await abortObserved.promise + + expect(settled).toBe(false) + expect(active).toBe(true) + expect(FakeQuery.sessionRequests).toEqual([]) + + cleanup.resolve(undefined) + const result = await pending + expect(active).toBe(false) + expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') + expect(text(result)).toBe('Error: parent preauthorization cancelled') + expect(warn).not.toHaveBeenCalled() + }) + it('redacts an unauthorized ancestor and prunes unauthorized descendant subtrees without hidden ids', async () => { const mounted = await mount() const hiddenParent = createSession(mounted.ctx, 'hidden-parent-secret', '/outside') @@ -635,6 +822,16 @@ describe('workspace authority and lineage redaction', () => { }) it.each([ + { + name: 'sensitive source conflict', + makeError: () => new SessionQueryError( + 'conflict with hidden-lineage-session-secret', + 'SESSION_QUERY_SOURCE_CONFLICT', + ), + code: 'SESSION_QUERY_TOOL_FAILED', + message: 'session query operation failed', + secret: 'hidden-lineage-session-secret', + }, { name: 'typed query error', makeError: () => new SessionQueryError( @@ -642,23 +839,56 @@ describe('workspace authority and lineage redaction', () => { 'SESSION_QUERY_PERSISTENCE_FAILED', ), code: 'SESSION_QUERY_PERSISTENCE_FAILED', - message: 'unrelated persistence failure', + message: 'session history storage is unavailable', + secret: 'unrelated persistence failure', }, { name: 'plain error', makeError: () => new Error('unrelated plain trace failure'), - code: undefined, - message: 'unrelated plain trace failure', + code: 'SESSION_QUERY_TOOL_FAILED', + message: 'session query operation failed', + secret: 'unrelated plain trace failure', }, - ])('preserves an unrelated $name from lineage tracing', async ({ makeError, code, message }) => { + ])('sanitizes an unrelated $name from lineage tracing', async ({ makeError, code, message, secret }) => { const mounted = await mount() const target = createSession(mounted.ctx, 'trace-failure-target', '/work') + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) vi.spyOn(mounted.ctx.sessionQuery, 'traceSession').mockRejectedValueOnce(makeError()) const result = await mounted.call('session_trace', { session_id: target.id }) expect(errorCode(result)).toBe(code) expect(text(result)).toBe(`Error: ${message}`) + expect(JSON.stringify(result)).not.toContain(secret) + expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret)) + }) + + it.each([ + 'session_event_trace', + 'session_event_read', + ] as const)('sanitizes typed service diagnostics from %s', async (toolName) => { + const mounted = await mount() + const target = createSession(mounted.ctx, `${toolName}-failure-target`, '/work') + target.append( + 'user/message', + { content: [{ type: 'text', text: 'event' }], source: { kind: 'user' } }, + { surfaceOp: 'append' }, + ) + const secret = `event missing beside hidden-${toolName}-secret` + const failure = new SessionQueryError(secret, 'SESSION_QUERY_EVENT_NOT_FOUND') + if (toolName === 'session_event_trace') { + vi.spyOn(mounted.ctx.sessionQuery, 'traceEvent').mockRejectedValueOnce(failure) + } else { + vi.spyOn(mounted.ctx.sessionQuery, 'readEvent').mockRejectedValueOnce(failure) + } + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call(toolName, { session_id: target.id, seq: 0 }) + + expect(errorCode(result)).toBe('SESSION_QUERY_EVENT_NOT_FOUND') + expect(text(result)).toBe('Error: session event was not found') + expect(JSON.stringify(result)).not.toContain(secret) + expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret)) }) it.each([ @@ -681,6 +911,7 @@ describe('workspace authority and lineage redaction', () => { const started = Promise.withResolvers() const abortObserved = Promise.withResolvers() const cleanup = Promise.withResolvers() + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) let observedSignal: AbortSignal | undefined let active = false const holdExactRead = async (signal?: AbortSignal): Promise => { @@ -731,6 +962,7 @@ describe('workspace authority and lineage redaction', () => { expect(active).toBe(false) expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') expect(text(result)).toBe(`Error: ${toolName} cancelled`) + expect(warn).not.toHaveBeenCalled() }) it('preserves caller cancellation while a lineage trace is pending', async () => { @@ -1052,6 +1284,239 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => expect(output).not.toContain('Result cap reached') }) + it.each([ + { + toolName: 'session_search', + args: { query: 'needle' }, + secrets: [ + 'session source conflict at hidden-search-session-secret', + 'hidden-search-cause-secret', + ], + failure: () => new SessionQueryError( + 'session source conflict at hidden-search-session-secret', + 'SESSION_QUERY_SOURCE_CONFLICT', + { cause: new Error('hidden-search-cause-secret') }, + ), + }, + { + toolName: 'session_event_search', + args: { query: 'needle' }, + secrets: [ + 'plain event provider failure at hidden-event-session-secret', + 'hidden-event-cause-secret', + ], + failure: () => new Error( + 'plain event provider failure at hidden-event-session-secret', + { cause: 'hidden-event-cause-secret' }, + ), + }, + ] as const)('sanitizes $toolName provider diagnostics', async ({ toolName, args, secrets, failure }) => { + const mounted = await mount() + if (toolName === 'session_search') { + FakeQuery.sessionSearch = () => Promise.reject(failure()) + } else { + FakeQuery.eventSearch = () => Promise.reject(failure()) + } + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call(toolName, args) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED') + expect(text(result)).toBe('Error: session query operation failed') + for (const secret of secrets) { + expect(JSON.stringify(result)).not.toContain(secret) + expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret)) + } + }) + + it.each([ + { + name: 'a hostile prototype trap', + secrets: ['proxy payload secret', 'getPrototypeOf secondary secret'], + diagnostic: '[unprintable session query failure]', + failure: (): unknown => new Proxy( + { payload: 'proxy payload secret' }, + { + getPrototypeOf() { + throw new Error('getPrototypeOf secondary secret') + }, + }, + ), + }, + { + name: 'a throwing stack getter', + secrets: ['stack primary secret', 'stack getter secondary secret'], + diagnostic: '[unprintable session query failure]', + failure: (): unknown => { + const error = new Error('stack primary secret') + Object.defineProperty(error, 'stack', { + get() { + throw new Error('stack getter secondary secret') + }, + }) + return error + }, + }, + { + name: 'a throwing cause getter', + secrets: ['cause primary secret', 'cause getter secondary secret'], + diagnostic: '[unprintable session query failure]', + failure: (): unknown => { + const error = new Error('cause primary secret') + Object.defineProperty(error, 'cause', { + get() { + throw new Error('cause getter secondary secret') + }, + }) + return error + }, + }, + { + name: 'throwing string coercion', + secrets: ['string payload secret', 'string coercion secondary secret'], + diagnostic: '[unprintable session query failure]', + failure: (): unknown => ({ + payload: 'string payload secret', + [Symbol.toPrimitive]() { + throw new Error('string coercion secondary secret') + }, + }), + }, + { + name: 'a throwing code getter', + secrets: ['code primary secret', 'code getter secondary secret'], + diagnostic: 'code primary secret', + failure: (): unknown => { + const error = new SessionQueryError( + 'code primary secret', + 'SESSION_QUERY_PERSISTENCE_FAILED', + ) + Object.defineProperty(error, 'code', { + get() { + throw new Error('code getter secondary secret') + }, + }) + return error + }, + }, + { + name: 'an unknown string code', + secrets: ['unknown code primary secret', '__proto__'], + diagnostic: 'unknown code primary secret', + failure: (): unknown => { + const error = new SessionQueryError( + 'unknown code primary secret', + 'SESSION_QUERY_PERSISTENCE_FAILED', + ) + Object.defineProperty(error, 'code', { value: '__proto__' }) + return error + }, + }, + { + name: 'a non-string code', + secrets: ['non-string code primary secret', 'non-string code secondary secret'], + diagnostic: 'non-string code primary secret', + failure: (): unknown => { + const error = new SessionQueryError( + 'non-string code primary secret', + 'SESSION_QUERY_PERSISTENCE_FAILED', + ) + Object.defineProperty(error, 'code', { + value: { + toString() { + throw new Error('non-string code secondary secret') + }, + }, + }) + return error + }, + }, + ])('fails generic when inspecting $name is unsafe', async ({ secrets, diagnostic, failure }) => { + const mounted = await mount() + // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- hostile unknown rejection is the scenario + FakeQuery.sessionSearch = () => Promise.reject(failure()) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call('session_search', { query: 'needle' }) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED') + expect(text(result)).toBe('Error: session query operation failed') + for (const secret of secrets) expect(JSON.stringify(result)).not.toContain(secret) + expect(warn).toHaveBeenCalledWith(expect.stringContaining(diagnostic)) + }) + + it('retains a fixed safe typed failure when only its nested diagnostic is unprintable', async () => { + const mounted = await mount() + const primary = 'typed outer diagnostic secret' + const nested = 'nested prototype secondary secret' + const cause = new Proxy( + {}, + { + getPrototypeOf() { + throw new Error(nested) + }, + }, + ) + FakeQuery.sessionSearch = () => Promise.reject( + new SessionQueryError( + primary, + 'SESSION_QUERY_PERSISTENCE_FAILED', + { cause }, + ), + ) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call('session_search', { query: 'needle' }) + + expect(errorCode(result)).toBe('SESSION_QUERY_PERSISTENCE_FAILED') + expect(text(result)).toBe('Error: session history storage is unavailable') + expect(JSON.stringify(result)).not.toContain(primary) + expect(JSON.stringify(result)).not.toContain(nested) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('[unprintable session query failure]')) + }) + + it('logs an inspectable cyclic cause chain without exposing it', async () => { + const mounted = await mount() + const outer = new Error('cyclic outer secret') + const inner = new Error('cyclic inner secret') + Object.defineProperty(outer, 'cause', { value: inner }) + Object.defineProperty(inner, 'cause', { value: outer }) + FakeQuery.sessionSearch = () => Promise.reject(outer) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call('session_search', { query: 'needle' }) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED') + expect(text(result)).toBe('Error: session query operation failed') + expect(JSON.stringify(result)).not.toContain('cyclic outer secret') + expect(JSON.stringify(result)).not.toContain('cyclic inner secret') + expect(warn).toHaveBeenCalledWith(expect.stringContaining('cyclic outer secret')) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('cyclic inner secret')) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('[circular error cause]')) + }) + + it('fails generic when internal warning logging throws', async () => { + const mounted = await mount() + const primary = 'typed persistence primary secret' + const secondary = 'logger warning secondary secret' + FakeQuery.sessionSearch = () => Promise.reject( + new SessionQueryError(primary, 'SESSION_QUERY_PERSISTENCE_FAILED'), + ) + const warn = vi.spyOn(mounted.ctx.logger, 'warn') + .mockImplementation(() => undefined) + .mockImplementationOnce(() => { + throw new Error(secondary) + }) + + const result = await mounted.call('session_search', { query: 'needle' }) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED') + expect(text(result)).toBe('Error: session query operation failed') + expect(JSON.stringify(result)).not.toContain(primary) + expect(JSON.stringify(result)).not.toContain(secondary) + expect(warn).toHaveBeenCalledTimes(1) + }) + it('preserves stale-cursor diagnostics without transparently restarting', async () => { const mounted = await mount({ maxSearchResults: 2 }) const cursor = SessionSearchCursor('stale-next') @@ -1070,6 +1535,7 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => FakeQuery.sessionSearch = () => Promise.resolve({ items: [], nextCursor: cursor }) const result = await mounted.call('session_search', { query: 'needle' }) expect(errorCode(result)).toBe('SESSION_QUERY_INVALID_CURSOR') + expect(text(result)).toBe('Error: session-search provider repeated a continuation cursor') expect(FakeQuery.sessionRequests).toHaveLength(2) }) @@ -1166,7 +1632,8 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) const result = await mounted.call('session_search', { query: 'needle' }) expect(result.isError).toBe(false) - expect(text(result)).toContain('untitled (title unavailable: TITLE_BACKEND)') + expect(text(result)).toContain('untitled (title unavailable: SESSION_QUERY_TOOL_FAILED)') + expect(JSON.stringify(result)).not.toContain('title backend failed') expect(warn).toHaveBeenCalledWith(expect.stringContaining('title backend failed')) expect(warn).toHaveBeenCalledWith(expect.stringContaining('HarnessError')) }) @@ -1174,7 +1641,7 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => it('reports unknown title failures and preserves an Error without a stack', async () => { const mounted = await mount() const first = createSession(mounted.ctx, 'unknown-title', '/work') - const second = createSession(mounted.ctx, 'stackless-title', '/work') + const second = createSession(mounted.ctx, 'second-title-failure', '/work') const stackless = new Error('stackless') Object.defineProperty(stackless, 'stack', { value: undefined }) const readTitles = vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots') @@ -1190,13 +1657,62 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => }) const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) const result = await mounted.call('session_search', { query: 'needle' }) - expect(text(result)).toContain('title unavailable: UNKNOWN') + expect(text(result)).toContain('title unavailable: SESSION_QUERY_TOOL_FAILED') + expect(JSON.stringify(result)).not.toContain('string failure') + expect(JSON.stringify(result)).not.toContain('stackless') expect(readTitles).toHaveBeenCalledTimes(1) expect(readTitles.mock.calls[0]?.[0]).toEqual([first.id, second.id]) expect(warn).toHaveBeenCalledWith(expect.stringContaining('string failure')) expect(warn).toHaveBeenCalledWith(expect.stringContaining('Error: stackless')) }) + it('isolates an unprintable per-title failure behind the generic unavailable marker', async () => { + const mounted = await mount() + const hit = createSession(mounted.ctx, 'hostile-title-failure', '/work') + const primary = 'per-title proxy payload secret' + const secondary = 'per-title prototype secondary secret' + const reason = new Proxy( + { payload: primary }, + { + getPrototypeOf() { + throw new Error(secondary) + }, + }, + ) + FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] }) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots').mockResolvedValueOnce([{ + sessionId: hit.id, + status: 'rejected', + reason, + }]) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call('session_search', { query: 'needle' }) + + expect(result.isError).toBe(false) + expect(text(result)).toContain('untitled (title unavailable: SESSION_QUERY_TOOL_FAILED)') + expect(JSON.stringify(result)).not.toContain(primary) + expect(JSON.stringify(result)).not.toContain(secondary) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('[unprintable session query failure]')) + }) + + it('sanitizes a thrown batch-title service failure instead of rendering its diagnostic', async () => { + const mounted = await mount() + const hit = createSession(mounted.ctx, 'thrown-title-failure', '/work') + const secret = 'title batch failed beside hidden-title-session-secret' + FakeQuery.sessionSearch = () => Promise.resolve({ items: [sessionHit(hit.id, '/work')] }) + vi.spyOn(mounted.ctx.sessionQuery, 'readTitleSnapshots') + .mockRejectedValueOnce(new Error(secret)) + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) + + const result = await mounted.call('session_search', { query: 'needle' }) + + expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_FAILED') + expect(text(result)).toBe('Error: session query operation failed') + expect(JSON.stringify(result)).not.toContain(secret) + expect(warn).toHaveBeenCalledWith(expect.stringContaining(secret)) + }) + it('does not downgrade cancellation during title enrichment', async () => { const mounted = await mount() const hit = createSession(mounted.ctx, 'abort-title', '/work') @@ -1237,6 +1753,8 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => const result = await mounted.call('session_search', { query: 'needle' }) expect(errorCode(result)).toBe('SESSION_QUERY_TOOL_UNAUTHORIZED') + expect(text(result)).toBe('Error: session target is outside the caller workspace') + expect(JSON.stringify(result)).not.toContain('title observation became unauthorized') expect(text(result)).not.toContain('title unavailable') }) @@ -1360,6 +1878,7 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => it('passes the exact execution signal to every FTS page and stops on cancellation', async () => { const mounted = await mount() const controller = new AbortController() + const warn = vi.spyOn(mounted.ctx.logger, 'warn').mockImplementation(() => undefined) let started!: () => void const bodyStarted = new Promise((resolve) => { started = resolve }) FakeQuery.sessionSearch = (_request, exec) => new Promise((_resolve, reject) => { @@ -1368,13 +1887,15 @@ describe('search paging, prior-history bounds, titles, and cancellation', () => reject(new SessionQueryError('aborted', 'SESSION_QUERY_ABORTED')) }, { once: true }) }) + const cancellation = new SessionQueryError('aborted', 'SESSION_QUERY_ABORTED') const pending = mounted.call('session_search', { query: 'needle' }, { signal: controller.signal }) await bodyStarted - controller.abort() + controller.abort(cancellation) const result = await pending expect(result.isError).toBe(true) expect(errorCode(result)).toBe('SESSION_QUERY_ABORTED') expect(FakeQuery.searchSignals).toEqual([controller.signal]) + expect(warn).not.toHaveBeenCalled() }) }) From 8f97f95d7bb03889bee91d14ad5b03a1fca7c6f9 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 21:06:54 +0800 Subject: [PATCH 027/113] docs(i18n): bilingual pair for the web e2e lane Agent Note Chinese counterpart translated per the terminology table and the 2026-07-18 TUI note's register; switcher lines added on both sides; pair recorded. doc-sync 24/24. --- ...6-07-24-web-gui-browser-e2e-lane.i18n.yaml | 6 ++ .../2026-07-24-web-gui-browser-e2e-lane.md | 2 + .../2026-07-24-web-gui-browser-e2e-lane.zh.md | 90 +++++++++++++++++++ 3 files changed, 98 insertions(+) create mode 100644 .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml create mode 100644 .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml new file mode 100644 index 0000000000..1f55dfce3e --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.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 +2026-07-24-web-gui-browser-e2e-lane.md: 3cabceb9667d3d1c153518d58b8d4c02b0578d20 +2026-07-24-web-gui-browser-e2e-lane.zh.md: 132caa453662f48619aa542c68b59f59b64acd0f diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md index fddd1e9a0c..3cabceb966 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-24-web-gui-browser-e2e-lane.zh.md) + ## Problem The web GUI ships as a real assembled chain — chromium page → client plugin bundles → HTTP unary RPC + two SSE streams → `toFetchHandler`/apiproxy → `bootHost`'s agent loop, tools, and JSONL persistence — and no test exercised that chain keylessly and deterministically. The [GUI testing system](../process/2026-07-20-gui-testing-system.md) covers tier 1 (wire isomorphism in node), tier 2 (object-layer state machines), and tier-3 smokes, but the keyless smoke drives `FixtureApiClient` — no host, no wire, no agent loop — while the full-chain smoke needs `DEEPSEEK_API_KEY` and a live model, so it is nondeterministic and self-skips in keyless CI. The snapshot philosophy of [docs/testing.md](../../../../docs/testing.md) — record once with a key, replay forever keyless, refresh on format churn — already covers the ACP, headless `stream-json`, and TUI transcript surfaces; the web surface was the one assembled product shape without it. The gap is exactly where the two confirmed GUI P0s hid: the wire carriage chain the fixture client short-circuits. diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md new file mode 100644 index 0000000000..132caa4536 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md @@ -0,0 +1,90 @@ +# Agent Note: Web GUI 的无密钥浏览器 e2e 车道 + +Status: implemented + +[English](2026-07-24-web-gui-browser-e2e-lane.md) | 中文 + +## 问题 + +Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bundle → HTTP 单次 RPC + 两条 SSE(Server-Sent Events)流 → `toFetchHandler`/apiproxy → `bootHost` 的 agent loop(智能体循环)、工具与 JSONL 持久化——却没有任何测试无密钥且确定性地检验这条链。[GUI 测试体系](../process/2026-07-20-gui-testing-system.md)覆盖第 1 层(Node 中的协议同构)、第 2 层(对象层状态机)与第 3 层冒烟测试,但无密钥冒烟驱动的是 `FixtureApiClient`——没有 host、没有 wire、没有 agent loop——而全链路冒烟需要 `DEEPSEEK_API_KEY` 和真实模型,因此不确定、在无密钥 CI 中自行跳过。[docs/testing.md](../../../../docs/testing.md) 的快照哲学——带密钥录制一次、永久无密钥回放、格式变动时刷新——已覆盖 ACP(Agent Client Protocol)、headless `stream-json` 与 TUI 三个文本记录(transcript)表面;web 表面是唯一没有这层保障的组装形态。而缺口恰恰是两起已实证 GUI P0 藏身之处:fixture(测试前置数据)客户端短路掉的 wire 承载链。 + +## 决策 + +`pnpm run test:web` 携带 `apps/web/tests/` 下的无密钥、确定性浏览器 e2e 车道:录制的会话日志 fixture 经 `@deepseek-ai/dsh-llm-replay` 对真实进程内 web 组装回放,断言规范化后的会话区 aria 预期输出加进程内世界状态。不新增包(package);产品侧增量只有 `BootHostOptions.llm` seam 和 `dsh-llm-replay` 的两处增量接口。 + +### Harness:`apps/web/tests/harness.ts` + +一个普通的共享 fixture 模块([测试政策认可的形态](../../../../docs/testing.md)),不是包:值得门禁把守的逻辑——回放推导、会话解析、日志脱敏、持久化——都在已受门禁的包 `dsh-llm-replay`、`dsh-acp-snapshot`、`dsh-session-persistence-jsonl` 中;剩下的只是启动接线和浏览器胶水,而驱动 chromium 的源码在无浏览器的覆盖率 runner 上无法诚实保持逐文件 100% 覆盖率。 + +`launchWebHarness()` 用导出的生产函数在进程内启动真实 web 组装——`startHost({ boot: { …, llm: false } })`、`installLlmReplay(host.ctx, { file, providers, paceMs })`、`mountWebPlugins(host.ctx, roster, anchor)`、`createHostWebPluginRegistry`、`startWebServer({ port: 0, … })`。这是 TUI 套件进程内挂载生产 bundle 的 web 对应物([TUI 快照](2026-07-18-tui-terminal-state-snapshots.md)):真实入口边界(`dsh web` bin 的参数解析、dist 解析)仍由 `smoke-real.e2e.ts` 中的无密钥 CLI 冒烟把守,且 web 表面没有可绕过的 `cordis.yml`——按[GUI 分层决策](../architecture/2026-07-19-gui-layering-and-rpc-protocol.md),组装写在应用里;本车道的设计评审明确重申了这一裁定(Loader 化 `dsh web` 被否决;那需要自己的提案)。与 `dsh web` shell 的两处刻意组装差异已注明在 harness 头部:`workspaceContext: false`(录制的 fixture 不得嵌入本仓库的 AGENTS.md),以及 `sessionTitleLlm` 保持 bootHost 的禁用默认值(其发后不管的标题调用会与循环自身的调用不确定地共享会话的回放游标)。 + +`llm: false` seam 是无密钥启动问题经评审后的定论:`BootHostOptions` 上的 `'deepseek' | false`,与 `workspaceContext: Config | false` 形态一致,且 `RunningHost.ctx` 的 JSDoc 把「填充刻意开放的能力 seam」列为其第三种认可用法。回放必须以提供方目录(providers-catalog)模式运行并发布 `contextWindow`(TUI 的 `PROVIDERS` 形态),绝不用 catch-all:没有注册适配器时,catch-all 会让 `resolveModelContext` 无路由可走,`compact-basic` 的步后压力检查将步步告警,而不是被可证明地闲置。 + +`seedSession()` 通过真实持久化 API 播种冷会话——一次性 `Context` 挂载 `SessionStore` + `SessionPersistenceJsonl` 指向 host 的根目录,`create()` + `append()`,一次 `utimes` 回拨保证侧栏顺序确定(`semantic-checkpoint.snapshot.ts` 先例)——绝不裸写文件,因此播种器对桶哈希、文件名编码、压缩一无所知,host 的 zstd 默认值也无需任何启动开关。种子在播种时即校验(可解析、以 `turn/end` 结尾——未闭合的最终轮次会被恢复(resume)的崩溃修复改写)。 + +### 确定性规则 + +提示一轮对话的屏障栈,按序:(1)host 侧 `await agent.whenIdle()` 加超时,以进程内 `turn/end` 为锚——空闲翻转发生在持久化落盘之后,一次等待同时覆盖轮次完成与持久性;(2)浏览器安定轮询(流式输出节点已卸载、最终文本可见);(3)任何日志采收都在 `host.dispose()` 之后。单独监听进程内 `turn/end` 是错误屏障(它先于 SSE 帧到达浏览器、先于 fsync 触发);文件轮询被禁止(NFS 上慢,且被 `whenIdle` 取代);`networkidle` 被彻底禁止(SSE 流保持打开时它永不解析)。 + +不做单次瞬态 DOM 断言:从回放产出到 React 提交的每一跳都可能合并分片,采样 `[data-streaming]` 天然就是竞态。流式输出的增量性由持久化的 `assistant/chunk` 事件断言(模型可见 ⟺ 已记录,使日志成为权威证据)。`dsh-llm-replay` 的可选 `paceMs`(默认缺省 = 突发)只是让浏览器观察到真正增量 SSE 的真实感旋钮;正确性绝不依赖它,且节奏等待期间中止会即时取消。 + +每个场景都会因任何 pageerror 或客户端的连接丢失/间隙修复控制台警告而失败:否则重连机制加历史重同步会把一条死掉的 SSE 通路自愈掉,套件反而认证了坏 wire。Harness 的 `close()` 调用 `ReplayHandle.assertConsumed()` 收尾检查(每个已录脚本都被绑定、每个游标都耗尽),把静默的少放与错绑变成清晰诊断。车道不设 vitest 重试;每文件一个 chromium、每场景一个新 context、每场景一个 host;视口固定;选择器只锚定 role、`data-*` 属性和可见文本。 + +### 预期输出 + +每场景一份提交的预期输出:会话区规范化 `ariaSnapshot()`(`ui.expected.md`)——uuid/cwd/工作区目录名/时长归一为稳定 token,在安定里程碑处轮询至两次相等再采集——外加几条 role/文本锚断言,让保语义的组件重写在预期输出可评审地变动时仍保持绿色锚点。aria 树是 client 规则「断言用户所见,绝不断言类名」的机械化。世界状态断言内联在 `host.ctx` 会话事件上(哪些工具运行了、`turn/end` 完成)而不是第二份提交的日志预期输出:持久化日志表面已由 ACP/headless/TUI 套件经同一循环和持久化钉住,在此重复钉住会违背分层纪律、翻倍刷新成本。`refresh` 是预期输出的唯一写入者——回放模式下预期输出缺失会连同修复命令一起报错,而不是静默自举。 + +类型检查平面切分是结构性的:`apps/web/tests/{harness,support,replay-round-trip.e2e,seeded-history.e2e}.ts` 是 host 平面程序(它们启动 host 主干),因此被排除出注册在 client 侧的 `apps/web` 工程,逐文件纳入 `tsconfig.host.json`——一个程序不能同时持有 cordis `Context` 合并的两侧。 + +### 模式与 fixture + +`DSH_SNAPSHOT` 以内联 spec 分支选择 replay(默认,无密钥)、record(带密钥)或 refresh(无密钥)——TUI 的形态,不是套件工厂:两个场景撑不起 acp-snapshot 工厂机制,且真正共享的部分已被导出(`scrubRequestHeaders`、`parseSessionLog`、`installLlmReplay`)。每个 spec 切分为驱动步骤(输入、发送、`whenTurnSettled`——所有模式都执行,绝不等待模型内容选择器,因此 record 不会因真实模型答法不同而挂起)与断言步骤(仅 replay/refresh)。Record = 经真实输入框实时驱动 + 采收内存中的 `session.header`/`session.events`(TUI 的 `rawSessionLog` 形态——无需文件解压)+ `scrubRequestHeaders` + `{{sessionId}}`/`{{cwd}}` token 化;随后一次无密钥 refresh 重新生成 `ui.expected.md`。两个场景的 fixture 都经此流程对本组装录制。一条漂移防线把每个 spec 的驱动提示词与 fixture 录制的 `user/message` 绑定。fixture 清单防线保持每个场景目录封闭(精确文件集合,每个 JSONL 都是脱敏不动点)。Web fixture 全部脱敏请求头且不钉任何头类别,沿用 TUI 先例而非[钉住请求头](2026-07-06-pin-request-header-content-in-one-scenario.md)的严格读法——见「暂缓」。 + +### 场景 + +1. **`replay-round-trip`**——新会话,经真实输入框发送提示词,回放流式输出推理(reasoning)+ 一次在临时工作区真实执行的 `bash` 工具调用 + 最终文本(15ms 节奏)。断言安定后的 markdown、aria 预期输出与内联世界状态(bash `tool/call`、完成的 `turn/end`、>10 个分片事件)。 +2. **`seeded-history`**——冷播种一份已录会话;侧栏列出它(分组行 → 会话行,默认折叠),打开后纯凭日志经 `session.history` 内的隐式冷恢复挂载渲染工具卡片与文本——replay 下零模型调用,因此没有任何绑定约束;record 模式实时驱动同一轮(真实 `read` 工具读取播种的工作区文件)来产出种子。 + +### CI 立场 + +车道随 `pnpm run test:web` 交付、豁免门禁,与该配置头部注释所记一致。往 CI 加 chromium 会推翻 [GUI 测试笔记](../process/2026-07-20-gui-testing-system.md)中「CI 无浏览器基础设施」的前提,因此需要自己的 Agent Note 并从那里交叉链接,分阶段推进:先作为非必需任务,再以量化标准晋升(连续绿色运行次数、耗时、零重试的抖动预算、runner 浏览器缓存策略)。`TODO(ci-browser)` 标记该接缝。场景目前面向 POSIX(车道不在 Windows 矩阵中)。 + +## 业界先例 + +调研了 AI 聊天/agent web UI 与 mock 层(LibreChat、vercel/ai-chatbot + AI SDK、lobe-chat、open-webui、OpenHands、Chainlit、continue、cline、langfuse、gradio/streamlit;Playwright HAR/route、MSW、Polly/nock、WireMock、aimock)。自有后端的应用的主流成熟架构是:真实后端 seam 后放一个进程内伪造/回放模型,下游全部真实(LibreChat 的 `LIBRECHAT_TEST_RUN_HOOK` 伪模型;ai-chatbot 的 `MockLanguageModelV3` + `simulateReadableStream`;continue 的脚本化 mock 提供方类)——这正是 `dsh-llm-replay` 已然所是。浏览器层 SSE 拦截无法检验增量渲染(`route.fulfill` 一次性交付整个响应体;playwright#33564),且服务端 SSE 栈完全失测,因此各项目只把它用于边缘用例。分片节奏作为 fixture 参数反复出现(LibreChat 默认 10ms 附慢速档;ai-chatbot 500ms);CI 里的真实模型会腐烂(open-webui 的套件长出 120 秒超时,先被禁用后被删除);会话在持久化层以受控时间戳播种(LibreChat 直插回拨时间的 Mongo 文档;langfuse 播种其数据库)。没有任何被调研项目为 UI 测试把录制的 agent 事件日志经真实后端回放——最接近的是提供方层录制 fixture(aimock)与前端层 socket 历史发射(OpenHands MSW)——因此会话日志即 fixture 的设计沿着本仓库「模型可见 ⟺ 已记录」不变式所指的方向比业界先例多走了一步。 + +## 曾考虑的替代方案 + +**浏览器网络层 SSE 拦截(`page.route`)。** 已否决:`route.fulfill` 无法流式输出,增量 token 渲染无从检验,且服务端 SSE/背压/关闭路径——两起已实证 P0 的藏身处——完全失测。 + +**`DEEPSEEK_BASE_URL` 处的 mock HTTP 提供方。** 作为本车道机制已否决(仅保留给既有的工作区探针冒烟):fixture 会变成手写的 OpenAI SSE 字节脚本,一种与仓库其余部分录制回放的会话日志格式渐行渐远的第二 fixture 格式;适配器的真实 HTTP 路径归带密钥 e2e 管。 + +**扩展 `?fixture` 客户端。** 已否决:分层纪律——`FixtureApiClient` 的存在意义就是脱离服务器测试客户端 shell;client API seam 以下按构造即失测。 + +**用占位 `DEEPSEEK_API_KEY` + 回放拦截替代 `llm: false` seam。** 尽管零产品改动且树内有两处先例仍被否决:它用谎言满足 `llm-deepseek` 的快速失败密钥检查,还留下一个挂载却被拦截的死适配器;seam 方案与既有选项形态一致,并在最早可解析点快速失败。 + +**`packages/support/web-snapshot` 包 + `defineWebSnapshotSuite` 工厂。** 已否决:驱动 chromium 的源码在无浏览器的覆盖率 runner 上无法诚实保持逐文件 100%,且两个场景就上工厂是从单一消费方过度泛化,真正共享的逻辑已从受门禁的包中导出。重启条件:出现第二个 web 形态消费方,或 ≥6 个场景的内联分支被证实各自漂移;届时包边界将画在无浏览器一侧。 + +**第二份提交的规范化会话日志预期输出。** 已否决:日志表面已由 ACP/headless/TUI 套件经同一循环与持久化钉住;在此只会翻倍刷新成本并重复测试下层。内联在 `host.ctx` 事件上的世界状态断言保住了验证世界的义务。 + +**以 `DSH_SNAPSHOT` 回放分支拉起 `dsh web` bin。** 已否决:它需要在产品 bin 里加测试模式分支和环境变量管道,而进程内路线用的是零产品改动的导出生产函数;bin 的薄胶水已由无密钥 CLI 冒烟覆盖。只有 web host 某天 Loader 化它才免费——评审中已否决,并重申了应用内组装的裁定。 + +**为可测试性改 wire 协议。** 已否决:契约已有第一等的无密钥同构 seam(`InProcessApiClient(toFetchHandler(api))`),逐事件不合批的 SSE 恰是回放在浏览器中可观测的原因,测试一条不再交付的 wire 会颠倒该层的存在意义。 + +**以真实模型浏览器测试充当无密钥车道。** 已否决:按构造即不确定;被调研的前车之鉴(open-webui)长出无界超时后被删除。带密钥的 W5 冒烟仍是真实模型侧的补充。 + +**客户端 `data-dsh-busy` 安定信号。** 暂缓:两个场景下多条件安定轮询已经够用,host 侧 `whenIdle` 屏障承担了重活。重启条件:第一次安定轮询抖动,或某场景需要等待 DOM 不暴露的状态。 + +## Testing + +车道自身:`pnpm run test:web` 与既有冒烟对一起无密钥运行两个场景;`DSH_SNAPSHOT=record pnpm exec vitest run --config vitest.web.config.ts apps/web/tests/` 对真实模型重录某场景的 fixture;`DSH_SNAPSHOT=refresh` 无密钥重写两份 aria 预期输出。`llm: false` seam 由 `packages/host/runtime/tests/host-runtime.spec.ts` 钉住(无密钥启动、首次流式调用 NO_ADAPTER、嵌入方经 ctx 填充);`paceMs` 校验、节奏下限、节奏中中止、`assertConsumed` 的两种失败形态钉在 `packages/support/llm-replay/tests/llm-replay.spec.ts`。 + +## 暂缓 + +- **Web 头类别钉住**:web fixture 处处 token 化 `{{system}}`/`{{tools}}`,没有场景钉住 bootHost 组装的提示词/工具 schema(`TODO(web-header-pin)`——harness 的 `recordFixture` JSDoc 有标记)。沿用 TUI 处处脱敏先例;当 web 组装的请求头与其镜像的 repl 组合进一步分叉时重审。 +- **CI 浏览器供给**:推翻 CI 无浏览器裁定,分阶段标准见上(`TODO(ci-browser)`)。 +- **恢复后追问场景**:真实 wire 上的历史/实时缝合路径;当该代码变更或回归时作为独立场景补充。 + +## 后果 + +Web 表面获得了录制一次/永久回放的层级:真实 chromium → SSE → apiproxy → 循环 → 工具 → 持久化的链路以约 10-30 秒无密钥运行,重复运行结果确定,fixture 由车道自身持有并可重录。接受的成本:每次有意的会话 UI 变更都以一次无密钥 `DSH_SNAPSHOT=refresh` 收尾(预期输出变动是受评审的 diff,锚断言保住语义绿色);aria 格式归 Playwright 所有——仓库唯一不受自己控制的提交快照格式——因此 playwright 版本升级必须是刻意的升级加刷新提交(依赖在 `apps/web/package.json` 中浮动为 `^1.49.0`;若变动伤人则改为精确锁定);回放的首次调用顺序绑定把每个场景限制为至多一个发起提示的会话,消费断言是绊线;`compact-basic` 与会话共享回放游标,仅在发布的 128k 目录窗口下保持闲置;在 CI 反转被单独决策之前,车道只在其运行之处(本地,`test:web`)把守回归。 From c14f488b0059311290d90bd916297629517c137f Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 21:15:53 +0800 Subject: [PATCH 028/113] fix(persistence): use normalized project directory names --- ...7-24-project-session-directories.i18n.yaml | 4 +-- .../2026-07-24-project-session-directories.md | 10 +++--- ...26-07-24-project-session-directories.zh.md | 10 +++--- .../session-persistence-jsonl/README.md | 4 +-- .../session-persistence-jsonl/src/format.ts | 12 +++---- .../tests/jsonl.spec.ts | 33 ++++++++++++++----- 6 files changed, 45 insertions(+), 28 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml index f6cd03ddfd..a848e64c8f 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.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 -2026-07-24-project-session-directories.md: f65045419d5c749525ebdefcd1875dfc8ea69182 -2026-07-24-project-session-directories.zh.md: 1b4320d925c85b9b42a6c3ec9ee4ec52f4600786 +2026-07-24-project-session-directories.md: 2091027e67528855a3d9722bc63347319aada678 +2026-07-24-project-session-directories.zh.md: a161cff5ac42fb67650bdff593f91b95af471d1b diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md index f65045419d..2091027e67 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md @@ -16,12 +16,14 @@ The JSONL backend stores sessions under a readable project key and gives every s ```text / - ----/ + ----/ / session.jsonl.zstd ``` -Raw mode uses `session.jsonl`, and sessions without a cwd use `_no-cwd`. Filesystem and drive separators become `-`, unsafe code units use `~XXXX`, and the readable prefix is bounded to keep the component within filesystem limits. A short SHA-256 suffix distinguishes project paths whose readable forms collide or truncate alike. +Raw mode uses `session.jsonl`, and sessions without a cwd use `_no-cwd`. Filesystem and drive separators become `-`, unsafe code units use `~XXXX`, and the readable name is bounded to keep the component within filesystem limits. + +The project key intentionally has no hash suffix. This follows the common human-readable convention used by coding agents and keeps the normalized project path as the complete directory name. The normalization is lossy: paths such as `/a/b-c` and `/a-b/c`, or long paths with the same retained prefix, share one project directory. Their distinct session ids still select separate session directories; reuse of the same session id remains a storage collision and is rejected. The configured root remains a deployment choice. The layout neither selects a global root nor requires projects to share one. When a deployment does centralize storage, project paths remain recognizable; a project-local root uses the same deterministic structure. @@ -35,7 +37,7 @@ Lazy materialization remains tied to the transcript: `create()` performs no file **Put session files directly in each project directory.** This matched Claude Code and pi's basic file organization but left no session-level ownership boundary for future artifacts. -**Replace separators without a collision suffix.** This is readable but lossy: paths containing literal `-` can collide with paths where `-` represents a separator. Retaining a short hash suffix preserves readable navigation without merging distinct projects. +**Add a collision-resistant hash suffix.** This distinguishes paths whose normalized forms collide, but makes the directory name more than the normalized project path. The chosen convention accepts lossy project grouping in exchange for the simpler, recognizable name. **Mandate a centralized root.** Rejected because storage placement belongs to deployment configuration. Project grouping is useful when roots are shared and harmless when they are not. @@ -45,4 +47,4 @@ Lazy materialization remains tied to the transcript: `create()` performs no file Shared stores can be navigated by recognizable project names, while local and custom roots keep their existing configuration freedom. Every session has a directory available for future backend-owned artifacts, and existing transcript consumers still receive a file path. -Project directory names are longer than the former 12-hex cwd hashes. Very long paths show only a bounded prefix plus their distinguishing hash, and moving a project still selects a different directory because the absolute cwd remains part of storage identity. +Project directory names are longer than the former 12-hex cwd hashes. Very long paths show only a bounded prefix. Moving a project usually selects a different directory, but distinct cwd strings that normalize to the same name share one project directory by design. diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md index 1b4320d925..a161cff5ac 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md @@ -16,12 +16,14 @@ JSONL 后端按可读的项目键存储会话,并为每个会话提供独立 ```text / - ----/ + ----/ / session.jsonl.zstd ``` -原始模式使用 `session.jsonl`,没有 cwd 的会话使用 `_no-cwd`。文件系统路径分隔符和驱动器分隔符会转换为 `-`,不安全的代码单元使用 `~XXXX`,可读前缀则限制长度,以确保目录项不超过文件系统限制。短 SHA-256 后缀用于区分可读形式发生冲突或被截断成相同形式的项目路径。 +原始模式使用 `session.jsonl`,没有 cwd 的会话使用 `_no-cwd`。文件系统路径分隔符和驱动器分隔符会转换为 `-`,不安全的代码单元使用 `~XXXX`,可读名称则限制长度,以确保目录项不超过文件系统限制。 + +项目键有意不带哈希后缀。这遵循 coding agent(编码智能体)常用的易读约定,使规范化后的项目路径本身就是完整的目录名。规范化过程有损:`/a/b-c` 与 `/a-b/c` 等路径,或者保留前缀相同的长路径,会共用同一个项目目录。不同的会话 id 仍会选择不同的会话目录;复用相同的会话 id 仍构成存储冲突,系统会予以拒绝。 根目录由部署配置决定。这种布局既不选择全局根目录,也不要求项目共享根目录。部署选择集中存储时,目录名仍能让项目路径易于辨认;使用项目本地根目录时,也采用同样的确定性结构。 @@ -35,7 +37,7 @@ JSONL 后端按可读的项目键存储会话,并为每个会话提供独立 **把会话文件直接放入各项目目录。** 这与 Claude Code 和 pi 的基本文件组织一致,但没有为未来产物提供会话级归属边界。 -**替换分隔符但不添加冲突后缀。** 这种方式可读但有损:路径中的字面 `-` 可能与用 `-` 表示分隔符的路径发生冲突。保留短哈希后缀,既能让不同项目保持区分,又不会牺牲可读的浏览体验。 +**添加防冲突的哈希后缀。** 这种方式能区分规范化形式相同的路径,但会使目录名不再只是规范化后的项目路径。所选约定接受有损的项目分组,以换取更简单、易于辨认的名称。 **强制使用集中式根目录。** 不予采纳,因为存储位置属于部署配置。项目分组在根目录共享时有用,在不共享时也没有负面影响。 @@ -45,4 +47,4 @@ JSONL 后端按可读的项目键存储会话,并为每个会话提供独立 共享存储可以通过易于辨认的项目名进行浏览,本地根目录和自定义根目录则继续保有现有的配置自由。每个会话都有一个可供后端未来存放自有产物的目录,而现有 transcript 消费方仍会收到文件路径。 -项目目录名比原先由 12 个十六进制字符组成的 cwd 哈希更长。路径很长时,目录名只显示长度受限的前缀和用于区分的哈希;移动项目仍会选择不同的目录,因为绝对 cwd 仍是存储身份的一部分。 +项目目录名比原先由 12 个十六进制字符组成的 cwd 哈希更长。路径很长时,目录名只显示长度受限的前缀。移动项目通常会选择不同的目录,但按设计,不同的 cwd 字符串如果规范化成相同名称,就会共用同一个项目目录。 diff --git a/packages/session-persistence/session-persistence-jsonl/README.md b/packages/session-persistence/session-persistence-jsonl/README.md index 8bd704f1e2..b90b47d3f5 100644 --- a/packages/session-persistence/session-persistence-jsonl/README.md +++ b/packages/session-persistence/session-persistence-jsonl/README.md @@ -6,7 +6,7 @@ The JSONL durable session-persistence backend — a concrete `SessionPersistence ``` / - ----/ # readable project directory (or _no-cwd/) + ----/ # readable project directory (or _no-cwd/) / # session-owned directory session.jsonl.zstd # default: checksummed header frame + append frames session.jsonl # only with compression: 'none' @@ -14,7 +14,7 @@ The JSONL durable session-persistence backend — a concrete `SessionPersistence - The first logical line is the immutable `SessionHeader` tagged `{ type: 'session', version, id, cwd?, createdAt, parentSession?, seedLength?, delegationDepth }`. `delegationDepth` is required on disk and is `0` for a top-level session; a missing or invalid value rejects the log. Every subsequent logical line is one storage record; `assistant/chunk` events are never dropped, and `seq` stays contiguous across the decoded log (`events[i].seq === i`). - A storage record is a `SessionEvent` JSON verbatim, or — written only under `packChunks` — a **packed chunk row** (`text-chunks` / `reasoning-chunks` / `tool-call-chunks`; bare slash-less tags like the header's `session`, so row tags cannot be confused with event types): one line holding a run of ≥3 consecutive same-block `assistant/chunk` delta events, `seq0`/`time0` plus per-member `dt` gaps reconstructing every member's `seq`/`time` exactly. The lossless codec lives in `@deepseek-ai/dsh-session` (`packChunkRuns`/`decodeStorageRecord`) and whitelists exact shapes — anything unrecognized stores verbatim. Reading is layout-blind: `load` always decodes rows, so packed, unpacked, and mixed files load identically. -- The project directory keeps the normalized cwd readable for navigation and adds a short SHA-256 suffix so paths that normalize alike remain distinct. Its readable prefix is bounded for filesystem component limits. The configured root remains deployment-controlled: it may be project-local, shared, temporary, or centralized. +- The project directory keeps the normalized cwd readable for navigation and is bounded for filesystem component limits. Separator replacement and truncation are intentionally lossy, so cwd strings that normalize alike share a project directory; session ids still select distinct session directories. The configured root remains deployment-controlled: it may be project-local, shared, temporary, or centralized. The [project-session directory decision](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md) records this tradeoff. - Session ids are unvalidated branded strings, so they are injectively escaped to a single safe path segment before use (no traversal, no collision). The resulting directory is reserved for additional session-owned artifacts; discovery reads only the fixed transcript filename. ## Config diff --git a/packages/session-persistence/session-persistence-jsonl/src/format.ts b/packages/session-persistence/session-persistence-jsonl/src/format.ts index bb55f5e00d..af91c67961 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/format.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/format.ts @@ -8,7 +8,6 @@ * @module dsh-session-persistence-jsonl/format */ -import { createHash } from 'node:crypto' import { join } from 'node:path' import { decodeStorageRecord, packChunkRuns } from '@deepseek-ai/dsh-session' import type { SessionEvent, SessionHeader, SessionId, StorageRecord } from '@deepseek-ai/dsh-session' @@ -120,11 +119,11 @@ export function encodeSegment(raw: string): string { } /** - * Build the readable, collision-resistant directory key for a project path. + * Build the readable directory key for a project path. * Filesystem separators and drive separators become `-`; unsafe code units use - * the same `~XXXX` escape as session ids. The readable prefix is bounded for - * filesystem component limits, and the hash suffix keeps distinct or truncated - * paths separate. + * the same `~XXXX` escape as session ids. The key is bounded for filesystem + * component limits. Separator replacement and truncation are intentionally + * lossy, following the common human-navigable project-directory convention. * @param cwd - the session's project directory. * @returns a single filesystem-safe project directory name. */ @@ -146,9 +145,8 @@ export function projectKey(cwd: string): string { separatorRun = false } } - const hash = createHash('sha256').update(cwd).digest('hex').slice(0, 12) const slug = readable.replace(/^-+/, '') || 'root' - return `--${slug.slice(0, 200)}--${hash}` + return `--${slug.slice(0, 251)}--` } /** diff --git a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts index 0c46afc6b8..5afa17f461 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts @@ -127,15 +127,13 @@ describe('SessionPersistenceJsonl: format helpers', () => { expect(() => encodeSegment('')).toThrow(/empty/) }) - it('projectKey keeps the path readable and disambiguates normalized collisions', () => { - expect(projectKey('/Users/qyj/work/deepseek-harness')).toMatch( - /^--Users-qyj-work-deepseek-harness--[a-f0-9]{12}$/, - ) - expect(projectKey('/a/b-c')).not.toBe(projectKey('/a-b/c')) - expect(projectKey('C:\\work\\agent')).toMatch(/^--C-work-agent--[a-f0-9]{12}$/) - expect(projectKey('/开发/~agent')).toMatch(/^--~5F00~53D1-~007Eagent--[a-f0-9]{12}$/) - expect(projectKey('/')).toMatch(/^--root--[a-f0-9]{12}$/) - expect(projectKey('/' + 'x'.repeat(1_000))).toHaveLength(216) + it('projectKey normalizes project paths into bounded readable names', () => { + expect(projectKey('/Users/qyj/work/deepseek-harness')).toBe('--Users-qyj-work-deepseek-harness--') + expect(projectKey('/a/b-c')).toBe(projectKey('/a-b/c')) + expect(projectKey('C:\\work\\agent')).toBe('--C-work-agent--') + expect(projectKey('/开发/~agent')).toBe('--~5F00~53D1-~007Eagent--') + expect(projectKey('/')).toBe('--root--') + expect(projectKey('/' + 'x'.repeat(1_000))).toHaveLength(255) expect(() => projectKey('')).toThrow(/empty project path/) }) @@ -815,6 +813,23 @@ describe('SessionPersistenceJsonl: edge cases', () => { expect(ids).toEqual(['p1', 'p2', 'p3']) }) + it('groups sessions whose cwd paths normalize to the same project directory', async () => { + const first = meta('normalized-first', '/a/b-c') + const second = meta('normalized-second', '/a-b/c') + await ctx.sessionPersistence.create(first) + await ctx.sessionPersistence.append(first.id, oneTurnLog()) + await ctx.sessionPersistence.create(second) + await ctx.sessionPersistence.append(second.id, oneTurnLog()) + + expect(projectDir(root, first.cwd)).toBe(projectDir(root, second.cwd)) + expect(await readdir(projectDir(root, first.cwd))).toEqual(expect.arrayContaining([ + encodeSegment(first.id), + encodeSegment(second.id), + ])) + expect((await ctx.sessionPersistence.list()).map(header => header.id).sort()) + .toEqual([first.id, second.id].sort()) + }) + it('list on an empty root returns nothing', async () => { expect(await ctx.sessionPersistence.list()).toEqual([]) }) From 224e00b2bdf53d3d0083f43681452f532317d85a Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Fri, 24 Jul 2026 21:27:07 +0800 Subject: [PATCH 029/113] fix: quiesce cancelled session reconciliation --- ...23-unified-session-query-service.i18n.yaml | 4 +- ...026-07-23-unified-session-query-service.md | 4 + ...-07-23-unified-session-query-service.zh.md | 4 + ...026-07-10-sqlite-session-query-provider.md | 6 +- docs/cordis-catalog/services.md | 3 +- docs/core-data-structures/persistence.md | 2 +- .../cordis/tool-cordis/src/api-catalog.ts | 4 +- .../session-persistence-jsonl/README.md | 2 +- .../session-persistence-jsonl/src/index.ts | 8 +- .../tests/jsonl.spec.ts | 50 ++++ .../session-persistence-sqlite/README.md | 2 +- .../session-persistence-sqlite/src/index.ts | 5 +- .../tests/sqlite.spec.ts | 25 ++ .../session-persistence/README.md | 4 +- .../session-persistence/src/index.ts | 3 +- .../session-persistence/tests/contract.ts | 2 + .../tests/persistence.spec.ts | 3 +- .../session-query-sqlite/README.md | 2 +- .../session-query-sqlite/src/index.ts | 15 +- .../session-query-sqlite/tests/sqlite.spec.ts | 242 +++++++++++++++++- 20 files changed, 359 insertions(+), 31 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.i18n.yaml index 2a27e6432f..7b83a5dc52 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.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 -2026-07-23-unified-session-query-service.md: 0a466e1c36ff1796c858666b0eb36bbd0f480bb0 -2026-07-23-unified-session-query-service.zh.md: 448122b8e6951058b9f633cd56112b0391e1912e +2026-07-23-unified-session-query-service.md: 676a42017ca42f9e649f6529f84787e7162faac0 +2026-07-23-unified-session-query-service.zh.md: d4449a415840d61cbb10f88def1062a13e556749 diff --git a/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.md b/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.md index 0a466e1c36..676a42017c 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.md +++ b/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.md @@ -16,6 +16,8 @@ The interface package already owns the shared record, filter, trace, search-requ `SessionQuerySqlite` extends that service and is the sole concrete backend. One mounted instance therefore exposes every operation through `ctx.sessionQuery`; its inherited exact operations use the shared corpus implementation, while its SQLite-owned lifecycle observes sources, reconciles the derived FTS index, ranks matches, and owns cursor generations. The interface package has no standalone concrete plugin, search-provider registry, or second context key. +SQLite reconciliation is one quiescent serialized state machine. It passes the caller's exact abort signal into durable snapshot listing and inspection, awaits each started backend operation itself, and checks cancellation after every await and before starting the next source or index operation. Cancellation therefore cannot release the serializer while an ignored or cooperative backend call is still cleaning up, and it cannot start a subsequent listing, inspection, reconciliation, or query after the signal is observed. + Backend configuration includes the inherited `readWindowMax` setting alongside its own index path, journal mode, page limits, and snippet limit. First-party apps that need session queries mount the SQLite backend and place its disposable index beside their configured persistence root. This service topology supersedes the separate-key portion of the [exact query decision](../feature/2026-07-10-session-query-service.md) and [SQLite search decision](../feature/2026-07-10-sqlite-session-query-provider.md); their corpus, query, tokenizer, reconciliation, and safety decisions remain in force. @@ -32,4 +34,6 @@ Consumers inject one service and can combine exact and full-text operations with The unified object deliberately retains two internal observation strategies: exact operations read authoritative live/persisted sources per call, while full-text operations reconcile a disposable index. Sharing the context key does not make the derived index authoritative or couple exact-read availability to an FTS query. +Queued cancellation remains prompt. Cancellation during active asynchronous source observation waits for that started operation to settle, which makes rejection a quiescence boundary and preserves single-file execution for a following search. Synchronous SQLite statements remain non-preemptible and are bracketed by signal checks. + Unit coverage pins inherited and abstract behavior on one key, SQLite coverage exercises both operation families on the concrete backend, and the real Loader path verifies that one exported plugin registers the combined service. diff --git a/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.zh.md b/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.zh.md index 448122b8e6..d4449a4158 100644 --- a/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-23-unified-session-query-service.zh.md @@ -16,6 +16,8 @@ Status: implemented `SessionQuerySqlite` 扩展该服务,并且是唯一的具体后端。因此,一个挂载实例便可通过 `ctx.sessionQuery` 暴露全部操作;其继承的精确操作使用共享的语料库实现,而由 SQLite 管理的生命周期负责观察数据源、对齐派生 FTS 索引、对匹配项排序并管理游标代际。接口包不提供独立的具体插件、搜索提供方注册表或第二个上下文键。 +SQLite 的对齐过程是一个具备静止性保证的串行状态机。它将调用方的原始中止信号传给持久化快照列表与检查操作,直接等待每个已经启动的后端操作,并在每次等待后以及启动下一个数据源或索引操作前检查是否已取消。因此,即使后端忽略取消或正在配合清理,串行器也不会提前释放;观察到中止信号后,也不会再启动后续的列表、检查、对齐或查询操作。 + 后端配置除了自身的索引路径、日志模式、分页限制与文本片段长度上限外,还包含继承的 `readWindowMax` 设置。需要会话查询的第一方应用挂载 SQLite 后端,并将其可丢弃索引放在已配置的持久化根目录旁。 这一服务拓扑取代了[精确查询决策](../feature/2026-07-10-session-query-service.md)和 [SQLite 搜索决策](../feature/2026-07-10-sqlite-session-query-provider.md)中关于分离上下文键的部分;其中关于语料库、查询、分词器、对齐与安全性的决策仍然有效。 @@ -32,4 +34,6 @@ Status: implemented 统一后的对象有意保留两种内部观察策略:精确操作在每次调用时读取权威的实时源或持久化源,全文操作则使可丢弃索引与数据源对齐。共用上下文键不会让派生索引成为权威来源,也不会使精确读取的可用性依赖 FTS 查询。 +排队阶段的取消仍会及时生效。在异步数据源观察已经开始后取消时,调用方会等待该操作完成清理后才收到拒绝;因此拒绝本身构成静止边界,并保证后续搜索仍按单一串行流程执行。同步 SQLite 语句无法在执行中被抢占,服务会在其前后检查中止信号。 + 单元测试在同一个键上同时固定继承实现与抽象方法的契约,SQLite 测试在具体后端上覆盖两类操作,真实 Loader 路径则验证单个导出的插件能够注册组合后的服务。 diff --git a/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md index ff57904358..7306ee6bd9 100644 --- a/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md +++ b/.agents/notes/implemented/feature/2026-07-10-sqlite-session-query-provider.md @@ -32,13 +32,13 @@ Both persistent and live FTS5 tables use `unicode61`. The implementation experim The shared extractor includes message text, reasoning, nested tool-call/result content, tool names and arguments, blocked-prompt reasons, todo status/content, and error or terminal status detail. Structural boundaries, stream chunks, request headers, successful completion markers, and unknown declaration-merged event/content variants produce no document. Surface classification reuses `foldSurface()` so search agrees with model-history derivation. -One serialized operation reads the provider-neutral `SessionPersistence` snapshot listing, compares each source-qualified opaque revision with the revision stored beside the indexed session, loads only new or changed logs, reconciles rows in one transaction, and executes the query. It never calls the backend's mutating `load()` for an id currently owned by `ctx.sessions`; the TEMP overlay records persisted availability, and the durable base refreshes after the live owner detaches. A revision identifies its backing persistence store as well as the backend-local log revision, so reopening against the same store reuses indexed rows while switching to an independent store cannot collide on a session id and local counter. Observation repeats when listing changes during a load; this incorporates a mutating load repair's refreshed revision before commit. Repeated queries and unchanged reopen load no full persisted logs. New, changed, and deleted sessions update on the next stable search. A source or extraction failure cannot mark a row current, and a transaction failure rolls back so a later search retries. +One serialized operation reads the provider-neutral `SessionPersistence` snapshot listing, compares each source-qualified opaque revision with the revision stored beside the indexed session, loads only new or changed logs, reconciles rows in one transaction, and executes the query. It passes the caller's exact abort signal into snapshot listing and non-mutating inspection, directly awaits every started backend operation, and checks cancellation after each await and before starting more work. Cancellation therefore rejects only after active backend work is quiescent, starts no subsequent observation or reconciliation step, and keeps a following search serialized behind cleanup even if a backend ignores the signal. The operation never calls the backend's mutating `load()` for an id currently owned by `ctx.sessions`; the TEMP overlay records persisted availability, and the durable base refreshes after the live owner detaches. A revision identifies its backing persistence store as well as the backend-local log revision, so reopening against the same store reuses indexed rows while switching to an independent store cannot collide on a session id and local counter. Observation repeats when listing changes during a load; this incorporates a mutating load repair's refreshed revision before commit. Repeated queries and unchanged reopen load no full persisted logs. New, changed, and deleted sessions update on the next stable search. A source or extraction failure cannot mark a row current, and a transaction failure rolls back so a later search retries. Persisted documents survive restarts. Live sessions use connection-local TEMP tables, shadow the persisted base for the same id, and reveal that base on detach. Closing the database drops live rows. Unmounting persistence hides durable rows without treating absence as authoritative deletion; remounting observes and reconciles the backend again. Conflicting immutable live and durable headers fail rather than combining sources. The derived schema has its own application id and monotonic schema version. A recognized incompatible version resets only this derived database. A database with a foreign application id or unrecognized user tables is refused before journal-mode mutation, which prevents an accidentally configured canonical session database from being changed. On POSIX filesystems, missing directories and database files are created owner-only so new SQLite sidecars inherit that mode; existing modes are preserved. One service in one process exclusively owns a derived-index path; cross-process writers are unsupported because generations and live TEMP shadow state are connection-owned. -Cancellation rejects queued operations and caller waits around asynchronous source observation without committing an aborted observation. Node's synchronous `DatabaseSync` MATCH call cannot be interrupted once it is executing on the JavaScript thread, so the service checks the signal at serialized boundaries but does not promise mid-statement preemption. +Cancellation rejects queued operations promptly. Once asynchronous source observation starts, the caller waits for that backend promise to settle before rejection, without committing an aborted observation or starting more source/index work. Node's synchronous `DatabaseSync` metadata and MATCH calls cannot be interrupted once executing on the JavaScript thread, so the service checks the signal around those calls but does not promise mid-statement preemption. ## Alternatives considered @@ -52,6 +52,6 @@ Cancellation rejects queued operations and caller waits around asynchronous sour Search has a small provider-neutral API while its only backend owns every derived-index state transition. The separate database adds configuration and a lightweight snapshot read before queries, but index corruption, reset, and tokenizer changes cannot endanger canonical logs. Durable revisions avoid full-log reads and rewrites for unchanged sessions; TEMP live overlays preserve current-session truth without making uncheckpointed events durable. -The chosen tokenizer supports short tokens with a smaller index but does not promise substring recall. Literal phrases make query syntax safe and predictable at the cost of excluding boolean/full MATCH expressions. Cancellation is effective while queued or awaiting sources, but synchronous SQLite execution remains a non-preemptible section. +The chosen tokenizer supports short tokens with a smaller index but does not promise substring recall. Literal phrases make query syntax safe and predictable at the cost of excluding boolean/full MATCH expressions. Cancellation is prompt while queued and quiescent while awaiting sources; synchronous SQLite execution remains a non-preemptible section bracketed by signal checks. Unit coverage pins extraction, filters, both search scopes, all default surfaces, metadata-before-ranking, snippets, literal escaping, deterministic ties, complete pagination, scoped cursor invalidation, dynamic persistence mount/unmount, restart reconciliation, live shadow/reveal/reopen, schema safety, rollback retry, and queued/in-flight source-wait cancellation. A keyless real-Loader-path test combines the package with the real SQLite persistence backend. diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 9281d6b2fc..3657d5e05c 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -960,9 +960,10 @@ abstract list(signal?: AbortSignal): Promise * successful mutating {@link load} repair changes the next listed revision. * Revisions also distinguish independently backed stores so backend-local * counters cannot compare equal across different persistence sources. + * @param signal - optional cancellation for backend snapshot-listing work. * @returns one header and opaque revision per materialized session without loading full logs. */ -abstract listSnapshots(): Promise +abstract listSnapshots(signal?: AbortSignal): Promise ``` Types: [SessionEvent](../core-data-structures/core.md) · [SessionHeader](../core-data-structures/persistence.md) · [SessionId](../core-data-structures/core.md) · [SessionLocation](../core-data-structures/persistence.md) · [SessionPersistenceSnapshot](../core-data-structures/persistence.md) diff --git a/docs/core-data-structures/persistence.md b/docs/core-data-structures/persistence.md index f45eb0417a..af34dfa058 100644 --- a/docs/core-data-structures/persistence.md +++ b/docs/core-data-structures/persistence.md @@ -126,7 +126,7 @@ interface SessionPersistenceSnapshot { ## The backends -Both implement the same abstract `SessionPersistence` (locate/create/append/load/inspect/list/listSnapshots over `SessionEvent`) and pass `runPersistenceContract`, proving the seam is genuinely backend-agnostic: +Both implement the same abstract `SessionPersistence` (locate/create/append/load/inspect/list/listSnapshots over `SessionEvent`, with optional cancellation on observation methods) and pass `runPersistenceContract`, proving the seam is genuinely backend-agnostic: - **[dsh-session-persistence-jsonl](../../packages/session-persistence/session-persistence-jsonl)** — an append-only logical JSONL log per session, stored as checksummed concatenated Zstandard frames by default or raw lines by configuration, with crash-safe atomic writes, interrupted-turn recovery, and a read/replay path. - **[dsh-session-persistence-sqlite](../../packages/session-persistence/session-persistence-sqlite)** — `node:sqlite`, one row per `SessionEvent`. The row shape `(session_id, seq, type, time, data, source_event_seqs, surface_op)` maps 1:1 onto the event, including optional surface metadata, so there is no parallel persisted schema to keep in sync. diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index aefea025b1..3c57dbd478 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -477,8 +477,8 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ jsDoc: '/**\n * Lightweight listing from metadata, without a full-log parse.\n * @param signal - optional cancellation for backend listing work.\n * @returns one header per materialized session.\n */', }, { - signature: 'abstract listSnapshots(): Promise', - jsDoc: '/**\n * List materialized sessions with cheap per-log change tokens.\n *\n * Repeated observations of an unchanged log return the same revision. A\n * successful mutating {@link load} repair changes the next listed revision.\n * Revisions also distinguish independently backed stores so backend-local\n * counters cannot compare equal across different persistence sources.\n * @returns one header and opaque revision per materialized session without loading full logs.\n */', + signature: 'abstract listSnapshots(signal?: AbortSignal): Promise', + jsDoc: '/**\n * List materialized sessions with cheap per-log change tokens.\n *\n * Repeated observations of an unchanged log return the same revision. A\n * successful mutating {@link load} repair changes the next listed revision.\n * Revisions also distinguish independently backed stores so backend-local\n * counters cannot compare equal across different persistence sources.\n * @param signal - optional cancellation for backend snapshot-listing work.\n * @returns one header and opaque revision per materialized session without loading full logs.\n */', }, ], }, diff --git a/packages/session-persistence/session-persistence-jsonl/README.md b/packages/session-persistence/session-persistence-jsonl/README.md index bf86bf8633..b7b70df847 100644 --- a/packages/session-persistence/session-persistence-jsonl/README.md +++ b/packages/session-persistence/session-persistence-jsonl/README.md @@ -39,7 +39,7 @@ A root belongs to one encoding. Startup discovery and targeted lookup reject the - **Crash recovery — preserve valid tail work.** `load` validates every complete compressed frame and scans their decompressed JSONL. If the last frame is structurally incomplete, the reader keeps its complete decoded records, truncates from that frame's start, and re-encodes those records with the synthetic tool, step, and turn closers required by the shared [persistence contract](../../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md). Raw mode truncates from its first incomplete line. A checksum/decompression failure in a complete frame, or a defect at or before the last committed `turn/end`, is corruption and rejects. - **Non-mutating inspection.** `inspect()` returns the detached valid prefix without truncating an incomplete tail or closing an interrupted turn, and leaves the lightweight revision unchanged. - **Contiguous-seq.** `append` rejects a batch whose first `seq` does not continue the stored log, and rejects non-JSON-serializable `event.data` naming the offending event type. -- **Lightweight revisions.** `listSnapshots()` identifies a log by its device, inode, size, and nanosecond timestamps, avoiding a full-log parse while changing after append, repair, replacement, or store changes. +- **Lightweight revisions.** `listSnapshots(signal?)` identifies a log by its device, inode, size, and nanosecond timestamps, avoiding a full-log parse while changing after append, repair, replacement, or store changes. It forwards the exact signal through artifact discovery and checks cancellation around every `stat`; because filesystem `stat` is not interruptible, cancellation waits for the active call to settle, then rejects without starting another. ## Write path diff --git a/packages/session-persistence/session-persistence-jsonl/src/index.ts b/packages/session-persistence/session-persistence-jsonl/src/index.ts index 6b2fe3d0cf..9740fbb7d8 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/index.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/index.ts @@ -281,11 +281,13 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } /** List metadata plus a stat-derived identity for each append-only log. */ - async listSnapshots(): Promise { + async listSnapshots(signal?: AbortSignal): Promise { const snapshots: SessionPersistenceSnapshot[] = [] - for (const artifact of await this.listArtifacts()) { + for (const artifact of await this.listArtifacts(signal)) { + signal?.throwIfAborted() try { const identity = await stat(artifact.path, { bigint: true }) + signal?.throwIfAborted() snapshots.push({ header: artifact.header, revision: SessionPersistenceRevision([ @@ -297,9 +299,11 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi ].join(':')), }) } catch (error: unknown) { + signal?.throwIfAborted() if (!isENOENT(error)) throw error } } + signal?.throwIfAborted() return snapshots } diff --git a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts index 2b49b7d55b..bc5142f1cb 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts @@ -265,6 +265,56 @@ describe('SessionPersistenceJsonl: durability and crash semantics', () => { discovery.mockRestore() }) + it('forwards snapshot-list cancellation and awaits in-flight discovery cleanup', async () => { + const persistence = ctx.sessionPersistence as unknown as { + listArtifacts(signal?: AbortSignal): Promise> + } + const started = Promise.withResolvers() + const cleanup = Promise.withResolvers() + vi.spyOn(persistence, 'listArtifacts').mockImplementation(async (signal) => { + if (signal === undefined) throw new Error('expected snapshot-list signal') + started.resolve(signal) + await cleanup.promise + return [] + }) + const reason = new Error('JSONL snapshot discovery cancelled') + const controller = new AbortController() + const pending = ctx.sessionPersistence.listSnapshots(controller.signal) + expect(await started.promise).toBe(controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + + controller.abort(reason) + await Promise.resolve() + expect(settled).toBe(false) + + cleanup.resolve(undefined) + await expect(pending).rejects.toBe(reason) + }) + + it('checks cancellation after an uncancellable snapshot stat settles', async () => { + const m = meta('snapshot-stat-cancellation') + await ctx.sessionPersistence.create(m) + await ctx.sessionPersistence.append(m.id, oneTurnLog()) + const persistence = ctx.sessionPersistence as unknown as { + listArtifacts(signal?: AbortSignal): Promise> + } + const discovery = vi.spyOn(persistence, 'listArtifacts').mockResolvedValue([{ + header: m, + path: rawLogPath(root, m.cwd, m.id), + }]) + const reason = new Error('JSONL snapshot stat cancelled') + const controller = new AbortController() + const pending = ctx.sessionPersistence.listSnapshots(controller.signal) + queueMicrotask(() => { controller.abort(reason) }) + + await expect(pending).rejects.toBe(reason) + expect(discovery).toHaveBeenCalledWith(controller.signal) + }) + it('rejects a stored v0 log containing a legacy request/header-delta event', async () => { const m = meta('legacy-header-delta', '/legacy') const path = rawLogPath(root, m.cwd, m.id) diff --git a/packages/session-persistence/session-persistence-sqlite/README.md b/packages/session-persistence/session-persistence-sqlite/README.md index f1f4bc1f7b..dda164fc33 100644 --- a/packages/session-persistence/session-persistence-sqlite/README.md +++ b/packages/session-persistence/session-persistence-sqlite/README.md @@ -20,7 +20,7 @@ On filesystems with POSIX modes, the backend requests mode `0700` for missing di - **Lazy materialization.** `create()` records intent in memory only — no row is written until the first `append`. A created-but-never-appended session has no `sessions` row, so it is absent from `list()` (which reports exactly the sessions that have a row). - **Interrupted-turn close on load.** `load()` implements the shared [crash-recovery contract](../../../.agents/notes/implemented/architecture/2026-06-14-session-persistence.md): preserve the valid interrupted turn, append its synthetic closing events in one transaction, and remove only a torn tail row. Committed parse errors or sequence gaps make the session unloadable. Because recovery mutates stored rows, the next append starts from a balanced log and accurate cursor. - **Non-mutating inspection.** `inspect()` returns the detached valid row prefix without deleting a torn tail row or appending recovery closers, and leaves the lightweight revision unchanged. -- **Lightweight revisions.** `listSnapshots()` combines the immutable store and database-file identity, a per-materialization incarnation id, and a per-session counter incremented in each mutating transaction. This keeps unchanged observations stable without parsing event rows and distinguishes independent stores and recreated same-id logs. +- **Lightweight revisions.** `listSnapshots(signal?)` combines the immutable store and database-file identity, a per-materialization incarnation id, and a per-session counter incremented in each mutating transaction. This keeps unchanged observations stable without parsing event rows and distinguishes independent stores and recreated same-id logs. It checks cancellation before and after shared readiness and the synchronous metadata query; the query itself is non-preemptible. ## Configuration (schemastery) diff --git a/packages/session-persistence/session-persistence-sqlite/src/index.ts b/packages/session-persistence/session-persistence-sqlite/src/index.ts index 0c1159f139..f771b9e3a7 100644 --- a/packages/session-persistence/session-persistence-sqlite/src/index.ts +++ b/packages/session-persistence/session-persistence-sqlite/src/index.ts @@ -266,9 +266,12 @@ export class SessionPersistenceSqlite extends SessionPersistence implements Pers } /** List metadata with a source-qualified monotonic revision per session. */ - async listSnapshots(): Promise { + async listSnapshots(signal?: AbortSignal): Promise { + signal?.throwIfAborted() await this.ready + signal?.throwIfAborted() const rows = this.db.prepare('SELECT * FROM sessions').all() as unknown as SessionRow[] + signal?.throwIfAborted() return rows.map(row => ({ header: rowToMeta(row), revision: SessionPersistenceRevision( diff --git a/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts b/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts index 3976e71549..e70c041bca 100644 --- a/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts +++ b/packages/session-persistence/session-persistence-sqlite/tests/sqlite.spec.ts @@ -441,6 +441,31 @@ describe('SessionPersistenceSqlite: durability and crash semantics', () => { await second.dispose() }) + it('awaits in-flight readiness before surfacing snapshot-list cancellation', async () => { + const b = await backend() + const internals = b.ctx.sessionPersistence as unknown as { ready: Promise } + const originalReady = internals.ready + const readiness = Promise.withResolvers() + internals.ready = readiness.promise + const reason = new Error('SQLite snapshot readiness cancelled') + const controller = new AbortController() + const pending = b.ctx.sessionPersistence.listSnapshots(controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + + controller.abort(reason) + await Promise.resolve() + expect(settled).toBe(false) + + readiness.resolve(undefined) + await expect(pending).rejects.toBe(reason) + internals.ready = originalReady + await b.dispose() + }) + it('exposes the schema version constant', () => { expect(SCHEMA_VERSION).toBe(8) }) diff --git a/packages/session-persistence/session-persistence/README.md b/packages/session-persistence/session-persistence/README.md index fa734fb736..199cad10c5 100644 --- a/packages/session-persistence/session-persistence/README.md +++ b/packages/session-persistence/session-persistence/README.md @@ -14,7 +14,7 @@ The persisted unit IS the existing `SessionEvent` (event-sourced model — the l | `load(id): Promise<{ meta; events }>` | Return a stored header plus a balanced contiguous log. A live load first flushes its snapshot and rejects while its turn is open; a cold load preserves an interrupted final turn and closes it with synthetic `tool/result`/`step/end?`/`turn/end {interrupted}` events. Only a torn tail fragment is dropped; committed corruption and unknown `version` reject. | | `inspect(id, signal?): Promise<{ meta; events }>` | Return a detached valid stored prefix without truncating a torn tail, synthesizing recovery closers, or publishing coordinator state. Serialized with same-id writes; the optional signal promptly rejects a queued caller, prevents that queued backend read from starting, and cancels active backend read work. Intended for read models and other observers that must never recover a log. | | `list(signal?): Promise` | Lightweight listing from metadata, no full-log parse. The optional signal cancels backend listing work. A zero-event lazily-materialized session is absent from `list`. | -| `listSnapshots(): Promise` | Lightweight metadata plus an opaque branded per-log revision, without loading event logs. A revision stays equal while that log and its backing store are unchanged, changes after append or mutating load repair, and cannot collide solely because two stores use the same local counter. | +| `listSnapshots(signal?): Promise` | Lightweight metadata plus an opaque branded per-log revision, without loading event logs. A revision stays equal while that log and its backing store are unchanged, changes after append or mutating load repair, and cannot collide solely because two stores use the same local counter. The optional signal requests cancellation of backend discovery work; first-party backends settle any started listing work before rejecting so an awaited call is quiescent. | ## Invariants every backend must honor @@ -33,7 +33,7 @@ Crash repair is cold-only. For a live id, `load(id)` snapshots the authoritative When a live session emits `session/disposed`, the coordinator waits for its controller, serializes a final drain, then releases state owned by that exact `Session` object. Failed retirement leaves the controller in the live-session map, so backend teardown can retry it. Backend teardown stops event admission first, flushes every remaining controller, awaits per-id operations, and only then closes the storage handle. -The side-effect-free `locate` and lightweight `listSnapshots` queries remain backend-owned because they describe storage topology and revision identity rather than write orchestration. +The side-effect-free `locate` and lightweight `listSnapshots` queries remain backend-owned because they describe storage topology and revision identity rather than write orchestration. `listSnapshots(signal?)` passes the caller's exact signal into backend discovery so observers can cancel that work without detaching it. The `PersistenceBackend` hooks (the only seam between the coordinator and storage): diff --git a/packages/session-persistence/session-persistence/src/index.ts b/packages/session-persistence/session-persistence/src/index.ts index 9eee07a323..9279e3c42c 100644 --- a/packages/session-persistence/session-persistence/src/index.ts +++ b/packages/session-persistence/session-persistence/src/index.ts @@ -122,9 +122,10 @@ export abstract class SessionPersistence extends Service { * successful mutating {@link load} repair changes the next listed revision. * Revisions also distinguish independently backed stores so backend-local * counters cannot compare equal across different persistence sources. + * @param signal - optional cancellation for backend snapshot-listing work. * @returns one header and opaque revision per materialized session without loading full logs. */ - abstract listSnapshots(): Promise + abstract listSnapshots(signal?: AbortSignal): Promise } export default SessionPersistence diff --git a/packages/session-persistence/session-persistence/tests/contract.ts b/packages/session-persistence/session-persistence/tests/contract.ts index eb77235057..e61fe65bb7 100644 --- a/packages/session-persistence/session-persistence/tests/contract.ts +++ b/packages/session-persistence/session-persistence/tests/contract.ts @@ -227,9 +227,11 @@ export function runPersistenceContract(name: string, make: () => Promise structuredClone(e.meta)) } - async listSnapshots(): Promise { + async listSnapshots(signal?: AbortSignal): Promise { + signal?.throwIfAborted() return [...this.store.values()].map(entry => ({ header: structuredClone(entry.meta), revision: SessionPersistenceRevision(`events:${entry.events.length}`), diff --git a/packages/session-query/session-query-sqlite/README.md b/packages/session-query/session-query-sqlite/README.md index 693b1275f2..3d2f2ce16b 100644 --- a/packages/session-query/session-query-sqlite/README.md +++ b/packages/session-query/session-query-sqlite/README.md @@ -34,7 +34,7 @@ The database is disposable but reset is guarded: every recognized schema version The index uses FTS5 `unicode61`. In the implementation experiment it supported the two-character query `AI` and produced an index about 2.1× smaller than the trigram alternative. The trade-off is token/phrase recall rather than arbitrary substring recall: `AI` does not match the token `BRAID`. Use `ctx.sessionQuery.filterEvents()` with a `text` clause when a literal whitespace-flexible substring scan is required. NUL is rejected in queries; reserved highlight markers and NUL in documents are normalized before indexing so presentation markers cannot collide with source text. -Abort signals stop queued work and caller waits around asynchronous source observation. Node's synchronous `DatabaseSync` API cannot interrupt a MATCH statement already executing on the JavaScript thread; the signal is checked immediately before and after the serialized observation/reconciliation boundary. +Abort signals stop queued work and flow unchanged through snapshot listing and non-mutating inspection. Once source work starts, the serialized state machine awaits that backend promise itself—even when a backend ignores cancellation—then checks the signal before starting any further listing, inspection, reconciliation, or query work. The caller therefore observes cancellation only after started backend work is quiescent, and a later search cannot enter the serializer while that cleanup is pending. Node's synchronous `DatabaseSync` API cannot interrupt a metadata or MATCH statement already executing on the JavaScript thread; signals are checked immediately before and after those non-preemptible calls. ## Model Experience diff --git a/packages/session-query/session-query-sqlite/src/index.ts b/packages/session-query/session-query-sqlite/src/index.ts index 3acf806646..0c073ccea5 100644 --- a/packages/session-query/session-query-sqlite/src/index.ts +++ b/packages/session-query/session-query-sqlite/src/index.ts @@ -352,6 +352,7 @@ export class SessionQuerySqlite extends SessionQueryService { } private async _reconcile(signal: AbortSignal | undefined): Promise { + assertNotAborted(signal) const db = this._requireDb() const persistedRows = db.prepare( 'SELECT id, revision, generation FROM persisted_sessions', @@ -452,7 +453,8 @@ export class SessionQuerySqlite extends SessionQueryService { try { const canReuseIndexed = this._lastPersistenceIdentity === undefined || this._lastPersistenceIdentity === persistenceBinding.identity - const before = await waitWithAbort(persistence.listSnapshots(), signal) + const before = await persistence.listSnapshots(signal) + assertNotAborted(signal) persisted = materializePersistenceSnapshots(before) for (const entry of persisted.values()) { if (canReuseIndexed && indexed.get(entry.header.id)?.revision === entry.revision) continue @@ -461,13 +463,16 @@ export class SessionQuerySqlite extends SessionQueryService { // crash-repair side effects; the live-membership retry below makes // the returned observation live-preferred. if (initiallyLive.has(entry.header.id) || this.ctx.sessions.get(entry.header.id) !== undefined) continue - const loaded = await waitWithAbort(persistence.inspect(entry.header.id), signal) + assertNotAborted(signal) + const loaded = await persistence.inspect(entry.header.id, signal) + assertNotAborted(signal) assertSessionHeadersCompatible(entry.header, loaded.meta) entry.loaded = observeSession(loaded.meta, loaded.events) } - const after = materializePersistenceSnapshots( - await waitWithAbort(persistence.listSnapshots(), signal), - ) + assertNotAborted(signal) + const afterSnapshots = await persistence.listSnapshots(signal) + assertNotAborted(signal) + const after = materializePersistenceSnapshots(afterSnapshots) if (!samePersistenceSnapshots(persisted, after)) continue if (this._persistenceBinding !== persistenceBinding) continue } catch (error: unknown) { diff --git a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts index b777ad8455..d39c82f336 100644 --- a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts +++ b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts @@ -69,11 +69,16 @@ class TestPersistence extends SessionPersistence { static nextRevision = 0 static loads = new Map() static inspections = new Map() + static inspectSignals: Array = [] + static snapshotSignals: Array = [] static loadEffect: ((entry: { meta: SessionHeader; events: SessionEvent[] }) => void) | undefined - static inspectEffect: ((entry: { meta: SessionHeader; events: SessionEvent[] }) => void | Promise) | undefined + static inspectEffect: (( + entry: { meta: SessionHeader; events: SessionEvent[] }, + signal?: AbortSignal, + ) => void | Promise) | undefined static listGate: Promise | undefined static listStarted: (() => void) | undefined - static snapshotEffect: (() => void | Promise) | undefined + static snapshotEffect: ((signal?: AbortSignal) => void | Promise) | undefined static snapshotOverride: (() => SessionPersistenceSnapshot[]) | undefined static failure: unknown @@ -86,6 +91,8 @@ class TestPersistence extends SessionPersistence { this.revisions = new Map() this.loads = new Map() this.inspections = new Map() + this.inspectSignals = [] + this.snapshotSignals = [] this.loadEffect = undefined this.inspectEffect = undefined for (const entry of entries) this.set(entry) @@ -128,12 +135,13 @@ class TestPersistence extends SessionPersistence { return structuredClone(entry) } - async inspect(id: SessionIdType): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { + async inspect(id: SessionIdType, signal?: AbortSignal): Promise<{ meta: SessionHeader; events: SessionEvent[] }> { TestPersistence.inspections.set(id, (TestPersistence.inspections.get(id) ?? 0) + 1) + TestPersistence.inspectSignals.push(signal) if (TestPersistence.failure !== undefined) throw TestPersistence.failure const entry = TestPersistence.entries.get(id) if (entry === undefined) throw new Error('missing test session') - await TestPersistence.inspectEffect?.(entry) + await TestPersistence.inspectEffect?.(entry, signal) TestPersistence.inspectEffect = undefined return structuredClone(entry) } @@ -146,7 +154,8 @@ class TestPersistence extends SessionPersistence { } - async listSnapshots(): Promise { + async listSnapshots(signal?: AbortSignal): Promise { + TestPersistence.snapshotSignals.push(signal) TestPersistence.listStarted?.() await TestPersistence.listGate if (TestPersistence.failure !== undefined) throw TestPersistence.failure @@ -155,7 +164,7 @@ class TestPersistence extends SessionPersistence { header: structuredClone(entry.meta), revision: SessionPersistenceRevision(`test:${TestPersistence.revisions.get(entry.meta.id)}`), })) - await TestPersistence.snapshotEffect?.() + await TestPersistence.snapshotEffect?.(signal) return snapshots } } @@ -1209,6 +1218,167 @@ describe('SQLite schema, cancellation, and real persistence integration', () => } }) + it.each(['sessions', 'events'] as const)( + 'forwards one exact reconciliation signal through both snapshot lists and persisted inspection for %s search', + async (scope) => { + const durable = header(`signal-${scope}`) + TestPersistence.reset([{ meta: durable, events: messageEvents('signal needle') }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + + const result = scope === 'sessions' + ? await ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal }) + : await ctx.sessionQuery.searchEvents( + { sessionId: durable.id, query: 'needle' }, + { signal: controller.signal }, + ) + + expect(result.items).toHaveLength(1) + expect(TestPersistence.snapshotSignals).toEqual([controller.signal, controller.signal]) + expect(TestPersistence.inspectSignals).toEqual([controller.signal]) + }, + ) + + it.each(['sessions', 'events'] as const)( + 'starts no persistence observation for a pre-aborted %s search', + async (scope) => { + const durable = header(`pre-aborted-${scope}`) + TestPersistence.reset([{ meta: durable, events: messageEvents('needle') }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const controller = new AbortController() + controller.abort(new Error(`pre-aborted ${scope}`)) + + const pending = scope === 'sessions' + ? ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal }) + : ctx.sessionQuery.searchEvents( + { sessionId: durable.id, query: 'needle' }, + { signal: controller.signal }, + ) + + await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED')) + expect(TestPersistence.snapshotSignals).toEqual([]) + expect(TestPersistence.inspectSignals).toEqual([]) + }, + ) + + it('awaits cooperative snapshot-list cancellation cleanup without starting another observation step', async () => { + const durable = header('cooperative-list-abort') + TestPersistence.reset([{ meta: durable, events: messageEvents('needle') }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const started = Promise.withResolvers() + const abortObserved = Promise.withResolvers() + const cleanup = Promise.withResolvers() + TestPersistence.snapshotEffect = async (signal) => { + TestPersistence.snapshotEffect = undefined + if (signal === undefined) throw new Error('expected reconciliation signal') + started.resolve(signal) + await new Promise((resolve) => { + signal.addEventListener('abort', () => { resolve() }, { once: true }) + }) + abortObserved.resolve(undefined) + await cleanup.promise + signal.throwIfAborted() + } + const controller = new AbortController() + const pending = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal }) + expect(await started.promise).toBe(controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + + controller.abort(new Error('cooperative list cancellation')) + await abortObserved.promise + expect(settled).toBe(false) + expect(TestPersistence.snapshotSignals).toEqual([controller.signal]) + expect(TestPersistence.inspectSignals).toEqual([]) + + cleanup.resolve(undefined) + await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED')) + }) + + it('keeps a second search serialized while an abort-ignoring snapshot list finishes', async () => { + const durable = header('serialized-list-abort') + TestPersistence.reset([{ meta: durable, events: messageEvents('needle') }]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const cleanup = Promise.withResolvers() + const started = Promise.withResolvers() + TestPersistence.listGate = cleanup.promise + TestPersistence.listStarted = () => { + TestPersistence.listStarted = undefined + started.resolve(undefined) + } + const controller = new AbortController() + const first = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal }) + await started.promise + let firstSettled = false + let secondSettled = false + void first.then( + () => { firstSettled = true }, + () => { firstSettled = true }, + ) + controller.abort(new Error('ignored list cancellation')) + const second = ctx.sessionQuery.searchEvents({ sessionId: durable.id, query: 'needle' }) + void second.then( + () => { secondSettled = true }, + () => { secondSettled = true }, + ) + await Promise.resolve() + + expect(firstSettled).toBe(false) + expect(secondSettled).toBe(false) + expect(TestPersistence.snapshotSignals).toEqual([controller.signal]) + expect(TestPersistence.inspectSignals).toEqual([]) + + cleanup.resolve(undefined) + await expect(first).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED')) + await expect(second).resolves.toMatchObject({ items: [{ sessionId: durable.id }] }) + }) + + it('awaits an abort-ignoring inspection and starts neither another inspection nor the after-list', async () => { + const first = header('ignored-inspect-first') + const second = header('ignored-inspect-second') + TestPersistence.reset([ + { meta: first, events: messageEvents('first needle') }, + { meta: second, events: messageEvents('second needle') }, + ]) + const ctx = await liveContext() + await ctx.plugin(TestPersistence) + const started = Promise.withResolvers() + const cleanup = Promise.withResolvers() + TestPersistence.inspectEffect = async (_entry, signal) => { + TestPersistence.inspectEffect = undefined + if (signal === undefined) throw new Error('expected reconciliation signal') + started.resolve(signal) + await cleanup.promise + } + const controller = new AbortController() + const pending = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal }) + expect(await started.promise).toBe(controller.signal) + let settled = false + void pending.then( + () => { settled = true }, + () => { settled = true }, + ) + + controller.abort(new Error('ignored inspect cancellation')) + await Promise.resolve() + expect(settled).toBe(false) + expect(TestPersistence.snapshotSignals).toEqual([controller.signal]) + expect(TestPersistence.inspections.get(first.id)).toBe(1) + expect(TestPersistence.inspections.get(second.id)).toBeUndefined() + + cleanup.resolve(undefined) + await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED')) + expect(TestPersistence.snapshotSignals).toEqual([controller.signal]) + expect(TestPersistence.inspections.get(second.id)).toBeUndefined() + }) + it('cancels both queued and in-flight source waits without committing them', async () => { TestPersistence.reset() const ctx = await liveContext() @@ -1262,8 +1432,15 @@ describe('SQLite schema, cancellation, and real persistence integration', () => const active = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: activeController.signal }) await activeStarted activeController.abort() - await expect(active).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED')) + let activeSettled = false + void active.then( + () => { activeSettled = true }, + () => { activeSettled = true }, + ) + await Promise.resolve() + expect(activeSettled).toBe(false) releaseActive() + await expect(active).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED')) const db = (ctx.sessionQuery as unknown as { _db: DatabaseSync })._db expect(db.prepare('SELECT COUNT(*) AS count FROM persisted_sessions').get()).toEqual({ count: 0 }) @@ -1271,6 +1448,57 @@ describe('SQLite schema, cancellation, and real persistence integration', () => .resolves.toMatchObject({ items: [{ header: { id: SessionId('uncommitted') } }] }) }) + it.each([ + [new Error('ready error'), 'ready error'], + ['non-error ready failure', 'session-search dependency rejected with a non-Error value'], + ])('normalizes a rejected readiness wait before mapping it to an index error', async (failure, detail) => { + TestPersistence.reset() + const ctx = await liveContext() + const internals = ctx.sessionQuery as unknown as { + _ready: Promise + _ensureReady(signal: AbortSignal): Promise + } + internals._ready = Promise.resolve().then(() => { + throw failure + }) + + await expect(internals._ensureReady(new AbortController().signal)) + .rejects.toThrow(`session-search SQLite index failed to open: ${detail}`) + }) + + it('checks cancellation after readiness before reconciliation accesses SQLite', async () => { + TestPersistence.reset() + const ctx = await liveContext() + const internals = ctx.sessionQuery as unknown as { + _db: DatabaseSync + _ready: Promise + _ensureReady(signal: AbortSignal | undefined): Promise + } + const readiness = Promise.withResolvers() + internals._ready = readiness.promise + const readyWaitStarted = Promise.withResolvers() + const ensureReady = internals._ensureReady.bind(internals) + vi.spyOn(internals, '_ensureReady').mockImplementation(async (signal) => { + const pending = ensureReady(signal) + readyWaitStarted.resolve(undefined) + return pending + }) + const prepare = vi.spyOn(internals._db, 'prepare') + const reason = new Error('cancelled after readiness') + const controller = new AbortController() + const pending = ctx.sessionQuery.searchSessions({ query: 'needle' }, { signal: controller.signal }) + await readyWaitStarted.promise + + const queueBoundaryAbort = readiness.promise.then(() => { + queueMicrotask(() => { controller.abort(reason) }) + }) + readiness.resolve(undefined) + await queueBoundaryAbort + + await expect(pending).rejects.toThrow(expectCode('SESSION_QUERY_ABORTED')) + expect(prepare).not.toHaveBeenCalled() + }) + it('rejects queued and future work when close waits for an accepted operation', async () => { TestPersistence.reset() let release!: () => void From 1ffdacb2c4dd0387ecf370b0ecde41979f046126 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 21:50:11 +0800 Subject: [PATCH 030/113] fix(jsonl): handle filesystem path aliases --- ...7-24-project-session-directories.i18n.yaml | 4 +-- .../2026-07-24-project-session-directories.md | 2 ++ ...26-07-24-project-session-directories.zh.md | 2 ++ .../session-persistence-jsonl/README.md | 2 +- .../session-persistence-jsonl/src/index.ts | 27 +++++++++++++++---- .../session-persistence-jsonl/src/win32.ts | 6 +++-- .../tests/jsonl.spec.ts | 19 ++++++++++++- .../tests/win32.spec.ts | 9 +++++++ 8 files changed, 60 insertions(+), 11 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml index a848e64c8f..321b958dc6 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.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 -2026-07-24-project-session-directories.md: 2091027e67528855a3d9722bc63347319aada678 -2026-07-24-project-session-directories.zh.md: a161cff5ac42fb67650bdff593f91b95af471d1b +2026-07-24-project-session-directories.md: 0aa3f513d5a1bb3e44cf33a0ae1eb791ee3a46c2 +2026-07-24-project-session-directories.zh.md: f6bb1bd0ddb1067b68d1389182ce5b3397ad81fd diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md index 2091027e67..0aa3f513d5 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md @@ -25,6 +25,8 @@ Raw mode uses `session.jsonl`, and sessions without a cwd use `_no-cwd`. Filesys The project key intentionally has no hash suffix. This follows the common human-readable convention used by coding agents and keeps the normalized project path as the complete directory name. The normalization is lossy: paths such as `/a/b-c` and `/a-b/c`, or long paths with the same retained prefix, share one project directory. Their distinct session ids still select separate session directories; reuse of the same session id remains a storage collision and is rejected. +Case-insensitive filesystems can also make differently cased project keys refer to one physical directory. Identity validation accepts such an alternate spelling only when filesystem canonicalization resolves the discovered and expected paths to the same transcript. A different canonical path remains corruption, so case aliases do not weaken the same-id collision check on case-sensitive stores. + The configured root remains a deployment choice. The layout neither selects a global root nor requires projects to share one. When a deployment does centralize storage, project paths remain recognizable; a project-local root uses the same deterministic structure. The encoded session id names an ownership directory rather than the transcript itself. `SessionPersistence.locate()` continues to return the fixed transcript path, preserving hook `transcript_path` and `DSH_SESSION_JSONL` semantics. Discovery ignores other entries inside the session directory so the backend can add session-owned artifacts without another layout change. diff --git a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md index a161cff5ac..f6bb1bd0dd 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-24-project-session-directories.zh.md @@ -25,6 +25,8 @@ JSONL 后端按可读的项目键存储会话,并为每个会话提供独立 项目键有意不带哈希后缀。这遵循 coding agent(编码智能体)常用的易读约定,使规范化后的项目路径本身就是完整的目录名。规范化过程有损:`/a/b-c` 与 `/a-b/c` 等路径,或者保留前缀相同的长路径,会共用同一个项目目录。不同的会话 id 仍会选择不同的会话目录;复用相同的会话 id 仍构成存储冲突,系统会予以拒绝。 +在不区分大小写的文件系统上,大小写不同的项目键也可能指向同一个物理目录。只有当文件系统路径规范化将发现路径和预期路径解析为同一个 transcript 时,身份验证才接受这种拼写变体。规范化后的路径如果不同,仍视为存储损坏,因此大小写别名不会让区分大小写的存储放宽同一 id 的冲突检查。 + 根目录由部署配置决定。这种布局既不选择全局根目录,也不要求项目共享根目录。部署选择集中存储时,目录名仍能让项目路径易于辨认;使用项目本地根目录时,也采用同样的确定性结构。 编码后的会话 id 用于命名归属目录,而不是 transcript(文本记录)文件本身。`SessionPersistence.locate()` 仍返回固定的 transcript 路径,从而保持钩子 `transcript_path` 和 `DSH_SESSION_JSONL` 的语义不变。发现过程会忽略会话目录中的其他条目,因此后端以后添加会话自有产物时无需再次改变布局。 diff --git a/packages/session-persistence/session-persistence-jsonl/README.md b/packages/session-persistence/session-persistence-jsonl/README.md index b90b47d3f5..a665b688ab 100644 --- a/packages/session-persistence/session-persistence-jsonl/README.md +++ b/packages/session-persistence/session-persistence-jsonl/README.md @@ -14,7 +14,7 @@ The JSONL durable session-persistence backend — a concrete `SessionPersistence - The first logical line is the immutable `SessionHeader` tagged `{ type: 'session', version, id, cwd?, createdAt, parentSession?, seedLength?, delegationDepth }`. `delegationDepth` is required on disk and is `0` for a top-level session; a missing or invalid value rejects the log. Every subsequent logical line is one storage record; `assistant/chunk` events are never dropped, and `seq` stays contiguous across the decoded log (`events[i].seq === i`). - A storage record is a `SessionEvent` JSON verbatim, or — written only under `packChunks` — a **packed chunk row** (`text-chunks` / `reasoning-chunks` / `tool-call-chunks`; bare slash-less tags like the header's `session`, so row tags cannot be confused with event types): one line holding a run of ≥3 consecutive same-block `assistant/chunk` delta events, `seq0`/`time0` plus per-member `dt` gaps reconstructing every member's `seq`/`time` exactly. The lossless codec lives in `@deepseek-ai/dsh-session` (`packChunkRuns`/`decodeStorageRecord`) and whitelists exact shapes — anything unrecognized stores verbatim. Reading is layout-blind: `load` always decodes rows, so packed, unpacked, and mixed files load identically. -- The project directory keeps the normalized cwd readable for navigation and is bounded for filesystem component limits. Separator replacement and truncation are intentionally lossy, so cwd strings that normalize alike share a project directory; session ids still select distinct session directories. The configured root remains deployment-controlled: it may be project-local, shared, temporary, or centralized. The [project-session directory decision](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md) records this tradeoff. +- The project directory keeps the normalized cwd readable for navigation and is bounded for filesystem component limits. Separator replacement and truncation are intentionally lossy, so cwd strings that normalize alike share a project directory; session ids still select distinct session directories. On a case-insensitive filesystem, identity validation accepts an alternate path spelling only when filesystem canonicalization resolves both spellings to the same transcript. The configured root remains deployment-controlled: it may be project-local, shared, temporary, or centralized. The [project-session directory decision](../../../.agents/notes/implemented/architecture/2026-07-24-project-session-directories.md) records this tradeoff. - Session ids are unvalidated branded strings, so they are injectively escaped to a single safe path segment before use (no traversal, no collision). The resulting directory is reserved for additional session-owned artifacts; discovery reads only the fixed transcript filename. ## Config diff --git a/packages/session-persistence/session-persistence-jsonl/src/index.ts b/packages/session-persistence/session-persistence-jsonl/src/index.ts index ad58cfe145..69b1d371d7 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/index.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/index.ts @@ -9,7 +9,7 @@ import { Context } from 'cordis' import z from 'schemastery' import { readdirSync } from 'node:fs' -import { open, mkdir, readFile, readdir, link, rm, stat, truncate } from 'node:fs/promises' +import { open, mkdir, readFile, readdir, realpath, link, rm, stat, truncate } from 'node:fs/promises' import { dirname, join, resolve } from 'node:path' import { randomBytes } from 'node:crypto' import { @@ -168,7 +168,7 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi : {}, } } - this.assertStoredIdentity(path, prefix.meta, expectedId) + await this.assertStoredIdentity(path, prefix.meta, expectedId) return prefix } @@ -291,7 +291,7 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi if (first === undefined) continue // empty/half-written file const meta = parseHeaderMeta(first) if (meta === undefined) continue // not a session header - this.assertStoredIdentity(path, meta) + await this.assertStoredIdentity(path, meta) if (ids.has(meta.id)) { throw new Error(`duplicate JSONL session id "${meta.id}" appears in multiple project directories`) } @@ -578,7 +578,7 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } /** Reject metadata that does not identify the selected physical log. */ - private assertStoredIdentity(path: string, meta: SessionHeader, expectedId?: SessionId): void { + private async assertStoredIdentity(path: string, meta: SessionHeader, expectedId?: SessionId): Promise { if (expectedId !== undefined && meta.id !== expectedId) { throw new Error(`corrupt session log "${path}": requested id "${expectedId}" does not match header id "${meta.id}"`) } @@ -588,11 +588,28 @@ export class SessionPersistenceJsonl extends SessionPersistence implements Persi } catch (error) { throw new Error(`corrupt session log "${path}": header id cannot name a storage path`, { cause: error }) } - if (path !== expectedPath) { + if (path !== expectedPath && !await this.sameFile(path, expectedPath)) { throw new Error(`corrupt session log "${path}": header id "${meta.id}" and cwd identify "${expectedPath}"`) } } + /** + * Whether two path spellings resolve to the same physical file. This admits + * case aliases on case-insensitive filesystems without weakening identity + * checks on case-sensitive stores. + */ + private async sameFile(path: string, expectedPath: string): Promise { + try { + const [actual, expected] = await Promise.all([realpath(path), realpath(expectedPath)]) + return actual === expected + } catch (error) { + /* v8 ignore else -- non-ENOENT realpath failures require an external permission or I/O fault */ + if (isENOENT(error)) return false + /* v8 ignore next -- non-ENOENT realpath failures are external I/O faults, propagated unchanged */ + throw error + } + } + /** The human-readable project directories under the configured root. */ private async listProjectDirs(): Promise { try { diff --git a/packages/session-persistence/session-persistence-jsonl/src/win32.ts b/packages/session-persistence/session-persistence-jsonl/src/win32.ts index a8c1b6fb8d..5b2b034574 100644 --- a/packages/session-persistence/session-persistence-jsonl/src/win32.ts +++ b/packages/session-persistence/session-persistence-jsonl/src/win32.ts @@ -12,7 +12,7 @@ */ import { mkdtemp, rm, stat } from 'node:fs/promises' -import { basename, join, parse, resolve, toNamespacedPath } from 'node:path' +import { join, parse, resolve, toNamespacedPath } from 'node:path' type MoveFileExW = (existing: string, replacement: string, flags: number) => number type GetLastError = () => number @@ -139,7 +139,9 @@ export async function ensureDurableDirectoryWin32(target: string): Promise } async function createLeafDirectoryWin32(parent: string, target: string): Promise { - const staging = await mkdtemp(join(parent, `.dsh-mkdir-${basename(target)}-`)) + // Keep the staging component independent of the target basename so a legal + // 255-byte target component does not make mkdtemp's sibling name too long. + const staging = await mkdtemp(join(parent, '.dsh-mkdir-')) try { await publishNewFileWin32(staging, target) } catch (error) { diff --git a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts index 5afa17f461..6f4da5fbfd 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/jsonl.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' -import { appendFile, mkdtemp, mkdir, rm, readFile, writeFile, readdir, stat } from 'node:fs/promises' +import { appendFile, mkdtemp, mkdir, rm, readFile, writeFile, readdir, stat, symlink } from 'node:fs/promises' import { tmpdir } from 'node:os' import { isAbsolute, join, relative, resolve } from 'node:path' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' @@ -913,6 +913,23 @@ describe('SessionPersistenceJsonl: edge cases', () => { await expect(ctx.sessionPersistence.list()).rejects.toThrow(/and cwd identify/) }) + it('accepts an alternate project path only when it identifies the same physical log', async () => { + const m = meta('physical-alias', '/stored') + await ctx.sessionPersistence.create(m) + await ctx.sessionPersistence.append(m.id, oneTurnLog()) + const path = rawLogPath(root, m.cwd, m.id) + const aliasCwd = '/alias' + await symlink( + projectDir(root, m.cwd), + projectDir(root, aliasCwd), + process.platform === 'win32' ? 'junction' : 'dir', + ) + await rewriteHeader(path, (header) => { header.cwd = aliasCwd }) + + expect((await ctx.sessionPersistence.load(m.id)).meta.cwd).toBe(aliasCwd) + expect((await ctx.sessionPersistence.list()).map(header => header.id)).toContain(m.id) + }) + it('list rejects a session header whose id cannot name a storage path', async () => { const dir = join(projectDir(root, undefined), 'invalid-id') await mkdir(dir, { recursive: true }) diff --git a/packages/session-persistence/session-persistence-jsonl/tests/win32.spec.ts b/packages/session-persistence/session-persistence-jsonl/tests/win32.spec.ts index b4a2d11f28..647ff8b292 100644 --- a/packages/session-persistence/session-persistence-jsonl/tests/win32.spec.ts +++ b/packages/session-persistence/session-persistence-jsonl/tests/win32.spec.ts @@ -151,6 +151,15 @@ describe('Windows durable namespace helpers', () => { expect(existsSync(raced)).toBe(true) }) + it('keeps staging names valid for a maximum-length target component', async () => { + const { ensureDurableDirectoryWin32 } = await importWithFilesystemMove() + const root = await tempRoot() + const target = join(root, 'x'.repeat(255)) + + await ensureDurableDirectoryWin32(target) + expect(existsSync(target)).toBe(true) + }) + it('surfaces directory publication failures other than an existing-target race', async () => { const { ensureDurableDirectoryWin32 } = await importWithError(ERROR_ACCESS_DENIED) const root = await tempRoot() From 6d3c25f494a3e9bd48ae02a7e5200773e4ec5261 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 22:18:19 +0800 Subject: [PATCH 031/113] refactor(web-e2e): rename harness -> scaffold; add interaction coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared test module was named harness.ts inside a repo whose product IS a harness — hopelessly ambiguous. Renamed to scaffold.ts with launchWebScaffold/WebScaffold; tsconfig plane-split entries, the seam JSDoc/README mentions, and both Agent Note languages updated. Both scenarios gain a Playwright interaction step over the settled transcript (after the golden capture, so committed aria surfaces stay untouched): replay-round-trip clicks the reasoning fold open/closed over wire-delivered state; seeded-history expands a read tool row rebuilt from the cold log and asserts the recorded result text appears (read rows are expand-in-place — rowExpands routes the click to the inline fold, not the details column). test:web 30 passed | 1 skipped. --- .../2026-07-24-web-gui-browser-e2e-lane.md | 10 ++--- .../2026-07-24-web-gui-browser-e2e-lane.zh.md | 10 ++--- apps/web/tests/replay-round-trip.e2e.ts | 36 ++++++++++----- apps/web/tests/{harness.ts => scaffold.ts} | 40 ++++++++--------- apps/web/tests/seeded-history.e2e.ts | 45 +++++++++++++------ apps/web/tsconfig.json | 4 +- packages/host/runtime/README.md | 2 +- packages/host/runtime/src/boot.ts | 2 +- tsconfig.host.json | 2 +- 9 files changed, 91 insertions(+), 60 deletions(-) rename apps/web/tests/{harness.ts => scaffold.ts} (93%) diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md index 3cabceb966..9bab4d1eb9 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md @@ -12,11 +12,11 @@ The web GUI ships as a real assembled chain — chromium page → client plugin `pnpm run test:web` carries a keyless, deterministic browser e2e lane under `apps/web/tests/`: recorded session-log fixtures replayed through `@deepseek-ai/dsh-llm-replay` against the real in-process web assembly, asserting a normalized conversation aria golden plus in-process world state. No new package; the product deltas are the `BootHostOptions.llm` seam and two additive `dsh-llm-replay` surfaces. -### Harness: `apps/web/tests/harness.ts` +### Scaffold: `apps/web/tests/scaffold.ts` A plain shared-fixture module (the [testing-policy sanctioned shape](../../../../docs/testing.md)), not a package: the gate-worthy logic — replay derivation, session parsing, log scrubbing, persistence — lives in the gated packages `dsh-llm-replay`, `dsh-acp-snapshot`, and `dsh-session-persistence-jsonl`; what remains is boot wiring and browser glue, and chromium-driving code cannot hold per-file 100% coverage on the browserless coverage runners. -`launchWebHarness()` boots the real web assembly in-process from the exported production functions — `startHost({ boot: { …, llm: false } })`, `installLlmReplay(host.ctx, { file, providers, paceMs })`, `mountWebPlugins(host.ctx, roster, anchor)`, `createHostWebPluginRegistry`, `startWebServer({ port: 0, … })`. This is the web analog of the TUI suite mounting the production bundle in-process ([TUI snapshots](2026-07-18-tui-terminal-state-snapshots.md)): the real entry boundary (`dsh web` bin arg-parsing, dist resolution) stays held by the keyless CLI smokes in `smoke-real.e2e.ts`, and the web surface has no `cordis.yml` to bypass — assembly is written in the app per the [GUI layering decision](../architecture/2026-07-19-gui-layering-and-rpc-protocol.md), a ruling this lane's design review explicitly reaffirmed (Loader-izing `dsh web` was declined; it would be its own proposal). Two deliberate assembly divergences from the `dsh web` shell, noted in the harness header: `workspaceContext: false` (recorded fixtures must not embed this repo's AGENTS.md) and `sessionTitleLlm` left at bootHost's disabled default (its fire-and-forget title call would share the session's replay cursor nondeterministically). +`launchWebScaffold()` boots the real web assembly in-process from the exported production functions — `startHost({ boot: { …, llm: false } })`, `installLlmReplay(host.ctx, { file, providers, paceMs })`, `mountWebPlugins(host.ctx, roster, anchor)`, `createHostWebPluginRegistry`, `startWebServer({ port: 0, … })`. This is the web analog of the TUI suite mounting the production bundle in-process ([TUI snapshots](2026-07-18-tui-terminal-state-snapshots.md)): the real entry boundary (`dsh web` bin arg-parsing, dist resolution) stays held by the keyless CLI smokes in `smoke-real.e2e.ts`, and the web surface has no `cordis.yml` to bypass — assembly is written in the app per the [GUI layering decision](../architecture/2026-07-19-gui-layering-and-rpc-protocol.md), a ruling this lane's design review explicitly reaffirmed (Loader-izing `dsh web` was declined; it would be its own proposal). Two deliberate assembly divergences from the `dsh web` shell, noted in the scaffold header: `workspaceContext: false` (recorded fixtures must not embed this repo's AGENTS.md) and `sessionTitleLlm` left at bootHost's disabled default (its fire-and-forget title call would share the session's replay cursor nondeterministically). The `llm: false` seam is the reviewed resolution of the keyless-boot question: `'deepseek' | false` on `BootHostOptions`, matching the `workspaceContext: Config | false` shape, with `RunningHost.ctx` JSDoc naming "filling a deliberately-open capability seam" as its third sanctioned use. Replay runs in providers-catalog mode with a published `contextWindow` (the TUI `PROVIDERS` shape), never catch-all: with no adapter registered, catch-all would leave `resolveModelContext` unroutable and `compact-basic`'s post-step pressure check would warn every step instead of being provably inert. @@ -28,13 +28,13 @@ The barrier stack for a prompted turn, in order: (1) host-side `await agent.when No single-shot transient-DOM assertions: every hop from replay yield to React commit can coalesce chunks, so sampling `[data-streaming]` is a race by construction. Streaming incrementality is asserted from the persisted `assistant/chunk` events (model-visible ⟺ logged makes the log the authoritative proof). `dsh-llm-replay`'s opt-in `paceMs` (default absent = burst) is a realism knob so the browser observes genuinely incremental SSE; correctness never leans on it, and abort during a pace wait cancels promptly. -Every scenario fails on any pageerror and on the client's connection-loss/gap-repair console warnings: the reconnect machine plus history resync would otherwise self-heal a dead SSE path and the suite would certify a broken wire. Harness `close()` calls the `ReplayHandle.assertConsumed()` teardown check (every recorded script bound, every cursor drained), converting silent underruns and shifted bindings into crisp diagnostics. No vitest retry on the lane; one chromium per file, fresh context per scenario, one host per scenario; viewport pinned; selectors anchor on roles, `data-*` attributes, and visible text. +Every scenario fails on any pageerror and on the client's connection-loss/gap-repair console warnings: the reconnect machine plus history resync would otherwise self-heal a dead SSE path and the suite would certify a broken wire. Scaffold `close()` calls the `ReplayHandle.assertConsumed()` teardown check (every recorded script bound, every cursor drained), converting silent underruns and shifted bindings into crisp diagnostics. No vitest retry on the lane; one chromium per file, fresh context per scenario, one host per scenario; viewport pinned; selectors anchor on roles, `data-*` attributes, and visible text. ### Expected outputs One committed golden per scenario: a normalized `ariaSnapshot()` of the conversation region (`ui.expected.md`) — uuid/cwd/workspace-basename/duration tokens normalized, captured poll-until-equal at the settled milestone — plus a few role/text anchor assertions that stay green under a semantics-preserving component rewrite while the golden churns reviewably. The aria tree is the mechanization of the client rule "assert what the user would see, never class names". World-state assertions ride `host.ctx` session events inline (which tools ran, `turn/end` completed) instead of a second committed log golden: the persisted-log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence, and re-pinning it here would double refresh cost against the tier discipline. `refresh` is the sole golden writer — a missing golden in replay mode fails with the healing command rather than self-bootstrapping. -The typecheck plane split is structural: `apps/web/tests/{harness,support,replay-round-trip.e2e,seeded-history.e2e}.ts` are host-plane programs (they boot the host spine), so they are excluded from the client-registered `apps/web` project and included file-by-file in `tsconfig.host.json` — one program cannot hold both sides of the cordis `Context` merges. +The typecheck plane split is structural: `apps/web/tests/{scaffold,support,replay-round-trip.e2e,seeded-history.e2e}.ts` are host-plane programs (they boot the host spine), so they are excluded from the client-registered `apps/web` project and included file-by-file in `tsconfig.host.json` — one program cannot hold both sides of the cordis `Context` merges. ### Modes and fixtures @@ -81,7 +81,7 @@ The lane itself: `pnpm run test:web` runs both scenarios keylessly alongside the ## Deferred -- **Web header-class pin**: web fixtures tokenize `{{system}}`/`{{tools}}` everywhere and no scenario pins bootHost's composed prompt/tool schemas (`TODO(web-header-pin)` — the harness `recordFixture` JSDoc marks it). Following the TUI scrub-everywhere precedent; revisit when the web assembly's header diverges from the repl composition it mirrors. +- **Web header-class pin**: web fixtures tokenize `{{system}}`/`{{tools}}` everywhere and no scenario pins bootHost's composed prompt/tool schemas (`TODO(web-header-pin)` — the scaffold `recordFixture` JSDoc marks it). Following the TUI scrub-everywhere precedent; revisit when the web assembly's header diverges from the repl composition it mirrors. - **CI browser provisioning**: reversal of the no-browser-in-CI ruling, staged criteria above (`TODO(ci-browser)`). - **Follow-up-prompt-after-resume scenario**: the history/live stitch path over the real wire; add as its own scenario when that code changes or regresses. diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md index 132caa4536..c61aee7ae5 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md @@ -12,11 +12,11 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu `pnpm run test:web` 携带 `apps/web/tests/` 下的无密钥、确定性浏览器 e2e 车道:录制的会话日志 fixture 经 `@deepseek-ai/dsh-llm-replay` 对真实进程内 web 组装回放,断言规范化后的会话区 aria 预期输出加进程内世界状态。不新增包(package);产品侧增量只有 `BootHostOptions.llm` seam 和 `dsh-llm-replay` 的两处增量接口。 -### Harness:`apps/web/tests/harness.ts` +### Scaffold:`apps/web/tests/scaffold.ts` 一个普通的共享 fixture 模块([测试政策认可的形态](../../../../docs/testing.md)),不是包:值得门禁把守的逻辑——回放推导、会话解析、日志脱敏、持久化——都在已受门禁的包 `dsh-llm-replay`、`dsh-acp-snapshot`、`dsh-session-persistence-jsonl` 中;剩下的只是启动接线和浏览器胶水,而驱动 chromium 的源码在无浏览器的覆盖率 runner 上无法诚实保持逐文件 100% 覆盖率。 -`launchWebHarness()` 用导出的生产函数在进程内启动真实 web 组装——`startHost({ boot: { …, llm: false } })`、`installLlmReplay(host.ctx, { file, providers, paceMs })`、`mountWebPlugins(host.ctx, roster, anchor)`、`createHostWebPluginRegistry`、`startWebServer({ port: 0, … })`。这是 TUI 套件进程内挂载生产 bundle 的 web 对应物([TUI 快照](2026-07-18-tui-terminal-state-snapshots.md)):真实入口边界(`dsh web` bin 的参数解析、dist 解析)仍由 `smoke-real.e2e.ts` 中的无密钥 CLI 冒烟把守,且 web 表面没有可绕过的 `cordis.yml`——按[GUI 分层决策](../architecture/2026-07-19-gui-layering-and-rpc-protocol.md),组装写在应用里;本车道的设计评审明确重申了这一裁定(Loader 化 `dsh web` 被否决;那需要自己的提案)。与 `dsh web` shell 的两处刻意组装差异已注明在 harness 头部:`workspaceContext: false`(录制的 fixture 不得嵌入本仓库的 AGENTS.md),以及 `sessionTitleLlm` 保持 bootHost 的禁用默认值(其发后不管的标题调用会与循环自身的调用不确定地共享会话的回放游标)。 +`launchWebScaffold()` 用导出的生产函数在进程内启动真实 web 组装——`startHost({ boot: { …, llm: false } })`、`installLlmReplay(host.ctx, { file, providers, paceMs })`、`mountWebPlugins(host.ctx, roster, anchor)`、`createHostWebPluginRegistry`、`startWebServer({ port: 0, … })`。这是 TUI 套件进程内挂载生产 bundle 的 web 对应物([TUI 快照](2026-07-18-tui-terminal-state-snapshots.md)):真实入口边界(`dsh web` bin 的参数解析、dist 解析)仍由 `smoke-real.e2e.ts` 中的无密钥 CLI 冒烟把守,且 web 表面没有可绕过的 `cordis.yml`——按[GUI 分层决策](../architecture/2026-07-19-gui-layering-and-rpc-protocol.md),组装写在应用里;本车道的设计评审明确重申了这一裁定(Loader 化 `dsh web` 被否决;那需要自己的提案)。与 `dsh web` shell 的两处刻意组装差异已注明在 scaffold 头部:`workspaceContext: false`(录制的 fixture 不得嵌入本仓库的 AGENTS.md),以及 `sessionTitleLlm` 保持 bootHost 的禁用默认值(其发后不管的标题调用会与循环自身的调用不确定地共享会话的回放游标)。 `llm: false` seam 是无密钥启动问题经评审后的定论:`BootHostOptions` 上的 `'deepseek' | false`,与 `workspaceContext: Config | false` 形态一致,且 `RunningHost.ctx` 的 JSDoc 把「填充刻意开放的能力 seam」列为其第三种认可用法。回放必须以提供方目录(providers-catalog)模式运行并发布 `contextWindow`(TUI 的 `PROVIDERS` 形态),绝不用 catch-all:没有注册适配器时,catch-all 会让 `resolveModelContext` 无路由可走,`compact-basic` 的步后压力检查将步步告警,而不是被可证明地闲置。 @@ -28,13 +28,13 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu 不做单次瞬态 DOM 断言:从回放产出到 React 提交的每一跳都可能合并分片,采样 `[data-streaming]` 天然就是竞态。流式输出的增量性由持久化的 `assistant/chunk` 事件断言(模型可见 ⟺ 已记录,使日志成为权威证据)。`dsh-llm-replay` 的可选 `paceMs`(默认缺省 = 突发)只是让浏览器观察到真正增量 SSE 的真实感旋钮;正确性绝不依赖它,且节奏等待期间中止会即时取消。 -每个场景都会因任何 pageerror 或客户端的连接丢失/间隙修复控制台警告而失败:否则重连机制加历史重同步会把一条死掉的 SSE 通路自愈掉,套件反而认证了坏 wire。Harness 的 `close()` 调用 `ReplayHandle.assertConsumed()` 收尾检查(每个已录脚本都被绑定、每个游标都耗尽),把静默的少放与错绑变成清晰诊断。车道不设 vitest 重试;每文件一个 chromium、每场景一个新 context、每场景一个 host;视口固定;选择器只锚定 role、`data-*` 属性和可见文本。 +每个场景都会因任何 pageerror 或客户端的连接丢失/间隙修复控制台警告而失败:否则重连机制加历史重同步会把一条死掉的 SSE 通路自愈掉,套件反而认证了坏 wire。Scaffold 的 `close()` 调用 `ReplayHandle.assertConsumed()` 收尾检查(每个已录脚本都被绑定、每个游标都耗尽),把静默的少放与错绑变成清晰诊断。车道不设 vitest 重试;每文件一个 chromium、每场景一个新 context、每场景一个 host;视口固定;选择器只锚定 role、`data-*` 属性和可见文本。 ### 预期输出 每场景一份提交的预期输出:会话区规范化 `ariaSnapshot()`(`ui.expected.md`)——uuid/cwd/工作区目录名/时长归一为稳定 token,在安定里程碑处轮询至两次相等再采集——外加几条 role/文本锚断言,让保语义的组件重写在预期输出可评审地变动时仍保持绿色锚点。aria 树是 client 规则「断言用户所见,绝不断言类名」的机械化。世界状态断言内联在 `host.ctx` 会话事件上(哪些工具运行了、`turn/end` 完成)而不是第二份提交的日志预期输出:持久化日志表面已由 ACP/headless/TUI 套件经同一循环和持久化钉住,在此重复钉住会违背分层纪律、翻倍刷新成本。`refresh` 是预期输出的唯一写入者——回放模式下预期输出缺失会连同修复命令一起报错,而不是静默自举。 -类型检查平面切分是结构性的:`apps/web/tests/{harness,support,replay-round-trip.e2e,seeded-history.e2e}.ts` 是 host 平面程序(它们启动 host 主干),因此被排除出注册在 client 侧的 `apps/web` 工程,逐文件纳入 `tsconfig.host.json`——一个程序不能同时持有 cordis `Context` 合并的两侧。 +类型检查平面切分是结构性的:`apps/web/tests/{scaffold,support,replay-round-trip.e2e,seeded-history.e2e}.ts` 是 host 平面程序(它们启动 host 主干),因此被排除出注册在 client 侧的 `apps/web` 工程,逐文件纳入 `tsconfig.host.json`——一个程序不能同时持有 cordis `Context` 合并的两侧。 ### 模式与 fixture @@ -81,7 +81,7 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu ## 暂缓 -- **Web 头类别钉住**:web fixture 处处 token 化 `{{system}}`/`{{tools}}`,没有场景钉住 bootHost 组装的提示词/工具 schema(`TODO(web-header-pin)`——harness 的 `recordFixture` JSDoc 有标记)。沿用 TUI 处处脱敏先例;当 web 组装的请求头与其镜像的 repl 组合进一步分叉时重审。 +- **Web 头类别钉住**:web fixture 处处 token 化 `{{system}}`/`{{tools}}`,没有场景钉住 bootHost 组装的提示词/工具 schema(`TODO(web-header-pin)`——scaffold 的 `recordFixture` JSDoc 有标记)。沿用 TUI 处处脱敏先例;当 web 组装的请求头与其镜像的 repl 组合进一步分叉时重审。 - **CI 浏览器供给**:推翻 CI 无浏览器裁定,分阶段标准见上(`TODO(ci-browser)`)。 - **恢复后追问场景**:真实 wire 上的历史/实时缝合路径;当该代码变更或回归时作为独立场景补充。 diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index faf1a1f6a8..c2476ed3ea 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -16,8 +16,8 @@ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import type { SessionEvent } from '@deepseek-ai/dsh-session' import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, - launchWebHarness, recordFixture, watchConsole, webSnapshotMode, type WebHarness, -} from './harness.ts' + launchWebScaffold, recordFixture, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' import { saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/fresh-round-trip', import.meta.url)) @@ -31,27 +31,27 @@ const MODE = webSnapshotMode() const PROMPT = 'Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop.' describe('web e2e: fresh round trip through the real assembly', () => { - let harness: WebHarness + let scaffold: WebScaffold let browser: Browser let page: Page let tripwire: ReturnType const sessionEvents: SessionEvent[] = [] beforeAll(async () => { - harness = await launchWebHarness({ + scaffold = await launchWebScaffold({ ...(MODE === 'record' ? {} : { replayFixture: FIXTURE, paceMs: 15 }), }) - harness.host.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) }) + scaffold.host.ctx.on('session/event', (_session, event: SessionEvent) => { sessionEvents.push(event) }) browser = await chromium.launch() page = await browser.newPage({ viewport: { width: 1680, height: 1000 } }) tripwire = watchConsole(page) - await page.goto(harness.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) afterAll(async () => { await browser?.close() - await harness?.close() + await scaffold?.close() }) it('drives the recorded prompt to a settled turn (all modes)', async () => { @@ -63,12 +63,12 @@ describe('web e2e: fresh round trip through the real assembly', () => { const input = page.locator('textarea').first() await input.waitFor({ timeout: 10_000 }) // Arm the host-side settled barrier BEFORE the send click. - const settled = harness.whenTurnSettled() + const settled = scaffold.whenTurnSettled() await input.fill(PROMPT) await input.press('Enter') const sessionId = await settled if (MODE === 'record') { - await recordFixture(harness, sessionId, FIXTURE) + await recordFixture(scaffold, sessionId, FIXTURE) } }, 200_000) @@ -96,14 +96,28 @@ describe('web e2e: fresh round trip through the real assembly', () => { // while the whole-region golden churns. await expect(page.getByRole('textbox').first().isVisible()).resolves.toBe(true) expect(await page.getByText('WEB_E2E_OK', { exact: false }).count()).toBeGreaterThanOrEqual(1) - const snapshot = await captureStableAria(page, '[class*="centerCol"]', harness.workspaceCwd) + const snapshot = await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd) await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) }) + it.skipIf(MODE === 'record')('expands and collapses the reasoning fold from its click target', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-round-trip-think')) + // Interaction over the REAL wire-delivered transcript (the fixture-client + // tier pins the same gesture against FixtureApiClient; this one runs on + // mux-frame-fed state). Runs after the golden capture so the committed + // aria surface stays the untouched settled state. + const think = page.getByRole('button', { name: /^Think/ }).first() + expect(await think.getAttribute('aria-expanded')).toBe('false') + await think.click() + await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true') + await think.click() + await expect.poll(() => think.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false') + }) + it.skipIf(MODE === 'record')('stayed clean: no pageerrors, no reconnect self-healing, no server errors', async () => { expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) - expect(harness.serverErrors).toEqual([]) + expect(scaffold.serverErrors).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, ['session.jsonl', 'ui.expected.md']) }) }) diff --git a/apps/web/tests/harness.ts b/apps/web/tests/scaffold.ts similarity index 93% rename from apps/web/tests/harness.ts rename to apps/web/tests/scaffold.ts index b2941c62e0..c7fb3b04fe 100644 --- a/apps/web/tests/harness.ts +++ b/apps/web/tests/scaffold.ts @@ -1,4 +1,4 @@ -// Shared harness for the keyless browser e2e lane (Agent Note: +// Shared scaffold for the keyless browser e2e lane (Agent Note: // .agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md). // Boots the REAL web assembly in-process from the exported production // functions — startHost (bootHost spine) + mountWebPlugins + registry + @@ -78,9 +78,9 @@ function loadRootEnv(): void { } } -/** A booted web harness: real assembly, mode-selected model backend, temp world. */ -export interface WebHarness { - /** The active snapshot mode this harness booted under. */ +/** A booted web scaffold: real assembly, mode-selected model backend, temp world. */ +export interface WebScaffold { + /** The active snapshot mode this scaffold booted under. */ mode: WebSnapshotMode /** Browser-facing origin (http://127.0.0.1:). */ baseUrl: string @@ -98,7 +98,7 @@ export interface WebHarness { close(): Promise } -/** Options for {@link launchWebHarness}. */ +/** Options for {@link launchWebScaffold}. */ export interface LaunchOptions { /** * Replay fixture (session.jsonl) served by dsh-llm-replay in replay/refresh @@ -114,9 +114,9 @@ export interface LaunchOptions { /** * Boot the real web assembly under the current snapshot mode. * @param options - replay fixture selection and pacing. - * @returns the running harness. + * @returns the running scaffold. */ -export async function launchWebHarness(options: LaunchOptions = {}): Promise { +export async function launchWebScaffold(options: LaunchOptions = {}): Promise { requireDist() const mode = webSnapshotMode() if (mode === 'record') { @@ -221,7 +221,7 @@ export async function launchWebHarness(options: LaunchOptions = {}): Promise failures.push(e)) await rm(workspaceCwd, { recursive: true, force: true }).catch((e: unknown) => failures.push(e)) await rm(persistenceRoot, { recursive: true, force: true }).catch((e: unknown) => failures.push(e)) - if (failures.length > 0) throw new AggregateError(failures, 'web harness teardown failed') + if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed') }, } } @@ -246,16 +246,16 @@ function rawSessionLog(session: Session): string { * work), tokenize the run-local session id and cwd ({{sessionId}}/{{cwd}}, * the committed ACP fixture convention — re-records then diff only on real * content), and write the committed fixture. - * @param harness - the record-mode harness. + * @param scaffold - the record-mode scaffold. * @param sessionId - the driven session. * @param fixturePath - the committed session.jsonl / seed.jsonl target. */ -export async function recordFixture(harness: WebHarness, sessionId: SessionId, fixturePath: string): Promise { - const agent = harness.host.ctx.agents.get(sessionId) +export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, fixturePath: string): Promise { + const agent = scaffold.host.ctx.agents.get(sessionId) if (agent === undefined) throw new Error(`record harvest: no live agent for ${sessionId}`) const tokenized = scrubRequestHeaders(rawSessionLog(agent.session)) .split(sessionId).join('{{sessionId}}') - .split(harness.workspaceCwd).join('{{cwd}}') + .split(scaffold.workspaceCwd).join('{{cwd}}') await writeFile(fixturePath, tokenized) } @@ -274,27 +274,27 @@ export function fixtureUserPrompts(fixtureText: string): string[] { } /** - * Seed a recorded session fixture into the harness's persistence root through + * Seed a recorded session fixture into the scaffold's persistence root through * the REAL backend API (throwaway Context + SessionStore + JSONL plugin — the * semantic-checkpoint precedent), never raw file writes: no knowledge of * bucket hashing, filename encoding, or compression, and malformed shapes * fail loud at seed time. The fixture's recorded cwd is rewritten to the - * harness workspace so header/path identity and event payload paths agree. - * @param harness - the target harness. + * scaffold workspace so header/path identity and event payload paths agree. + * @param scaffold - the target scaffold. * @param fixtureText - raw recorded session.jsonl contents. * @param id - the seeded session id (stable for deterministic goldens). * @returns the seeded id. */ -export async function seedSession(harness: WebHarness, fixtureText: string, id: string): Promise { +export async function seedSession(scaffold: WebScaffold, fixtureText: string, id: string): Promise { // Committed fixtures tokenize run-local identity ({{sessionId}}/{{cwd}}, // written by recordFixture); realize both for this world before parsing. const realized = fixtureText .split('{{sessionId}}').join(id) - .split('{{cwd}}').join(harness.workspaceCwd) + .split('{{cwd}}').join(scaffold.workspaceCwd) const fixtureCwd = (JSON.parse(realized.split('\n', 1)[0]!) as { cwd?: string }).cwd const rewritten = fixtureCwd === undefined ? realized - : realized.split(fixtureCwd).join(harness.workspaceCwd) + : realized.split(fixtureCwd).join(scaffold.workspaceCwd) const events = parseSessionLog(rewritten) if (events.length === 0) throw new Error('seed fixture has no events') const last = events[events.length - 1]! @@ -305,7 +305,7 @@ export async function seedSession(harness: WebHarness, fixtureText: string, id: version: SESSION_FORMAT_VERSION, id: SessionId(id), createdAt: Date.now() - 60_000, - cwd: harness.workspaceCwd, + cwd: scaffold.workspaceCwd, delegationDepth: 0, } const ctx = new Context() @@ -313,7 +313,7 @@ export async function seedSession(harness: WebHarness, fixtureText: string, id: await ctx.plugin(SessionStore) // Same root as the host with the plugin's own default compression, so the // host's directory-scan list() sees one consistent encoding. - await ctx.plugin(SessionPersistenceJsonl, { root: harness.persistenceRoot }) + await ctx.plugin(SessionPersistenceJsonl, { root: scaffold.persistenceRoot }) await ctx.sessionPersistence.create(meta) await ctx.sessionPersistence.append(meta.id, events) // Deterministic sidebar order: cold summaries take updatedAt from mtime. diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index 734c0848c4..67bb5131c5 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -15,8 +15,8 @@ import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { join } from 'node:path' import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, - launchWebHarness, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebHarness, -} from './harness.ts' + launchWebScaffold, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' import { saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/seeded-history', import.meta.url)) @@ -28,44 +28,44 @@ const SEED_ID = 'seeded-history-web-e2e' const PROMPT = 'Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop.' describe('web e2e: seeded history renders through cold resume', () => { - let harness: WebHarness + let scaffold: WebScaffold let browser: Browser let page: Page let tripwire: ReturnType beforeAll(async () => { - harness = await launchWebHarness({}) + scaffold = await launchWebScaffold({}) // The read-tool targets exist in both modes: record needs them for the // live turn; replay's seeded log carries their recorded contents but the - // workspace stays consistent for any user poking the harness. - await writeFile(join(harness.workspaceCwd, 'a.txt'), 'alpha\n') - await writeFile(join(harness.workspaceCwd, 'b.txt'), 'beta\n') + // workspace stays consistent for any user poking the scaffold. + await writeFile(join(scaffold.workspaceCwd, 'a.txt'), 'alpha\n') + await writeFile(join(scaffold.workspaceCwd, 'b.txt'), 'beta\n') if (MODE !== 'record') { const raw = await readFile(SEED, 'utf8') expect(fixtureUserPrompts(raw), 'seed fixture must carry exactly the drive prompt').toEqual([PROMPT]) - await seedSession(harness, raw, SEED_ID) + await seedSession(scaffold, raw, SEED_ID) } browser = await chromium.launch() page = await browser.newPage({ viewport: { width: 1680, height: 1000 } }) tripwire = watchConsole(page) - await page.goto(harness.baseUrl, { waitUntil: 'load' }) + await page.goto(scaffold.baseUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) }, 120_000) afterAll(async () => { await browser?.close() - await harness?.close() + await scaffold?.close() }) it.skipIf(MODE !== 'record')('records the seed turn live through the composer', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-record')) const input = page.locator('textarea').first() await input.waitFor({ timeout: 10_000 }) - const settled = harness.whenTurnSettled() + const settled = scaffold.whenTurnSettled() await input.fill(PROMPT) await input.press('Enter') const sessionId = await settled - await recordFixture(harness, sessionId, SEED) + await recordFixture(scaffold, sessionId, SEED) }, 200_000) it.skipIf(MODE === 'record')('lists the seeded session cold and renders its history from the log', async () => { @@ -89,17 +89,34 @@ describe('web e2e: seeded history renders through cold resume', () => { it.skipIf(MODE === 'record')('matches the historical conversation aria golden', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-aria')) - const snapshot = (await captureStableAria(page, '[class*="centerCol"]', harness.workspaceCwd)) + const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) .split(SEED_ID).join('{{seededId}}') await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) }) + it.skipIf(MODE === 'record')('expands and collapses a tool row rebuilt from the cold log', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-toolrow')) + // Interaction over cold-resumed history: read rows are expand-in-place + // rows (rowExpands routes the click to toggleExpand, not openDetails), so + // the gesture under test is the inline fold over log-rebuilt content. + // Runs after the golden capture; still zero model calls. + const row = page.locator('[data-variant] [data-clickable][role="button"]').first() + await row.waitFor({ timeout: 10_000 }) + expect(await row.getAttribute('aria-expanded')).toBe('false') + await row.click() + await expect.poll(() => row.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('true') + // The expanded body renders the recorded tool result (a.txt's contents). + await expect.poll(() => page.getByText('alpha', { exact: false }).count(), { timeout: 5_000 }).toBeGreaterThan(0) + await row.click() + await expect.poll(() => row.getAttribute('aria-expanded'), { timeout: 5_000 }).toBe('false') + }) + it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => { // No replay fixture was installed and the llm seam is open — any stray // stream would have failed the turn loudly. Cleanliness pins the wire. expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) - expect(harness.serverErrors).toEqual([]) + expect(scaffold.serverErrors).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, ['seed.jsonl', 'ui.expected.md']) }) }) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 514cbe4d57..e1b68a4309 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -17,12 +17,12 @@ "src", "tests" ], - // The web e2e lane (harness + replay specs) boots the host spine and reads + // The web e2e lane (scaffold + replay specs) boots the host spine and reads // its Context merges — host-plane programs, checked in tsconfig.host.json; // this client-registered project must not also hold them (one program // cannot see both sides of the cordis Context merges). "exclude": [ - "tests/harness.ts", + "tests/scaffold.ts", "tests/replay-round-trip.e2e.ts", "tests/seeded-history.e2e.ts" ], diff --git a/packages/host/runtime/README.md b/packages/host/runtime/README.md index 4384f591a1..90a547c210 100644 --- a/packages/host/runtime/README.md +++ b/packages/host/runtime/README.md @@ -2,7 +2,7 @@ Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence and immediate fallback titles, optional first-message model summaries, system prompt, tools, agents, agent loop, workspace instructions, local bash, and the provider-neutral user-interaction service), `createApiProxy` implements the [`dsh-host-apiproxy`](../apiproxy/README.md) contract over that composition, and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }`. -Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly three sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`), headless session-event subscription, and filling a capability seam the boot options deliberately left open (`llm: false` → the embedder installs its own LLM backend, e.g. the keyless web e2e harness's replay); consuming clients must not bypass `api` through it. +Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly three sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`), headless session-event subscription, and filling a capability seam the boot options deliberately left open (`llm: false` → the embedder installs its own LLM backend, e.g. the keyless web e2e scaffold's replay); consuming clients must not bypass `api` through it. ## Configuration diff --git a/packages/host/runtime/src/boot.ts b/packages/host/runtime/src/boot.ts index e2f24a98ac..7e89a435db 100644 --- a/packages/host/runtime/src/boot.ts +++ b/packages/host/runtime/src/boot.ts @@ -69,7 +69,7 @@ export interface BootHostOptions { * LLM adapter selection: `'deepseek'` (default) mounts the DeepSeek adapter * (requires an API key at load), `false` mounts no adapter and leaves the * `llm` capability seam open for the embedder to fill on the returned ctx - * (e.g. the keyless web e2e harness installing a replay backend). With + * (e.g. the keyless web e2e scaffold installing a replay backend). With * `false` and nothing filled, the first stream fails loud with NO_ADAPTER — * the earliest resolvable point for an open capability seam. */ diff --git a/tsconfig.host.json b/tsconfig.host.json index a5f48ed22d..a8688ab3fb 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -8,7 +8,7 @@ "rewriteRelativeImportExtensions": false }, "include": [ - "apps/web/tests/harness.ts", + "apps/web/tests/scaffold.ts", "apps/web/tests/support.ts", "apps/web/tests/replay-round-trip.e2e.ts", "apps/web/tests/seeded-history.e2e.ts", From 13345fdadcd6625d60bdbd7fa61b4206292a53c0 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 22:46:04 +0800 Subject: [PATCH 032/113] docs(i18n): re-record web e2e note pair after the scaffold rename The rename commit edited both sides of the bilingual pair but missed the re-record; the pairing gate compares blob hashes and went red. --- .../testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml index 1f55dfce3e..d759047151 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.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 -2026-07-24-web-gui-browser-e2e-lane.md: 3cabceb9667d3d1c153518d58b8d4c02b0578d20 -2026-07-24-web-gui-browser-e2e-lane.zh.md: 132caa453662f48619aa542c68b59f59b64acd0f +2026-07-24-web-gui-browser-e2e-lane.md: 9bab4d1eb9ec24acae0057143379629c87194d1f +2026-07-24-web-gui-browser-e2e-lane.zh.md: c61aee7ae5c070d1c82dda0ab78d8db44c16b9bf From 1e78054a78f037d2ea58f27cd7e0298f575f51cc Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 23:04:57 +0800 Subject: [PATCH 033/113] ci: retrigger workflows (push event for 7a4cd7857 was dropped by Actions) From e4553deceda22b8088c108c92367366bcd09bd1c Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Fri, 24 Jul 2026 23:13:03 +0800 Subject: [PATCH 034/113] docs(i18n): re-record testing.md pair after merging master's bilingual split The merge added the web-browser-snapshot bullet to both sides of the now bilingual docs/testing.md; the pair record needs the post-merge hashes. --- docs/testing.i18n.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/testing.i18n.yaml b/docs/testing.i18n.yaml index 8ebdff8c55..e01ada78dd 100644 --- a/docs/testing.i18n.yaml +++ b/docs/testing.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 -testing.md: fd38fb7b20d76ef48c81c86badcf501f7c0dbd4e -testing.zh.md: 4584492350aefd5d72692093b08c0dcd4910a8af +testing.md: bf202c23574194d61d138c0f03073136dd29484a +testing.zh.md: 8b98f17c955fbb8cf7588b5bccc2e4c1298d3cf4 From 83cccd7ffc4340251d097684df796178cbafe413 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 25 Jul 2026 08:20:40 +0800 Subject: [PATCH 035/113] feat(llm): add scriptable mock fault server --- ...scriptable-llm-wire-fault-server.i18n.yaml | 6 + ...-07-25-scriptable-llm-wire-fault-server.md | 41 + ...-25-scriptable-llm-wire-fault-server.zh.md | 41 + docs/config-catalog.md | 1 + package.json | 1 + packages/llm/llm-retry/package.json | 3 + .../tests/transport-recovery.spec.ts | 230 ++++++ packages/support/README.md | 3 +- packages/support/llm-mock-server/README.md | 84 ++ packages/support/llm-mock-server/package.json | 45 ++ packages/support/llm-mock-server/src/bin.ts | 50 ++ packages/support/llm-mock-server/src/cli.ts | 212 +++++ packages/support/llm-mock-server/src/index.ts | 723 ++++++++++++++++++ .../support/llm-mock-server/src/invariant.ts | 30 + .../support/llm-mock-server/tests/cli.spec.ts | 121 +++ .../llm-mock-server/tests/invariant.spec.ts | 18 + .../llm-mock-server/tests/server.spec.ts | 312 ++++++++ .../support/llm-mock-server/tsconfig.json | 15 + .../support/llm-mock-server/tsdown.config.ts | 17 + pnpm-lock.yaml | 18 + .../verify-package-readme-model-experience.ts | 1 + tsconfig.host.json | 1 + 22 files changed, 1972 insertions(+), 1 deletion(-) create mode 100644 .agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.i18n.yaml create mode 100644 .agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md create mode 100644 .agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md create mode 100644 packages/llm/llm-retry/tests/transport-recovery.spec.ts create mode 100644 packages/support/llm-mock-server/README.md create mode 100644 packages/support/llm-mock-server/package.json create mode 100644 packages/support/llm-mock-server/src/bin.ts create mode 100644 packages/support/llm-mock-server/src/cli.ts create mode 100644 packages/support/llm-mock-server/src/index.ts create mode 100644 packages/support/llm-mock-server/src/invariant.ts create mode 100644 packages/support/llm-mock-server/tests/cli.spec.ts create mode 100644 packages/support/llm-mock-server/tests/invariant.spec.ts create mode 100644 packages/support/llm-mock-server/tests/server.spec.ts create mode 100644 packages/support/llm-mock-server/tsconfig.json create mode 100644 packages/support/llm-mock-server/tsdown.config.ts diff --git a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.i18n.yaml b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.i18n.yaml new file mode 100644 index 0000000000..4eea19c9c0 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.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 +2026-07-25-scriptable-llm-wire-fault-server.md: 92f7d6aad8e7b4dc8bb08e98bb5847ff27470229 +2026-07-25-scriptable-llm-wire-fault-server.zh.md: 2f5fcc1321b0e4f501f3814e5e96d4b26cf18ec6 diff --git a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md new file mode 100644 index 0000000000..92f7d6aad8 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md @@ -0,0 +1,41 @@ +# Agent Note: Scriptable LLM wire fault server + +Status: implemented + +English | [中文](2026-07-25-scriptable-llm-wire-fault-server.zh.md) + +## Problem + +Adapter unit tests use local HTTP servers to classify individual provider failures, while retry tests use an in-process scripted `LlmAdapter` to prove closed-step recovery. Neither boundary provides a reusable server for running the shipping HTTP adapter, agent loop, and retry policy together, and neither lets a developer point an existing app at deterministic transport faults by changing only its base URL and API key. + +Connection refusal, a reset before the first event, clean EOF without `[DONE]`, a valid content-less completion, and a reset after partial output have different adapter and recovery outcomes. Treating them as one generic mock failure hides whether the provider boundary preserved the distinction and whether failed chunks remained outside committed model history. + +## Decision + +`@deepseek-ai/dsh-llm-mock-server` is a support package with an importable Node HTTP server and a standalone CLI. It accepts OpenAI-compatible root and `/v1` chat-completions paths, validates an optional bearer token, captures requests, and consumes one explicit behavior per accepted request. Script exhaustion fails loud; repetition requires `repeatLast`. + +Request behaviors cover socket reset, post-header disconnect, partial disconnect, stall, valid empty completion, clean truncated streams, malformed payloads, representative HTTP failures, complete text/reasoning/tool-call responses, slow streaming, and max-token completion. A true `connection_refused` is a CLI listener-lifecycle phase because a bound request handler cannot refuse its own TCP connection. + +The `random` script entry performs a new weighted selection for every request. The server exposes and logs its unsigned 32-bit seed, accepts caller-supplied relative weights, and ships a success-heavy stress profile that mixes transport, protocol, provider, timeout, and semantic-empty outcomes. The profile is configurable test pressure rather than an estimate of production incident frequency; `connection_refused` remains outside the request-level pool. + +The server reports wire facts only and does not classify retryability. Real-composition tests route it through `dsh-llm-deepseek`, `dsh-agent-loop`, and `dsh-llm-retry`: connection refusal, hard disconnect, partial reset, and idle timeout recover under the existing default policy; a valid content-less completion succeeds without retry; clean partial EOF remains `STREAM_CLOSED` and is not retried by default. The package does not change those policies. + +## Verification + +Package tests exercise every request behavior, HTTP validation without script consumption, script exhaustion/repetition, stalled-connection teardown, CLI parsing, random seed reproducibility, weight validation, telemetry, lifecycle cleanup, and the invariant companion under the per-file coverage gate. The retry integration suite proves exact request counts, numbered retry steps, request-body identity, failed partial-chunk isolation, empty-success semantics, clean-EOF classification, timeout recovery, true refused-connection recovery after delayed listener startup, and bounded exhaustion through the real HTTP/SSE adapter. + +## Alternatives considered + +**Implement the server in Python** — rejected because Node's standard HTTP and socket APIs expose every required fault, while TypeScript keeps the server, CLI parser, tests, package build, lint, and coverage inside the repository's existing toolchain. A second runtime would add environment and subprocess dependencies without increasing wire isolation. + +**Keep separate inline mock servers in adapter tests** — rejected because those fixtures cannot be launched by an existing app and would duplicate behavior sequencing, randomization, telemetry, and connection cleanup across suites. A support package gives tests a shared implementation without promoting it to product API. + +**Use only an in-process `LlmAdapter` mock** — rejected because it bypasses fetch, HTTP status/header parsing, SSE framing, socket termination, and the adapter idle watchdog: the exact boundaries this test infrastructure exists to exercise. + +**Change retry defaults with the server** — rejected because the server reveals existing semantics rather than deciding policy. Adding `STREAM_CLOSED` or semantic-empty recovery requires a separate decision with its own cost, latency, and duplicate-generation trade-offs. + +## Consequences + +Developers can reproduce fault sequences by changing only provider URL/key configuration, and automated tests can keep socket-level failures deterministic through explicit scripts and seeds. The same wire fixture now exposes gaps between hard resets, clean truncation, and successful empty completions without splicing attempts or modifying model history. + +The server adds a support package, executable build entry, and behavior vocabulary that must remain compatible with both direct tests and CLI examples. Arrival-ordered scripts are intentionally shared across clients, random defaults are stress weights rather than operational truth, and exact connection refusal requires coordinating the client attempt with the pre-listen interval. diff --git a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md new file mode 100644 index 0000000000..2f5fcc1321 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md @@ -0,0 +1,41 @@ +# Agent Note: 可脚本控制的 LLM(大语言模型)协议层故障服务器 + +Status: implemented + +[English](2026-07-25-scriptable-llm-wire-fault-server.md) | 中文 + +## 问题 + +适配器单元测试使用本地 HTTP 服务器对各类提供方故障逐一分类,重试测试则使用进程内的脚本化 `LlmAdapter` 证明已关闭步骤的恢复能力。这两个边界都无法提供可复用的服务器,以便同时运行交付版本的 HTTP 适配器、agent loop(智能体循环)和重试策略;开发者也无法仅修改现有应用的 base URL 与 API key,就让应用连接到确定性的传输故障。 + +连接遭拒、首个事件前连接被重置、未收到 `[DONE]` 即正常 EOF、合法但无内容的完成,以及输出部分内容后连接被重置,会产生不同的适配器与恢复结果。把它们统一视为普通 mock 故障,会掩盖提供方边界是否保留了这些区别,以及失败请求的分片是否确实没有进入已提交的模型历史。 + +## 决策 + +`@deepseek-ai/dsh-llm-mock-server` 是一个支持包(package),提供可导入的 Node HTTP 服务器和独立 CLI(命令行界面)。它接受兼容 OpenAI 的根路径和 `/v1` chat-completions 路径,校验可选的 bearer token,捕获请求,并对每个已接受请求消耗一个显式行为。脚本耗尽时快速失败;只有设置 `repeatLast` 才会重复最后一个行为。 + +请求行为覆盖 socket 重置、发送 header 后断开、发送部分内容后断开、停滞、合法空完成、正常关闭但被截断的流、畸形 payload、典型 HTTP 故障、完整的文本/推理/工具调用响应、慢速流式输出以及达到 token 上限的完成。真正的 `connection_refused` 由 CLI 的监听器生命周期阶段实现,因为已经绑定端口的请求处理器无法拒绝自身的 TCP 连接。 + +脚本项 `random` 会为每个请求重新执行一次加权选择。服务器公开并记录其无符号 32 位 seed,允许调用方提供相对权重,并内置一套偏重成功结果的压力测试配置,将传输、协议、提供方、超时和语义空结果混合在一起。该配置用于提供可调的测试压力,并非对生产事故发生频率的估算;`connection_refused` 仍不进入请求级随机池。 + +服务器只报告协议层事实,不判断是否可重试。真实组合测试让请求依次经过 `dsh-llm-deepseek`、`dsh-agent-loop` 和 `dsh-llm-retry`:在现有默认策略下,连接遭拒、硬断开、部分输出后重置以及空闲超时均可恢复;合法的无内容完成无需重试即可成功;正常关闭的部分输出 EOF 仍归类为 `STREAM_CLOSED`,默认不重试。该包不会改变这些策略。 + +## 验证 + +包测试覆盖所有请求行为、不消耗脚本的 HTTP 校验、脚本耗尽与重复、停滞连接清理、CLI 解析、随机 seed 可复现性、权重校验、遥测、生命周期清理,以及逐文件覆盖率门禁下的配套不变式插件。重试集成套件通过真实 HTTP/SSE(Server-Sent Events)适配器,验证准确的请求次数、带编号的重试步骤、请求体完全一致、失败的部分分片不会泄漏、空完成成功语义、正常 EOF 分类、超时恢复、监听器延迟启动后从真实连接遭拒中恢复,以及有界重试耗尽。 + +## 曾考虑的替代方案 + +**使用 Python 实现服务器**:不予采纳。Node 的标准 HTTP 与 socket API 足以暴露所有所需故障,而 TypeScript 可以让服务器、CLI 解析器、测试、包构建、lint 和覆盖率全部留在仓库现有工具链中。引入第二套运行时会增加环境与子进程依赖,却不能增强协议隔离。 + +**在适配器测试中继续使用各自独立的内联 mock 服务器**:不予采纳。这些 fixture(测试前置数据)无法作为独立服务器启动并供现有应用连接,还会让不同测试套件重复实现行为编排、随机化、遥测和连接清理。支持包让测试共享同一套实现,又不会将其提升为产品 API。 + +**仅使用进程内的 `LlmAdapter` mock**:不予采纳。它会绕过 fetch、HTTP 状态与 header 解析、SSE 分帧、socket 终止以及适配器的空闲看门狗,而这正是这套测试基础设施要覆盖的边界。 + +**随服务器一起修改默认重试策略**:不予采纳。服务器用于揭示既有语义,而非决定策略。是否为 `STREAM_CLOSED` 或语义空结果增加恢复能力,需要单独决策,并权衡成本、延迟和重复生成风险。 + +## 后果 + +开发者只需修改提供方 URL/key 配置即可复现故障序列;自动化测试则可通过显式脚本和 seed,让 socket 层故障保持确定性。同一套协议 fixture 现在可以暴露硬重置、正常截断与成功空完成之间的差异,而不会拼接多次尝试的内容或修改模型历史。 + +服务器新增了一个支持包、可执行构建入口和行为词汇,三者必须同时兼容直接测试与 CLI 示例。按请求到达顺序执行的脚本有意由所有客户端共享;随机模式的默认值代表压力测试权重,而非实际运行规律;精确模拟连接遭拒时,需要让客户端尝试与监听开始前的时间区间协调一致。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 49a0a1510f..ed0969a053 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1953,6 +1953,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-host-runtime` ([`packages/host/runtime/src/index.ts`](../packages/host/runtime/src/index.ts)) - `@deepseek-ai/dsh-host-webserver` ([`packages/host/webserver/src/index.ts`](../packages/host/webserver/src/index.ts)) - `@deepseek-ai/dsh-jsonrpc-demo` ([`packages/examples/jsonrpc-demo/src/index.ts`](../packages/examples/jsonrpc-demo/src/index.ts)) +- `@deepseek-ai/dsh-llm-mock-server` ([`packages/support/llm-mock-server/src/index.ts`](../packages/support/llm-mock-server/src/index.ts)) - `@deepseek-ai/dsh-loader-smoke` ([`packages/support/loader-smoke/src/index.ts`](../packages/support/loader-smoke/src/index.ts)) - `@deepseek-ai/dsh-paths` ([`packages/util/paths/src/index.ts`](../packages/util/paths/src/index.ts)) - `@deepseek-ai/dsh-retention` ([`packages/util/retention/src/index.ts`](../packages/util/retention/src/index.ts)) diff --git a/package.json b/package.json index 3ff149b80a..fb1a56c29d 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "demo:cordis": "node --import tsx packages/examples/tui-demo/src/bin.ts examples/cordis-agent/cordis.yml", "demo:acp": "node --import tsx packages/examples/acp-demo/src/bin.ts --config examples/acp-agent/cordis.yml", "demo:web": "npm run build && npm run build:web && node --import tsx apps/cli/src/bin.ts web", + "mock:llm": "node --import tsx packages/support/llm-mock-server/src/bin.ts", "dev:web": "tsx scripts/dev-web.ts --poll", "postinstall": "node scripts/install-lefthook.mjs" }, diff --git a/packages/llm/llm-retry/package.json b/packages/llm/llm-retry/package.json index 6d6c27636c..64cd601b05 100644 --- a/packages/llm/llm-retry/package.json +++ b/packages/llm/llm-retry/package.json @@ -41,8 +41,11 @@ "@cordisjs/plugin-loader": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", + "@deepseek-ai/dsh-llm-deepseek": "workspace:^", + "@deepseek-ai/dsh-llm-mock-server": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-session-persistence-sqlite": "workspace:^", diff --git a/packages/llm/llm-retry/tests/transport-recovery.spec.ts b/packages/llm/llm-retry/tests/transport-recovery.spec.ts new file mode 100644 index 0000000000..790e3e22f7 --- /dev/null +++ b/packages/llm/llm-retry/tests/transport-recovery.spec.ts @@ -0,0 +1,230 @@ +import { createServer } from 'node:http' +import type { AddressInfo } from 'node:net' +import { afterEach, describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' +import type { MockLlmBehavior, MockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' +import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' +import { SessionId } from '@deepseek-ai/dsh-session' +import * as Retry from '../src/index.ts' + +let context: Context | undefined +const servers: MockLlmServer[] = [] + +afterEach(async () => { + await context?.fiber.dispose() + context = undefined + await Promise.all(servers.splice(0).map(server => server.close())) +}) + +async function start( + sequence: readonly MockLlmBehavior[], + options: Omit[0], 'sequence'> = {}, +): Promise { + const server = await startMockLlmServer({ sequence, ...options }) + servers.push(server) + return server +} + +async function harness( + baseURL: string, + options: { streamIdleTimeoutMs?: number; initialDelayMs?: number } = {}, +): Promise { + const ctx = new Context() + await mountAgentLoopTestDependencies(ctx) + await ctx.plugin(LlmDeepSeek, { + apiKey: 'mock-key', + baseURL, + streamIdleTimeoutMs: options.streamIdleTimeoutMs ?? 1_000, + }) + await ctx.plugin(Retry, { + maxTransientRetries: 2, + initialDelayMs: options.initialDelayMs ?? 10, + maxDelayMs: options.initialDelayMs ?? 10, + jitterRatio: 0, + }) + await ctx.plugin(AgentLoop, { agents: [] }) + return ctx +} + +function waitForIdle(ctx: Context, agent: Agent): Promise { + return new Promise((resolve) => { + const dispose = ctx.on('agent/status', (subject, status) => { + if (subject !== agent || status !== 'idle') return + dispose() + resolve() + }) + }) +} + +function sendAndWait(ctx: Context, agent: Agent): Promise { + const idle = waitForIdle(ctx, agent) + agent.followup([{ type: 'text', text: 'recover through the provider boundary' }]) + return idle +} + +function finalAssistantText(agent: Agent): string | undefined { + const message = agent.session.deriveMessages().at(-1) + if (message?.role !== 'assistant') return undefined + return message.content + .filter(block => block.type === 'text') + .map(block => block.text) + .join('') +} + +async function unusedPort(): Promise { + const server = createServer() + await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) }) + const port = (server.address() as AddressInfo).port + await new Promise((resolve) => { server.close(() => { resolve() }) }) + return port +} + +describe('bounded retry through the real DeepSeek HTTP/SSE adapter', () => { + it('recovers from a true refused connection after the endpoint starts during backoff', async () => { + const port = await unusedPort() + context = await harness(`http://127.0.0.1:${port}`, { initialDelayMs: 100 }) + const agent = context.agentLoop.create(SessionId('wire-refused'), { + provider: 'deepseek', + model: 'mock-model', + }) + let recoveryServer: Promise | undefined + context.on('session/event', (session, event) => { + if (session !== agent.session || event.type !== 'llm/retry' || event.data.retry !== 1) return + recoveryServer = start(['success'], { port, apiKey: 'mock-key', successText: 'connected after retry' }) + }) + + await sendAndWait(context, agent) + const server = await recoveryServer + + expect(server).toBeDefined() + expect(server?.requests).toHaveLength(1) + expect(agent.session.events.filter(event => event.type === 'step/start').map(event => event.data.step)) + .toEqual([1, 2]) + expect(agent.session.events.filter(event => event.type === 'llm/retry').map(event => event.data.failure.code)) + .toEqual(['TRANSPORT']) + expect(finalAssistantText(agent)).toBe('connected after retry') + }) + + it.each([ + ['stream_disconnect', 0] as const, + ['partial_disconnect', 2] as const, + ])('retries %s without committing failed chunks', async (behavior, failedChunkCount) => { + const server = await start([behavior, 'success'], { + apiKey: 'mock-key', + partialText: 'discard me', + chunkSize: 100, + disconnectDelayMs: 20, + successText: 'recovered response', + }) + context = await harness(server.baseURL) + const agent = context.agentLoop.create(SessionId(`wire-${behavior}`), { + provider: 'deepseek', + model: 'mock-model', + }) + + await sendAndWait(context, agent) + + expect(server.requests).toHaveLength(2) + expect(server.requests[0]?.body).toEqual(server.requests[1]?.body) + expect(agent.session.events.filter(event => + event.type === 'assistant/chunk' && event.data.step === 1, + )).toHaveLength(failedChunkCount) + expect(agent.session.events.filter(event => event.type === 'assistant/message').map(event => event.data.step)) + .toEqual([2]) + expect(agent.session.events.filter(event => event.type === 'llm/retry').map(event => event.data.failure.code)) + .toEqual(['TRANSPORT']) + expect(finalAssistantText(agent)).toBe('recovered response') + }) + + it('treats a wire-valid content-less completion as success without retrying', async () => { + const server = await start(['empty', 'success'], { apiKey: 'mock-key' }) + context = await harness(server.baseURL) + const agent = context.agentLoop.create(SessionId('wire-empty'), { + provider: 'deepseek', + model: 'mock-model', + }) + + await sendAndWait(context, agent) + + expect(server.requests).toHaveLength(1) + expect(agent.session.events.some(event => event.type === 'llm/retry')).toBe(false) + expect(agent.session.events.find(event => event.type === 'assistant/message')).toMatchObject({ + data: { turn: 1, step: 1, content: [] }, + }) + expect(agent.session.events.at(-1)).toMatchObject({ + type: 'turn/end', + data: { reason: { kind: 'completed' } }, + }) + expect(finalAssistantText(agent)).toBeUndefined() + }) + + it('exposes a clean partial EOF as non-default-retryable STREAM_CLOSED', async () => { + const server = await start(['partial_eof', 'success'], { + apiKey: 'mock-key', + partialText: 'discarded clean eof', + chunkSize: 100, + }) + context = await harness(server.baseURL) + const agent = context.agentLoop.create(SessionId('wire-partial-eof'), { + provider: 'deepseek', + model: 'mock-model', + }) + + await sendAndWait(context, agent) + + expect(server.requests).toHaveLength(1) + expect(agent.session.events.filter(event => + event.type === 'assistant/chunk' && event.data.step === 1, + )).toHaveLength(2) + expect(agent.session.events.some(event => event.type === 'assistant/message')).toBe(false) + expect(agent.session.events.some(event => event.type === 'llm/retry')).toBe(false) + expect(agent.session.events.at(-1)).toMatchObject({ + type: 'turn/end', + data: { reason: { kind: 'error', failure: { code: 'STREAM_CLOSED' } } }, + }) + }) + + it('turns a stalled body into TIMEOUT and succeeds on the next request', async () => { + const server = await start(['stall', 'success'], { + apiKey: 'mock-key', + successText: 'recovered after timeout', + }) + context = await harness(server.baseURL, { streamIdleTimeoutMs: 30 }) + const agent = context.agentLoop.create(SessionId('wire-stall'), { + provider: 'deepseek', + model: 'mock-model', + }) + + await sendAndWait(context, agent) + + expect(server.requests.map(record => record.behavior)).toEqual(['stall', 'success']) + expect(agent.session.events.filter(event => event.type === 'llm/retry').map(event => event.data.failure.code)) + .toEqual(['TIMEOUT']) + expect(finalAssistantText(agent)).toBe('recovered after timeout') + }) + + it('stops after the configured transport retry budget is exhausted', async () => { + const server = await start(['connection_reset', 'connection_reset', 'connection_reset'], { + apiKey: 'mock-key', + }) + context = await harness(server.baseURL) + const agent = context.agentLoop.create(SessionId('wire-exhausted'), { + provider: 'deepseek', + model: 'mock-model', + }) + + await sendAndWait(context, agent) + + expect(server.requests).toHaveLength(3) + expect(agent.session.events.filter(event => event.type === 'step/start')).toHaveLength(3) + expect(agent.session.events.filter(event => event.type === 'llm/retry')).toHaveLength(2) + expect(agent.session.events.at(-1)).toMatchObject({ + type: 'turn/end', + data: { reason: { kind: 'error', failure: { code: 'TRANSPORT' } } }, + }) + }) +}) diff --git a/packages/support/README.md b/packages/support/README.md index 045b69d390..31a64aa357 100644 --- a/packages/support/README.md +++ b/packages/support/README.md @@ -8,6 +8,7 @@ Packages that exist to serve development, testing, and the examples rather than | `agent-loop-testkit/` | Shared prerequisite mounting for tests that exercise the concrete agent loop | (library — imported by AgentLoop integration tests) | | `invariants/` | Runtime event-contract assertions for development diagnostics | (listens on `session/*`, `agent/*`) | | `loader-smoke/` | Shared real-Loader subprocess harness for keyless example smokes | (library — imported by example e2e suites) | +| `llm-mock-server/` | Scriptable OpenAI-compatible HTTP/SSE fault server + CLI for LLM recovery tests | (standalone server and test library) | | `llm-replay/` | Record/replay adapter: short-circuits `llm/stream` from a recorded session JSONL (keyless snapshot tests) | (listens on `llm/stream`) | -`invariants` is development support but has no environment guard: it runs wherever registered, and the default `dsh-agent-spine-demo` bundle mounts it unconditionally. `agent-loop-testkit` centralizes the mandatory service spine for hand-built AgentLoop tests without owning their loop or scenario. `llm-replay` backs the demos and the snapshot test tier under the per-file coverage gate. `acp-snapshot` carries the ACP subprocess/client boundary plus the snapshot harness, normalizers, and suite machinery, while `loader-smoke` owns the parallel real-Loader launch boundary used by keyless example e2e suites. A package graduates OUT of `support/` into a product group only when it gains documented product consumers. +`invariants` is development support but has no environment guard: it runs wherever registered, and the default `dsh-agent-spine-demo` bundle mounts it unconditionally. `agent-loop-testkit` centralizes the mandatory service spine for hand-built AgentLoop tests without owning their loop or scenario. `llm-replay` backs the demos and the snapshot test tier under the per-file coverage gate, while `llm-mock-server` drives real provider adapters through deterministic HTTP/SSE faults. `acp-snapshot` carries the ACP subprocess/client boundary plus the snapshot harness, normalizers, and suite machinery, while `loader-smoke` owns the parallel real-Loader launch boundary used by keyless example e2e suites. A package graduates OUT of `support/` into a product group only when it gains documented product consumers. diff --git a/packages/support/llm-mock-server/README.md b/packages/support/llm-mock-server/README.md new file mode 100644 index 0000000000..20efe731d5 --- /dev/null +++ b/packages/support/llm-mock-server/README.md @@ -0,0 +1,84 @@ +# `@deepseek-ai/dsh-llm-mock-server` + +A scriptable OpenAI-compatible HTTP/SSE server for exercising real LLM adapters, the agent loop, and recovery policy without a provider key. It accepts `POST /chat/completions` and `POST /v1/chat/completions`; each accepted request consumes one configured behavior in arrival order. Invalid methods, paths, bearer tokens, and JSON do not consume the script. + +The library entry exports `startMockLlmServer(options)`, behavior and telemetry types, the default random stress weights, and a running handle with the bound `baseURL`, generated or configured `randomSeed`, captured requests, and idempotent `close()`. Closing force-terminates stalled connections. + +## Standalone use + +Run the source entry from this repository: + +```sh +pnpm run mock:llm -- \ + --port 8000 \ + --api-key mock-key \ + --sequence partial_disconnect,success \ + --partial-text "discard this half" +``` + +Point the shipping DeepSeek adapter at the server; it appends `/chat/completions` to the configured base: + +```sh +DEEPSEEK_BASE_URL=http://127.0.0.1:8000/v1 \ +DEEPSEEK_API_KEY=mock-key \ +pnpm run demo:headless "test provider recovery" +``` + +The built package also exposes `dsh-llm-mock-server`. Stdout is JSONL: a `ready` record carries the `/v1` base URL and random seed, followed by request/result records that name both the scripted behavior and the concrete selected behavior. + +## Behavior script + +`--sequence` is a comma-separated FIFO. Exhaustion returns a structured HTTP 500; `--repeat-last` explicitly reuses the last entry. + +| Behavior | Wire result | +|---|---| +| `connection_reset` | Destroy the socket before HTTP headers | +| `stream_disconnect` | Send SSE headers, then reset before the first event | +| `partial_disconnect` | Send text deltas, then reset the socket | +| `stall` | Send SSE headers and remain idle until client/server cancellation | +| `empty` | Send a valid content-less stop and `[DONE]` | +| `empty_body` / `stream_eof` / `partial_eof` | End cleanly without the required `[DONE]` boundary | +| `malformed_json` / `malformed_event` | Send invalid SSE JSON or an invalid provider chunk shape | +| `rate_limit` / `server_error` / `service_unavailable` | Return retry-oriented 429/500/503 JSON errors | +| `auth_error` / `invalid_request` / `context_overflow` / `quota_exceeded` | Return terminal or separately recovered provider errors | +| `success` / `slow_success` / `reasoning_success` | Stream a complete text response, optionally delayed or preceded by reasoning | +| `tool_call_success` / `max_tokens` | Complete with a tool call or `length` finish | +| `wrong_content_type` | Send a valid SSE body under `application/json` | +| `random` | Select a concrete request behavior from weighted seeded randomness | + +`connection_refused` is CLI-only and must be the first entry. It delays binding a caller-specified nonzero port, so requests during `--listen-delay-ms` receive a real TCP refusal; the remaining entries begin after the listener starts. + +## Random mode + +Use a repeating `random` entry for an open-ended mixed run: + +```sh +pnpm run mock:llm -- \ + --port 8000 \ + --sequence random \ + --repeat-last \ + --seed 42 \ + --random-weights 'success=60,slow_success=10,connection_reset=5,stream_disconnect=5,partial_disconnect=10,empty=5,server_error=5' +``` + +Omitting `--seed` generates one and prints it in the `ready` record. `--random-weights` accepts non-negative relative `behavior=weight` entries and requires at least one positive concrete behavior. The exported default is a success-heavy stress profile containing reset, disconnect, partial output, empty completion, stall, 429/5xx, clean truncation, and malformed JSON; it is test pressure, not an estimate of production incident frequency. `connection_refused` is excluded because a bound request handler cannot produce a true refusal. + +When random weights include `stall`, configure the client under test with a short stream-idle timeout so the scenario terminates promptly. + +## Timing and content controls + +The CLI exposes `--success-text`, `--partial-text`, `--reasoning-text`, `--chunk-size`, `--chunk-delay-ms`, `--disconnect-delay-ms`, `--retry-after-ms`, `--request-id`, `--tool-name`, and `--tool-arguments`. The library accepts the same camel-case options. An optional exact `apiKey` validates `Authorization: Bearer `; omission accepts any token. + +## Model Experience + +None, as this test server substitutes provider wire behavior without invoking a real model. + +#### KV Cache effect + +None; requests terminate locally and never reach a provider cache. + +## Known Limitations and Deferred Work + +- **Random weights model test pressure, not production incidence** — callers that want an environment-specific distribution must provide measured weights and record the emitted seed. +- **Request scripts are arrival-ordered** — concurrent callers share one cursor, so deterministic per-session fault assignment requires separate server instances. +- **True connection refusal is a listener lifecycle phase** — the CLI delay must overlap the client attempt; request-level random selection can only reset an accepted connection. diff --git a/packages/support/llm-mock-server/package.json b/packages/support/llm-mock-server/package.json new file mode 100644 index 0000000000..790365407b --- /dev/null +++ b/packages/support/llm-mock-server/package.json @@ -0,0 +1,45 @@ +{ + "name": "@deepseek-ai/dsh-llm-mock-server", + "description": "Scriptable OpenAI-compatible HTTP/SSE fault server for LLM recovery tests", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "bin": { + "dsh-llm-mock-server": "lib/bin.js" + }, + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./bin": { + "types": "./lib/types/bin.d.ts", + "default": "./lib/bin.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/bin.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ], + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-invariants": "^0.0.1", + "cordis": "^4.0.0-rc.7" + }, + "devDependencies": { + "@deepseek-ai/dsh-invariants": "workspace:^", + "cordis": "^4.0.0-rc.7" + } +} diff --git a/packages/support/llm-mock-server/src/bin.ts b/packages/support/llm-mock-server/src/bin.ts new file mode 100644 index 0000000000..e77de74dad --- /dev/null +++ b/packages/support/llm-mock-server/src/bin.ts @@ -0,0 +1,50 @@ +#!/usr/bin/env node +/** + * Standalone process wrapper for the scriptable mock LLM server. + * @module @deepseek-ai/dsh-llm-mock-server/bin + */ + +import { setTimeout as delay } from 'node:timers/promises' +import { MOCK_LLM_CLI_USAGE, parseMockLlmCliArgs } from './cli.ts' +import { startMockLlmServer } from './index.ts' + +/* v8 ignore start -- thin process/signal glue; parser and server behavior are covered directly */ +try { + const parsed = parseMockLlmCliArgs(process.argv.slice(2)) + if (parsed.kind === 'help') { + process.stdout.write(MOCK_LLM_CLI_USAGE) + } else { + const { server: serverOptions, listenDelayMs, startsUnavailable } = parsed.config + const host = serverOptions.host ?? '127.0.0.1' + const port = serverOptions.port ?? 8_000 + if (startsUnavailable) { + process.stdout.write(`${JSON.stringify({ + type: 'unavailable', + baseURL: `http://${host}:${port}/v1`, + listenDelayMs, + })}\n`) + await delay(listenDelayMs) + } + const server = await startMockLlmServer({ + ...serverOptions, + onEvent: (event) => { process.stdout.write(`${JSON.stringify(event)}\n`) }, + }) + process.stdout.write(`${JSON.stringify({ + type: 'ready', + baseURL: `${server.baseURL}/v1`, + randomSeed: server.randomSeed, + })}\n`) + let closing = false + const close = (code: number): void => { + if (closing) return + closing = true + void server.close().finally(() => { process.exit(code) }) + } + process.on('SIGINT', () => { close(130) }) + process.on('SIGTERM', () => { close(143) }) + } +} catch (error: unknown) { + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n\n${MOCK_LLM_CLI_USAGE}`) + process.exitCode = 1 +} +/* v8 ignore stop */ diff --git a/packages/support/llm-mock-server/src/cli.ts b/packages/support/llm-mock-server/src/cli.ts new file mode 100644 index 0000000000..12d10072f2 --- /dev/null +++ b/packages/support/llm-mock-server/src/cli.ts @@ -0,0 +1,212 @@ +/** + * Dependency-free CLI parsing for the standalone mock LLM server. + * @module @deepseek-ai/dsh-llm-mock-server/cli + */ + +import { MOCK_LLM_BEHAVIORS } from './index.ts' +import type { + ConcreteMockLlmBehavior, + MockLlmBehavior, + MockLlmRandomWeights, + MockLlmServerOptions, +} from './index.ts' + +/** Listener lifecycle behavior understood only by the standalone CLI. */ +export const CONNECTION_REFUSED_BEHAVIOR = 'connection_refused' + +/** Parsed CLI configuration, including a pre-listen unavailable interval. */ +export interface MockLlmCliConfig { + /** Server options after removing the lifecycle-only `connection_refused` entry. */ + readonly server: MockLlmServerOptions + /** Delay before binding the model port; zero starts immediately. */ + readonly listenDelayMs: number + /** Whether the original sequence requested a true pre-listen refusal phase. */ + readonly startsUnavailable: boolean +} + +/** Result of parsing `dsh-llm-mock-server` arguments. */ +export type MockLlmCliParseResult = + | { readonly kind: 'help' } + | { readonly kind: 'run'; readonly config: MockLlmCliConfig } + +const BEHAVIORS = new Set(MOCK_LLM_BEHAVIORS) +const DEFAULT_LISTEN_DELAY_MS = 750 + +/** Command usage written for `--help` and invalid arguments. */ +export const MOCK_LLM_CLI_USAGE = `Usage: dsh-llm-mock-server [options] + +Required: + --sequence Ordered behaviors; connection_refused is allowed first + +Listener: + --host Default 127.0.0.1 + --port Default 8000; required and nonzero for connection_refused + --api-key Validate exact Bearer token when present + --listen-delay-ms Unavailable interval (default 750 with connection_refused) + --repeat-last Repeat the final request behavior after exhaustion + --seed Reproduce random selections + --random-weights Relative weights for concrete behaviors + +Response: + --success-text + --partial-text + --reasoning-text + --chunk-size + --chunk-delay-ms + --disconnect-delay-ms + --retry-after-ms + --request-id + --tool-name + --tool-arguments + +Other: + --help +` + +function optionValue(argv: readonly string[], index: number, option: string): string { + const value = argv[index + 1] + if (value === undefined || value.startsWith('--')) { + throw new Error(`dsh-llm-mock-server: ${option} requires a value`) + } + return value +} + +function numberValue(option: string, value: string): number { + const parsed = Number(value) + if (!Number.isFinite(parsed)) throw new Error(`dsh-llm-mock-server: ${option} must be a finite number`) + return parsed +} + +function parseSequence(raw: string): { startsUnavailable: boolean; sequence: MockLlmBehavior[] } { + const entries = raw.split(',').map(entry => entry.trim()) + if (entries.some(entry => entry.length === 0)) { + throw new Error('dsh-llm-mock-server: --sequence must contain non-empty comma-separated behaviors') + } + const startsUnavailable = entries[0] === CONNECTION_REFUSED_BEHAVIOR + if (entries.slice(1).includes(CONNECTION_REFUSED_BEHAVIOR)) { + throw new Error('dsh-llm-mock-server: connection_refused is allowed only as the first behavior') + } + const requestEntries = startsUnavailable ? entries.slice(1) : entries + if (requestEntries.length === 0) { + throw new Error('dsh-llm-mock-server: connection_refused must be followed by a request behavior') + } + for (const entry of requestEntries) { + if (!BEHAVIORS.has(entry)) throw new Error(`dsh-llm-mock-server: unknown behavior ${JSON.stringify(entry)}`) + } + return { startsUnavailable, sequence: requestEntries as MockLlmBehavior[] } +} + +function parseRandomWeights(raw: string): MockLlmRandomWeights { + const weights: MockLlmRandomWeights = {} + for (const entry of raw.split(',')) { + const [behavior, rawWeight, ...extra] = entry.split('=') + if (behavior === undefined || behavior === '' || rawWeight === undefined || rawWeight === '' || extra.length > 0) { + throw new Error('dsh-llm-mock-server: --random-weights expects behavior=weight comma-separated entries') + } + if (!BEHAVIORS.has(behavior) || behavior === 'random') { + throw new Error(`dsh-llm-mock-server: random weight requires a concrete behavior, got ${JSON.stringify(behavior)}`) + } + if (Object.hasOwn(weights, behavior)) { + throw new Error(`dsh-llm-mock-server: duplicate random weight for ${JSON.stringify(behavior)}`) + } + weights[behavior as ConcreteMockLlmBehavior] = numberValue('--random-weights', rawWeight) + } + return weights +} + +/** + * Parse standalone server arguments without starting a process or listener. + * @param argv - arguments after the executable name. + * @returns help or validated run configuration. + */ +export function parseMockLlmCliArgs(argv: readonly string[]): MockLlmCliParseResult { + if (argv.includes('--help')) return { kind: 'help' } + + let sequenceRaw: string | undefined + let host: string | undefined + let port = 8_000 + let apiKey: string | undefined + let listenDelayMs: number | undefined + let repeatLast = false + let randomSeed: number | undefined + let randomWeights: MockLlmRandomWeights | undefined + let successText: string | undefined + let partialText: string | undefined + let reasoningText: string | undefined + let chunkSize: number | undefined + let chunkDelayMs: number | undefined + let disconnectDelayMs: number | undefined + let retryAfterMs: number | undefined + let requestId: string | undefined + let toolName: string | undefined + let toolArguments: string | undefined + + for (let index = 0; index < argv.length; index += 1) { + const option = argv[index] as string + if (option === '--repeat-last') { + repeatLast = true + continue + } + const value = optionValue(argv, index, option) + index += 1 + switch (option) { + case '--sequence': sequenceRaw = value; break + case '--host': host = value; break + case '--port': port = numberValue(option, value); break + case '--api-key': apiKey = value; break + case '--listen-delay-ms': listenDelayMs = numberValue(option, value); break + case '--seed': randomSeed = numberValue(option, value); break + case '--random-weights': randomWeights = parseRandomWeights(value); break + case '--success-text': successText = value; break + case '--partial-text': partialText = value; break + case '--reasoning-text': reasoningText = value; break + case '--chunk-size': chunkSize = numberValue(option, value); break + case '--chunk-delay-ms': chunkDelayMs = numberValue(option, value); break + case '--disconnect-delay-ms': disconnectDelayMs = numberValue(option, value); break + case '--retry-after-ms': retryAfterMs = numberValue(option, value); break + case '--request-id': requestId = value; break + case '--tool-name': toolName = value; break + case '--tool-arguments': toolArguments = value; break + default: throw new Error(`dsh-llm-mock-server: unknown option ${JSON.stringify(option)}`) + } + } + + if (sequenceRaw === undefined) throw new Error('dsh-llm-mock-server: --sequence is required') + const parsedSequence = parseSequence(sequenceRaw) + if (parsedSequence.startsUnavailable && port === 0) { + throw new Error('dsh-llm-mock-server: connection_refused requires an explicit nonzero --port') + } + if (!parsedSequence.startsUnavailable && listenDelayMs !== undefined) { + throw new Error('dsh-llm-mock-server: --listen-delay-ms requires connection_refused first in --sequence') + } + if (!parsedSequence.sequence.includes('random') && (randomSeed !== undefined || randomWeights !== undefined)) { + throw new Error('dsh-llm-mock-server: --seed and --random-weights require random in --sequence') + } + + return { + kind: 'run', + config: { + server: { + sequence: parsedSequence.sequence, + port, + repeatLast, + ...randomSeed === undefined ? {} : { randomSeed }, + ...randomWeights === undefined ? {} : { randomWeights }, + ...host === undefined ? {} : { host }, + ...apiKey === undefined ? {} : { apiKey }, + ...successText === undefined ? {} : { successText }, + ...partialText === undefined ? {} : { partialText }, + ...reasoningText === undefined ? {} : { reasoningText }, + ...chunkSize === undefined ? {} : { chunkSize }, + ...chunkDelayMs === undefined ? {} : { chunkDelayMs }, + ...disconnectDelayMs === undefined ? {} : { disconnectDelayMs }, + ...retryAfterMs === undefined ? {} : { retryAfterMs }, + ...requestId === undefined ? {} : { requestId }, + ...toolName === undefined ? {} : { toolName }, + ...toolArguments === undefined ? {} : { toolArguments }, + }, + listenDelayMs: parsedSequence.startsUnavailable ? listenDelayMs ?? DEFAULT_LISTEN_DELAY_MS : 0, + startsUnavailable: parsedSequence.startsUnavailable, + }, + } +} diff --git a/packages/support/llm-mock-server/src/index.ts b/packages/support/llm-mock-server/src/index.ts new file mode 100644 index 0000000000..45dda839e2 --- /dev/null +++ b/packages/support/llm-mock-server/src/index.ts @@ -0,0 +1,723 @@ +/** + * Scriptable OpenAI-compatible HTTP/SSE server for transport, protocol, and + * semantic-empty LLM recovery tests. Each accepted chat-completions request + * consumes one behavior; the server never retries or interprets harness policy. + * + * @module @deepseek-ai/dsh-llm-mock-server + */ + +import { createServer } from 'node:http' +import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http' +import { randomBytes } from 'node:crypto' +import type { AddressInfo } from 'node:net' +import { setTimeout as delay } from 'node:timers/promises' + +/** Request-scoped behaviors accepted by {@link startMockLlmServer}. */ +export const MOCK_LLM_BEHAVIORS = [ + 'connection_reset', + 'stream_disconnect', + 'empty', + 'empty_body', + 'stream_eof', + 'partial_eof', + 'partial_disconnect', + 'stall', + 'malformed_json', + 'malformed_event', + 'wrong_content_type', + 'rate_limit', + 'server_error', + 'service_unavailable', + 'auth_error', + 'invalid_request', + 'context_overflow', + 'quota_exceeded', + 'success', + 'reasoning_success', + 'tool_call_success', + 'max_tokens', + 'slow_success', + 'random', +] as const + +/** One scripted mock behavior name; `random` selects a concrete behavior per request. */ +export type MockLlmBehavior = typeof MOCK_LLM_BEHAVIORS[number] + +/** One concrete request behavior after resolving a `random` script entry. */ +export type ConcreteMockLlmBehavior = Exclude + +/** Relative non-negative weights for random request behavior selection. */ +export type MockLlmRandomWeights = Partial> + +/** + * Default stress profile for `random`. Weights are configurable test pressure, + * not a claim about production incident frequency. + */ +export const DEFAULT_MOCK_LLM_RANDOM_WEIGHTS: Readonly = Object.freeze({ + success: 48, + slow_success: 10, + max_tokens: 2, + connection_reset: 5, + stream_disconnect: 5, + partial_disconnect: 10, + empty: 5, + stall: 2, + rate_limit: 5, + server_error: 4, + service_unavailable: 2, + partial_eof: 1, + malformed_json: 1, +}) + +/** How one accepted request ended at the mock boundary. */ +export type MockLlmRequestOutcome = 'completed' | 'reset' | 'stalled' | 'client_closed' | 'server_error' + +/** Immutable telemetry emitted when a request starts or reaches an outcome. */ +export type MockLlmServerEvent = + | { + readonly type: 'request' + readonly attempt: number + readonly scriptBehavior: MockLlmBehavior | 'script_exhausted' + readonly behavior: ConcreteMockLlmBehavior | 'script_exhausted' + readonly path: string + } + | { + readonly type: 'result' + readonly attempt: number + readonly scriptBehavior: MockLlmBehavior | 'script_exhausted' + readonly behavior: ConcreteMockLlmBehavior | 'script_exhausted' + readonly outcome: MockLlmRequestOutcome + readonly chunksSent: number + } + +/** Captured wire request and its final server-side outcome. */ +export interface MockLlmRequestRecord { + /** One-based accepted chat-completions request number. */ + readonly attempt: number + /** Script entry consumed for this request before random resolution. */ + readonly scriptBehavior: MockLlmBehavior | 'script_exhausted' + /** Concrete behavior selected for this request, or exhaustion after the configured script. */ + readonly behavior: ConcreteMockLlmBehavior | 'script_exhausted' + /** Original request path, including a `/v1` prefix when the client supplied one. */ + readonly path: string + /** Detached request headers. */ + readonly headers: Readonly + /** Parsed JSON request body. */ + readonly body: unknown + /** Number of SSE `data:` events handed to Node before the outcome. */ + chunksSent: number + /** Final server-side outcome; absent while a stalled request remains open. */ + outcome?: MockLlmRequestOutcome +} + +/** Configuration for one mock server instance. */ +export interface MockLlmServerOptions { + /** Loopback host by default. */ + readonly host?: string + /** TCP port; zero requests an OS-assigned port. */ + readonly port?: number + /** Optional exact bearer token; omission accepts any authorization header. */ + readonly apiKey?: string + /** Ordered request behaviors; exhaustion fails loud unless `repeatLast` is true. */ + readonly sequence: readonly MockLlmBehavior[] + /** Reuse the final behavior after the sequence is consumed. */ + readonly repeatLast?: boolean + /** Optional deterministic unsigned 32-bit seed; omission generates and exposes one. */ + readonly randomSeed?: number + /** Relative weights used whenever a script entry is `random`. */ + readonly randomWeights?: Readonly + /** Complete text returned by success-shaped behaviors. */ + readonly successText?: string + /** Text emitted before partial EOF/reset behaviors terminate. */ + readonly partialText?: string + /** Reasoning text emitted by `reasoning_success`. */ + readonly reasoningText?: string + /** Unicode code-point count per text or reasoning SSE delta. */ + readonly chunkSize?: number + /** Inter-chunk delay for `slow_success`, in milliseconds. */ + readonly chunkDelayMs?: number + /** Delay after headers/deltas before a forced disconnect, in milliseconds. */ + readonly disconnectDelayMs?: number + /** Provider retry delay; the wire `Retry-After` value rounds up to whole seconds. */ + readonly retryAfterMs?: number + /** Optional provider request id returned on HTTP failures. */ + readonly requestId?: string + /** Tool name emitted by `tool_call_success`. */ + readonly toolName?: string + /** Raw JSON arguments emitted by `tool_call_success`. */ + readonly toolArguments?: string + /** Optional observer for JSONL CLI telemetry; observer failures never affect wire behavior. */ + readonly onEvent?: (event: MockLlmServerEvent) => void +} + +/** Running mock server and captured request state. */ +export interface MockLlmServer { + /** Base URL without `/v1`; both root and `/v1` chat-completions paths are accepted. */ + readonly baseURL: string + /** Actual bound port, including an OS-assigned value. */ + readonly port: number + /** Seed used for random behavior selection, including the generated default. */ + readonly randomSeed: number + /** Live request records in arrival order. */ + readonly requests: readonly MockLlmRequestRecord[] + /** Stop accepting requests and force-close stalled/streaming connections; idempotent. */ + close(): Promise +} + +interface ResolvedOptions { + readonly host: string + readonly port: number + readonly apiKey?: string + readonly sequence: readonly MockLlmBehavior[] + readonly lastBehavior: MockLlmBehavior + readonly repeatLast: boolean + readonly randomSeed: number + readonly randomWeights: readonly (readonly [ConcreteMockLlmBehavior, number])[] + readonly successText: string + readonly partialText: string + readonly reasoningText: string + readonly chunkSize: number + readonly chunkDelayMs: number + readonly disconnectDelayMs: number + readonly retryAfterMs: number + readonly requestId?: string + readonly toolName: string + readonly toolArguments: string + readonly onEvent?: (event: MockLlmServerEvent) => void +} + +const MAX_TIMER_DELAY_MS = 2_147_483_647 +const DEFAULT_SUCCESS_TEXT = 'mock response recovered' +const DEFAULT_PARTIAL_TEXT = 'discarded partial response' +const DEFAULT_REASONING_TEXT = 'mock reasoning' +const CONCRETE_BEHAVIORS = new Set(MOCK_LLM_BEHAVIORS.filter(behavior => behavior !== 'random')) + +function boundedInteger(name: string, value: number, min: number, max: number): number { + if (!Number.isInteger(value) || value < min || value > max) { + throw new Error(`llm-mock-server: ${name} must be an integer between ${min} and ${max}`) + } + return value +} + +function resolveOptions(options: MockLlmServerOptions): ResolvedOptions { + const host = options.host ?? '127.0.0.1' + const port = boundedInteger('port', options.port ?? 0, 0, 65_535) + const chunkSize = boundedInteger('chunkSize', options.chunkSize ?? 8, 1, Number.MAX_SAFE_INTEGER) + const chunkDelayMs = boundedInteger('chunkDelayMs', options.chunkDelayMs ?? 25, 0, MAX_TIMER_DELAY_MS) + const disconnectDelayMs = boundedInteger( + 'disconnectDelayMs', + options.disconnectDelayMs ?? 10, + 0, + MAX_TIMER_DELAY_MS, + ) + const retryAfterMs = boundedInteger('retryAfterMs', options.retryAfterMs ?? 1_000, 1, MAX_TIMER_DELAY_MS) + const randomSeed = boundedInteger( + 'randomSeed', + options.randomSeed ?? randomBytes(4).readUInt32LE(0), + 0, + 0xffff_ffff, + ) + const successText = options.successText ?? DEFAULT_SUCCESS_TEXT + const partialText = options.partialText ?? DEFAULT_PARTIAL_TEXT + const reasoningText = options.reasoningText ?? DEFAULT_REASONING_TEXT + const toolName = options.toolName ?? 'mock_tool' + const toolArguments = options.toolArguments ?? '{"value":"mock"}' + + if (host.length === 0) throw new Error('llm-mock-server: host must not be empty') + if (options.sequence.length === 0) throw new Error('llm-mock-server: sequence must not be empty') + const lastBehavior = options.sequence.reduce((_previous, behavior) => behavior) + if (options.apiKey === '') throw new Error('llm-mock-server: apiKey must not be empty') + if (successText.length === 0) throw new Error('llm-mock-server: successText must not be empty') + if (partialText.length === 0) throw new Error('llm-mock-server: partialText must not be empty') + if (reasoningText.length === 0) throw new Error('llm-mock-server: reasoningText must not be empty') + if (toolName.length === 0) throw new Error('llm-mock-server: toolName must not be empty') + if (options.requestId === '') throw new Error('llm-mock-server: requestId must not be empty') + try { + JSON.parse(toolArguments) + } catch { + throw new Error('llm-mock-server: toolArguments must be valid JSON') + } + + const configuredWeights = options.randomWeights ?? DEFAULT_MOCK_LLM_RANDOM_WEIGHTS + const randomWeights: Array = [] + for (const [behavior, weight] of Object.entries(configuredWeights)) { + if (!CONCRETE_BEHAVIORS.has(behavior)) { + throw new Error(`llm-mock-server: randomWeights contains unknown concrete behavior ${JSON.stringify(behavior)}`) + } + if (!Number.isFinite(weight) || weight < 0) { + throw new Error(`llm-mock-server: random weight for ${behavior} must be a non-negative finite number`) + } + if (weight > 0) randomWeights.push([behavior as ConcreteMockLlmBehavior, weight]) + } + if (randomWeights.length === 0) { + throw new Error('llm-mock-server: randomWeights must contain at least one positive weight') + } + + return { + host, + port, + ...options.apiKey === undefined ? {} : { apiKey: options.apiKey }, + sequence: [...options.sequence], + lastBehavior, + repeatLast: options.repeatLast ?? false, + randomSeed, + randomWeights, + successText, + partialText, + reasoningText, + chunkSize, + chunkDelayMs, + disconnectDelayMs, + retryAfterMs, + ...options.requestId === undefined ? {} : { requestId: options.requestId }, + toolName, + toolArguments, + ...options.onEvent === undefined ? {} : { onEvent: options.onEvent }, + } +} + +function emit(options: ResolvedOptions, event: MockLlmServerEvent): void { + try { + options.onEvent?.(Object.freeze(event)) + } catch (_telemetryObserverFailure) { + // Test telemetry is observational; a broken observer cannot change provider wire behavior. + } +} + +async function readJsonBody(request: IncomingMessage): Promise { + let body = '' + for await (const chunk of request) body += Buffer.from(chunk).toString('utf8') + return body.length === 0 ? undefined : JSON.parse(body) +} + +function splitText(text: string, size: number): string[] { + const points = Array.from(text) + const chunks: string[] = [] + for (let index = 0; index < points.length; index += size) chunks.push(points.slice(index, index + size).join('')) + return chunks +} + +function openSse(response: ServerResponse, contentType = 'text/event-stream; charset=utf-8'): void { + response.writeHead(200, { + 'content-type': contentType, + 'cache-control': 'no-cache', + 'connection': 'keep-alive', + }) + response.flushHeaders() +} + +function writeSse(record: MockLlmRequestRecord, response: ServerResponse, payload: unknown): void { + response.write(`data: ${typeof payload === 'string' ? payload : JSON.stringify(payload)}\n\n`) + record.chunksSent += 1 +} + +function writeDone(record: MockLlmRequestRecord, response: ServerResponse): void { + writeSse(record, response, '[DONE]') +} + +function finishRecord( + options: ResolvedOptions, + record: MockLlmRequestRecord, + outcome: MockLlmRequestOutcome, +): void { + record.outcome = outcome + emit(options, { + type: 'result', + attempt: record.attempt, + scriptBehavior: record.scriptBehavior, + behavior: record.behavior, + outcome, + chunksSent: record.chunksSent, + }) +} + +function httpError( + options: ResolvedOptions, + record: MockLlmRequestRecord, + response: ServerResponse, + status: number, + message: string, + code: string, + type = 'mock_error', +): void { + const headers: Record = { 'content-type': 'application/json' } + if (record.behavior === 'rate_limit') { + headers['retry-after'] = String(Math.ceil(options.retryAfterMs / 1_000)) + } + if (options.requestId !== undefined) headers['x-request-id'] = options.requestId + response.writeHead(status, headers) + response.end(JSON.stringify({ error: { message, type, code } })) + finishRecord(options, record, 'completed') +} + +function terminalChunk(reason: string, outputTokens: number): unknown { + return { + choices: [{ index: 0, delta: { content: '' }, finish_reason: reason }], + usage: { prompt_tokens: 3, completion_tokens: outputTokens }, + } +} + +async function pause(milliseconds: number, response: ServerResponse): Promise { + if (milliseconds === 0) return !response.destroyed + const controller = new AbortController() + const stop = (): void => { controller.abort() } + response.once('close', stop) + try { + await delay(milliseconds, undefined, { signal: controller.signal }) + return true + } catch (_responseClosed) { + // The timer only receives this response-owned abort signal; closing the response cancels its wait. + return false + } finally { + response.off('close', stop) + } +} + +async function streamText( + options: ResolvedOptions, + record: MockLlmRequestRecord, + response: ServerResponse, + text: string, + delayMs: number, +): Promise { + for (const chunk of splitText(text, options.chunkSize)) { + writeSse(record, response, { choices: [{ index: 0, delta: { content: chunk }, finish_reason: null }] }) + if (!await pause(delayMs, response)) return false + } + return true +} + +async function completeText( + options: ResolvedOptions, + record: MockLlmRequestRecord, + response: ServerResponse, + reason: 'stop' | 'length', + delayMs: number, +): Promise { + if (!await streamText(options, record, response, options.successText, delayMs)) { + finishRecord(options, record, 'client_closed') + return + } + writeSse(record, response, terminalChunk(reason, Array.from(options.successText).length)) + writeDone(record, response) + response.end() + finishRecord(options, record, 'completed') +} + +async function disconnect( + options: ResolvedOptions, + record: MockLlmRequestRecord, + response: ServerResponse, +): Promise { + if (!await pause(options.disconnectDelayMs, response)) { + finishRecord(options, record, 'client_closed') + return + } + finishRecord(options, record, 'reset') + response.destroy() +} + +function toolCallChunks(options: ResolvedOptions): readonly unknown[] { + const midpoint = Math.max(1, Math.floor(options.toolArguments.length / 2)) + return [ + { + choices: [{ + index: 0, + delta: { + tool_calls: [{ + index: 0, + id: 'mock-call-1', + type: 'function', + function: { name: options.toolName, arguments: options.toolArguments.slice(0, midpoint) }, + }], + }, + finish_reason: null, + }], + }, + { + choices: [{ + index: 0, + delta: { tool_calls: [{ index: 0, function: { arguments: options.toolArguments.slice(midpoint) } }] }, + finish_reason: null, + }], + }, + ] +} + +async function runBehavior( + options: ResolvedOptions, + record: MockLlmRequestRecord, + request: IncomingMessage, + response: ServerResponse, +): Promise { + switch (record.behavior) { + case 'script_exhausted': + httpError(options, record, response, 500, 'mock script exhausted', 'MOCK_SCRIPT_EXHAUSTED') + return + case 'connection_reset': + finishRecord(options, record, 'reset') + request.socket.destroy() + return + case 'stream_disconnect': + openSse(response) + await disconnect(options, record, response) + return + case 'empty': + openSse(response) + writeSse(record, response, terminalChunk('stop', 0)) + writeDone(record, response) + response.end() + finishRecord(options, record, 'completed') + return + case 'empty_body': + openSse(response) + response.end() + finishRecord(options, record, 'completed') + return + case 'stream_eof': + openSse(response) + writeSse(record, response, { choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] }) + response.end() + finishRecord(options, record, 'completed') + return + case 'partial_eof': + openSse(response) + await streamText(options, record, response, options.partialText, 0) + response.end() + finishRecord(options, record, 'completed') + return + case 'partial_disconnect': + openSse(response) + if (!await streamText(options, record, response, options.partialText, options.chunkDelayMs)) return + await disconnect(options, record, response) + return + case 'stall': + openSse(response) + finishRecord(options, record, 'stalled') + return + case 'malformed_json': + openSse(response) + writeSse(record, response, '{not-json') + writeDone(record, response) + response.end() + finishRecord(options, record, 'completed') + return + case 'malformed_event': + openSse(response) + writeSse(record, response, { choices: [null] }) + writeDone(record, response) + response.end() + finishRecord(options, record, 'completed') + return + case 'wrong_content_type': + openSse(response, 'application/json') + await completeText(options, record, response, 'stop', 0) + return + case 'rate_limit': + httpError(options, record, response, 429, 'mock rate limit', 'rate_limit') + return + case 'server_error': + httpError(options, record, response, 500, 'mock server error', 'server_error') + return + case 'service_unavailable': + httpError(options, record, response, 503, 'mock service unavailable', 'service_unavailable') + return + case 'auth_error': + httpError(options, record, response, 401, 'mock authentication failed', 'invalid_api_key') + return + case 'invalid_request': + httpError(options, record, response, 400, 'mock invalid request', 'invalid_request') + return + case 'context_overflow': + httpError( + options, + record, + response, + 400, + 'mock input exceeds the model context window', + 'context_length_exceeded', + 'invalid_request_error', + ) + return + case 'quota_exceeded': + httpError(options, record, response, 429, 'mock insufficient quota', 'insufficient_quota') + return + case 'success': + openSse(response) + await completeText(options, record, response, 'stop', 0) + return + case 'reasoning_success': + openSse(response) + for (const chunk of splitText(options.reasoningText, options.chunkSize)) { + writeSse(record, response, { + choices: [{ index: 0, delta: { reasoning_content: chunk }, finish_reason: null }], + }) + } + await completeText(options, record, response, 'stop', 0) + return + case 'tool_call_success': + openSse(response) + for (const chunk of toolCallChunks(options)) writeSse(record, response, chunk) + writeSse(record, response, terminalChunk('tool_calls', 2)) + writeDone(record, response) + response.end() + finishRecord(options, record, 'completed') + return + case 'max_tokens': + openSse(response) + await completeText(options, record, response, 'length', 0) + return + case 'slow_success': + openSse(response) + await completeText(options, record, response, 'stop', options.chunkDelayMs) + return + } +} + +function seededRandom(seed: number): () => number { + let state = seed + return () => { + state = (state + 0x6d2b_79f5) >>> 0 + let mixed = state + mixed = Math.imul(mixed ^ mixed >>> 15, mixed | 1) + mixed ^= mixed + Math.imul(mixed ^ mixed >>> 7, mixed | 61) + return ((mixed ^ mixed >>> 14) >>> 0) / 0x1_0000_0000 + } +} + +function chooseRandomBehavior( + weights: readonly (readonly [ConcreteMockLlmBehavior, number])[], + random: () => number, +): ConcreteMockLlmBehavior { + const total = weights.reduce((sum, entry) => sum + entry[1], 0) + let draw = random() * total + for (const [behavior, weight] of weights) { + if (draw < weight) return behavior + draw -= weight + } + // Floating-point subtraction can only leave a rounding residue at the upper boundary. + /* v8 ignore next -- seededRandom is strictly less than one; this guards floating-point residue only */ + return (weights.at(-1) as readonly [ConcreteMockLlmBehavior, number])[0] +} + +/** + * Start a local chat-completions server that consumes one configured behavior + * per accepted request. Only a `POST` path ending in `/chat/completions` consumes the script; + * invalid routes, methods, authorization, and JSON receive ordinary 4xx + * responses. Closing the handle terminates stalled connections. + * + * @param options - listener, script, response content, timing, and telemetry options. + * @returns the listening handle after the port is bound. + */ +export async function startMockLlmServer(options: MockLlmServerOptions): Promise { + const resolved = resolveOptions(options) + const requests: MockLlmRequestRecord[] = [] + const random = seededRandom(resolved.randomSeed) + let cursor = 0 + + const selectBehavior = (): { + scriptBehavior: MockLlmBehavior | 'script_exhausted' + behavior: ConcreteMockLlmBehavior | 'script_exhausted' + } => { + const selected = resolved.sequence[cursor] + cursor += 1 + const scriptBehavior = selected + ?? (resolved.repeatLast ? resolved.lastBehavior : 'script_exhausted') + return { + scriptBehavior, + behavior: scriptBehavior === 'random' + ? chooseRandomBehavior(resolved.randomWeights, random) + : scriptBehavior, + } + } + + const handle = async (request: IncomingMessage, response: ServerResponse): Promise => { + /* v8 ignore next -- node:http server requests always carry a URL despite the shared optional type */ + const path = new URL(request.url ?? '/', 'http://mock.invalid').pathname + if (request.method !== 'POST') { + response.writeHead(405, { allow: 'POST' }).end() + return + } + if (!path.endsWith('/chat/completions')) { + response.writeHead(404).end() + return + } + if (resolved.apiKey !== undefined && request.headers.authorization !== `Bearer ${resolved.apiKey}`) { + response.writeHead(401, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ error: { message: 'invalid mock bearer token', code: 'invalid_api_key' } })) + return + } + + let body: unknown + try { + body = await readJsonBody(request) + } catch { + response.writeHead(400, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ error: { message: 'request body must be valid JSON', code: 'invalid_json' } })) + return + } + + const selected = selectBehavior() + const record: MockLlmRequestRecord = { + attempt: requests.length + 1, + scriptBehavior: selected.scriptBehavior, + behavior: selected.behavior, + path, + headers: { ...request.headers }, + body, + chunksSent: 0, + } + requests.push(record) + response.once('close', () => { + if (!response.writableFinished && record.outcome === undefined) { + finishRecord(resolved, record, 'client_closed') + } + }) + emit(resolved, { + type: 'request', + attempt: record.attempt, + scriptBehavior: record.scriptBehavior, + behavior: record.behavior, + path, + }) + await runBehavior(resolved, record, request, response) + } + + const server = createServer((request, response) => { + /* v8 ignore start -- last-resort containment for Node response failures after validated test inputs */ + handle(request, response).catch((error: unknown) => { + const record = requests.at(-1) + if (record !== undefined) finishRecord(resolved, record, 'server_error') + if (response.headersSent) { + response.destroy(error instanceof Error ? error : new Error(String(error))) + return + } + response.writeHead(500, { 'content-type': 'application/json' }) + response.end(JSON.stringify({ error: { message: 'mock server handler failed', code: 'MOCK_HANDLER_FAILED' } })) + }) + /* v8 ignore stop */ + }) + + let closing: Promise | undefined + const close = (): Promise => (closing ??= new Promise((resolveClose) => { + server.close(() => { resolveClose() }) + server.closeAllConnections() + })) + + await new Promise((resolveListen, rejectListen) => { + server.once('error', rejectListen) + server.listen(resolved.port, resolved.host, () => { + server.off('error', rejectListen) + resolveListen() + }) + }) + + const address = server.address() as AddressInfo + return { + baseURL: `http://${resolved.host}:${address.port}`, + port: address.port, + randomSeed: resolved.randomSeed, + requests, + close, + } +} diff --git a/packages/support/llm-mock-server/src/invariant.ts b/packages/support/llm-mock-server/src/invariant.ts new file mode 100644 index 0000000000..b8fbc2dd40 --- /dev/null +++ b/packages/support/llm-mock-server/src/invariant.ts @@ -0,0 +1,30 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-llm-mock-server`. + * @module @deepseek-ai/dsh-llm-mock-server/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-llm-mock-server' + +/** Cordis companion plugin name. */ +export const name = 'llm-mock-server-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: this standalone test server owns no Cordis event stream or shared data; + * its wire behavior and lifecycle are exercised through direct HTTP and assembled-loop tests. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/support/llm-mock-server/tests/cli.spec.ts b/packages/support/llm-mock-server/tests/cli.spec.ts new file mode 100644 index 0000000000..66a3868963 --- /dev/null +++ b/packages/support/llm-mock-server/tests/cli.spec.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from 'vitest' +import { + MOCK_LLM_CLI_USAGE, + parseMockLlmCliArgs, +} from '../src/cli.ts' + +describe('mock LLM server CLI parser', () => { + it('returns help without requiring a sequence', () => { + expect(parseMockLlmCliArgs(['--help'])).toEqual({ kind: 'help' }) + expect(MOCK_LLM_CLI_USAGE).toContain('--sequence') + }) + + it('parses every request and listener option', () => { + expect(parseMockLlmCliArgs([ + '--sequence', 'connection_refused,partial_disconnect,success', + '--host', 'localhost', + '--port', '9010', + '--api-key', 'mock-key', + '--listen-delay-ms', '100', + '--repeat-last', + '--success-text', 'done', + '--partial-text', 'half', + '--reasoning-text', 'think', + '--chunk-size', '2', + '--chunk-delay-ms', '3', + '--disconnect-delay-ms', '4', + '--retry-after-ms', '5000', + '--request-id', 'request-1', + '--tool-name', 'lookup', + '--tool-arguments', '{"id":1}', + ])).toEqual({ + kind: 'run', + config: { + startsUnavailable: true, + listenDelayMs: 100, + server: { + sequence: ['partial_disconnect', 'success'], + host: 'localhost', + port: 9010, + apiKey: 'mock-key', + repeatLast: true, + successText: 'done', + partialText: 'half', + reasoningText: 'think', + chunkSize: 2, + chunkDelayMs: 3, + disconnectDelayMs: 4, + retryAfterMs: 5000, + requestId: 'request-1', + toolName: 'lookup', + toolArguments: '{"id":1}', + }, + }, + }) + }) + + it('uses standalone defaults for an ordinary sequence', () => { + expect(parseMockLlmCliArgs(['--sequence', 'success'])).toEqual({ + kind: 'run', + config: { + startsUnavailable: false, + listenDelayMs: 0, + server: { + sequence: ['success'], + port: 8000, + repeatLast: false, + }, + }, + }) + }) + + it('uses the default unavailable interval', () => { + const result = parseMockLlmCliArgs(['--sequence', 'connection_refused,success', '--port', '8001']) + expect(result).toMatchObject({ + kind: 'run', + config: { startsUnavailable: true, listenDelayMs: 750 }, + }) + }) + + it('parses a reproducible weighted random profile', () => { + expect(parseMockLlmCliArgs([ + '--sequence', 'random', + '--repeat-last', + '--seed', '42', + '--random-weights', 'success=8,partial_disconnect=2', + ])).toEqual({ + kind: 'run', + config: { + startsUnavailable: false, + listenDelayMs: 0, + server: { + sequence: ['random'], + port: 8000, + repeatLast: true, + randomSeed: 42, + randomWeights: { success: 8, partial_disconnect: 2 }, + }, + }, + }) + }) + + it.each([ + [[], /--sequence is required/], + [['--wat'], /requires a value/], + [['--wat', 'x'], /unknown option/], + [['--port', 'NaN', '--sequence', 'success'], /finite number/], + [['--sequence', 'success,'], /non-empty/], + [['--sequence', 'success,connection_refused'], /only as the first/], + [['--sequence', 'connection_refused'], /must be followed/], + [['--sequence', 'unknown'], /unknown behavior/], + [['--sequence', 'connection_refused,success', '--port', '0'], /nonzero/], + [['--sequence', 'success', '--listen-delay-ms', '5'], /requires connection_refused/], + [['--sequence', 'success', '--seed', '1'], /require random/], + [['--sequence', 'random', '--random-weights', 'success'], /expects behavior=weight/], + [['--sequence', 'random', '--random-weights', 'random=1'], /concrete behavior/], + [['--sequence', 'random', '--random-weights', 'success=1,success=2'], /duplicate/], + [['--sequence', 'random', '--random-weights', 'success=nope'], /finite number/], + ])('rejects invalid argv %#', (argv, expected) => { + expect(() => parseMockLlmCliArgs(argv)).toThrow(expected) + }) +}) diff --git a/packages/support/llm-mock-server/tests/invariant.spec.ts b/packages/support/llm-mock-server/tests/invariant.spec.ts new file mode 100644 index 0000000000..f45320d989 --- /dev/null +++ b/packages/support/llm-mock-server/tests/invariant.spec.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import InvariantService from '@deepseek-ai/dsh-invariants' +import * as MockServerInvariant from '../src/invariant.ts' + +describe('mock LLM server invariant companion', () => { + it('registers its explained empty runtime invariant', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService) + const fiber = await ctx.plugin(MockServerInvariant) + + expect(() => { + ctx.invariants.register('@deepseek-ai/dsh-llm-mock-server', () => {}) + }).toThrow(/already registered/) + await fiber.dispose() + await ctx.fiber.dispose() + }) +}) diff --git a/packages/support/llm-mock-server/tests/server.spec.ts b/packages/support/llm-mock-server/tests/server.spec.ts new file mode 100644 index 0000000000..b84931bc9f --- /dev/null +++ b/packages/support/llm-mock-server/tests/server.spec.ts @@ -0,0 +1,312 @@ +import { afterEach, describe, expect, it } from 'vitest' +import type { MockLlmBehavior, MockLlmServer, MockLlmServerEvent } from '../src/index.ts' +import { startMockLlmServer } from '../src/index.ts' + +const running: MockLlmServer[] = [] + +afterEach(async () => { + await Promise.all(running.splice(0).map(server => server.close())) +}) + +async function start( + sequence: readonly MockLlmBehavior[], + options: Omit[0], 'sequence'> = {}, +): Promise { + const server = await startMockLlmServer({ sequence, ...options }) + running.push(server) + return server +} + +function chat( + server: MockLlmServer, + options: { path?: string; key?: string; body?: string; signal?: AbortSignal } = {}, +): Promise { + return fetch(`${server.baseURL}${options.path ?? '/v1/chat/completions'}`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + ...options.key === undefined ? {} : { authorization: `Bearer ${options.key}` }, + }, + body: options.body ?? JSON.stringify({ model: 'mock', messages: [], stream: true }), + ...options.signal === undefined ? {} : { signal: options.signal }, + }) +} + +describe('mock LLM server wire behaviors', () => { + it('streams a complete text response and captures the request', async () => { + const events: MockLlmServerEvent[] = [] + const server = await start(['success'], { + apiKey: 'mock-key', + successText: 'recovered', + chunkSize: 3, + onEvent: (event) => { events.push(event) }, + }) + + const response = await chat(server, { key: 'mock-key' }) + const body = await response.text() + + expect(response.status).toBe(200) + expect(response.headers.get('content-type')).toContain('text/event-stream') + expect(body).toContain('"content":"rec"') + expect(body).toContain('"content":"ove"') + expect(body).toContain('"content":"red"') + expect(body).toContain('"finish_reason":"stop"') + expect(body).toContain('data: [DONE]') + expect(server.requests).toEqual([expect.objectContaining({ + attempt: 1, + behavior: 'success', + path: '/v1/chat/completions', + body: { model: 'mock', messages: [], stream: true }, + chunksSent: 5, + outcome: 'completed', + })]) + expect(events).toEqual([ + { + type: 'request', + attempt: 1, + scriptBehavior: 'success', + behavior: 'success', + path: '/v1/chat/completions', + }, + { + type: 'result', + attempt: 1, + scriptBehavior: 'success', + behavior: 'success', + outcome: 'completed', + chunksSent: 5, + }, + ]) + }) + + it('supports root paths and intentionally ignores telemetry observer failures', async () => { + const server = await start(['empty'], { + onEvent() { + throw new Error('observer failed') + }, + }) + const response = await chat(server, { path: '/chat/completions' }) + + expect(response.status).toBe(200) + expect(await response.text()).toContain('data: [DONE]') + expect(server.requests[0]).toMatchObject({ path: '/chat/completions', outcome: 'completed' }) + }) + + it.each([ + ['empty_body', 0, ''] as const, + ['stream_eof', 1, '"role":"assistant"'] as const, + ['partial_eof', 1, 'discarded partial response'] as const, + ['malformed_json', 2, 'data: {not-json'] as const, + ['malformed_event', 2, '"choices":[null]'] as const, + ])('serves %s without inventing a terminal completion', async (behavior, chunks, marker) => { + const server = await start([behavior], { chunkSize: 100 }) + const response = await chat(server) + const body = await response.text() + + expect(response.status).toBe(200) + expect(body).toContain(marker) + if (behavior !== 'malformed_json' && behavior !== 'malformed_event') { + expect(body).not.toContain('[DONE]') + } + expect(server.requests[0]).toMatchObject({ behavior, chunksSent: chunks, outcome: 'completed' }) + }) + + it.each([ + ['connection_reset', false] as const, + ['stream_disconnect', true] as const, + ['partial_disconnect', true] as const, + ])('forces the %s transport boundary', async (behavior, receivesHeaders) => { + const server = await start([behavior], { disconnectDelayMs: 20, partialText: 'half' }) + + let headersReceived = false + await expect((async () => { + const response = await chat(server) + headersReceived = true + await response.text() + })()).rejects.toThrow() + + expect(headersReceived).toBe(receivesHeaders) + expect(server.requests[0]).toMatchObject({ + behavior, + chunksSent: behavior === 'partial_disconnect' ? 1 : 0, + outcome: 'reset', + }) + }) + + it('holds a stalled stream until the client aborts and server close remains idempotent', async () => { + const server = await start(['stall']) + const controller = new AbortController() + const response = await chat(server, { signal: controller.signal }) + + expect(response.status).toBe(200) + expect(server.requests[0]).toMatchObject({ behavior: 'stall', outcome: 'stalled' }) + controller.abort() + await expect(response.text()).rejects.toThrow() + await server.close() + await server.close() + }) + + it.each([ + ['slow_success', 100] as const, + ['stream_disconnect', 100] as const, + ['partial_disconnect', 100] as const, + ])('records a client that closes during %s', async (behavior, delayMs) => { + const server = await start([behavior], { + chunkDelayMs: delayMs, + disconnectDelayMs: delayMs, + chunkSize: 1, + }) + const controller = new AbortController() + const response = await chat(server, { signal: controller.signal }) + controller.abort() + await expect(response.text()).rejects.toThrow() + await new Promise((resolve) => { setTimeout(resolve, 5) }) + + expect(server.requests[0]).toMatchObject({ behavior, outcome: 'client_closed' }) + }) + + it('emits reasoning, tool calls, max-token finishes, slow chunks, and a wrong content type', async () => { + const server = await start([ + 'reasoning_success', + 'tool_call_success', + 'max_tokens', + 'slow_success', + 'wrong_content_type', + ], { + successText: 'answer', + reasoningText: 'think', + toolName: 'lookup', + toolArguments: '{"id":7}', + chunkDelayMs: 1, + chunkSize: 2, + }) + + const bodies: string[] = [] + const contentTypes: Array = [] + for (let index = 0; index < 5; index += 1) { + const response = await chat(server) + contentTypes.push(response.headers.get('content-type')) + bodies.push(await response.text()) + } + + expect(bodies[0]).toContain('"reasoning_content":"th"') + expect(bodies[1]).toContain('"name":"lookup"') + expect(bodies[1]).toContain('"arguments":"{\\"id"') + expect(bodies[1]).toContain('"finish_reason":"tool_calls"') + expect(bodies[2]).toContain('"finish_reason":"length"') + expect(bodies[3]).toContain('"finish_reason":"stop"') + expect(contentTypes[4]).toBe('application/json') + expect(server.requests).toHaveLength(5) + expect(server.requests.every(record => record.outcome === 'completed')).toBe(true) + }) + + it.each([ + ['rate_limit', 429, 'mock rate limit'] as const, + ['server_error', 500, 'mock server error'] as const, + ['service_unavailable', 503, 'mock service unavailable'] as const, + ['auth_error', 401, 'mock authentication failed'] as const, + ['invalid_request', 400, 'mock invalid request'] as const, + ['context_overflow', 400, 'context_length_exceeded'] as const, + ['quota_exceeded', 429, 'insufficient_quota'] as const, + ])('serves %s as a structured HTTP error', async (behavior, status, marker) => { + const server = await start([behavior], { retryAfterMs: 1_001, requestId: 'mock-request-1' }) + const response = await chat(server) + const body = await response.text() + + expect(response.status).toBe(status) + expect(body).toContain(marker) + expect(response.headers.get('x-request-id')).toBe('mock-request-1') + if (behavior === 'rate_limit') expect(response.headers.get('retry-after')).toBe('2') + else expect(response.headers.get('retry-after')).toBeNull() + expect(server.requests[0]?.outcome).toBe('completed') + }) + + it('fails loud on script exhaustion and can explicitly repeat the final behavior', async () => { + const exhausted = await start(['success'], { successText: 'once' }) + await (await chat(exhausted)).text() + const exhaustedResponse = await chat(exhausted) + expect(exhaustedResponse.status).toBe(500) + expect(await exhaustedResponse.text()).toContain('mock script exhausted') + expect(exhausted.requests.map(record => record.behavior)).toEqual(['success', 'script_exhausted']) + + const repeating = await start(['empty'], { repeatLast: true }) + await (await chat(repeating)).text() + await (await chat(repeating)).text() + expect(repeating.requests.map(record => record.behavior)).toEqual(['empty', 'empty']) + }) + + it('selects weighted random behaviors reproducibly and reports the concrete choice', async () => { + const options = { + sequence: ['random'] as const, + repeatLast: true, + randomSeed: 42, + randomWeights: { success: 1, empty: 1 }, + successText: 'random success', + } + const first = await startMockLlmServer(options) + const second = await startMockLlmServer(options) + running.push(first, second) + + for (let attempt = 0; attempt < 12; attempt += 1) { + await (await chat(first)).text() + await (await chat(second)).text() + } + + const firstChoices = first.requests.map(record => record.behavior) + expect(first.randomSeed).toBe(42) + expect(second.randomSeed).toBe(42) + expect(firstChoices).toEqual(second.requests.map(record => record.behavior)) + expect(new Set(firstChoices)).toEqual(new Set(['success', 'empty'])) + expect(first.requests.every(record => record.scriptBehavior === 'random')).toBe(true) + }) + + it('rejects invalid method, route, bearer token, and JSON without consuming the script', async () => { + const server = await start(['success'], { apiKey: 'expected' }) + const method = await fetch(`${server.baseURL}/v1/chat/completions`) + const route = await fetch(`${server.baseURL}/v1/other`, { method: 'POST', body: '{}' }) + const auth = await chat(server, { key: 'wrong' }) + const json = await chat(server, { key: 'expected', body: '{' }) + + expect(method.status).toBe(405) + expect(method.headers.get('allow')).toBe('POST') + expect(route.status).toBe(404) + expect(auth.status).toBe(401) + expect(json.status).toBe(400) + expect(server.requests).toHaveLength(0) + + const emptyRequest = await fetch(`${server.baseURL}/v1/chat/completions`, { + method: 'POST', + headers: { authorization: 'Bearer expected' }, + }) + expect(emptyRequest.status).toBe(200) + expect(server.requests[0]?.behavior).toBe('success') + expect(server.requests[0]?.body).toBeUndefined() + }) +}) + +describe('mock LLM server option validation', () => { + it.each([ + [{ sequence: [] }, /sequence/], + [{ sequence: ['success'], host: '' }, /host/], + [{ sequence: ['success'], port: -1 }, /port/], + [{ sequence: ['success'], port: 65_536 }, /port/], + [{ sequence: ['success'], apiKey: '' }, /apiKey/], + [{ sequence: ['success'], successText: '' }, /successText/], + [{ sequence: ['success'], partialText: '' }, /partialText/], + [{ sequence: ['success'], reasoningText: '' }, /reasoningText/], + [{ sequence: ['success'], chunkSize: 0 }, /chunkSize/], + [{ sequence: ['success'], chunkDelayMs: -1 }, /chunkDelayMs/], + [{ sequence: ['success'], disconnectDelayMs: Number.POSITIVE_INFINITY }, /disconnectDelayMs/], + [{ sequence: ['success'], retryAfterMs: 0 }, /retryAfterMs/], + [{ sequence: ['success'], requestId: '' }, /requestId/], + [{ sequence: ['success'], toolName: '' }, /toolName/], + [{ sequence: ['success'], toolArguments: '{' }, /toolArguments/], + [{ sequence: ['random'], randomSeed: -1 }, /randomSeed/], + [{ sequence: ['random'], randomWeights: { random: 1 } }, /unknown concrete behavior/], + [{ sequence: ['random'], randomWeights: { success: -1 } }, /non-negative/], + [{ sequence: ['random'], randomWeights: { success: 0 } }, /positive weight/], + ] as const)('rejects invalid options %#', async (options, expected) => { + await expect(startMockLlmServer(options as Parameters[0])) + .rejects.toThrow(expected) + }) +}) diff --git a/packages/support/llm-mock-server/tsconfig.json b/packages/support/llm-mock-server/tsconfig.json new file mode 100644 index 0000000000..d970a00263 --- /dev/null +++ b/packages/support/llm-mock-server/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/support/llm-mock-server/tsdown.config.ts b/packages/support/llm-mock-server/tsdown.config.ts new file mode 100644 index 0000000000..3dcb19efab --- /dev/null +++ b/packages/support/llm-mock-server/tsdown.config.ts @@ -0,0 +1,17 @@ +import { defineConfig } from 'tsdown' + +/** Builds each public entry as a self-contained file admitted by the package whitelist. */ +export default defineConfig([ + { + entry: ['lib/types/index.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', + fixedExtension: false, outputOptions: { codeSplitting: false }, dts: false, clean: false, + }, + { + entry: ['lib/types/invariant.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', + fixedExtension: false, outputOptions: { codeSplitting: false }, dts: false, clean: false, + }, + { + entry: ['lib/types/bin.js'], outDir: 'lib', format: ['esm'], platform: 'node', target: 'es2024', + fixedExtension: false, outputOptions: { codeSplitting: false }, dts: false, clean: false, + }, +]) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index edd75466c5..5986b8f978 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2290,12 +2290,21 @@ importers: '@deepseek-ai/dsh-agent-loop': specifier: workspace:^ version: link:../../core/agent-loop + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:^ + version: link:../../support/agent-loop-testkit '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../llm + '@deepseek-ai/dsh-llm-deepseek': + specifier: workspace:^ + version: link:../llm-deepseek + '@deepseek-ai/dsh-llm-mock-server': + specifier: workspace:^ + version: link:../../support/llm-mock-server '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session @@ -3455,6 +3464,15 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/support/llm-mock-server: + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../invariants + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/support/llm-replay: devDependencies: '@deepseek-ai/dsh-invariants': diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index d5fa282a24..b5a39fa5f9 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -90,6 +90,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/support/agent-loop-testkit': { kind: 'none', reason: 'The test helper mounts services but neither drives nor modifies model requests.' }, 'packages/support/invariants': { kind: 'none', reason: 'The observer validates requests but never rewrites their context.' }, 'packages/support/loader-smoke': { kind: 'none', reason: 'The test harness observes child-process streams without changing live requests.' }, + 'packages/support/llm-mock-server': { kind: 'none', reason: 'The test server substitutes provider wire behavior without invoking a real model.' }, 'packages/support/llm-replay': { kind: 'none', reason: 'The keyless adapter invokes no provider model.' }, 'packages/tasks/tasks': { kind: 'indirect', reason: 'Producer and control-surface plugins own all model rendering over the task registry.' }, 'packages/examples/acp-demo': { kind: 'indirect', reason: 'The app bundle delegates request composition to dsh-agent-spine-demo and dsh-acp.' }, diff --git a/tsconfig.host.json b/tsconfig.host.json index a13bcf35e3..d074f3a658 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -115,6 +115,7 @@ { "path": "./packages/support/llm-replay" }, { "path": "./packages/support/acp-snapshot" }, { "path": "./packages/support/loader-smoke" }, + { "path": "./packages/support/llm-mock-server" }, { "path": "./packages/subagent/subagent" }, { "path": "./packages/subagent/tool-subagent" }, { "path": "./packages/subagent/subagent-inprocess" }, From 870fb1cafa32feeac857b1ca62028df79b843a25 Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 25 Jul 2026 12:43:59 +0800 Subject: [PATCH 036/113] refactor(cli): make dsh the sole terminal front door, drop RESUME_SESSION_ID MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove the redundant dsh-tui-demo bin and the RESUME_SESSION_ID environment variable, leaving dsh as the one terminal entrypoint. The dsh-tui-demo package was a plugin (the TUI app bundle mounted by dsh's config) plus a bin that booted a leaf cordis.yml — the same job `dsh [config]` does. The bin, its ./bin export, its built-bin.e2e.ts, the tsdown bin entry, and the now-unused dsh-app-boot dependency are removed; the package keeps its plugin and invariant. demo:cordis, demo:code-mode, and the tui-agent and cordis-agent keyless PTY smokes now launch through apps/cli/src/bin.ts with the config as the positional argument. cli-demo/acp-demo/jsonrpc-demo keep their bins (distinct surfaces). RESUME_SESSION_ID was the only bridge from --resume into the shipped config; --resume now provides the id on the boot context via ctx.provide( RESUME_SESSION_ID_KEY, id), and the four configs read it as a bare identifier through a quoted typeof-guarded !!js expression. The TUI resumeCommand fixtures and docs move to `dsh --resume {session}`. Agent Note and its Chinese pair updated; config-catalog regenerated. --- ...4-dsh-commander-argument-adapter.i18n.yaml | 4 +- ...26-07-24-dsh-commander-argument-adapter.md | 20 +++- ...07-24-dsh-commander-argument-adapter.zh.md | 20 +++- ...07-20-retire-readline-front-door.i18n.yaml | 4 +- .../2026-07-20-retire-readline-front-door.md | 2 +- ...026-07-20-retire-readline-front-door.zh.md | 2 +- apps/cli/README.md | 2 +- apps/cli/src/args.ts | 5 +- docs/config-catalog.md | 4 +- examples/README.md | 2 +- .../cordis-agent/tests/keyless-smoke.e2e.ts | 2 +- examples/tui-agent/README.md | 2 +- .../tui-agent/tests/tui-keyless-smoke.e2e.ts | 5 +- knip.json | 3 +- package.json | 2 +- packages/examples/README.md | 4 +- packages/examples/tui-demo/README.md | 8 +- packages/examples/tui-demo/package.json | 12 +-- packages/examples/tui-demo/src/bin.ts | 27 ----- packages/examples/tui-demo/src/index.ts | 4 +- .../examples/tui-demo/tests/built-bin.e2e.ts | 98 ------------------- packages/examples/tui-demo/tsdown.config.ts | 12 +-- .../loader-smoke/tests/example-launch.spec.ts | 6 +- packages/ui/app-boot/README.md | 2 +- packages/ui/tui/tests/tui.snapshot.ts | 2 +- packages/ui/tui/tests/tui.spec.ts | 6 +- pnpm-lock.yaml | 3 - scripts/demo-code-mode.mjs | 2 +- 28 files changed, 76 insertions(+), 189 deletions(-) delete mode 100644 packages/examples/tui-demo/src/bin.ts delete mode 100644 packages/examples/tui-demo/tests/built-bin.e2e.ts diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml index 03b3c8e6f7..1780a5f57e 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.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 -2026-07-24-dsh-commander-argument-adapter.md: 4decd926c7fffc8f7d24200f8b91044eaa1d00f1 -2026-07-24-dsh-commander-argument-adapter.zh.md: eaccc221d362804b0aa3081d0593e9dee8af1d4c +2026-07-24-dsh-commander-argument-adapter.md: 60c47ef40cb0db833f7a2a526437b6a8ce812433 +2026-07-24-dsh-commander-argument-adapter.zh.md: 41a98499036c16330263d5072aa0fa454b892a24 diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md index 4decd926c7..60c47ef40c 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md @@ -10,12 +10,20 @@ The `dsh` CLI entry (`apps/cli`) parsed argv in three hand-rolled idioms that di ## Decision -Argv is parsed once, in `apps/cli/src/args.ts`, through a Commander adapter (the same parser the SDK bins — `create-sdk`, `dsh-scripts` — already standardize on). `parseDshArgs(argv, version)` resolves the invocation into a discriminated `DshInvocation` union: `{ mode: 'tui', config?, resume? }`, `{ mode: 'headless', prompt }`, `{ mode: 'web', host, port }`, `{ mode: 'help' | 'version', text }`, or `{ mode: 'error', message }`. Commander runs under `exitOverride()` with output captured, so it never writes or exits on its own — `--help`, `--version`, and every parse error come back as data. +Argv is parsed once, in `apps/cli/src/args.ts`, through a Commander adapter (the same parser the SDK bins — `create-sdk`, `dsh-scripts` — already standardize on). `parseDshArgs(argv, version)` resolves the invocation into a discriminated `DshInvocation` union: `{ mode: 'tui', config?, resume? }`, `{ mode: 'headless', prompt }`, `{ mode: 'web', host, port, dev }`, `{ mode: 'help' | 'version', text }`, or `{ mode: 'error', message }`. Commander runs under `exitOverride()` with output captured, so it never writes or exits on its own — `--help`, `--version`, and every parse error come back as data. -`bin.ts` calls the adapter once and switches on `mode` (closed union, `satisfies never` default), dynamic-importing only the chosen mode's module. Each mode module now consumes already-parsed values: `runTui(config, resume)`, `runHeadless(task)`, `runWeb(host, port)` — none re-reads argv. `web` is a **reserved first token**: `parseDshArgs` dispatches a leading `web` to its own Commander parser and everything else to the default TUI/headless parser, so root flags and `web` flags never share a grammar — `dsh web -p x` fails loud (`web` has no `-p`) and `dsh -p x web` is just a headless prompt whose second positional is dropped, with no cross-command leakage to guard against. Each parser reads Commander's `opts()`/`processedArgs` after `parse()` rather than through action closures. `--host` is a `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])` and `--port` an `argParser` that range-checks 0–65535, moving both from the inline `runWeb` checks into the parser. Two post-parse checks preserve the "never silently start fresh" invariant: an empty `--resume=` id and an empty `-p` task each become a `mode: 'error'`, because agent-loop treats an empty resume id as no-resume and an empty prompt has nothing to run. A repeated `--resume` is Commander's natural last-wins (the old bespoke scanner rejected it; last-wins is the standard CLI behavior and needs no special case). `--version` reads this app's `package.json`. +`bin.ts` calls the adapter once and switches on `mode` (closed union, `satisfies never` default), dynamic-importing only the chosen mode's module. Each mode module now consumes already-parsed values: `runTui(config, resume)`, `runHeadless(task)`, `runWeb(host, port, dev)` — none re-reads argv. `web` is a **reserved first token**: `parseDshArgs` dispatches a leading `web` to its own Commander parser and everything else to the default TUI/headless parser, so root flags and `web` flags never share a grammar — `dsh web -p x` fails loud (`web` has no `-p`) and `dsh -p x web` is just a headless prompt whose second positional is dropped, with no cross-command leakage to guard against. Each parser reads Commander's `opts()`/`processedArgs` after `parse()` rather than through action closures. `--host` is a `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])` and `--port` an `argParser` that range-checks 0–65535, moving both from the inline `runWeb` checks into the parser; `--dev` mounts the client HMR driver and bundle watch. Two post-parse checks preserve the "never silently start fresh" invariant: an empty `--resume=` id and an empty `-p` task each become a `mode: 'error'`, because agent-loop treats an empty resume id as no-resume and an empty prompt has nothing to run. A repeated `--resume` is Commander's natural last-wins (the old bespoke scanner rejected it; last-wins is the standard CLI behavior and needs no special case). `--version` reads this app's `package.json`. `parseResumeArg` is deleted from `dsh-app-boot` (its export, its README row, and its unit block); the pre-release stance permits the removal. `dsh-app-boot` keeps its boot/env/config/personal-overlay helpers — only the argv scanner leaves. +## Resume without an environment variable + +Merging the concurrent safe-session-resume feature onto this parser retired the `RESUME_SESSION_ID` environment variable, which had been the only bridge from `--resume` into the shipped config's `resumeSessionId: !!js process.env.RESUME_SESSION_ID`. `runTui` now injects the already-parsed id through `boot`'s `prepare(ctx)` hook — `ctx.provide(RESUME_SESSION_ID_KEY, id)` (a new `dsh-app-boot` export, value `'resumeSessionId'`) — and the four tui-agent/cordis configs read it as a bare identifier: `resumeSessionId: !!js "typeof resumeSessionId === 'string' ? resumeSessionId : undefined"`. The expression is quoted because YAML otherwise parses the `?`/`:` as a mapping; the `typeof` guard tolerates a bin that never provides the slot. The `/resume` in-place handoff (`process.execve`) rebuilds its re-exec argv directly as `dsh [config] --resume ` from the parsed values, so `replaceResumeArg` (which the merge brought in) is dropped alongside `parseResumeArg`. + +## One terminal front door: `dsh` + +The `dsh-tui-demo` package was a plugin (the TUI app bundle mounted by `dsh`'s config) plus a redundant `bin` that booted a leaf `cordis.yml` — the same job `dsh [config]` does. The bin is removed: `demo:cordis`, `demo:code-mode`, and both the tui-agent and cordis-agent keyless PTY smokes now launch through `apps/cli/src/bin.ts` with the config as the positional argument, and the package keeps only its plugin and invariant entries. The peer/dev `dsh-app-boot` dependency, the `bin`/`./bin` export, the `built-bin.e2e.ts` (its TUI piped-launch refusal is covered by `dsh`'s own TTY guard in the tui-agent PTY smoke), and the tsdown `bin` entry all leave with it. `cli-demo`, `acp-demo`, and `jsonrpc-demo` keep their bins because each is a distinct surface (headless, ACP, JSON-RPC) `dsh` does not provide. + ## Package topology The argument surface stays inside `apps/cli`, the assembly tier, not a `packages/*` library: it is this one app's routing, not a reusable seam. `dsh-app-boot` shrinks to boot glue with no CLI-parsing responsibility. `commander@^15` is added to `apps/cli/package.json`, matching the SDK bins' pin. @@ -30,10 +38,14 @@ The argument surface stays inside `apps/cli`, the assembly tier, not a `packages **Make the argument surface a `packages/*` seam** — rejected: nothing outside `dsh` consumes it, and capability seams are not split preemptively. The Commander adapter is `apps/cli`'s own concern. +**Keep `RESUME_SESSION_ID` as the resume bridge** — rejected: with `--resume` parsed into a value the bin already holds, threading it through an environment variable the config re-reads is indirection with no benefit, and it left the demo bin a second, env-only resume path. Providing the id on the boot context is the same channel `boot`'s `prepare` hook already uses for `tuiResumeHost`. + +**Keep the `dsh-tui-demo` bin** — rejected: it duplicated `dsh [config]` exactly, and keeping it forced the demo-only `RESUME_SESSION_ID` fallback to stay alive. Its plugin is what the configs actually mount; only the front-door bin was redundant, and `dsh` is the one terminal entry point. + ## Testing -`apps/cli/tests/args.spec.ts` (new; `apps/*/tests` added to the vitest include and `apps/cli/tests` to `tsconfig.host.json`) covers the adapter at the level that matters: mode routing by shape, the fail-loud checks (empty resume/prompt, bad host/port, unknown option), and `--help`/`--version` surfacing as data. The `dsh CLI keyless smoke` group in `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` exercises the real `bin.ts` dispatch end to end through a PTY (default boot, personal overlay, invalid config, `--resume` failure, source-path prompt) and stays green unchanged. `packages/ui/app-boot/tests/app-boot.spec.ts` drops its `parseResumeArg` block. +`apps/cli/tests/args.spec.ts` (new; `apps/*/tests` added to the vitest include and `apps/cli/tests` to `tsconfig.host.json`) covers the adapter at the level that matters: mode routing by shape (including `web --dev`), the fail-loud checks (empty resume/prompt, bad host/port, unknown option), and `--help`/`--version` surfacing as data. Both PTY smoke groups in `examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` now drive the real `apps/cli/src/bin.ts`: the `tui-agent` group boots the config as a positional, and the `dsh CLI` group covers default boot, personal overlay, invalid config, the `--resume` config intake, the `process.execve` in-place resume handoff, and the source-path prompt. `examples/cordis-agent/tests/keyless-smoke.e2e.ts` likewise launches through `dsh`. `packages/ui/app-boot/tests/app-boot.spec.ts` drops its `parseResumeArg`/`replaceResumeArg` blocks; the TUI unit and snapshot fixtures use the `dsh --resume {session}` resume command. ## Consequences -`dsh` gains rendered `--help`/`--version` and consistent fail-loud parse errors, and mode routing no longer depends on flag position. Argv parsing lives in one place with one parser idiom shared with the SDK bins, at the cost of a `commander` dependency on `apps/cli` and Commander's parse semantics (its error strings, its `exitOverride` contract) now sitting on the CLI's front door. `dsh-app-boot` no longer owns any CLI-parsing surface; a future consumer needing `--resume`-style parsing composes Commander rather than reviving the deleted scanner. +`dsh` gains rendered `--help`/`--version` and consistent fail-loud parse errors, and mode routing no longer depends on flag position. Argv parsing lives in one place with one parser idiom shared with the SDK bins, at the cost of a `commander` dependency on `apps/cli` and Commander's parse semantics (its error strings, its `exitOverride` contract) now sitting on the CLI's front door. `dsh-app-boot` no longer owns any CLI-parsing surface; a future consumer needing `--resume`-style parsing composes Commander rather than reviving the deleted scanner. Resuming a session needs no environment variable, and `dsh` is the single terminal front door — the `dsh-tui-demo` package is now a plugin bundle with no bin. Anyone who ran `dsh-tui-demo ` or `RESUME_SESSION_ID= dsh-tui-demo` uses `dsh ` / `dsh --resume ` instead. diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md index eaccc221d3..41a9849903 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md @@ -10,12 +10,20 @@ Status: implemented ## 决策 -argv 只在 `apps/cli/src/args.ts` 中解析一次,通过一个 Commander 适配器(即 SDK bin,如 `create-sdk`、`dsh-scripts`,已经统一采用的那个解析器)。`parseDshArgs(argv, version)` 将调用解析为一个判别式 `DshInvocation` 联合类型:`{ mode: 'tui', config?, resume? }`、`{ mode: 'headless', prompt }`、`{ mode: 'web', host, port }`、`{ mode: 'help' | 'version', text }` 或 `{ mode: 'error', message }`。Commander 在 `exitOverride()` 下运行并捕获输出,因此它自身从不写出或退出:`--help`、`--version` 和每个解析错误都以数据形式返回。 +argv 只在 `apps/cli/src/args.ts` 中解析一次,通过一个 Commander 适配器(即 SDK bin,如 `create-sdk`、`dsh-scripts`,已经统一采用的那个解析器)。`parseDshArgs(argv, version)` 将调用解析为一个判别式 `DshInvocation` 联合类型:`{ mode: 'tui', config?, resume? }`、`{ mode: 'headless', prompt }`、`{ mode: 'web', host, port, dev }`、`{ mode: 'help' | 'version', text }` 或 `{ mode: 'error', message }`。Commander 在 `exitOverride()` 下运行并捕获输出,因此它自身从不写出或退出:`--help`、`--version` 和每个解析错误都以数据形式返回。 -`bin.ts` 调用一次适配器,并对 `mode` 做分支切换(封闭联合类型,默认分支为 `satisfies never`),只动态导入所选模式对应的模块。每个模式模块现在只消费已解析好的值:`runTui(config, resume)`、`runHeadless(task)`、`runWeb(host, port)`,都不会再次读取 argv。`web` 是一个**保留的首个 token**:`parseDshArgs` 将开头的 `web` 分发给它自己的 Commander 解析器,其余一切分发给默认的 TUI/headless 解析器,因此根级标志与 `web` 标志从不共用同一套语法——`dsh web -p x` 会显式报错(`web` 没有 `-p`),而 `dsh -p x web` 只是一个 headless prompt,其第二个位置参数被丢弃,无需防范任何跨命令泄漏。每个解析器都在 `parse()` 之后读取 Commander 的 `opts()`/`processedArgs`,而不是通过 action 闭包。`--host` 是一个 `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])`,`--port` 是一个对 0–65535 做范围检查的 `argParser`,二者都从内联的 `runWeb` 检查移入了解析器。两处解析后的检查保留了「绝不静默重新开始」不变式:空的 `--resume=` id 和空的 `-p` 任务各自变为 `mode: 'error'`,因为 agent-loop 把空的 resume id 视为不恢复,而空的 prompt 没有任何内容可运行。重复出现的 `--resume` 采用 Commander 天然的后者胜出(旧的定制扫描器会拒绝它;后者胜出是标准的 CLI 行为,无需特殊处理)。`--version` 读取本应用的 `package.json`。 +`bin.ts` 调用一次适配器,并对 `mode` 做分支切换(封闭联合类型,默认分支为 `satisfies never`),只动态导入所选模式对应的模块。每个模式模块现在只消费已解析好的值:`runTui(config, resume)`、`runHeadless(task)`、`runWeb(host, port, dev)`,都不会再次读取 argv。`web` 是一个**保留的首个 token**:`parseDshArgs` 将开头的 `web` 分发给它自己的 Commander 解析器,其余一切分发给默认的 TUI/headless 解析器,因此根级标志与 `web` 标志从不共用同一套语法——`dsh web -p x` 会显式报错(`web` 没有 `-p`),而 `dsh -p x web` 只是一个 headless prompt,其第二个位置参数被丢弃,无需防范任何跨命令泄漏。每个解析器都在 `parse()` 之后读取 Commander 的 `opts()`/`processedArgs`,而不是通过 action 闭包。`--host` 是一个 `.choices([LOOPBACK_HOST, ALL_INTERFACES_HOST])`,`--port` 是一个对 0–65535 做范围检查的 `argParser`,二者都从内联的 `runWeb` 检查移入了解析器;`--dev` 会挂载客户端 HMR(热模块替换)驱动,并启用构建产物监视。两处解析后的检查保留了「绝不静默重新开始」不变式:空的 `--resume=` id 和空的 `-p` 任务各自变为 `mode: 'error'`,因为 agent-loop 把空的 resume id 视为不恢复,而空的 prompt 没有任何内容可运行。重复出现的 `--resume` 采用 Commander 天然的后者胜出(旧的定制扫描器会拒绝它;后者胜出是标准的 CLI 行为,无需特殊处理)。`--version` 读取本应用的 `package.json`。 `parseResumeArg` 从 `dsh-app-boot` 中删除(包括其导出、README 中的对应行以及单元测试块);预发布阶段的立场允许这次删除。`dsh-app-boot` 保留其 boot/env/config/个人覆盖辅助函数,只有 argv 扫描器被移除。 +## 无需环境变量即可恢复 + +将与本解析器并行开发的安全会话恢复功能合入时,系统移除了 `RESUME_SESSION_ID` 环境变量。此前,它是将 `--resume` 的值传给随产品提供的配置字段 `resumeSessionId: !!js process.env.RESUME_SESSION_ID` 的唯一通道。`runTui` 现在通过 `boot` 的 `prepare(ctx)` 钩子注入已解析的 id:`ctx.provide(RESUME_SESSION_ID_KEY, id)`(`dsh-app-boot` 的新导出,值为 `'resumeSessionId'`);tui-agent 和 cordis-agent 的四份配置将该值作为裸标识符读取:`resumeSessionId: !!js "typeof resumeSessionId === 'string' ? resumeSessionId : undefined"`。这个表达式需要加引号,否则 YAML 会把 `?` 和 `:` 解析为映射;`typeof` 守卫使从未提供该槽位的 bin 也能正常运行。`/resume` 原地交接(`process.execve`)直接根据解析后的值将重新执行的 argv 构造成 `dsh [config] --resume `,因此合并时引入的 `replaceResumeArg` 与 `parseResumeArg` 一并删除。 + +## 唯一的终端入口:`dsh` + +`dsh-tui-demo` 包(package)原本包含一个插件(即 `dsh` 配置挂载的 TUI 应用组合)和一个冗余的 `bin`;后者启动一份叶子配置 `cordis.yml`,所做的工作与 `dsh [config]` 相同。该 bin 已移除:`demo:cordis`、`demo:code-mode` 以及 tui-agent 和 cordis-agent 的两个无密钥 PTY 冒烟测试现在都通过 `apps/cli/src/bin.ts` 启动,并将配置作为位置参数;该包只保留插件入口和不变式入口。与该 bin 一同移除的还有对 `dsh-app-boot` 的对等依赖(peer dependency)和开发依赖、`bin` 和 `./bin` 导出、`built-bin.e2e.ts`(其中拒绝通过管道启动 TUI 的行为已由 tui-agent PTY 冒烟测试中 `dsh` 自身的 TTY 守卫覆盖),以及 tsdown 的 `bin` 入口。`cli-demo`、`acp-demo` 和 `jsonrpc-demo` 保留各自的 bin,因为它们分别提供 `dsh` 所没有的独立接口(headless、ACP(Agent Client Protocol)、JSON-RPC)。 + ## 包拓扑 参数解析留在 `apps/cli`(组装层)内,而不是 `packages/*` 库中:它是这一个应用自身的路由,而非可复用的 seam。`dsh-app-boot` 收缩为纯粹的 boot 胶水代码,不再承担 CLI 解析职责。`commander@^15` 被加入 `apps/cli/package.json`,与 SDK bin 锁定的版本一致。 @@ -30,10 +38,14 @@ argv 只在 `apps/cli/src/args.ts` 中解析一次,通过一个 Commander 适 **把参数解析做成 `packages/*` 的 seam。** 已否决:`dsh` 之外没有任何消费方使用它,而能力 seam 不应被提前拆分。这个 Commander 适配器是 `apps/cli` 自身的事务。 +**保留 `RESUME_SESSION_ID` 作为恢复通道**:不予采纳。`--resume` 已被解析成 bin 当前持有的值;若再通过环境变量传递并由配置重新读取,只会引入无益的间接层,还会使演示 bin 保留第二条仅依赖环境变量的恢复路径。在启动上下文中提供 id,与 `boot` 的 `prepare` 钩子为 `tuiResumeHost` 提供值所采用的是同一通道。 + +**保留 `dsh-tui-demo` bin**:不予采纳。它与 `dsh [config]` 的功能完全重复;保留它还会迫使演示专用的 `RESUME_SESSION_ID` 回退路径继续存在。配置实际挂载的是该包的插件;冗余的只有作为终端入口的 bin,而 `dsh` 是唯一的终端入口。 + ## 测试 -`apps/cli/tests/args.spec.ts`(新增;`apps/*/tests` 加入 vitest include,`apps/cli/tests` 加入 `tsconfig.host.json`)在关键层面覆盖适配器:按形态进行的模式路由、显式报错检查(空 resume/prompt、错误的 host/port、未知选项),以及 `--help`/`--version` 以数据形式呈现。`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 中的 `dsh CLI keyless smoke` 组通过 PTY 端到端地运行真实的 `bin.ts` 分发(默认启动、个人覆盖、无效配置、`--resume` 失败、源路径 prompt),且保持绿色不变。`packages/ui/app-boot/tests/app-boot.spec.ts` 移除其 `parseResumeArg` 测试块。 +`apps/cli/tests/args.spec.ts`(新增;`apps/*/tests` 加入 vitest include,`apps/cli/tests` 加入 `tsconfig.host.json`)覆盖适配器的关键行为:根据参数形态选择模式(包括 `web --dev`)、显式报错场景(空的恢复会话 id、空提示词、非法主机、非法端口和未知选项),以及将 `--help` 和 `--version` 作为数据返回。`examples/tui-agent/tests/tui-keyless-smoke.e2e.ts` 中的两组 PTY 冒烟测试现在都驱动真实的 `apps/cli/src/bin.ts`:`tui-agent` 组将配置作为位置参数启动,`dsh CLI` 组覆盖默认启动、个人覆盖、无效配置、配置对 `--resume` 的接收、通过 `process.execve` 原地恢复交接,以及包含源码路径的系统提示词。`examples/cordis-agent/tests/keyless-smoke.e2e.ts` 同样通过 `dsh` 启动。`packages/ui/app-boot/tests/app-boot.spec.ts` 移除其 `parseResumeArg` 和 `replaceResumeArg` 测试块;TUI 单元测试和快照 fixture(测试前置数据)使用 `dsh --resume {session}` 恢复命令。 ## 影响 -`dsh` 获得了渲染出的 `--help`/`--version` 以及一致的显式报错式解析错误,模式路由也不再依赖标志位置。argv 解析集中在一处,并与 SDK bin 共用一套解析器方式,代价是 `apps/cli` 新增一项 `commander` 依赖,且 Commander 的解析语义(它的错误字符串、它的 `exitOverride` 契约)如今落在 CLI 的入口处。`dsh-app-boot` 不再拥有任何 CLI 解析职责;未来需要 `--resume` 式解析的消费方应组合 Commander,而不是复活已删除的扫描器。 +`dsh` 获得了渲染出的 `--help`/`--version` 以及一致的显式报错式解析错误,模式路由也不再依赖标志位置。argv 解析集中在一处,并与 SDK bin 共用一套解析器方式,代价是 `apps/cli` 新增一项 `commander` 依赖,且 Commander 的解析语义(它的错误字符串、它的 `exitOverride` 契约)如今落在 CLI 的入口处。`dsh-app-boot` 不再拥有任何 CLI 解析职责;未来需要 `--resume` 式解析的消费方应组合 Commander,而不是复活已删除的扫描器。恢复会话不再需要环境变量,且 `dsh` 是唯一的终端入口;`dsh-tui-demo` 包现在是一个不带 bin 的插件组合包。原先运行 `dsh-tui-demo ` 或 `RESUME_SESSION_ID= dsh-tui-demo` 的用户,改用 `dsh ` 或 `dsh --resume `。 diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml index 232fec495b..1e1968e09d 100644 --- a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.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 -2026-07-20-retire-readline-front-door.md: 7ebcfdc246bdf6971418609c61acbd4019aa90cb -2026-07-20-retire-readline-front-door.zh.md: cf4d03594ed3a0cf31bed96eb2133bd37959084a +2026-07-20-retire-readline-front-door.md: d8e6a5c172b576ce6bc76911186c9f81a4ece88f +2026-07-20-retire-readline-front-door.zh.md: bea685cdc3f8f1530d56ae3eb5dcc34cff0b46af diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md index 7ebcfdc246..d8e6a5c172 100644 --- a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.md @@ -26,7 +26,7 @@ Pipes remain the default test medium. PTY-driven subprocess tests are sanctioned - `examples/echo-agent/tests/echo.e2e.ts` proves the Loader boot + mock-model tool round-trip through `stream-json` records instead of readline transcript lines. - The CI demo-smoke gate (`scripts/run-gates.ts`, AGENTS.md) runs `demo:echo --output-format stream-json -p "echo ci smoke"` and parses the records structurally. -- `packages/examples/tui-demo/tests/built-bin.e2e.ts` proves the built bin's piped-launch refusal (nonzero exit + pointer at `dsh-cli-demo`); the echo-round-trip-under-plain-Node and missing-config fail-loud proofs live in `cli-demo`'s built-bin suite. +- The TUI's piped-launch refusal (nonzero exit + pointer at the one-shot CLI) is covered by the `dsh` TTY guard exercised in `examples/tui-agent`'s PTY smoke; the echo-round-trip-under-plain-Node and missing-config fail-loud proofs live in `cli-demo`'s built-bin suite. - `packages/context/time-context/tests/time-context.e2e.ts` runs one one-shot turn; multi-turn elapsed rendering stays unit-covered in its spec. ## Accepted losses diff --git a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md index cf4d03594e..bea685cdc3 100644 --- a/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md +++ b/.agents/notes/implemented/simplification/2026-07-20-retire-readline-front-door.zh.md @@ -26,7 +26,7 @@ Status: implemented - `examples/echo-agent/tests/echo.e2e.ts` 通过 `stream-json` 记录证明 Loader 启动 + mock 模型的工具往返,而不是匹配 readline 文本记录行。 - CI 演示冒烟门禁(`scripts/run-gates.ts`、AGENTS.md)运行 `demo:echo --output-format stream-json -p "echo ci smoke"` 并结构化解析记录。 -- `packages/examples/tui-demo/tests/built-bin.e2e.ts` 证明构建产物 bin 对管道启动的拒绝(非零退出 + 指向 `dsh-cli-demo` 的提示);纯 Node 下的 echo 往返证明与缺失配置的快速失败证明位于 `cli-demo` 的 built-bin 套件。 +- TUI 对管道启动的拒绝(非零退出 + 指向单次任务 CLI 的提示)由 `examples/tui-agent` 的 PTY 冒烟测试所行使的 `dsh` TTY 守卫覆盖;纯 Node 下的 echo 往返证明与缺失配置的快速失败证明位于 `cli-demo` 的 built-bin 套件。 - `packages/context/time-context/tests/time-context.e2e.ts` 运行一个单次任务轮次;多轮 elapsed 渲染仍由其单元测试覆盖。 ## 接受的损失 diff --git a/apps/cli/README.md b/apps/cli/README.md index 43360ef589..d94b577552 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -7,7 +7,7 @@ Argv is parsed once through a [Commander](https://github.com/tj/commander.js) ad The TUI surface: - boots the shipped default config (`examples/tui-agent/cordis.yml`) or an explicit config argument, through [`dsh-app-boot`](../../packages/ui/app-boot/README.md); -- resumes a persisted session with `dsh --resume ` and, when the Node host exposes `process.execve`, supplies the TUI's in-place handoff host: after selector preflight and current-session flush, the host disposes the app and replaces the process with a normalized resume flag; runtimes without process replacement keep the displayed command fallback, the flag still sets `RESUME_SESSION_ID` before boot, and a missing or unreadable id fails loud instead of creating a fresh session; +- resumes a persisted session with `dsh --resume ` and, when the Node host exposes `process.execve`, supplies the TUI's in-place handoff host: after selector preflight and current-session flush, the host disposes the app and replaces the process with a normalized `dsh --resume `; runtimes without process replacement keep the displayed command fallback. The flag provides the id on the boot context under `RESUME_SESSION_ID_KEY` (no environment variable), which the shipped config reads through `!!js`, and a missing or unreadable id fails loud instead of creating a fresh session; - treats the **invoking directory** as the workspace — sessions, relative paths, and workspace instructions resolve from the cwd; - tells the agent where its own source lives: after boot it adds a prompt section naming this harness checkout, resolved from the launcher's real path so it holds under a PATH symlink and an arbitrary cwd, so the self-referential `cordis` toolset can read and modify it; - applies the personal overlay from `~/.dsh` (see [app-boot's Personal config](../../packages/ui/app-boot/README.md#personal-config)): `.env` fills environment gaps (ambient > project `.env` > personal `.env`), `config.yaml` patches the booted tree. diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts index 61e99cca44..37e87a1db7 100644 --- a/apps/cli/src/args.ts +++ b/apps/cli/src/args.ts @@ -31,7 +31,10 @@ interface HeadlessInvocation { prompt: string } -/** Browser UI: `dsh web`. Host constrained to {@link LOOPBACK_HOST}/{@link ALL_INTERFACES_HOST}; port already coerced and range-checked; `dev` mounts the client HMR driver and bundle watch. */ +/** + * Browser UI: `dsh web`. Host constrained to {@link LOOPBACK_HOST}/{@link ALL_INTERFACES_HOST}; + * port already coerced and range-checked; `dev` mounts the client HMR driver and bundle watch. + */ interface WebInvocation { mode: 'web' host: string diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 49a0a1510f..dec711cfda 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1665,8 +1665,8 @@ export interface Config { /** * Shell command template the TUI prints on exit and lists under `/resume`, * with `{session}` replaced by the live session id (forwarded to the front - * door). Set it to a command that resumes via this app's env var, e.g. - * `RESUME_SESSION_ID={session} dsh`. + * door). Set it to a command that resumes the session, e.g. + * `dsh --resume {session}`. */ resumeCommand?: string /** Full-screen TUI presentation settings. */ diff --git a/examples/README.md b/examples/README.md index b895259965..cf244eb4ba 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,6 +1,6 @@ # Examples -Runnable demos (not workspaces) that showcase how the harness is wired. Each example is a **thin leaf**: a `cordis.yml` that picks swappable backends, loads one app package, and may add optional product tools. The composition and boot glue live in [`@deepseek-ai/dsh-tui-demo`](../packages/examples/tui-demo), [`@deepseek-ai/dsh-cli-demo`](../packages/examples/cli-demo), [`@deepseek-ai/dsh-acp-demo`](../packages/examples/acp-demo), and their shared [`@deepseek-ai/dsh-agent-spine-demo`](../packages/examples/agent-spine-demo) bundle. There is no `start.ts`; the `demo:*` scripts invoke each app package's bin. +Runnable demos (not workspaces) that showcase how the harness is wired. Each example is a **thin leaf**: a `cordis.yml` that picks swappable backends, loads one app package, and may add optional product tools. The composition and boot glue live in [`@deepseek-ai/dsh-tui-demo`](../packages/examples/tui-demo), [`@deepseek-ai/dsh-cli-demo`](../packages/examples/cli-demo), [`@deepseek-ai/dsh-acp-demo`](../packages/examples/acp-demo), and their shared [`@deepseek-ai/dsh-agent-spine-demo`](../packages/examples/agent-spine-demo) bundle. There is no `start.ts`; the terminal `demo:*` scripts boot through the [`dsh`](../apps/cli/README.md) CLI (which mounts the `tui-demo` bundle), and the headless/ACP scripts invoke the `cli-demo`/`acp-demo` bins. ## headless-agent diff --git a/examples/cordis-agent/tests/keyless-smoke.e2e.ts b/examples/cordis-agent/tests/keyless-smoke.e2e.ts index 6e5cca3b08..c340eea036 100644 --- a/examples/cordis-agent/tests/keyless-smoke.e2e.ts +++ b/examples/cordis-agent/tests/keyless-smoke.e2e.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import { LOADER_SMOKE_TEST_TIMEOUT_MS } from '@deepseek-ai/dsh-loader-smoke' import { runTuiPtySmoke } from '../../tui-agent/tests/pty-harness.ts' -const binScript = fileURLToPath(new URL('../../../packages/examples/tui-demo/src/bin.ts', import.meta.url)) +const binScript = fileURLToPath(new URL('../../../apps/cli/src/bin.ts', import.meta.url)) const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url)) const tsconfigPath = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)) diff --git a/examples/tui-agent/README.md b/examples/tui-agent/README.md index 2e87df0a27..5196de053b 100644 --- a/examples/tui-agent/README.md +++ b/examples/tui-agent/README.md @@ -27,7 +27,7 @@ Each run starts a fresh session by default (its event log lands under `./.sessio dsh --resume ``` -`/resume` opens a searchable keyboard selector with titles, activity, last-turn results, model route, durable goal phase, and live/persisted state. The installed `dsh` host flushes and disposes the current app, then replaces the process with `dsh --resume `. The TUI still prints that command on exit and shows it when a custom host cannot hand off. The flag sets `RESUME_SESSION_ID`, wired through `cordis.yml` (`resumeSessionId: !!js process.env.RESUME_SESSION_ID`); the env var still works directly for the uninstalled demo (`RESUME_SESSION_ID= pnpm run demo:tui`), and with neither set the agent starts a new session. A missing or unreadable id starts no agent and emits `agent-loop/config-start-failed`: the TUI prints the failure and exits nonzero. The selector has no cross-process session lock, so deployments with concurrent hosts must coordinate session ownership separately. +`/resume` opens a searchable keyboard selector with titles, activity, last-turn results, model route, durable goal phase, and live/persisted state. The installed `dsh` host flushes and disposes the current app, then replaces the process with `dsh --resume `. The TUI still prints that command on exit and shows it when a custom host cannot hand off. `dsh --resume ` provides the id on the boot context, which `cordis.yml` reads (`resumeSessionId: !!js "typeof resumeSessionId === 'string' ? resumeSessionId : undefined"`); with no flag the agent starts a new session. A missing or unreadable id starts no agent and emits `agent-loop/config-start-failed`: the TUI prints the failure and exits nonzero. The selector has no cross-process session lock, so deployments with concurrent hosts must coordinate session ownership separately. ## Code Mode diff --git a/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts b/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts index a1366621a0..c464fa2a96 100644 --- a/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts +++ b/examples/tui-agent/tests/tui-keyless-smoke.e2e.ts @@ -8,7 +8,6 @@ import { SessionId, type SessionEvent, type SessionHeader } from '@deepseek-ai/d import { logPath, toHeaderLine } from '../../../packages/session-persistence/session-persistence-jsonl/src/format.ts' import { runTuiPtySmoke, type TuiPtySmokeOptions } from './pty-harness.ts' -const binScript = fileURLToPath(new URL('../../../packages/examples/tui-demo/src/bin.ts', import.meta.url)) const dshBinScript = fileURLToPath(new URL('../../../apps/cli/src/bin.ts', import.meta.url)) const configPath = fileURLToPath(new URL('../cordis.yml', import.meta.url)) const codeModeConfigPath = fileURLToPath(new URL('../code-mode.cordis.yml', import.meta.url)) @@ -87,11 +86,11 @@ async function readLoggedSystemPrompt(cwd: string): Promise { throw new Error(`session log ${logRelPath} has no request/header event`) } -/** Shared defaults: the keyless key, the tui-demo bin, and the live cordis.yml. */ +/** Shared defaults: the keyless key, the dsh bin, and the live cordis.yml (passed as the positional config). */ function smoke(overrides: Partial & { label: string }): Promise { return runTuiPtySmoke({ tempDirPrefix: 'tui-agent-smoke-', - binScript, + binScript: dshBinScript, configPath, tsconfigPath, env: { DEEPSEEK_API_KEY: 'keyless-tui-no-call' }, diff --git a/knip.json b/knip.json index 59658e1df6..da6dc977e6 100644 --- a/knip.json +++ b/knip.json @@ -417,8 +417,7 @@ }, "packages/examples/tui-demo": { "entry": [ - "tests/**/*.spec.ts", - "tests/**/*.e2e.ts" + "tests/**/*.spec.ts" ], "project": [ "src/**/*.ts", diff --git a/package.json b/package.json index 3ff149b80a..3d534c5d39 100644 --- a/package.json +++ b/package.json @@ -92,7 +92,7 @@ "demo:headless": "node --import tsx packages/examples/cli-demo/src/bin.ts --config examples/headless-agent/cordis.yml", "demo:tui": "node --import tsx apps/cli/src/bin.ts", "demo:code-mode": "node scripts/demo-code-mode.mjs", - "demo:cordis": "node --import tsx packages/examples/tui-demo/src/bin.ts examples/cordis-agent/cordis.yml", + "demo:cordis": "node --import tsx apps/cli/src/bin.ts examples/cordis-agent/cordis.yml", "demo:acp": "node --import tsx packages/examples/acp-demo/src/bin.ts --config examples/acp-agent/cordis.yml", "demo:web": "npm run build && npm run build:web && node --import tsx apps/cli/src/bin.ts web", "dev:web": "tsx scripts/dev-web.ts --poll", diff --git a/packages/examples/README.md b/packages/examples/README.md index d247577b44..8c6eaddfc9 100644 --- a/packages/examples/README.md +++ b/packages/examples/README.md @@ -5,12 +5,12 @@ Pre-composed plugin bundles a thin leaf `cordis.yml` loads instead of assembling | Package | npm name | Role | |---|---|---| | `agent-spine-demo/` | `@deepseek-ai/dsh-agent-spine-demo` | The executor-less/UI-less agent spine as one bundle plugin, with fallback session titles and an opt-in persisted-goal stack | -| `tui-demo/` | `@deepseek-ai/dsh-tui-demo` | Full-screen terminal app: the spine + persisted goals + `/goal` command + JSONL persistence + `dsh-tui` + a pre-created `main` agent, with a boot `bin` | +| `tui-demo/` | `@deepseek-ai/dsh-tui-demo` | Full-screen terminal app bundle: the spine + persisted goals + `/goal` command + JSONL persistence + `dsh-tui` + a pre-created `main` agent; no bin, booted by the [`dsh`](../../apps/cli/README.md) CLI | | `cli-demo/` | `@deepseek-ai/dsh-cli-demo` | Headless one-shot app: the spine + JSONL persistence + a pre-created `main` agent, with text and DSH-native JSON output | | `acp-demo/` | `@deepseek-ai/dsh-acp-demo` | ACP server app: the spine + persisted goals + `/goal` command + JSONL persistence + the [`acp`](../ui/acp/README.md) bridge (no stdout logger), with a boot `bin` | | `jsonrpc-demo/` | `@deepseek-ai/dsh-jsonrpc-demo` | Bin-only runtime that boots an external `cordis.yml` for the stdio JSON-RPC SDK client | -`agent-spine-demo` is the shared bundle; `tui-demo`, `cli-demo`, and `acp-demo` compose it with full-screen terminal, headless one-shot, and ACP front doors and own their boot bins. `jsonrpc-demo` mounts no composition of its own — it boots whatever tree the deployment's `cordis.yml` names, and is what the Python SDK runtime launches. +`agent-spine-demo` is the shared bundle; `tui-demo`, `cli-demo`, and `acp-demo` compose it with full-screen terminal, headless one-shot, and ACP front doors. `cli-demo` and `acp-demo` own their boot bins; `tui-demo` ships only the bundle plugin, and the product [`dsh`](../../apps/cli/README.md) CLI is its terminal front door. `jsonrpc-demo` mounts no composition of its own — it boots whatever tree the deployment's `cordis.yml` names, and is what the Python SDK runtime launches. These are **not** product API. The spine pieces they bundle live in [`core/`](../core/README.md), the bridges/channels/boot-glue in [`ui/`](../ui/README.md), and the swappable backends (LLM adapter, bash executor) in their capability groups; a demo bundle just picks one concrete composition of them. Swap or fork one freely. diff --git a/packages/examples/tui-demo/README.md b/packages/examples/tui-demo/README.md index 10ff7872c5..b6c80687a4 100644 --- a/packages/examples/tui-demo/README.md +++ b/packages/examples/tui-demo/README.md @@ -1,8 +1,8 @@ # @deepseek-ai/dsh-tui-demo -The full-screen terminal app: a Cordis plugin that composes [`@deepseek-ai/dsh-agent-spine-demo`](../agent-spine-demo/README.md), persisted same-session goals, the human-command registry and `/goal` producer, JSONL persistence, keyboard-backed user interaction, a pre-created `main` agent, and [`@deepseek-ai/dsh-tui`](../../ui/tui/README.md). Its `bin` boots a leaf `cordis.yml`. +The full-screen terminal app bundle: a Cordis plugin that composes [`@deepseek-ai/dsh-agent-spine-demo`](../agent-spine-demo/README.md), persisted same-session goals, the human-command registry and `/goal` producer, JSONL persistence, keyboard-backed user interaction, a pre-created `main` agent, and [`@deepseek-ai/dsh-tui`](../../ui/tui/README.md). A `cordis.yml` mounts it as one entry; the [`dsh`](../../../apps/cli/README.md) CLI is the front door that boots such a config. -Use [`@deepseek-ai/dsh-cli-demo`](../cli-demo/README.md) for pipes, scripts, and other non-interactive runs. This package requires a TTY pair and has no line-oriented fallback. +Use [`@deepseek-ai/dsh-cli-demo`](../cli-demo/README.md) for pipes, scripts, and other non-interactive runs. This bundle requires a TTY pair and has no line-oriented fallback. ## What it bakes in @@ -47,9 +47,9 @@ Swappable LLM, bash, filesystem, and other capability providers remain in the le Fresh runs mint a `main-session-` session id and pass it to both the TUI and configured agent. Resumed runs bind both components to `resumeSessionId`. The TUI mounts before the spine so it can render a matching config-start failure instead of leaving a blank terminal. The app composes persistence and session query for `/resume`; an embedding host may additionally provide `tuiResumeHost` for in-place process handoff. -## The bin +## Front door -`dsh-tui-demo [path-to-cordis.yml]` defaults to `./cordis.yml`, loads the optional cwd `.env`, boots the Cordis Loader, and waits for the full plugin tree. The repository installs Loader's optional native helper, so bare package specifiers resolve under plain Node. +This package ships no bin. The [`dsh`](../../../apps/cli/README.md) CLI is the terminal front door: `dsh [path-to-cordis.yml]` boots a leaf config that mounts this bundle (defaulting to the shipped `examples/tui-agent/cordis.yml`), loads the optional cwd `.env`, drives the Cordis Loader, and waits for the full plugin tree. The repository installs Loader's optional native helper, so bare package specifiers resolve under plain Node. ## Example leaf diff --git a/packages/examples/tui-demo/package.json b/packages/examples/tui-demo/package.json index 1ddf5060b1..26e3e64183 100644 --- a/packages/examples/tui-demo/package.json +++ b/packages/examples/tui-demo/package.json @@ -1,14 +1,11 @@ { "name": "@deepseek-ai/dsh-tui-demo", - "description": "Full-screen terminal app: agent spine + persisted goals + human commands + JSONL persistence + pi-tui front door + pre-created main agent", + "description": "Full-screen TUI app bundle plugin: agent spine + persisted goals + human commands + JSONL persistence + pi-tui front door + pre-created main agent (mounted by the dsh CLI's config)", "version": "0.0.1", "private": true, "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", - "bin": { - "dsh-tui-demo": "lib/bin.js" - }, "exports": { ".": { "types": "./lib/types/index.d.ts", @@ -18,17 +15,12 @@ "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" }, - "./bin": { - "types": "./lib/types/bin.d.ts", - "default": "./lib/bin.js" - }, "./src/*": "./src/*", "./package.json": "./package.json" }, "files": [ "lib/index.js", "lib/invariant.js", - "lib/bin.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" @@ -37,7 +29,6 @@ "peerDependencies": { "@cordisjs/plugin-include": "^1.0.4", "@cordisjs/plugin-loader": "^1.0.0-rc.5", - "@deepseek-ai/dsh-app-boot": "^0.0.1", "@deepseek-ai/dsh-agent": "^0.0.1", "@deepseek-ai/dsh-agent-loop": "^0.0.1", "@deepseek-ai/dsh-commands": "^0.0.1", @@ -62,7 +53,6 @@ "devDependencies": { "@cordisjs/plugin-include": "workspace:^", "@cordisjs/plugin-loader": "workspace:^", - "@deepseek-ai/dsh-app-boot": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", diff --git a/packages/examples/tui-demo/src/bin.ts b/packages/examples/tui-demo/src/bin.ts deleted file mode 100644 index 5073e203df..0000000000 --- a/packages/examples/tui-demo/src/bin.ts +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env node -/** - * Boot a TUI app from a leaf `cordis.yml`; usage is `dsh-tui-demo [config]`, defaulting to the - * cwd file. Shared `.env` loading, fail-loud Loader guards, and settled-tree boot live in - * dsh-app-boot. The tui-agent and cordis-agent demos invoke this bin with their own leaf configs. - * @module @deepseek-ai/dsh-tui-demo/bin - */ - -import { boot, installFailLoud, loadEnv, resolveConfigPath } from '@deepseek-ai/dsh-app-boot' - -const NAME = 'dsh-tui-demo' - -/* v8 ignore start -- thin self-executing composition over the unit-tested - dsh-app-boot helpers; exercised end-to-end by the tui-agent PTY smoke and - the built-bin fail-loud smoke */ -// Refuse pipes BEFORE booting: a compose-time throw inside the Loader tree is -// logged per-entry rather than rethrown, so a piped launch would otherwise -// settle into an idle UI-less process instead of exiting nonzero. -if (!process.stdin.isTTY || !process.stdout.isTTY) { - process.stderr.write(`${NAME}: the TUI requires stdin and stdout to be interactive TTYs; ` - + 'use the one-shot dsh-cli-demo bin for pipes and automation\n') - process.exit(1) -} -installFailLoud(NAME) -loadEnv(NAME) -await boot(NAME, resolveConfigPath(process.argv[2] ?? './cordis.yml', undefined)) -/* v8 ignore stop */ diff --git a/packages/examples/tui-demo/src/index.ts b/packages/examples/tui-demo/src/index.ts index 29f985c8e7..8a88859ab3 100644 --- a/packages/examples/tui-demo/src/index.ts +++ b/packages/examples/tui-demo/src/index.ts @@ -64,8 +64,8 @@ export interface Config { /** * Shell command template the TUI prints on exit and lists under `/resume`, * with `{session}` replaced by the live session id (forwarded to the front - * door). Set it to a command that resumes via this app's env var, e.g. - * `RESUME_SESSION_ID={session} dsh`. + * door). Set it to a command that resumes the session, e.g. + * `dsh --resume {session}`. */ resumeCommand?: string /** Full-screen TUI presentation settings. */ diff --git a/packages/examples/tui-demo/tests/built-bin.e2e.ts b/packages/examples/tui-demo/tests/built-bin.e2e.ts deleted file mode 100644 index 6a793bf104..0000000000 --- a/packages/examples/tui-demo/tests/built-bin.e2e.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { spawn } from 'node:child_process' -import { existsSync } from 'node:fs' -import { mkdtemp, mkdir, rm, symlink, readFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' -import { afterEach, describe, expect, it } from 'vitest' - -/** - * Published-entry smoke: run `lib/bin.js` under plain Node in a symlinked external consumer. - * The TUI app owns no non-TTY fallback, so the piped subprocess must refuse to boot with a - * nonzero exit and a stderr pointer at the one-shot CLI — the bin guards BEFORE the Loader - * because a compose-time throw inside the tree is logged per-entry, not rethrown. The consumer - * links only the bin's import chain (dsh-app-boot and its vendored Loader stack): the refusal - * fires before any config is read, so no plugin tree is needed. Missing-config fail-loud and - * full-boot coverage for the shared dsh-app-boot glue live in cli-demo's built-bin suite; it - * skips before build, and interactive TTY behavior is PTY-covered by examples/tui-agent (the - * one sanctioned PTY surface). - */ - -const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url)) -const tuiBin = join(repoRoot, 'packages/examples/tui-demo/lib/bin.js') - -// Symlink each package the bin imports at module load by package name so plain -// Node resolves its built `main`, matching an installed dependency rather than -// tsconfig paths. -const dshPackages = ['examples/tui-demo', 'ui/app-boot'] -const vendorPackages = ['cordis', 'loader', 'include', 'schemastery', 'cosmokit'] - -async function pkgName(absDir: string): Promise { - const json = JSON.parse(await readFile(join(absDir, 'package.json'), 'utf8')) as { name: string } - return json.name -} - -/** Build a temporary external consumer with built workspace/vendor links. */ -async function makeConsumer(): Promise { - const dir = await mkdtemp(join(tmpdir(), 'tui-built-bin-')) - const nm = join(dir, 'node_modules') - for (const rel of dshPackages) { - const abs = join(repoRoot, 'packages', rel) - const target = join(nm, await pkgName(abs)) - await mkdir(dirname(target), { recursive: true }) - await symlink(abs, target) - } - for (const v of vendorPackages) { - const abs = join(repoRoot, 'vendor', v) - const target = join(nm, await pkgName(abs)) - await mkdir(dirname(target), { recursive: true }) - await symlink(abs, target) - } - return dir -} - -/** Run the built bin in `cwd` with PIPED stdio; resolve with output + exit code. */ -function runBuiltBin(cwd: string): Promise<{ stdout: string; code: number; stderr: string }> { - return new Promise((resolve, reject) => { - // NO tsx — this is the published `node lib/bin.js` path; the guard fires - // before the Loader resolves the config tree. - const child = spawn(process.execPath, [tuiBin, './cordis.yml'], { - cwd, - env: { ...process.env, DSH_HOME: join(cwd, '.dsh'), DSH_AGENTS_HOME: join(cwd, '.agents') }, - stdio: ['pipe', 'pipe', 'pipe'], - }) - let stdout = '' - let stderr = '' - child.stdout.setEncoding('utf8') - child.stdout.on('data', (c: string) => { stdout += c }) - child.stderr.setEncoding('utf8') - child.stderr.on('data', (c: string) => { stderr += c }) - const timer = setTimeout(() => { - child.kill('SIGKILL') - reject(new Error(`built bin did not exit within 25s. stdout:\n${stdout}\nstderr:\n${stderr}`)) - }, 25_000) - child.on('exit', (code) => { clearTimeout(timer); resolve({ stdout, code: code ?? -1, stderr }) }) - child.on('error', (err) => { clearTimeout(timer); reject(err) }) - child.stdin.end() - }) -} - -let consumer: string | undefined - -afterEach(async () => { - // Windows can briefly retain released handles after exit; retry removal. - if (consumer !== undefined) await rm(consumer, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) - consumer = undefined -}) - -describe.skipIf(!existsSync(tuiBin))('dsh-tui-demo BUILT bin (node lib/bin.js, no tsx)', () => { - it('refuses pipes LOUD (non-zero exit + stderr) before booting the Loader', async () => { - consumer = await makeConsumer() - const { stdout, code, stderr } = await runBuiltBin(consumer) - expect(code).not.toBe(0) - expect(stderr).toContain('requires stdin and stdout to be interactive TTYs') - expect(stderr).toContain('dsh-cli-demo') - // The refusal happens before any plugin mounts: stdout stays silent. - expect(stdout).toBe('') - }, 30_000) -}) diff --git a/packages/examples/tui-demo/tsdown.config.ts b/packages/examples/tui-demo/tsdown.config.ts index 06efc0b4db..1033dc08df 100644 --- a/packages/examples/tui-demo/tsdown.config.ts +++ b/packages/examples/tui-demo/tsdown.config.ts @@ -1,14 +1,14 @@ import { defineConfig } from 'tsdown' /** - * tui-demo ships two entries: the plugin (`index`) and the CLI `bin` - * (`bin`), the latter referenced by package.json `bin`/`exports["./bin"]`. - * The root tsdown builds only `lib/types/index.js`, so this override adds - * `lib/types/bin.js`. Declarations come from `tsc -b` (dts: false), - * matching every package. + * tui-demo ships the plugin (`index`) and its invariant companion; the CLI + * front door is `dsh` (apps/cli), which mounts this bundle through its config. + * The root tsdown builds only `lib/types/index.js`, so this override adds the + * invariant entry. Declarations come from `tsc -b` (dts: false), matching + * every package. */ export default defineConfig({ - entry: ['lib/types/index.js', 'lib/types/invariant.js', 'lib/types/bin.js'], + entry: ['lib/types/index.js', 'lib/types/invariant.js'], outDir: 'lib', format: ['esm'], platform: 'node', diff --git a/packages/support/loader-smoke/tests/example-launch.spec.ts b/packages/support/loader-smoke/tests/example-launch.spec.ts index 8033645d53..8cf75d3be9 100644 --- a/packages/support/loader-smoke/tests/example-launch.spec.ts +++ b/packages/support/loader-smoke/tests/example-launch.spec.ts @@ -5,7 +5,7 @@ import { resolveExampleMode, } from '@deepseek-ai/dsh-loader-smoke' -const SRC_BIN = '/repo/packages/examples/tui-demo/src/bin.ts' +const SRC_BIN = '/repo/packages/examples/cli-demo/src/bin.ts' const TSCONFIG = '/repo/tsconfig.json' const originalMode = process.env[EXAMPLE_MODE_ENV] @@ -65,7 +65,7 @@ describe('resolveExampleLaunch', () => { env: { DSH_HOME: '/tmp/home' }, }) expect(args).not.toContain('--import') - expect(args).toContain('/repo/packages/examples/tui-demo/lib/bin.js') + expect(args).toContain('/repo/packages/examples/cli-demo/lib/bin.js') expect(args.slice(-2)).toEqual(['--config', './cordis.yml']) expect(env.TSX_TSCONFIG_PATH).toBeUndefined() expect(env.DSH_HOME).toBe('/tmp/home') @@ -100,6 +100,6 @@ describe('resolveExampleLaunch', () => { it('defaults the mode from the environment', () => { process.env[EXAMPLE_MODE_ENV] = 'lib' const { args } = resolveExampleLaunch({ srcBin: SRC_BIN }) - expect(args).toContain('/repo/packages/examples/tui-demo/lib/bin.js') + expect(args).toContain('/repo/packages/examples/cli-demo/lib/bin.js') }) }) diff --git a/packages/ui/app-boot/README.md b/packages/ui/app-boot/README.md index da44317c94..efc5575950 100644 --- a/packages/ui/app-boot/README.md +++ b/packages/ui/app-boot/README.md @@ -1,6 +1,6 @@ # `@deepseek-ai/dsh-app-boot` -Shared boot glue for the app bins ([`dsh-tui-demo`](../../examples/tui-demo/README.md), [`dsh-cli-demo`](../../examples/cli-demo/README.md), [`dsh-acp-demo`](../../examples/acp-demo/README.md)): each bin is a thin self-executing composition over these helpers, parameterized by its diagnostic prefix, so the loader-failure lore lives once — under the per-file coverage gate — instead of drifting between published artifacts. +Shared boot glue for the app bins ([`dsh`](../../../apps/cli/README.md), [`dsh-cli-demo`](../../examples/cli-demo/README.md), [`dsh-acp-demo`](../../examples/acp-demo/README.md)): each bin is a thin self-executing composition over these helpers, parameterized by its diagnostic prefix, so the loader-failure lore lives once — under the per-file coverage gate — instead of drifting between published artifacts. | Export | Role | |---|---| diff --git a/packages/ui/tui/tests/tui.snapshot.ts b/packages/ui/tui/tests/tui.snapshot.ts index d837841286..82830a5ca0 100644 --- a/packages/ui/tui/tests/tui.snapshot.ts +++ b/packages/ui/tui/tests/tui.snapshot.ts @@ -650,7 +650,7 @@ describe('TUI terminal-state snapshots', () => { const dateNow = vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2026-07-23T08:00:00.000Z')) const earlier = { version: 0, id: SessionId('earlier-session'), createdAt: Date.parse('2024-01-01T00:00:00Z'), cwd: '/workspace/project' } const harness = await setupSnapshot({ - config: { resumeCommand: 'RESUME_SESSION_ID={session} dsh' }, + config: { resumeCommand: 'dsh --resume {session}' }, sessionPersistence: { list: async () => [earlier], load: async () => ({ diff --git a/packages/ui/tui/tests/tui.spec.ts b/packages/ui/tui/tests/tui.spec.ts index 0fea8b2750..a1d9848678 100644 --- a/packages/ui/tui/tests/tui.spec.ts +++ b/packages/ui/tui/tests/tui.spec.ts @@ -206,7 +206,7 @@ describe('TUI config', () => { }) describe('resume command and /resume', () => { - const RESUME = 'RESUME_SESSION_ID={session} dsh' + const RESUME = 'dsh --resume {session}' const header = (id: string, createdAt: number, cwd: string): SessionHeader => ({ version: 0, id: SessionId(id), createdAt, cwd }) const resumeEvents = ( @@ -234,7 +234,7 @@ describe('resume command and /resume', () => { result.terminal.send('/exit') result.terminal.send('\r') await tick() - expect(result.terminal.output).toContain('To resume this session: RESUME_SESSION_ID=main-session dsh') + expect(result.terminal.output).toContain('To resume this session: dsh --resume main-session') expect(result.exit).toHaveBeenCalledWith(0) await dispose(result) }) @@ -1000,7 +1000,7 @@ describe('resume command and /resume', () => { result.terminal.send('\r') await tick() expect(result.terminal.output).toContain('This host cannot hand off in place. Exit and run:') - expect(result.terminal.output).toContain('RESUME_SESSION_ID=fallback-session') + expect(result.terminal.output).toContain('dsh --resume fallback-session') expect(result.terminal.stopped).toBe(0) await dispose(result) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 15baee1425..0cccc15282 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1554,9 +1554,6 @@ importers: '@deepseek-ai/dsh-agent-spine-demo': specifier: workspace:^ version: link:../agent-spine-demo - '@deepseek-ai/dsh-app-boot': - specifier: workspace:^ - version: link:../../ui/app-boot '@deepseek-ai/dsh-command-goal': specifier: workspace:^ version: link:../../goal/command-goal diff --git a/scripts/demo-code-mode.mjs b/scripts/demo-code-mode.mjs index c3e7849a6b..7b06b859f2 100644 --- a/scripts/demo-code-mode.mjs +++ b/scripts/demo-code-mode.mjs @@ -7,7 +7,7 @@ import { spawn } from 'node:child_process' // Each UI's node invocation matches its base demo script plus the overlay config. const UIS = new Map([ - ['tui', ['--import', 'tsx', 'packages/examples/tui-demo/src/bin.ts', 'examples/tui-agent/code-mode.cordis.yml']], + ['tui', ['--import', 'tsx', 'apps/cli/src/bin.ts', 'examples/tui-agent/code-mode.cordis.yml']], ['acp', ['--import', 'tsx', 'packages/examples/acp-demo/src/bin.ts', '--config', 'examples/acp-agent/code-mode.cordis.yml']], ]) From 0901140b3fa6cd6206a67c29f55091ed1962b49f Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 25 Jul 2026 13:01:45 +0800 Subject: [PATCH 037/113] test(cli): cover the dsh built-bin non-TTY refusal Removing the dsh-tui-demo bin dropped the only test of the TUI's piped-launch refusal. Add apps/cli/tests/built-bin.e2e.ts (apps/*/tests added to the e2e vitest include) running the built lib/bin.js under plain Node with piped stdio, and point the refusal message at `dsh -p "task"` for automation. --- ...4-dsh-commander-argument-adapter.i18n.yaml | 4 +- ...26-07-24-dsh-commander-argument-adapter.md | 2 +- ...07-24-dsh-commander-argument-adapter.zh.md | 2 +- apps/cli/src/tui.ts | 4 +- apps/cli/tests/built-bin.e2e.ts | 54 +++++++++++++++++++ vitest.e2e.config.ts | 2 +- 6 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 apps/cli/tests/built-bin.e2e.ts diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml index 1780a5f57e..3a85dedb0d 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.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 -2026-07-24-dsh-commander-argument-adapter.md: 60c47ef40cb0db833f7a2a526437b6a8ce812433 -2026-07-24-dsh-commander-argument-adapter.zh.md: 41a98499036c16330263d5072aa0fa454b892a24 +2026-07-24-dsh-commander-argument-adapter.md: c038f4facdc62039b8a31be5d660648fd81aebd2 +2026-07-24-dsh-commander-argument-adapter.zh.md: 285917af7c4b0da769ae7595bb1a6e5966adafd9 diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md index 60c47ef40c..c038f4facd 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.md @@ -22,7 +22,7 @@ Merging the concurrent safe-session-resume feature onto this parser retired the ## One terminal front door: `dsh` -The `dsh-tui-demo` package was a plugin (the TUI app bundle mounted by `dsh`'s config) plus a redundant `bin` that booted a leaf `cordis.yml` — the same job `dsh [config]` does. The bin is removed: `demo:cordis`, `demo:code-mode`, and both the tui-agent and cordis-agent keyless PTY smokes now launch through `apps/cli/src/bin.ts` with the config as the positional argument, and the package keeps only its plugin and invariant entries. The peer/dev `dsh-app-boot` dependency, the `bin`/`./bin` export, the `built-bin.e2e.ts` (its TUI piped-launch refusal is covered by `dsh`'s own TTY guard in the tui-agent PTY smoke), and the tsdown `bin` entry all leave with it. `cli-demo`, `acp-demo`, and `jsonrpc-demo` keep their bins because each is a distinct surface (headless, ACP, JSON-RPC) `dsh` does not provide. +The `dsh-tui-demo` package was a plugin (the TUI app bundle mounted by `dsh`'s config) plus a redundant `bin` that booted a leaf `cordis.yml` — the same job `dsh [config]` does. The bin is removed: `demo:cordis`, `demo:code-mode`, and both the tui-agent and cordis-agent keyless PTY smokes now launch through `apps/cli/src/bin.ts` with the config as the positional argument, and the package keeps only its plugin and invariant entries. The peer/dev `dsh-app-boot` dependency, the `bin`/`./bin` export, the demo's `built-bin.e2e.ts`, and the tsdown `bin` entry all leave with it. `dsh`'s own TTY guard (refuse piped stdio before booting, pointing at `dsh -p` for automation) gains a matching `apps/cli/tests/built-bin.e2e.ts` that runs the built `lib/bin.js` under plain Node with piped stdio (`apps/*/tests` added to the e2e vitest include). `cli-demo`, `acp-demo`, and `jsonrpc-demo` keep their bins because each is a distinct surface (headless, ACP, JSON-RPC) `dsh` does not provide. ## Package topology diff --git a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md index 41a9849903..285917af7c 100644 --- a/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-24-dsh-commander-argument-adapter.zh.md @@ -22,7 +22,7 @@ argv 只在 `apps/cli/src/args.ts` 中解析一次,通过一个 Commander 适 ## 唯一的终端入口:`dsh` -`dsh-tui-demo` 包(package)原本包含一个插件(即 `dsh` 配置挂载的 TUI 应用组合)和一个冗余的 `bin`;后者启动一份叶子配置 `cordis.yml`,所做的工作与 `dsh [config]` 相同。该 bin 已移除:`demo:cordis`、`demo:code-mode` 以及 tui-agent 和 cordis-agent 的两个无密钥 PTY 冒烟测试现在都通过 `apps/cli/src/bin.ts` 启动,并将配置作为位置参数;该包只保留插件入口和不变式入口。与该 bin 一同移除的还有对 `dsh-app-boot` 的对等依赖(peer dependency)和开发依赖、`bin` 和 `./bin` 导出、`built-bin.e2e.ts`(其中拒绝通过管道启动 TUI 的行为已由 tui-agent PTY 冒烟测试中 `dsh` 自身的 TTY 守卫覆盖),以及 tsdown 的 `bin` 入口。`cli-demo`、`acp-demo` 和 `jsonrpc-demo` 保留各自的 bin,因为它们分别提供 `dsh` 所没有的独立接口(headless、ACP(Agent Client Protocol)、JSON-RPC)。 +`dsh-tui-demo` 包(package)原本包含一个插件(即 `dsh` 配置挂载的 TUI 应用组合)和一个冗余的 `bin`;后者启动一份叶子配置 `cordis.yml`,所做的工作与 `dsh [config]` 相同。该 bin 已移除:`demo:cordis`、`demo:code-mode` 以及 tui-agent 和 cordis-agent 的两个无密钥 PTY 冒烟测试现在都通过 `apps/cli/src/bin.ts` 启动,并将配置作为位置参数;该包只保留插件入口和不变式入口。与该 bin 一同移除的还有对 `dsh-app-boot` 的对等依赖(peer dependency)和开发依赖、`bin` 和 `./bin` 导出、演示包的 `built-bin.e2e.ts`,以及 tsdown 的 `bin` 入口。`dsh` 自身的 TTY 守卫会在标准输入输出接入管道时,于启动应用前拒绝运行,并提示自动化场景改用 `dsh -p`;为此新增的 `apps/cli/tests/built-bin.e2e.ts` 将标准输入输出接入管道,直接使用 Node 运行构建后的 `lib/bin.js`(`apps/*/tests` 已加入 e2e Vitest 的测试文件匹配范围)。`cli-demo`、`acp-demo` 和 `jsonrpc-demo` 保留各自的 bin,因为它们分别提供 `dsh` 所没有的独立接口(headless、ACP(Agent Client Protocol)、JSON-RPC)。 ## 包拓扑 diff --git a/apps/cli/src/tui.ts b/apps/cli/src/tui.ts index 819cb22e42..6ddad89302 100644 --- a/apps/cli/src/tui.ts +++ b/apps/cli/src/tui.ts @@ -53,7 +53,9 @@ export async function runTui(config: string | undefined, resumeSessionId: string // is logged per-entry rather than rethrown, so a piped launch would // otherwise settle into an idle UI-less process instead of exiting nonzero. if (!process.stdin.isTTY || !process.stdout.isTTY) { - process.stderr.write(`${NAME}: the TUI requires stdin and stdout to be interactive TTYs\n`) + process.stderr.write( + `${NAME}: the TUI requires stdin and stdout to be interactive TTYs; use \`${NAME} -p "task"\` for pipes and automation\n`, + ) process.exit(1) } installFailLoud(NAME) diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts new file mode 100644 index 0000000000..6a77e8919d --- /dev/null +++ b/apps/cli/tests/built-bin.e2e.ts @@ -0,0 +1,54 @@ +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +/** + * Published-entry smoke for the `dsh` bin: run the built `lib/bin.js` under + * plain Node (no tsx) with PIPED stdio and assert the TUI refuses to boot. + * `dsh` is the sole terminal front door; the TUI owns no non-TTY fallback, so a + * piped launch must exit nonzero with a stderr pointer at the one-shot `-p` + * mode. The guard fires inside `runTui` BEFORE the Loader resolves the config + * tree — a compose-time throw inside the tree is logged per-entry, not + * rethrown, so without this guard a piped launch would settle into an idle + * UI-less process. The bin resolves its workspace deps through the repo's + * node_modules, so no external consumer is assembled; missing-config fail-loud + * and full-boot coverage for the shared dsh-app-boot glue live in cli-demo's + * built-bin suite, and interactive TTY behavior is PTY-covered by + * examples/tui-agent. Skips before the bin is built. + */ + +const repoRoot = fileURLToPath(new URL('../../../', import.meta.url)) +const dshBin = join(repoRoot, 'apps/cli/lib/bin.js') + +/** Run the built bin with PIPED stdio; resolve with output + exit code. */ +function runBuiltBin(): Promise<{ stdout: string; code: number; stderr: string }> { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [dshBin], { stdio: ['pipe', 'pipe', 'pipe'] }) + let stdout = '' + let stderr = '' + child.stdout.setEncoding('utf8') + child.stdout.on('data', (c: string) => { stdout += c }) + child.stderr.setEncoding('utf8') + child.stderr.on('data', (c: string) => { stderr += c }) + const timer = setTimeout(() => { + child.kill('SIGKILL') + reject(new Error(`dsh built bin did not exit within 25s. stdout:\n${stdout}\nstderr:\n${stderr}`)) + }, 25_000) + child.on('exit', (code) => { clearTimeout(timer); resolve({ stdout, code: code ?? -1, stderr }) }) + child.on('error', (err) => { clearTimeout(timer); reject(err) }) + child.stdin.end() + }) +} + +describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', () => { + it('refuses pipes LOUD (non-zero exit + stderr) before booting the Loader', async () => { + const { stdout, code, stderr } = await runBuiltBin() + expect(code).not.toBe(0) + expect(stderr).toContain('requires stdin and stdout to be interactive TTYs') + expect(stderr).toContain('dsh -p') + // The refusal happens before any plugin mounts: stdout stays silent. + expect(stdout).toBe('') + }, 30_000) +}) diff --git a/vitest.e2e.config.ts b/vitest.e2e.config.ts index 2e2221b6e8..e8ca907439 100644 --- a/vitest.e2e.config.ts +++ b/vitest.e2e.config.ts @@ -38,7 +38,7 @@ export default defineConfig({ plugins: [tsconfigPaths({ projects: ['./tsconfig.base.json'] })], test: { setupFiles: ['./scripts/test-invariants.ts'], - include: ['packages/*/*/tests/**/*.e2e.ts', 'examples/*/tests/**/*.e2e.ts'], + include: ['packages/*/*/tests/**/*.e2e.ts', 'apps/*/tests/**/*.e2e.ts', 'examples/*/tests/**/*.e2e.ts'], // Real model calls: generous timeouts, and retries for transient flakes // (the shared internal key hits concurrency quotas). No coverage — the // unit suites own the coverage gate. From fac6c35e9a54ef20a2f4d185ca6cbb43a2a0188b Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 25 Jul 2026 13:02:37 +0800 Subject: [PATCH 038/113] Trim redundant source comments --- apps/web/src/node-module-stub.ts | 8 +- apps/web/tests/smoke-real.e2e.ts | 6 +- docs/config-catalog.md | 20 ++-- docs/core-data-structures/subagent.i18n.yaml | 4 +- docs/core-data-structures/subagent.md | 37 ++------ docs/core-data-structures/subagent.zh.md | 37 ++------ examples/acp-agent/tests/acp.e2e.ts | 3 +- examples/acp-agent/tests/hooks.e2e.ts | 2 +- .../client/connection/src/client/index.ts | 14 +-- packages/client/connection/src/index.ts | 8 +- packages/client/i18n/src/client/index.ts | 13 +-- packages/client/i18n/src/index.ts | 9 +- .../runtime/src/client/contract/store.ts | 6 +- packages/client/runtime/src/client/index.ts | 38 ++------ .../src/client/sessions/fold-adapter.ts | 8 +- .../runtime/src/client/sessions/service.ts | 3 +- .../runtime/src/client/sessions/session.ts | 23 ++--- packages/client/runtime/src/index.ts | 9 +- .../runtime/tests/sessions-service.spec.ts | 3 +- .../ui-conversation/src/client/apply.ts | 27 +----- .../src/client/chat/StatsLine.tsx | 7 +- .../src/client/contract/slots.ts | 26 +---- .../src/client/contract/views.ts | 19 +--- .../ui-conversation/src/client/index.ts | 11 +-- .../ui-conversation/src/client/service.ts | 14 +-- .../src/client/skeleton/InputBar.tsx | 13 +-- .../ui-conversation/src/client/stores.ts | 27 +----- packages/client/ui-conversation/src/index.ts | 10 +- .../tests/apply-inject.spec.tsx | 1 - .../ui-conversation/tests/chat-store.spec.ts | 7 +- .../tests/chat-toolview-slot.spec.tsx | 2 - .../ui-conversation/tests/chat-view.spec.tsx | 2 +- .../tests/gate-branch-tails.spec.tsx | 5 - packages/client/ui-conversation/tests/hook.ts | 10 +- .../tests/selection-survival.spec.ts | 13 +-- packages/client/ui-layout/src/index.ts | 10 +- .../client/ui-layout/tests/app-frame.spec.tsx | 2 +- packages/client/ui-primitives/src/index.ts | 4 +- .../ui-question/tests/browser-plugin.spec.ts | 4 +- .../ui-sidebar/src/client/SidebarRoot.tsx | 14 +-- .../client/ui-sidebar/src/client/index.ts | 21 +--- packages/client/ui-sidebar/src/client/tree.ts | 9 +- packages/client/ui-sidebar/src/index.ts | 10 +- .../client/ui-sidebar/tests/apply.spec.tsx | 3 +- .../ui-sidebar/tests/sidebar-root.spec.tsx | 3 +- packages/client/ui-slots/src/index.ts | 13 +-- packages/client/ui-slots/src/renderer.ts | 12 +-- packages/client/ui-slots/src/store.ts | 16 +--- packages/client/ui-theme/src/client/index.ts | 8 +- packages/client/ui-theme/src/index.ts | 9 +- .../client/ui-trajectory/src/client/index.ts | 10 +- packages/client/ui-trajectory/src/index.ts | 10 +- .../client/ui-trajectory/tests/views.spec.tsx | 3 +- packages/client/web-react/src/index.ts | 13 +-- .../client/web-react/src/scoped-slots.tsx | 19 +--- .../client/web-react/src/session-provider.tsx | 21 ++-- packages/client/web-react/tests/bind.spec.tsx | 6 +- .../tests/stale-authorization.spec.tsx | 6 +- packages/client/web/src/app-shell.ts | 19 +--- packages/client/web/src/platform.ts | 8 +- packages/core/agent-loop/tests/agent.spec.ts | 9 +- packages/core/agent-loop/tests/cancel.spec.ts | 2 - .../tests/contract-regressions.spec.ts | 2 - packages/core/session/tests/surface.spec.ts | 4 - packages/core/tools/tests/tools.spec.ts | 3 - packages/fs/fs-local/src/fsio.ts | 4 +- packages/fs/tool-fs/tests/fs-tools.e2e.ts | 11 +-- .../tests/repeat-tool-guard.spec.ts | 3 +- .../hooks-claude/tests/coverage-cases.ts | 5 - .../host/webserver/tests/web-plugins.spec.ts | 1 - packages/mcp/mcp-client/src/index.ts | 18 ++-- packages/mcp/mcp-client/tests/apply.spec.ts | 2 - .../mcp/mcp-client/tests/mcp-client.e2e.ts | 5 +- .../mcp/mcp-client/tests/mcp-client.spec.ts | 1 - .../subagent-acp/tests/subagent-acp.e2e.ts | 2 +- .../subagent-spawn/tests/spawn.e2e.ts | 11 +-- packages/subagent/subagent/src/types.ts | 43 +++------ packages/ui/acp/src/index.ts | 95 ++++--------------- packages/ui/acp/tests/bridge.spec.ts | 5 - packages/ui/acp/tests/config-options.spec.ts | 2 +- packages/ui/acp/tests/dispose.spec.ts | 29 +----- packages/ui/acp/tests/properties.spec.ts | 7 +- packages/ui/tui/tests/tui.spec.ts | 5 +- 83 files changed, 219 insertions(+), 748 deletions(-) diff --git a/apps/web/src/node-module-stub.ts b/apps/web/src/node-module-stub.ts index c64f307f7c..0a9b04ea5f 100644 --- a/apps/web/src/node-module-stub.ts +++ b/apps/web/src/node-module-stub.ts @@ -1,10 +1,6 @@ /** - * Browser stand-in for `node:module`, mapped by the vite alias in - * vite.config.ts (design §2.4). The vendored Loader's internal.ts imports - * `createRequire` at module scope but only calls it inside - * `ModuleLoader.fromInternal()`, whose version probe is compiled to the - * `"0.0.0"` define in the browser build — so this throw is a fail-loud - * tripwire for any path that would genuinely need Node's module machinery. + * Browser stand-in for `node:module`. `createRequire` is unreachable in the + * configured loader path and fails loud if that assumption changes. */ /** Throwing stand-in for node:module's createRequire (never reached in the browser boot). */ diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index 9cd34530be..a3d511df16 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -333,10 +333,8 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY || notReady.length > 0)('web smoke const prompt = `Please answer this request carefully: explain event sourcing in two sentences, ending with exactly ${ROUND_DONE_MARKER}.` await input.fill(prompt) await input.press('Enter') - // startSession chain: session mounts, composer moves to the bottom. - // Regression pin (P0, 585671106): this send used to white-screen the tree - // (scope tag lost to a duplicate inlined runtime instance) — body going - // near-empty here means that class of bug is back. + // The first send must keep the session tree mounted; a near-empty body + // reveals a duplicate runtime bundle with incompatible scope tags. await page.waitForFunction(() => document.body.innerText.length > 50, undefined, { timeout: 15_000 }) expect(pageErrors).toEqual([]) await page.waitForFunction( diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 49a0a1510f..e2d434d532 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -27,7 +27,7 @@ export interface AcpConfig { Depends on: `Stream` (`@agentclientprotocol/sdk`) -Source: [`packages/ui/acp/src/index.ts:285`](../packages/ui/acp/src/index.ts) +Source: [`packages/ui/acp/src/index.ts:275`](../packages/ui/acp/src/index.ts) ## `@deepseek-ai/dsh-acp-demo` @@ -710,12 +710,12 @@ Source: [`packages/lsp/lsp-local/src/index.ts:85`](../packages/lsp/lsp-local/src Requires: `tools` ```ts config-catalog -/** Discriminated union of all supported MCP transport configurations. */ +/** Configuration for one stdio or Streamable HTTP MCP server. */ export type Config = StdioConfig | StreamableHttpConfig /** Config for connecting to an MCP server via a spawned child process over stdio. */ export interface StdioConfig { - /** Transport type: spawn a child process and communicate over stdio. */ + /** Selects child-process stdio transport. */ transport: 'stdio' /** * Stable local namespace for this server's model-facing tool names @@ -723,21 +723,21 @@ export interface StdioConfig { * unique across live mcp-client instances. */ serverName: string - /** Executable to spawn. */ + /** Executable used to start the server. */ command: string - /** Arguments passed to the command. */ + /** Arguments passed directly, without shell interpolation. */ args: string[] /** Extra env vars merged on top of scrubbed ambient env. */ env: Record /** Working directory for the child process. */ cwd: string - /** Timeout per callTool invocation (ms). */ + /** Per-tool-call timeout in milliseconds. */ toolCallTimeoutMs: number } /** Config for connecting to an MCP server over Streamable HTTP (SSE). */ export interface StreamableHttpConfig { - /** Transport type: connect to an MCP server over Streamable HTTP (SSE). */ + /** Selects Streamable HTTP transport. */ transport: 'streamable-http' /** * Stable local namespace for this server's model-facing tool names @@ -745,11 +745,11 @@ export interface StreamableHttpConfig { * unique across live mcp-client instances. */ serverName: string - /** MCP server URL. */ + /** MCP endpoint URL. */ url: string - /** Extra headers (e.g. auth tokens). */ + /** Additional headers attached to MCP requests. */ headers: Record - /** Timeout per callTool invocation (ms). */ + /** Per-tool-call timeout in milliseconds. */ toolCallTimeoutMs: number } ``` diff --git a/docs/core-data-structures/subagent.i18n.yaml b/docs/core-data-structures/subagent.i18n.yaml index d8d6a493d7..fcd9e2f4f7 100644 --- a/docs/core-data-structures/subagent.i18n.yaml +++ b/docs/core-data-structures/subagent.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 -subagent.md: 0335a3f0780ae17b57ae730f5a49a269261c8073 -subagent.zh.md: dac48b624f6e0cfc28737e3e1a2774ba2d97e85b +subagent.md: fda4b4b738c648c893c65a633e4a0d6a1761424f +subagent.zh.md: ba43789a3e4efe59b197f6454c977db52d90aca1 diff --git a/docs/core-data-structures/subagent.md b/docs/core-data-structures/subagent.md index 0335a3f078..fda4b4b738 100644 --- a/docs/core-data-structures/subagent.md +++ b/docs/core-data-structures/subagent.md @@ -22,13 +22,9 @@ A provider advertises its **start-time** features on a static descriptor the ser * is the capability. */ interface SubagentCapabilities { - /** Honor {@link SubagentStartRequest.outputSchema} (structured final output). */ readonly outputSchema: boolean - /** Enforce {@link SubagentStartRequest.maxDepth} (recursion cap). */ readonly depthLimit: boolean - /** Enforce {@link SubagentStartRequest.toolFilter} (child tool scoping). */ readonly toolFilter: boolean - /** Honor {@link SubagentStartRequest.persona} (a per-child persona). */ readonly persona: boolean } ``` @@ -45,16 +41,11 @@ The tool layer builds this request from the model input and its own config; the * passes it to {@link SubagentProvider.start}. */ interface SubagentStartRequest { - /** The task/prompt for the child agent (a user message in the child session). */ + /** Content delivered as the child's user message. */ readonly prompt: ContentBlock[] /** - * The spawning ("parent") agent — the one whose tool call started this - * subagent. REQUIRED: in-process backends read `parent.session.header` for - * the working directory, the `parentSession` lineage to stamp on the child, - * and the parent's delegation depth. The out-of-process backend (ACP) reads - * exactly one field — the session header's cwd, the child's workspace when - * no deployment `cwd` override is configured; nothing else crosses the - * process boundary. + * The spawning agent. In-process providers derive workspace, lineage, and + * delegation depth from its durable session state; ACP uses only its cwd. */ readonly parent: Agent /** @@ -65,7 +56,6 @@ interface SubagentStartRequest { * afterward. */ readonly signal: AbortSignal - /** Per-child agent options (model and plugin-defined extension fields). */ readonly agentOptions?: AgentOptions /** * Object-rooted JSON Schema within `assertObjectJsonSchema`'s enforced subset. Start rejects @@ -135,15 +125,12 @@ interface SubagentResult { * non-`completed` result to an `isError` tool result. */ interface SubagentStopReasonMap { - /** The child finished its turn normally. */ completed: 'completed' - /** The run was cancelled by its request signal or by disposal. */ + /** Cancelled through the request signal or disposal. */ aborted: 'aborted' - /** The child failed (model error, transport error). */ + /** Model or transport failure. */ error: 'error' - /** The child hit its token ceiling before finishing. */ 'max-tokens': 'max-tokens' - /** The child declined the task. */ refusal: 'refusal' } ``` @@ -180,9 +167,8 @@ interface SubagentRun { */ readonly result: Promise /** - * Cancel remaining work, reach child quiescence, and release the run's - * resources (in-process: dispose the owned agent and remove its session; - * ACP: kill and reap the subprocess). Idempotent. + * Cancel remaining work, reach child quiescence, and release resources. + * Idempotent. */ dispose(): Promise /** @@ -206,12 +192,9 @@ Each provider is a named child-agent transport, and multiple providers may coexi ```ts type-equiv /** - * A subagent backend: one transport for running a child agent (in-process - * spawn/fork, ACP to another process, …). Implementations register under a - * unique name via {@link SubagentService.registerProvider}; multiple providers - * coexist in one context (unlike the single-implementation bash seam). The - * Providers are trusted same-process implementations; callers treat their - * descriptors and returned values as borrowed immutable data. + * One registered transport for running child agents. Providers are trusted + * same-process implementations; callers treat descriptors and returned values + * as borrowed immutable data. */ interface SubagentProvider { /** Unique registry name (e.g. `spawn`, `fork`, `acp`). */ diff --git a/docs/core-data-structures/subagent.zh.md b/docs/core-data-structures/subagent.zh.md index dac48b624f..ba43789a3e 100644 --- a/docs/core-data-structures/subagent.zh.md +++ b/docs/core-data-structures/subagent.zh.md @@ -22,13 +22,9 @@ subagent seam:一个 agent(智能体)将工作委派给子 agent。与 [ba * is the capability. */ interface SubagentCapabilities { - /** Honor {@link SubagentStartRequest.outputSchema} (structured final output). */ readonly outputSchema: boolean - /** Enforce {@link SubagentStartRequest.maxDepth} (recursion cap). */ readonly depthLimit: boolean - /** Enforce {@link SubagentStartRequest.toolFilter} (child tool scoping). */ readonly toolFilter: boolean - /** Honor {@link SubagentStartRequest.persona} (a per-child persona). */ readonly persona: boolean } ``` @@ -45,16 +41,11 @@ interface SubagentCapabilities { * passes it to {@link SubagentProvider.start}. */ interface SubagentStartRequest { - /** The task/prompt for the child agent (a user message in the child session). */ + /** Content delivered as the child's user message. */ readonly prompt: ContentBlock[] /** - * The spawning ("parent") agent — the one whose tool call started this - * subagent. REQUIRED: in-process backends read `parent.session.header` for - * the working directory, the `parentSession` lineage to stamp on the child, - * and the parent's delegation depth. The out-of-process backend (ACP) reads - * exactly one field — the session header's cwd, the child's workspace when - * no deployment `cwd` override is configured; nothing else crosses the - * process boundary. + * The spawning agent. In-process providers derive workspace, lineage, and + * delegation depth from its durable session state; ACP uses only its cwd. */ readonly parent: Agent /** @@ -65,7 +56,6 @@ interface SubagentStartRequest { * afterward. */ readonly signal: AbortSignal - /** Per-child agent options (model and plugin-defined extension fields). */ readonly agentOptions?: AgentOptions /** * Object-rooted JSON Schema within `assertObjectJsonSchema`'s enforced subset. Start rejects @@ -135,15 +125,12 @@ interface SubagentResult { * non-`completed` result to an `isError` tool result. */ interface SubagentStopReasonMap { - /** The child finished its turn normally. */ completed: 'completed' - /** The run was cancelled by its request signal or by disposal. */ + /** Cancelled through the request signal or disposal. */ aborted: 'aborted' - /** The child failed (model error, transport error). */ + /** Model or transport failure. */ error: 'error' - /** The child hit its token ceiling before finishing. */ 'max-tokens': 'max-tokens' - /** The child declined the task. */ refusal: 'refusal' } ``` @@ -182,9 +169,8 @@ interface SubagentRun { */ readonly result: Promise /** - * Cancel remaining work, reach child quiescence, and release the run's - * resources (in-process: dispose the owned agent and remove its session; - * ACP: kill and reap the subprocess). Idempotent. + * Cancel remaining work, reach child quiescence, and release resources. + * Idempotent. */ dispose(): Promise /** @@ -208,12 +194,9 @@ interface SubagentRun { ```ts type-equiv /** - * A subagent backend: one transport for running a child agent (in-process - * spawn/fork, ACP to another process, …). Implementations register under a - * unique name via {@link SubagentService.registerProvider}; multiple providers - * coexist in one context (unlike the single-implementation bash seam). The - * Providers are trusted same-process implementations; callers treat their - * descriptors and returned values as borrowed immutable data. + * One registered transport for running child agents. Providers are trusted + * same-process implementations; callers treat descriptors and returned values + * as borrowed immutable data. */ interface SubagentProvider { /** Unique registry name (e.g. `spawn`, `fork`, `acp`). */ diff --git a/examples/acp-agent/tests/acp.e2e.ts b/examples/acp-agent/tests/acp.e2e.ts index 46592e4704..37154d9fb1 100644 --- a/examples/acp-agent/tests/acp.e2e.ts +++ b/examples/acp-agent/tests/acp.e2e.ts @@ -114,11 +114,10 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('acp-agent e2e: real prompt over }) expect(['end_turn', 'max_tokens']).toContain(res.stopReason) - // Verify the WORLD, not the agent's self-report: read the file from disk. + // Assert the filesystem effect independently of the model response. const proof = await readFile(join(workdir, 'proof.txt'), 'utf8') expect(proof).toContain('ACP_OK') - // And the client saw tool-call activity stream through. const toolCalls = updates.filter(u => u.sessionUpdate === 'tool_call') expect(toolCalls.length).toBeGreaterThan(0) diff --git a/examples/acp-agent/tests/hooks.e2e.ts b/examples/acp-agent/tests/hooks.e2e.ts index 528823f3c5..d8f05291ff 100644 --- a/examples/acp-agent/tests/hooks.e2e.ts +++ b/examples/acp-agent/tests/hooks.e2e.ts @@ -62,7 +62,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('acp-agent e2e: a PreToolUse hook // the model, not a turn failure). expect(['end_turn', 'max_tokens']).toContain(res.stopReason) - // Verify that the denied hook left no filesystem effect. + // Assert the denied operation independently of the model response. await expect(access(join(workdir, 'proof.txt'))).rejects.toThrow() // A blocked call is still streamed with the hook's reason as an error. diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index b017d1c9e2..673aa978da 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -1,10 +1,7 @@ /** - * Browser half of the wire consumer layer (contract: api-contracts v3 - * section 3; export inventory = v3 §3.2). The wire is this package's client - * half in its entirety — apply mounts ctx.connection: the shared api client - * plus the connection controller handle. Mode selection (?fixture) happens - * here so the rest of the client tree is mode-blind; the controller's sinks - * are wired by the runtime plugin (object layer), which injects this service. + * Browser wire client. The plugin selects fixture or HTTP transport, provides + * the shared API client, and lets the runtime object layer start the stream + * controller with its sinks. */ import type { Context } from 'cordis' import type { IApiClient } from './api.ts' @@ -23,9 +20,8 @@ export type { } from './api.ts' export { RpcId, AbstractApiClient, transportError } from './api.ts' -// ---- Connection loop types (part of the ConnectionHandle.start contract; -// the controller class itself stays package-internal — apply owns the loop, -// tests reach it via src) ---- +// Connection loop types are public through ConnectionHandle.start; the +// controller remains package-internal. export type { ConnectionConfig, ConnectionSinks, ConnectionState } diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 313db07225..16074233e7 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -1,10 +1,4 @@ -/** - * Connection plugin, node half. The package IS a dshClient plugin: the wire - * consumer layer lives in its client half in full (src/client/ — contract: - * api-contracts v3 section 3, inventory §3.2); consumers import the /client - * subpath. The empty apply exists so the plugin appears in the host Loader - * (lifecycle governance + dshClient discovery). - */ +/** Host loader entry for the browser wire client exported from `./client`. */ /** Host plugin body — no host-side behavior for the connection plugin. */ export function apply(_ctx: unknown): void {} diff --git a/packages/client/i18n/src/client/index.ts b/packages/client/i18n/src/client/index.ts index 37e1c0cdb5..9dea9c4bd4 100644 --- a/packages/client/i18n/src/client/index.ts +++ b/packages/client/i18n/src/client/index.ts @@ -1,15 +1,10 @@ /** - * i18n plugin, browser half: namespace x locale dictionary registry with a - * bound translate function whose reference is stable (safe for inject - * surfaces). Mounts ctx.i18n and seeds the zh/en base dictionaries. - * Contract: api-contracts v3 section 8. + * Browser-side locale registry. Bound translation functions retain stable + * identity for injected consumers. */ import type { Context } from 'cordis' -// The snapshot-store engine lives in runtime (store relocation): framework -// data stores like this locale cell use it directly. The store carries no -// hook — a React consumer binds a selector hook via web-react's -// bindSnapshotSelector at its own seam (none exists today; the current -// consumers are translate() reads and test-side subscribe/set). +// Snapshot stores are framework-neutral; React consumers bind hooks at their +// rendering boundary. import type { SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import { en } from '../locales/en.ts' diff --git a/packages/client/i18n/src/index.ts b/packages/client/i18n/src/index.ts index 1e2de41ace..e759f1edc1 100644 --- a/packages/client/i18n/src/index.ts +++ b/packages/client/i18n/src/index.ts @@ -1,11 +1,4 @@ -/** - * i18n plugin, node half. Pure UI plugin: the empty apply exists so the - * plugin appears in the host cordis.yml / Loader (load and lifecycle follow - * the host; the browser half ships via exports["./client"], discovered - * through the package.json dshClient declaration). Everything else — - * I18nService, Translate, LocaleDict — lives in the client half; consumers - * import the /client subpath. Contract: api-contracts v3 section 8. - */ +/** Host loader entry for the browser implementation exported from `./client`. */ /** Host plugin body — no host-side behavior for the i18n plugin. */ export function apply(): void {} diff --git a/packages/client/runtime/src/client/contract/store.ts b/packages/client/runtime/src/client/contract/store.ts index ce4444cf36..7dc3b584ba 100644 --- a/packages/client/runtime/src/client/contract/store.ts +++ b/packages/client/runtime/src/client/contract/store.ts @@ -161,11 +161,7 @@ function deepFreeze(value: unknown): void { } } -// ---- defineStore shell (slot terminal design §4) ---- -// The type authority is ui-slots' store family (create(scopeKey?) and -// clearPersisted() included); this module houses only the engine-backed -// implementation. The one engine-side widening left: instances expose the -// raw engine store for framework/test surfaces. +// ui-slots owns the contract; this module supplies the engine implementation. /** A live engine instance: the contract instance plus the raw engine store. */ export interface EngineStoreInstance> extends StoreInstance { diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index 33097d4573..4c0bf3d01f 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -1,12 +1,7 @@ /** - * Browser half: the whole runtime contract surface (api-contracts v3 §4) — - * SlotsService (declaration ledger + renderer seam + store axis, built-in - * 'root'), SessionsService (list store + current selection + scope tree + - * object layer), and the cordis Context/Events merges. apply mounts - * ctx.slots + ctx.sessions and wires the connection stream loop into the - * object layer. A static-arrival entry: the web shell bundles this module - * and mounts it through the host graph (module loading lives in - * @deepseek-ai/dsh-client-modules, entry governance in the vendored Loader). + * Browser runtime services for slots, sessions, and connection-stream + * delivery. The web shell mounts this static client entry through the host + * plugin graph. */ import type { Context } from 'cordis' import type { ConnectionHandle, SessionId } from '@deepseek-ai/dsh-client-connection/client' @@ -17,15 +12,11 @@ import type { SessionListState } from './sessions/service.ts' import type { ConversationSnapshot, RunningToolCall, ToolResultNode } from './sessions/conversation.ts' export { SlotsService } from './slots.ts' -// RootOwnerProps rides the 'root' SlotMap row (both migrated here from -// ui-layout: the framework slot is declared by the framework package). export type { RootOwnerProps } from './slots.ts' export { SessionsService, scopeOf } from './sessions/service.ts' export type { Session } from './sessions/session.ts' export type { SessionBinding, SessionListState, SessionSummary } from './sessions/service.ts' -// The snapshot-store engine lives here since the store migration (the data -// layer owns its substrate; web-react is React glue only). The './client' -// main export is the single serving door — no store subpath. +// Runtime owns the snapshot store; web-react only binds it to React. export { createSnapshotStore, defineStore, shallowEqual } from './contract/store.ts' export type { EngineStoreHandle, EngineStoreInstance, ObservableSnapshot, SnapshotStore, @@ -35,21 +26,11 @@ export type { RunningToolCall, SteeringMessageNode, ToolResultNode, UnknownSurfaceNode, UserMessageNode, } from './sessions/conversation.ts' -// PendingWait is a value export: tests construct fixture waits directly. export { PendingWait } from './sessions/pending.ts' export type { PendingInteraction, PendingKind, PendingPayloads } from './sessions/pending.ts' export type { SessionId } from '@deepseek-ai/dsh-client-connection/client' -// ---- Narrowed aliases (the single narrowing point of the slot type chain: -// ui-slots/web-react stay generic and dependency-inverted; the client-tree -// concrete types live here, where their subjects live) ---- - -/** - * The client cordis context face: the base Context plus the service keys - * this package's declaration merge contributes (slots/sessions/loader) and - * every later plugin's merge. A plain alias — the merges land on Context - * itself inside the client program; the name marks intent at consumer seams. - */ +/** Client-side Cordis context after declaration merging. */ export type ClientContext = Context /** The conversation-snapshot selector hook (ConvViewProps/ToolRowProps take this). */ @@ -69,14 +50,12 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * every session-scope slot component receives these from the framework. */ interface SessionStandardProps { - /** Selector hook over this session's conversation snapshot. */ useSession: SnapshotSelectorHook /** The framework-resolved session id (owners never pass it). */ sessionId: SessionId } - /** Global standard kit, real members: the session-list hook every slot component receives. */ + /** Props injected into every global slot component. */ interface GlobalStandardProps { - /** Selector hook over the session list snapshot (`current` included — the arbitrated selection seat). */ useSessions: SnapshotSelectorHook } } @@ -99,9 +78,8 @@ declare module 'cordis' { /** Required services: the wire handle mounted by the connection plugin. */ export const inject = ['connection'] -/** - * Client plugin body: mount slots + sessions, start the stream loop. - * @param ctx - client cordis context. +/** Mounts the browser runtime services and connection stream. + * @param ctx - Client Cordis context. */ export function apply(ctx: Context): void { ctx.plugin(SlotsService) diff --git a/packages/client/runtime/src/client/sessions/fold-adapter.ts b/packages/client/runtime/src/client/sessions/fold-adapter.ts index 23b35f86bf..0f40d9bf2a 100644 --- a/packages/client/runtime/src/client/sessions/fold-adapter.ts +++ b/packages/client/runtime/src/client/sessions/fold-adapter.ts @@ -24,10 +24,10 @@ export interface CallIndexEntry { callView: ToolCallView | null } -/** Non-surface-eligible sentinel event (safely skipped by surfaceOpOf's undefined branch). - * 'noop/padding' is not a real event type on purpose: a genuine type with fake data would - * surface as garbage the day anyone adds handling for it (design §D.1; the cast is the one - * place a synthetic event enters the window). */ +/** Non-surface sentinel used to preserve paged-window sequence offsets. + * `noop/padding` is deliberately not a real event type, so it cannot acquire + * surface behavior; this cast is the only synthetic event entry point. + */ function paddingEvent(seq: number): SessionEvent { return { type: 'noop/padding', seq, time: 0, data: {} } as unknown as SessionEvent } diff --git a/packages/client/runtime/src/client/sessions/service.ts b/packages/client/runtime/src/client/sessions/service.ts index d8a6f05762..af07362f08 100644 --- a/packages/client/runtime/src/client/sessions/service.ts +++ b/packages/client/runtime/src/client/sessions/service.ts @@ -291,8 +291,7 @@ export class SessionsService { fiber, ctx, binding: { sessionId: id, session, ctx }, - // Bare source form (store migration): the Session object IS the - // observable; the React side binds the useSession hook per cell. + // Session is the observable; React binds a selector hook at its own seam. cell: { sessionId: id, session }, } this.scopes.set(id, record) diff --git a/packages/client/runtime/src/client/sessions/session.ts b/packages/client/runtime/src/client/sessions/session.ts index 6b773e0903..0681e2bb5f 100644 --- a/packages/client/runtime/src/client/sessions/session.ts +++ b/packages/client/runtime/src/client/sessions/session.ts @@ -1,7 +1,4 @@ -// Session: wraps every contract call that needs a sessionId + all conversation state for this -// session (design §A.2/§A.9/§D.2/§D.3). Instances are resident (ruling 2): never destroyed once -// created, they keep consuming mux frames in the background; React connects directly via -// subscribe/getSnapshot. +// Sessions remain resident after creation so they continue consuming mux frames off-screen. import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' import type { SessionEvent } from '@deepseek-ai/dsh-session/types' @@ -22,14 +19,12 @@ import { FoldAdapter } from './fold-adapter.ts' import { Notifier } from './notifier.ts' import { PartialAccumulator } from './partial.ts' -/** Messages per page (F.4 ledger: promote to Config at graduation; every call site references this constant). */ +/** Messages requested per history page. */ export const PAGE_MESSAGES = 50 /** - * Per-session state owner: event window + fold + partial, snapshot out via - * subscribe/getSnapshot (see the web client architecture RFC). Bare source - * only (store migration): the React machinery binds the per-cell useSession - * hook at its own seam — no selector hook member lives on the data layer. + * Owns a session's event window, derived conversation state, and observable + * snapshot. React bindings remain outside this data layer. */ export class Session implements ObservableSnapshot { // ---- Window and derived state (all private; the snapshot is the only read surface) ---- @@ -54,8 +49,7 @@ export class Session implements ObservableSnapshot { * Derived from window events (turn/end sweep) — rebuilt by rebuildDerivedFromWindow like partial/openCalls. */ private frozenNodes: ConversationNode[] = [] private pending = new Map() - // Revision counters + caches backing the snapshot's reference-stability contract (§A.9.4/§C.2, - // audit S5): buildSnapshot reuses the previous array when the revision is unchanged, so + // Revision counters preserve array identity when derived content is unchanged, so // React.memo children survive unrelated snapshot swaps (chunk storms must not re-render every // tool card and pending card). Mutation sites bump the matching revision. partial needs no // counter — PartialAccumulator.toPartial already returns a cached reference when unchanged. @@ -69,9 +63,9 @@ export class Session implements ObservableSnapshot { private removed = false private promptError: PromptError | null = null private lastAgentError: string | null = null - /** Buffer for live events arriving while open/resync is in flight (stitched by seq once history lands, §D.3). */ + /** Live events buffered during open/resync and stitched by sequence once history lands. */ private liveBuffer: { event: SessionEvent; view: ToolEventView | undefined }[] = [] - /** Gap-repair (resync-lite) in flight: acceptLiveEvent detours to liveBuffer until the tail page lands (audit S3). */ + /** Gap repair in flight; live events detour to the buffer until the tail page lands. */ private stitching = false /** subscribed.lastSeq baseline (gap detection; null when no subscribed frame arrived — degrade to the liveBuffer dedup path). */ private subscribedLastSeq: number | null = null @@ -292,8 +286,7 @@ export class Session implements ObservableSnapshot { this.notifier.markDirty() } - /** Instance-eviction hook, reserved no-op (design §F.6): resident instances are never destroyed - * in v1; an eviction policy lands here (unsubscribe, drop buffers) without touching call sites. */ + /** No-op because session instances remain resident. */ dispose(): void {} // ---- 私有 ---- diff --git a/packages/client/runtime/src/index.ts b/packages/client/runtime/src/index.ts index b0d0f0a7c8..c1ea85d1e5 100644 --- a/packages/client/runtime/src/index.ts +++ b/packages/client/runtime/src/index.ts @@ -1,11 +1,4 @@ -/** - * Runtime plugin, node half. The implementation lives entirely in the client - * half (src/client/ — SlotsService, SessionsService + object layer, and the - * shell-held ClientLoader under ./loader); consumers import the /client or - * /loader subpaths. The empty apply exists so the plugin appears in the host - * Loader (lifecycle governance + dshClient discovery). Contract: - * api-contracts v3 section 4. - */ +/** Host loader entry for the browser runtime exported from `./client` and `./loader`. */ /** Host plugin body — no host-side behavior for the runtime plugin. */ export function apply(_ctx: unknown): void {} diff --git a/packages/client/runtime/tests/sessions-service.spec.ts b/packages/client/runtime/tests/sessions-service.spec.ts index 8c850426bd..2b469ca055 100644 --- a/packages/client/runtime/tests/sessions-service.spec.ts +++ b/packages/client/runtime/tests/sessions-service.spec.ts @@ -187,8 +187,7 @@ describe('cell (render-layer session kit)', () => { const cell = b.svc.cell('s1') expect(cell).toBeDefined() expect(cell?.sessionId).toBe('s1') - // Bare-source form (store migration): the cell carries the Session - // observable itself; hook binding happens in the React machinery. + // Hook binding happens in React; the cell carries the observable itself. expect(cell?.session).toBe(b.svc.manager.get(sid('s1'))) expect(b.svc.cell('s1')).toBe(cell) expect(b.svc.cell('ghost')).toBeUndefined() diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 372eb36c80..536859b59a 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -1,14 +1,4 @@ -/** - * Client plugin body: register the conversation/details slot occupants and - * the no-session empty state, contribute the chat entry into the - * 'conversation.view' ring that the conversation registration declares, then - * mount the conversation service (class plugin) and the bash toolview sample. - * Assembly only — components receive everything through props: the framework - * standard kit and store faces arrive automatically from the declarations - * below; the inject factories contribute the plain-data-and-callbacks - * business face (design §5). Tool rows are ordinary keyed-slot registrations - * into 'conversation.chat.toolview' — no dedicated registry exists. - */ +/** Registers the conversation components, shared store, and service callbacks. */ import type { Context } from 'cordis' import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId, SessionsService } from '@deepseek-ai/dsh-client-runtime/client' @@ -25,7 +15,7 @@ import { ConversationRoot } from './skeleton/ConversationRoot.tsx' import { DetailsPanel } from './skeleton/DetailsPanel.tsx' import { EmptyState } from './skeleton/EmptyState.tsx' -/** Required services (cordis fiber inject — the loader passes the whole export surface as an object plugin). */ +/** Services required by the conversation plugin. */ export const inject = ['slots', 'layout', 'sessions'] /** Resolve the session-scoped conversation service (scope-addressed send/cancel), failing loud. */ @@ -37,24 +27,17 @@ function scopedConversation(sessions: SessionsService, id: SessionId): Conversat return conversation } -/** - * Client plugin body. - * @param ctx - client root context. +/** Mounts the conversation plugin. + * @param ctx - Client root context. */ export function apply(ctx: Context): void { const sessions = ctx.sessions const layout = ctx.layout const slots = ctx.slots - // Shared store handle, constructed here so its identity lives and dies with - // this fiber (a module-level handle would be a de-facto singleton). The - // conversation, chat-view, and details registrations all declare it; same - // scope key = same instance, so chat-view selection writes and details - // reads meet in one store. + // Apply-time construction keeps store identity bound to this fiber. const chatStore = createChatStore() - // Tab projection over the view ring's ledger (list entries carry id/order/ - // label as registration options; the ledger keeps them order-sorted). const viewTabs = (): ViewTab[] => { const tabs: ViewTab[] = [] for (const entry of slots.entries('conversation.view')) { diff --git a/packages/client/ui-conversation/src/client/chat/StatsLine.tsx b/packages/client/ui-conversation/src/client/chat/StatsLine.tsx index d7211f2f91..50dead9529 100644 --- a/packages/client/ui-conversation/src/client/chat/StatsLine.tsx +++ b/packages/client/ui-conversation/src/client/chat/StatsLine.tsx @@ -1,9 +1,4 @@ -// StatsLine: the session stats row (figma 122:11212 "cache hit 92% · 1,284 -// tokens · 45.2s · 5 turns · 32 steps"), rendered by ChatView under the flow -// (part of the chat view body — the chrome attachment mechanism retired with -// the view ring). Duration has no data source in P-I (ledger). Subscribes to -// `nodes` only: chunk batches never swap that reference, so the row renders -// zero times during streaming (the RFC performance model's acceptance row). +// Settled-node identity prevents stream-delta updates from rerendering this row. import { memo, useMemo } from 'react' import type { ConversationSnapshot } from '@deepseek-ai/dsh-client-runtime/client' diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index ffbc13ff59..9745c4518b 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -1,15 +1,4 @@ -/** - * Slot-ring contract for the conversation package: the 'conversation.view' - * slot this package declares (the view ring — one list entry per conversation - * view tab), the chat view's per-tool row hole ('conversation.chat.toolview', - * keyed on the wire tool name), and the composed props shapes its registrants - * mount into the layout-owned slots (conversation / details / - * conversation.empty) plus its own slots. Terminal slot design (§3): full - * component props are the automatic shares — PropsRuntime (framework - * standard kit) & PropsRenderSlots (declared children) & PropsStore - * (declared store's read/write faces) & the injected business face declared - * here. - */ +/** Conversation slot declarations and their composed component props. */ import type { PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' import type { PendingInteraction, SessionId, ToolCallBlock } from '@deepseek-ai/dsh-client-runtime/client' import type { createChatStore } from '../stores.ts' @@ -93,15 +82,9 @@ export type ConvViewProps = PropsRuntime<'conversation.view'> /** The shared chat store handle type (apply constructs one; the conversation, details, and chat-view registrations all declare it). */ export type ChatStore = ReturnType -/** - * Injected share of the conversation slot: plain data and callbacks only - * (design §5 — hooks are framework-made). The store lines that used to ride - * here live in the declared {@link ChatStore}; ancestry derives from the - * standard useSessions hook in-component; views render through the declared - * 'conversation.view' child slot, with this face projecting the tab strip. - */ +/** Business callbacks injected into the conversation slot. */ export interface ConversationInjected { - /** View tab read face (uSES triple over the 'conversation.view' slot ledger). */ + /** Views projected from the `conversation.view` slot ledger. */ views: { list(): readonly ViewTab[] subscribe(fn: () => void): () => void @@ -111,7 +94,6 @@ export interface ConversationInjected { send(text: string, mode: 'queue' | 'steer'): void /** Cancel the in-flight turn (failure surfaces via snapshot.promptError). */ stop(): void - /** Navigate to another session (breadcrumb ancestors). */ open(id: SessionId): void } @@ -123,7 +105,6 @@ export interface ConversationInjected { * with zero owner changes. */ export interface ComposerChainProps { - /** The session's live pending waits, in arrival order (snapshot reference). */ interactions: readonly PendingInteraction[] } @@ -139,7 +120,6 @@ export type ConversationSlotProps = export interface ChatViewInjected { /** Selection write + details panel opening in one gesture (store action + layout orchestration). */ openDetails(target: SelectionTarget): void - /** Pull one older history page. */ loadOlder(): void } diff --git a/packages/client/ui-conversation/src/client/contract/views.ts b/packages/client/ui-conversation/src/client/contract/views.ts index da573f007a..9ef9515f19 100644 --- a/packages/client/ui-conversation/src/client/contract/views.ts +++ b/packages/client/ui-conversation/src/client/contract/views.ts @@ -1,14 +1,4 @@ -/** - * Shared conversation contract primitives: the view tab projection (slot - * entries in 'conversation.view' surface as tabs), the chat store state - * shared through the declared store, and the selection primitives every - * domain consumes. Shared face between the skeleton domain (tab strip + - * view outlet) and the chat domain; domain implementation files import this, - * never each other. The view ring itself IS the 'conversation.view' slot - * (contract in slots.ts) — the package-local view registry is retired, and - * so is the hand-threaded translate channel (framework-level per-slot i18n - * injection is the planned replacement). - */ +/** Shared conversation view, selection, and store-state contracts. */ /** Tool call identity as carried on the wire (branded upstream in connection). */ export type CallId = string @@ -23,11 +13,8 @@ export interface SelectionTarget { turnSeq: number; stepSeq?: number; callId?: C export interface ViewTab { id: string; label: string } /** - * Chat store state (slot terminal design §4): the per-session store shared by - * the conversation, chat-view, and details registrations. `createChatStore` - * implements this shape. `view` may carry a stale persisted id after a view - * plugin unloads — the slot ledger is the runtime validator (unknown ids fall - * back to the first registered view). + * Per-session state shared by conversation, chat-view, and details slots. + * Unknown persisted view ids fall back to the first registered view. */ export interface ChatStoreState { /** Details-linkage channel (conversation writes, details reads). */ diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 8cfebac81c..d55ba1bd1e 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -1,12 +1,7 @@ /** - * Conversation domain plugin, browser half: skeleton (header/tabs/composer), - * the 'conversation.view' slot ring (chat entry here; other plugins - * contribute view tabs through ctx.slots), the chat view's keyed - * 'conversation.chat.toolview' row hole, scope-addressed ConversationService, - * minimal details panel. Contract: api-contracts v3 section 7. Thin shell: - * type surfaces live in contract/, assembly in apply.ts; the implementation - * domains (skeleton/chat) never import each other — contract/ is their only - * shared face. + * Browser conversation plugin. `contract/` is the shared type boundary + * between the independently implemented skeleton and chat domains; `apply.ts` + * owns their slot assembly. */ import type { ConversationService } from './service.ts' diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 0c6b9632bb..68fb7c4c31 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -1,17 +1,11 @@ /** - * ConversationService implementation: scope-addressed send/cancel and the - * empty-state startSession chain. Contract: api-contracts v3 section 7. - * Selection/draft state moved to the declared chat store (slot terminal - * design §4); the view registry moved to the 'conversation.view' slot (slot - * ledger owns registration, ordering, and disposal) — what remains is the - * send/stop orchestration face. + * Scope-addressed conversation send, cancel, and empty-state session startup. * * Scope addressing rides the cordis Service tracker: property access through * `ctx.conversation` rebinds `this.ctx` to the caller's context, so methods - * read the session tag with scopeOf (same mechanism as the host tool - * registry). Mutable state lives in plain objects reached by one property - * read — field assignment through the tracker's shadow proxy is off-limits, - * as are `#` hard-private fields. + * read the session tag with `scopeOf`. Mutable state must remain reachable + * through one property read; assignment through the tracker proxy and `#` + * private fields bypass that rebinding. */ import { Service } from 'cordis' import type { Context } from 'cordis' diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 04d1dd867d..a27a2662b7 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -1,12 +1,5 @@ -// InputBar: the one composer input (figma Input_Bottom). The same component -// serves the empty state (variant='hero': centered launch card) and the -// resident composer (variant='composer') — the empty→content transition is a -// position move of this component, never a swap (layout ruling). Running -// LOCKS the input: textarea disabled with the draft visible, stop is the only -// action; the turn ending re-enables and refocuses. -// -// Bottom chrome (attach / Plan / Read-only / model) is visual-only for now — -// local native { setPathDraft(e.target.value) }} - onKeyDown={(e) => { - if (e.key === 'Enter') { - e.preventDefault() - confirmPath() - } - }} - /> - - - - - - )} - > - { setWorkspaceName(e.target.value) }} - onKeyDown={(e) => { - if (e.key === 'Enter') { - e.preventDefault() - confirmCreate() - } - }} - /> - {modalError !== null &&

{modalError}
} - - + { sendSession() }} + onAdd={() => { setPickerOpen(true) }} + /> ) } diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css index 7161a31931..d7338f8f2e 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.module.css @@ -19,18 +19,27 @@ padding: 0; } -.error { +.error, +.status { width: 100%; max-width: 800px; margin-bottom: 6px; padding: 4px 8px; border-radius: 8px; - background: var(--dsw-alias-interactive-bg-hover-danger); - color: var(--dsw-alias-state-error-primary); font-size: 12px; line-height: 18px; } +.status { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-secondary); +} + +.error { + background: var(--dsw-alias-interactive-bg-hover-danger); + color: var(--dsw-alias-state-error-primary); +} + .card { display: flex; flex-direction: column; diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index a27a2662b7..e65e08ec53 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -9,7 +9,7 @@ import css from './InputBar.module.css' /** Prompt failure surface (mirrors the session snapshot's promptError shape). */ export interface InputBarError { - op: 'send' | 'stop' + op: 'workspace' | 'session' | 'send' | 'stop' message: string } @@ -18,12 +18,17 @@ export interface InputBarProps { running: boolean disabled: boolean error: InputBarError | null + /** Observable async phase for browser fixtures and assistive technology. */ + status?: string + /** Hero = empty-state centered card; composer = resident bottom bar. */ variant: 'hero' | 'composer' placeholder?: string accessory?: ReactNode onDraftChange: (text: string) => void onSend: (mode: 'queue' | 'steer') => void onStop: () => void + onAdd?: () => void + addLabel?: string } interface SelectOption { @@ -47,7 +52,8 @@ const MODEL_OPTIONS: readonly SelectOption[] = [ ] export function InputBar({ - draft, running, disabled, error, variant, placeholder, accessory, onDraftChange, onSend, onStop, + draft, running, disabled, error, status, variant, placeholder, accessory, + onDraftChange, onSend, onStop, onAdd, addLabel = 'Add attachment', }: InputBarProps) { const empty = draft.trim() === '' const inputRef = useRef(null) @@ -98,7 +104,7 @@ export function InputBar({ inputRef.current?.focus() } - const primaryLabel = running ? '停止' : '发送' + const primaryLabel = running ? 'Stop generating' : 'Send message' const onPrimary = (): void => { if (running) { onStop() @@ -129,11 +135,8 @@ export function InputBar({ return (
- {error !== null && ( -
- {error.op === 'stop' ? '停止失败' : '发送失败'}:{error.message} -
- )} + {status !== undefined &&
{status}
} + {error !== null &&
{error.message}
}
{accessory !== undefined &&
{accessory}
} {/* Mirror-div auto-grow: the hidden mirror renders draft+'\n' and stretches the wrapper @@ -145,7 +148,7 @@ export function InputBar({ className={css.input} value={draft} disabled={locked} - placeholder={placeholder ?? (disabled ? '会话不可用' : running ? '回复生成中,可停止后再输入' : '输入消息,Enter 发送,Shift+Enter 换行')} + placeholder={placeholder ?? (disabled ? 'Session unavailable' : running ? 'Generating a response…' : 'Message the agent')} rows={2} onChange={(e) => onDraftChange(e.target.value)} onKeyDown={onKeyDown} @@ -159,10 +162,11 @@ export function InputBar({ @@ -177,7 +181,7 @@ export function InputBar({ type="button" className={clsx(css.primary, running && css.stopping)} aria-label={primaryLabel} - title={running ? '停止本轮' : '发送(Enter)'} + title={primaryLabel} disabled={!running && (empty || disabled)} onMouseDown={keepFocus} onClick={onPrimary} diff --git a/packages/client/ui-conversation/tests/apply-inject.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.spec.tsx index 1447b6486a..21fe70499e 100644 --- a/packages/client/ui-conversation/tests/apply-inject.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.spec.tsx @@ -3,8 +3,8 @@ // shape: the conversation surface (views triple, send choreography incl. // optimistic clear + failure restore THROUGH the declared store actions, // openDetails = select action + layout orchestration, sessions.open -// navigation), the injectless-but-closeDetails details surface, and the -// one-callback empty surface. Complements chat-apply.spec.tsx (registration) +// navigation), and the closeDetails details surface. Complements +// chat-apply.spec.tsx (registration) // and selection-survival.spec.ts (store axis). History opening is NOT an // inject concern anymore — the runtime sessions service opens on watch // (sessions-service.spec.ts owns that behavior). @@ -14,9 +14,11 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { cleanup } from '@testing-library/react' import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import { SlotsService, scopeOf } from '@deepseek-ai/dsh-client-runtime/client' -import type { SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client' +import type { + SessionId, SessionListState, WorkspaceListState, +} from '@deepseek-ai/dsh-client-runtime/client' import type { SlotRendererHost } from '@deepseek-ai/dsh-client-web-react' -import { ConversationService, apply, inject } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { ChatViewInjected, ConversationInjected, DetailsInjected, EmptyStateInjected, } from '@deepseek-ai/dsh-client-ui-conversation/client' @@ -53,10 +55,14 @@ async function bench() { ids: [ROOT], byId: { [ROOT]: { id: ROOT, title: 'R', displayTitle: 'R', cwd: '/proj', running: false, updatedAt: 1 } }, current: ROOT, - } as SessionListState) + intent: undefined, + phase: 'ready', + }) const sessionFake = { open: vi.fn(() => Promise.resolve()), loadOlder: vi.fn(() => Promise.resolve()), + updatePendingPrompt: vi.fn(), + retryPendingPrompt: vi.fn(), prompt: vi.fn<() => Promise<{ ok: boolean; value?: object; error?: { code: string; message: string } }>>( () => Promise.resolve({ ok: true, value: { accepted: true } })), cancel: vi.fn<() => Promise<{ ok: boolean; value?: object; error?: { code: string; message: string } }>>( @@ -73,15 +79,24 @@ async function bench() { } const sessionsFake = { list: listStore, - manager: { get: () => sessionFake }, + binding: (id: SessionId) => ({ sessionId: id, session: sessionFake, ctx: mint(id) }), scope: (id: SessionId) => mint(id), cell: () => undefined, scopeOf, - create: vi.fn(() => Promise.resolve(ROOT)), - createWorkspace: vi.fn(() => Promise.resolve(ROOT)), open: vi.fn(), + updateIntent: vi.fn(), } ctx.provide('sessions', sessionsFake) + const workspaceStore = createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) + const workspacesFake = { + list: workspaceStore, + startSession: vi.fn(), + sendSession: vi.fn(), + } + ctx.provide('workspaces', workspacesFake) const layoutFake = { openDetails: vi.fn(), closeDetails: vi.fn() } ctx.provide('layout', layoutFake) ctx.provide('i18n', { bind: () => (key: string) => key }) @@ -124,19 +139,25 @@ async function bench() { id, instance.actions) return { instance, injected } } - return { ctx, slots, hostFace, entryOf, conversationSurface, chatViewSurface, sessionFake, sessionsFake, layoutFake, mint } + const emptySurface = () => { + const entry = entryOf('conversation.empty') + return (entry.inject as unknown as () => EmptyStateInjected)() + } + return { + ctx, slots, hostFace, entryOf, conversationSurface, chatViewSurface, emptySurface, + sessionFake, sessionsFake, workspacesFake, layoutFake, mint, + } } describe('conversation slot inject surface', () => { - it('assembles the thin surface side-effect-free, navigates via sessions.open', async () => { + it('assembles the thin surface side-effect-free', async () => { const b = await bench() const { injected } = b.conversationSurface(ROOT) // Assembly has no session side effects: opening the event window belongs // to the runtime watch path, not the inject factory. expect(b.sessionFake.open).not.toHaveBeenCalled() expect(injected.views.list().map(v => v.id)).toEqual(['chat']) - injected.open(ROOT) - expect(b.sessionsFake.open).toHaveBeenCalledWith(ROOT) + const chatView = b.chatViewSurface(ROOT) chatView.injected.loadOlder() expect(b.sessionFake.loadOlder).toHaveBeenCalledTimes(1) @@ -202,6 +223,17 @@ describe('conversation slot inject surface', () => { expect(conv.instance).toBe(instance) }) + it('routes navigation through SessionsService and the retained prompt through the scoped Session', async () => { + const b = await bench() + const { injected } = b.conversationSurface(ROOT) + injected.open(ROOT) + injected.updateSessionPrompt('revised') + injected.retrySessionPrompt() + expect(b.sessionsFake.open).toHaveBeenCalledWith(ROOT) + expect(b.sessionFake.updatePendingPrompt).toHaveBeenCalledWith('revised') + expect(b.sessionFake.retryPendingPrompt).toHaveBeenCalledOnce() + }) + it('views read face projects the ring ledger (subscribe/version through ctx.slots)', async () => { const b = await bench() const { injected } = b.conversationSurface(ROOT) @@ -225,7 +257,7 @@ describe('conversation slot inject surface', () => { }) }) -describe('details and empty inject surfaces', () => { +describe('details inject surface', () => { it('details injects the one layout callback; selection rides the shared store instead', async () => { const b = await bench() const entry = b.entryOf('details') @@ -239,29 +271,18 @@ describe('details and empty inject surfaces', () => { expect(details).toBe(conv) }) - it('empty injects startSession and createWorkspaceSession (no store, cwds derive in-component)', async () => { + it('empty state injects the runtime intent actions and remains storeless', async () => { const b = await bench() const entry = b.entryOf('conversation.empty') expect(entry.store).toBeUndefined() - const injected = (entry.inject as unknown as () => EmptyStateInjected)() - expect(Object.keys(injected).sort()).toEqual(['createWorkspaceSession', 'startSession']) - await injected.startSession({ text: 'go', mode: 'queue' }) - expect(b.sessionsFake.create).toHaveBeenCalled() - expect(b.sessionsFake.open).toHaveBeenCalledWith(ROOT) - expect(b.sessionFake.prompt).toHaveBeenCalledWith([{ type: 'text', text: 'go' }], 'queue') - b.sessionsFake.open.mockClear() - await injected.createWorkspaceSession('Fresh') - expect(b.sessionsFake.createWorkspace).toHaveBeenCalledWith('Fresh') - expect(b.sessionsFake.open).toHaveBeenCalledWith(ROOT) - }) - - it('startSession fails loud on a torn boot (conversation service fiber gone)', async () => { - const b = await bench() - const injected = (b.entryOf('conversation.empty').inject as unknown as () => EmptyStateInjected)() - // Tear the service's own fiber (registry keyed by the class): the slot - // entries survive, so the gesture-time read hits the loud branch. - b.ctx.registry.delete(ConversationService) - await vi.waitFor(() => { expect(b.ctx.get('conversation')).toBeUndefined() }) - expect(() => injected.startSession({ text: 'go', mode: 'queue' })).toThrow(/conversation service unavailable/) + const injected = b.emptySurface() + injected.startSession(undefined, 'fresh') + injected.startSession('workspace-1' as never, 'retargeted') + injected.updateSessionPrompt('typed') + injected.sendSession() + expect(b.workspacesFake.startSession).toHaveBeenNthCalledWith(1, undefined, 'fresh') + expect(b.workspacesFake.startSession).toHaveBeenNthCalledWith(2, 'workspace-1', 'retargeted') + expect(b.sessionsFake.updateIntent).toHaveBeenCalledWith('typed') + expect(b.workspacesFake.sendSession).toHaveBeenCalledOnce() }) }) diff --git a/packages/client/ui-conversation/tests/chat-apply.spec.tsx b/packages/client/ui-conversation/tests/chat-apply.spec.tsx index adb9271c71..dcfe2d7de7 100644 --- a/packages/client/ui-conversation/tests/chat-apply.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-apply.spec.tsx @@ -30,16 +30,23 @@ async function bench() { [CHILD]: { id: CHILD, title: 'C', displayTitle: 'C', parentId: ROOT, running: false, updatedAt: 2 }, }, current: undefined, + intent: undefined, + phase: 'ready', } as SessionListState) const sessionsFake = { list: listStore, - manager: { get: vi.fn() }, + binding: vi.fn(), scope: () => undefined, cell: () => undefined, create: vi.fn(), open: vi.fn(), + updateIntent: vi.fn(), } ctx.provide('sessions', sessionsFake) + ctx.provide('workspaces', { + startSession: vi.fn(), + sendSession: vi.fn(), + }) ctx.provide('layout', { openDetails: vi.fn(), closeDetails: vi.fn() }) ctx.provide('i18n', { bind: () => (key: string) => key }) @@ -84,7 +91,7 @@ describe('apply wiring', () => { expect(b.slots.spec('conversation.chat.toolview')).toEqual({ kind: 'keyed', scope: 'session' }) }) - it('occupies the three slots + the ring; session entries share one store handle, empty declares none', async () => { + it('occupies the three slots + the ring; session entries share one store handle, empty injects runtime actions', async () => { const b = await bench() await b.fiber.await() const conversation = renderEntryOf(b.slots, 'conversation') diff --git a/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx b/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx index 4d3383b2d1..d73f8243ae 100644 --- a/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx @@ -27,8 +27,8 @@ const assistant = (seq: number, turn: number, usage?: unknown): AssistantMessage function snapshotBase(): ConversationSnapshot { return { sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], - pending: [], running: false, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null, + pending: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null, + hasMore: false, loadingOlder: false, promptError: null, intent: null, pendingPrompt: null, lastAgentError: null, } } @@ -127,6 +127,8 @@ describe('bash sample row', () => { [CHILD]: { id: CHILD, title: 'c', displayTitle: 'c', parentId: ROOT, running: false, updatedAt: 0 }, }, current: undefined, + intent: undefined, + phase: 'ready', } as SessionListState) } diff --git a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx index 7f66d1deb8..bfae743cff 100644 --- a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx @@ -15,7 +15,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, render } from '@testing-library/react' import { createSnapshotStore, SlotsService } from '@deepseek-ai/dsh-client-runtime/client' import type { - ConversationSnapshot, SessionId, SessionListState, ToolResultNode, + ConversationSnapshot, SessionId, SessionListState, ToolResultNode, WorkspaceListState, } from '@deepseek-ai/dsh-client-runtime/client' import { createSlotRenderer } from '@deepseek-ai/dsh-client-web-react' import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' @@ -40,8 +40,8 @@ const toolResult = (seq: number, callId: string, name: string, args = '{"command function snapshotWith(nodes: ToolResultNode[]): ConversationSnapshot { return { sessionId: SID, nodes, foldDegraded: false, partial: null, runningCalls: [], - pending: [], running: false, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null, + pending: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null, + hasMore: false, loadingOlder: false, promptError: null, intent: null, pendingPrompt: null, lastAgentError: null, } as ConversationSnapshot } @@ -65,9 +65,11 @@ async function bench(nodes: ToolResultNode[]) { const session = createSnapshotStore(snapshotWith(nodes)) const list = createSnapshotStore({ ids: [SID], - byId: { [SID]: { id: SID, title: 'S', running: false, updatedAt: 1 } }, + byId: { [SID]: { id: SID, title: 'S', displayTitle: 'S', running: false, updatedAt: 1 } }, current: SID, - } as SessionListState) + intent: undefined, + phase: 'ready', + }) // Identity-stable cell: the renderer caches hooks per source and inject // results per cell, both by object identity. const cell = { sessionId: SID, session } @@ -75,11 +77,20 @@ async function bench(nodes: ToolResultNode[]) { const layout = { openDetails: vi.fn(), closeDetails: vi.fn() } ctx.provide('sessions', { list, - manager: { get: () => ({ loadOlder: vi.fn() }) }, + binding: (id: SessionId) => ({ sessionId: id, session: { loadOlder: vi.fn() } }), scope: () => ({ get: () => scoped }), cell: (id: string) => (id === SID ? cell : undefined), create: vi.fn(), open: vi.fn(), + updateIntent: vi.fn(), + }) + ctx.provide('workspaces', { + list: createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }), + startSession: vi.fn(), + sendSession: vi.fn(), }) ctx.provide('layout', layout) ctx.provide('i18n', { bind: () => (key: string) => key }) @@ -182,12 +193,23 @@ describe('registrant load-order seam', () => { await slotsFiber.await() const slots = ctx.get('slots') as SlotsService ctx.provide('sessions', { - list: createSnapshotStore({ ids: [], byId: {}, current: undefined } as SessionListState), - manager: { get: vi.fn() }, + list: createSnapshotStore({ + ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready', + }), + binding: () => undefined, scope: () => undefined, cell: () => undefined, create: vi.fn(), open: vi.fn(), + updateIntent: vi.fn(), + }) + ctx.provide('workspaces', { + list: createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }), + startSession: vi.fn(), + sendSession: vi.fn(), }) ctx.provide('layout', { openDetails: vi.fn(), closeDetails: vi.fn() }) ctx.provide('i18n', { bind: () => (key: string) => key }) diff --git a/packages/client/ui-conversation/tests/chat-view.spec.tsx b/packages/client/ui-conversation/tests/chat-view.spec.tsx index aeda8ef6d2..bb55fcac77 100644 --- a/packages/client/ui-conversation/tests/chat-view.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-view.spec.tsx @@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Profiler } from 'react' import { act, cleanup, fireEvent, render } from '@testing-library/react' import type { - AssistantMessageNode, ConversationNode, ConversationSnapshot, RunningToolCall, SessionId, SessionListState, ToolResultNode, UserMessageNode, + AssistantMessageNode, ConversationNode, ConversationSnapshot, RunningToolCall, SessionId, SessionListState, ToolResultNode, UserMessageNode, WorkspaceListState, } from '@deepseek-ai/dsh-client-runtime/client' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' import { createSnapshotStore, PendingWait } from '@deepseek-ai/dsh-client-runtime/client' @@ -29,8 +29,8 @@ const SID = 's1' as SessionId function snapshotBase(): ConversationSnapshot { return { sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], - pending: [], running: false, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null, + pending: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null, + hasMore: false, loadingOlder: false, promptError: null, intent: null, pendingPrompt: null, lastAgentError: null, } } @@ -72,7 +72,15 @@ const runningCall = (callId: string, name = 'bash'): RunningToolCall => ({ /** Empty sessions-list hook for the global standard-kit seat. */ function emptySessions() { const store = createSnapshotStore( - { ids: [], byId: {}, current: undefined } as SessionListState) + { ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' }) + return bindSnapshotSelector(store) +} + +function emptyWorkspaces() { + const store = createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) return bindSnapshotSelector(store) } @@ -95,6 +103,7 @@ function makeHarness(init?: Partial) { sessionId: SID, useSession: bindSnapshotSelector(source), useSessions: emptySessions(), + useWorkspaces: emptyWorkspaces(), useStore: bindSnapshotSelector(chat), actions: chat.actions, renderSlot, diff --git a/packages/client/ui-conversation/tests/coverage-tails.spec.tsx b/packages/client/ui-conversation/tests/coverage-tails.spec.tsx index 66ae3e802c..451c860972 100644 --- a/packages/client/ui-conversation/tests/coverage-tails.spec.tsx +++ b/packages/client/ui-conversation/tests/coverage-tails.spec.tsx @@ -87,8 +87,10 @@ describe('tails', () => { const sid = 'root-1' as SessionId const list = createSnapshotStore({ ids: [sid], - byId: { [sid]: { id: sid, title: 'r', running: false, updatedAt: 0 } }, + byId: { [sid]: { id: sid, title: 'r', displayTitle: 'r', running: false, updatedAt: 0 } }, current: undefined, + intent: undefined, + phase: 'ready', } as SessionListState) const props = { callId: 'c1', toolName: 'bash', block: errorResult, openDetails: vi.fn(), diff --git a/packages/client/ui-conversation/tests/gate-branch-tails.spec.tsx b/packages/client/ui-conversation/tests/gate-branch-tails.spec.tsx index aaf1142266..7994930b75 100644 --- a/packages/client/ui-conversation/tests/gate-branch-tails.spec.tsx +++ b/packages/client/ui-conversation/tests/gate-branch-tails.spec.tsx @@ -5,7 +5,7 @@ import { cleanup, render } from '@testing-library/react' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import type { UseSession } from '@deepseek-ai/dsh-client-web-react' -import type { ConversationSnapshot, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client' +import type { ConversationSnapshot, SessionId, SessionListState, WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client' import type { SelectionTarget } from '@deepseek-ai/dsh-client-ui-conversation/client' import { createChatStore } from '../src/client/stores.ts' import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' @@ -19,8 +19,8 @@ const SID = 's1' as SessionId function snapshotBase(): ConversationSnapshot { return { sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], - pending: [], running: false, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null, + pending: [], running: false, composerPhase: 'active', removed: false, openState: 'open', openError: null, + hasMore: false, loadingOlder: false, promptError: null, intent: null, pendingPrompt: null, lastAgentError: null, } as ConversationSnapshot } @@ -65,12 +65,17 @@ describe('render branch tails', () => { const chat = createChatStore().create() chat.actions.select({ turnSeq: 1, callId: 'ghost' } satisfies SelectionTarget) const emptyList = createSnapshotStore( - { ids: [], byId: {}, current: undefined } as SessionListState) + { ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' }) + const emptyWorkspaces = createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) const view = render( snap, subscribe: () => () => {} }) as unknown as UseSession} useSessions={bindSnapshotSelector(emptyList)} + useWorkspaces={bindSnapshotSelector(emptyWorkspaces)} useStore={bindSnapshotSelector(chat)} actions={chat.actions} closeDetails={vi.fn()} diff --git a/packages/client/ui-conversation/tests/hook.ts b/packages/client/ui-conversation/tests/hook.ts deleted file mode 100644 index ef01792747..0000000000 --- a/packages/client/ui-conversation/tests/hook.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Test-local selector binding through the production uSES implementation. - * Runtime remains React-free, so specs bind observable sources here. - */ -import { bindSnapshotSelector } from '../../web-react/src/bind.ts' - -/** Minimal observable source (engine stores and scripted fakes both satisfy it). */ -export interface HookSource { - getSnapshot(): T - subscribe(fn: () => void): () => void -} - -/** - * Bind a selector hook over a snapshot source. - * @param src - the source. - * @returns a SnapshotSelectorHook-shaped hook. - */ -export function hookOf(src: HookSource) { - return bindSnapshotSelector(src) -} diff --git a/packages/client/ui-conversation/tests/input-bar.spec.tsx b/packages/client/ui-conversation/tests/input-bar.spec.tsx index 6bf58f7d59..d6367ad12a 100644 --- a/packages/client/ui-conversation/tests/input-bar.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.spec.tsx @@ -19,9 +19,9 @@ function setup(over?: Partial) { } const view = render() const textarea = view.container.querySelector('textarea')! - // aria-label (not role name): title also contains 发送/停止 and would double-match. + // aria-label (not role name): title carries the same label and would double-match. const button = view.container.querySelector( - `button[aria-label="${over?.running === true ? '停止' : '发送'}"]`, + `button[aria-label="${over?.running === true ? 'Stop generating' : 'Send message'}"]`, )! return { view, textarea, button, props } } @@ -80,7 +80,7 @@ describe('running lock and primary button', () => { it('running locks the textarea and turns the primary into stop', () => { const { textarea, button, props } = setup({ running: true }) expect(textarea.disabled).toBe(true) - expect(button.getAttribute('aria-label')).toBe('停止') + expect(button.getAttribute('aria-label')).toBe('Stop generating') fireEvent.click(button) expect(props.onStop).toHaveBeenCalledTimes(1) expect(props.onSend).not.toHaveBeenCalled() @@ -100,30 +100,30 @@ describe('running lock and primary button', () => { const textarea = view.container.querySelector('textarea')! expect(document.activeElement).toBe(textarea) textarea.blur() - fireEvent.mouseDown(view.container.querySelector('button[aria-label="发送"]')!) + fireEvent.mouseDown(view.container.querySelector('button[aria-label="Send message"]')!) expect(document.activeElement).toBe(textarea) }) it('disabled state shows the unavailable placeholder; typing forwards drafts', () => { const { textarea } = setup({ disabled: true, draft: '' }) - expect(textarea.placeholder).toBe('会话不可用') + expect(textarea.placeholder).toBe('Session unavailable') const live = setup({ draft: '' }) - expect(live.textarea.placeholder).toContain('Enter 发送') + expect(live.textarea.placeholder).toBe('Message the agent') fireEvent.change(live.textarea, { target: { value: 'typed' } }) expect(live.props.onDraftChange).toHaveBeenCalledWith('typed') const runningPh = setup({ running: true, draft: '' }) - expect(runningPh.textarea.placeholder).toContain('停止') - const custom = setup({ placeholder: '自定义' }) - expect(custom.textarea.placeholder).toBe('自定义') + expect(runningPh.textarea.placeholder).toBe('Generating a response…') + const custom = setup({ placeholder: 'Custom placeholder' }) + expect(custom.textarea.placeholder).toBe('Custom placeholder') }) }) describe('error strip and variants', () => { it('renders send and stop failure copy', () => { const send = setup({ error: { op: 'send', message: 'boom' } }) - expect(send.view.getByText(/发送失败:boom/)).toBeTruthy() + expect(send.view.container.querySelector('[role="alert"]')?.textContent).toBe('boom') const stop = setup({ error: { op: 'stop', message: 'halt' } }) - expect(stop.view.getByText(/停止失败:halt/)).toBeTruthy() + expect(stop.view.container.querySelector('[role="alert"]')?.textContent).toBe('halt') }) it('hero variant adds the hero class and accessory row renders', () => { @@ -136,7 +136,7 @@ describe('error strip and variants', () => { describe('placeholder chrome', () => { it('renders attach / Plan / Read-only / model controls', () => { const { view } = setup() - expect(view.getByLabelText('添加')).toBeTruthy() + expect(view.getByLabelText('Add attachment')).toBeTruthy() expect((view.getByLabelText('Plan mode') as HTMLSelectElement).value).toBe('plan') expect((view.getByLabelText('Access mode') as HTMLSelectElement).value).toBe('readonly') expect((view.getByLabelText('Model') as HTMLSelectElement).value).toBe('v4-pro-high') @@ -162,7 +162,7 @@ describe('placeholder chrome', () => { it('running locks the chrome selects and attach control', () => { const { view } = setup({ running: true }) - expect((view.getByLabelText('添加') as HTMLButtonElement).disabled).toBe(true) + expect((view.getByLabelText('Add attachment') as HTMLButtonElement).disabled).toBe(true) expect((view.getByLabelText('Plan mode') as HTMLSelectElement).disabled).toBe(true) expect((view.getByLabelText('Model') as HTMLSelectElement).disabled).toBe(true) }) diff --git a/packages/client/ui-conversation/tests/selection-survival.spec.ts b/packages/client/ui-conversation/tests/selection-survival.spec.ts index 866b34e2a6..6210b6e492 100644 --- a/packages/client/ui-conversation/tests/selection-survival.spec.ts +++ b/packages/client/ui-conversation/tests/selection-survival.spec.ts @@ -5,27 +5,31 @@ */ import { Context } from 'cordis' import { beforeEach, describe, expect, it } from 'vitest' -import { SessionsService, SlotsService } from '@deepseek-ai/dsh-client-runtime/client' -import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client' +import { createSnapshotStore, SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import type { SessionId, SessionListState, WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client' import { createChatStore } from '../src/client/stores.ts' -// Use the runtime's programmable fake to drive the real session service. -import { FakeApiClient, ok } from '../../runtime/tests/fake-api.ts' - const sid = (s: string): SessionId => s as SessionId interface Bench { - ctx: Context - api: FakeApiClient - sessions: SessionsService slots: SlotsService chat: ReturnType } function bench(): Bench { const ctx = new Context() - const api = new FakeApiClient() - const sessions = new SessionsService(ctx, api) + ctx.provide('sessions', { + list: createSnapshotStore({ + ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready', + }), + cell: () => undefined, + }) + ctx.provide('workspaces', { + list: createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }), + }) // Service self-registers as ctx 'slots' (cordis Service constructor). const slots = new SlotsService(ctx) const chat = createChatStore() @@ -42,22 +46,7 @@ function bench(): Bench { }, (_p: { renderSlot?: unknown }) => null) slots.register({ name: 'conversation', store: chat }, () => null) slots.register({ name: 'details', store: chat }, () => null) - return { ctx, api, sessions, slots, chat } -} - -async function flush(): Promise { - // Manager notifier + store batching are microtask-based. - await Promise.resolve() - await Promise.resolve() -} - -function feed(b: Bench, rows: { id: string; cwd?: string; running?: boolean }[]): void { - b.api.onList = () => Promise.resolve(ok({ - items: rows.map(r => ({ - sessionId: sid(r.id), updatedAt: 1, running: r.running ?? false, - ...(r.cwd !== undefined ? { cwd: r.cwd } : {}), - })), - }) as never) + return { slots, chat } } /** Resolve the store instance the renderer would hand a slot's component for a session. */ @@ -87,11 +76,8 @@ beforeEach(() => { }) describe('selection survives on the store seat', () => { - it('one session, two slots: conversation writes, details reads the SAME instance', async () => { + it('one session, two slots: conversation writes, details reads the SAME instance', () => { const b = bench() - feed(b, [{ id: 's1' }]) - await b.sessions.manager.refreshList() - await flush() const conv = storeFor(b, 'conversation', sid('s1')) const details = storeFor(b, 'details', sid('s1')) @@ -101,11 +87,8 @@ describe('selection survives on the store seat', () => { expect(details).toBe(conv) }) - it('sessions are isolated: s2 selection never bleeds into s1', async () => { + it('sessions are isolated: s2 selection never bleeds into s1', () => { const b = bench() - feed(b, [{ id: 's1' }, { id: 's2' }]) - await b.sessions.manager.refreshList() - await flush() const one = storeFor(b, 'conversation', sid('s1')) const two = storeFor(b, 'conversation', sid('s2')) @@ -116,25 +99,17 @@ describe('selection survives on the store seat', () => { expect(two.store.getSnapshot().selection).toEqual({ turnSeq: 9, callId: 'z' }) }) - it('a display-title-upgrading list refresh keeps instance identity and the selection value', async () => { + it('a list-projection update keeps instance identity and the selection value', () => { const b = bench() - // First-send shape: client-side create inserts the row without cwd (title = bare id). - b.api.onCreate = () => Promise.resolve(ok({ sessionId: sid('s1') })) - const id = await b.sessions.create({}) - await flush() - expect(b.sessions.list.getSnapshot().byId[id]).toMatchObject({ displayTitle: 's1' }) - expect(b.sessions.list.getSnapshot().byId[id]?.title).toBeUndefined() + const id = sid('s1') + const projection = createSnapshotStore({ displayTitle: 's1' }) const store = storeFor(b, 'conversation', id) store.actions.select({ turnSeq: 3, callId: 'c1' }) store.actions.setDraft('half-typed') - // The late list refresh lands (host knows the cwd → better fallback label). - feed(b, [{ id: 's1', cwd: '/w/proj-a' }]) - await b.sessions.manager.refreshList() - await flush() - expect(b.sessions.list.getSnapshot().byId[id]).toMatchObject({ displayTitle: 'proj-a' }) - expect(b.sessions.list.getSnapshot().byId[id]?.title).toBeUndefined() + projection.set({ displayTitle: 'proj-a' }) + expect(projection.getSnapshot().displayTitle).toBe('proj-a') const after = storeFor(b, 'conversation', id) expect(after).toBe(store) @@ -142,32 +117,20 @@ describe('selection survives on the store seat', () => { expect(after.store.getSnapshot().draft).toBe('half-typed') }) - it('session death buries the instance and its persisted draft', async () => { + it('session death buries the instance and its persisted draft', () => { const b = bench() - feed(b, [{ id: 's1' }, { id: 's2' }]) - await b.sessions.manager.refreshList() - await flush() - // Mint the scope (store prune rides the scope-teardown axis: no scope, - // no teardown — the real page always resolves the binding to render). - b.sessions.binding(sid('s1')) const doomed = storeFor(b, 'conversation', sid('s1')) doomed.actions.setDraft('to be buried') doomed.actions.select({ turnSeq: 1 }) expect(localStorage.getItem('dsh.conversation.chat.s1')).not.toBeNull() - // Watch elsewhere so s1's scope teardown is not deferred, then remove it. - b.sessions.binding(sid('s2')) - feed(b, [{ id: 's2' }]) - await b.sessions.manager.refreshList() - await flush() + // SessionsService calls this public slot lifecycle seam when the scope dies. + b.slots.pruneStoreScope(sid('s1')) // Persisted residue is gone with the session... expect(localStorage.getItem('dsh.conversation.chat.s1')).toBeNull() // ...and a re-created same-id session starts from a FRESH instance. - feed(b, [{ id: 's1' }, { id: 's2' }]) - await b.sessions.manager.refreshList() - await flush() const reborn = storeFor(b, 'conversation', sid('s1')) expect(reborn).not.toBe(doomed) expect(reborn.store.getSnapshot()).toEqual({ selection: null, draft: '', view: null }) diff --git a/packages/client/ui-conversation/tests/service-orchestration.spec.ts b/packages/client/ui-conversation/tests/service-orchestration.spec.ts index 2d3be81a4d..0b107c6dbd 100644 --- a/packages/client/ui-conversation/tests/service-orchestration.spec.ts +++ b/packages/client/ui-conversation/tests/service-orchestration.spec.ts @@ -1,154 +1,70 @@ // @vitest-environment jsdom -/** - * ConversationService orchestration half after the store-seat slimming: - * scope-addressed send/cancel (result folding, root throw), the startSession - * chain (create → sessions.open → scoped send), and the service-unavailable - * loud failures. Selection/draft state left this service for the declared - * chat store (chat-store.spec.ts / selection-survival.spec.ts); the view - * registry left for the 'conversation.view' slot (views-type-chain.spec.tsx). - */ import { Context } from 'cordis' import { describe, expect, it, vi } from 'vitest' import { scopeOf } from '@deepseek-ai/dsh-client-runtime/client' import type { SessionId, SessionsService } from '@deepseek-ai/dsh-client-runtime/client' import { ConversationService } from '@deepseek-ai/dsh-client-ui-conversation/client' -const sid = (s: string): SessionId => s as SessionId - -/** Recover the module-private scope tag through the public seam (same probe as apply-inject.spec). */ +const sid = (id: string) => id as SessionId const SCOPE_TAG: symbol = (() => { - const recorded: (string | symbol)[] = [] - const spy = new Proxy(new Context(), { - get(target, prop, receiver): unknown { - recorded.push(prop) - return Reflect.get(target, prop, receiver) + const reads: (string | symbol)[] = [] + const proxy = new Proxy(new Context(), { + get(target, property, receiver): unknown { + reads.push(property) + return Reflect.get(target, property, receiver) }, }) - void scopeOf(spy) - const symbol = recorded.find((p): p is symbol => typeof p === 'symbol') - if (symbol === undefined) throw new Error('scopeOf probe recorded no symbol read') - return symbol + void scopeOf(proxy) + return reads.find((value): value is symbol => typeof value === 'symbol')! })() -interface SessionDouble { - prompt: ReturnType - cancel: ReturnType -} - -async function bench(opts?: { sessions?: boolean }) { +async function bench(withSessions = true) { const ctx = new Context() - const sessionDoubles = new Map() - const scopes = new Map() - const mint = (id: SessionId): Context => { - let scoped = scopes.get(id) - if (scoped === undefined) { - const fiber = ctx.plugin(() => {}) - scoped = fiber.ctx.extend({ [SCOPE_TAG]: id }) - scopes.set(id, scoped) - } - return scoped - } - const createMock = vi.fn(() => Promise.resolve(sid('new-1'))) - const openMock = vi.fn() - const sessionsFake = { - manager: { - get: (id: SessionId) => { - let s = sessionDoubles.get(id) - if (s === undefined) { - s = { - prompt: vi.fn(() => Promise.resolve({ ok: true, value: { accepted: true } })), - cancel: vi.fn(() => Promise.resolve({ ok: true, value: { accepted: true } })), - } - sessionDoubles.set(id, s) - } - return s - }, - }, - create: createMock, - open: openMock, - scope: (id: SessionId) => (id === sid('new-1') ? mint(id) : scopes.get(id)), + const prompt = vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })) + const cancel = vi.fn(() => Promise.resolve({ ok: true as const, value: { accepted: true as const } })) + const loadOlder = vi.fn(() => Promise.resolve()) + const updatePendingPrompt = vi.fn() + const retryPendingPrompt = vi.fn() + const sessions = { + binding: (sessionId: SessionId) => ({ + sessionId, session: { prompt, cancel, loadOlder, updatePendingPrompt, retryPendingPrompt }, + }), scopeOf, } as unknown as SessionsService - if (opts?.sessions !== false) ctx.provide('sessions', sessionsFake) - // Class-plugin mount — the same form apply.ts uses in production. - const fiber = ctx.plugin(ConversationService) - await fiber.await() - const svc = ctx.get('conversation') as ConversationService - const scopedSvc = (id: SessionId) => mint(id).get('conversation') as ConversationService - return { ctx, svc, scopedSvc, mint, sessionDoubles, sessionsFake, createMock, openMock } + if (withSessions) ctx.provide('sessions', sessions) + await ctx.plugin(ConversationService).await() + const root = ctx.get('conversation') as ConversationService + const scoped = ctx.plugin(() => {}).ctx.extend({ [SCOPE_TAG]: sid('s1') }).get('conversation') as ConversationService + return { root, scoped, prompt, cancel, loadOlder, updatePendingPrompt, retryPendingPrompt } } -describe('send / cancel', () => { - it('sends one text block through the scoped session with the mode', async () => { +describe('ConversationService', () => { + it('routes ordinary and retained-prompt operations through the public Session binding', async () => { const b = await bench() - await b.scopedSvc(sid('s1')).send('hello', 'steer') - expect(b.sessionDoubles.get(sid('s1'))!.prompt).toHaveBeenCalledWith( - [{ type: 'text', text: 'hello' }], 'steer') + await b.scoped.send('hello', 'steer') + await b.scoped.cancel() + await b.scoped.loadOlder() + b.scoped.updatePendingPrompt('revised') + b.scoped.retryPendingPrompt() + expect(b.prompt).toHaveBeenCalledWith([{ type: 'text', text: 'hello' }], 'steer') + expect(b.cancel).toHaveBeenCalledOnce() + expect(b.loadOlder).toHaveBeenCalledOnce() + expect(b.updatePendingPrompt).toHaveBeenCalledWith('revised') + expect(b.retryPendingPrompt).toHaveBeenCalledOnce() }) - it('folds business failure into a thrown error carrying code and message', async () => { + it('folds Session business failures into callback rejections', async () => { const b = await bench() - const s = b.scopedSvc(sid('s1')) - // Materialize the double first (manager.get is the lazy mint point). - b.sessionsFake.manager.get(sid('s1')) - const double = b.sessionDoubles.get(sid('s1'))! - double.prompt.mockResolvedValue({ ok: false, error: { code: 'agent-busy', message: 'busy' } }) - await expect(s.send('x', 'queue')).rejects.toThrow(/send failed: agent-busy: busy/) + b.prompt.mockResolvedValueOnce({ ok: false, error: { code: 'agent-busy', message: 'busy', details: {} } } as never) + await expect(b.scoped.send('x', 'queue')).rejects.toThrow('conversation.send failed: agent-busy: busy') + b.cancel.mockResolvedValueOnce({ ok: false, error: { code: 'internal', message: 'nope', details: {} } } as never) + await expect(b.scoped.cancel()).rejects.toThrow('conversation.cancel failed: internal: nope') }) - it('cancel resolves on ok and throws the folded business error', async () => { + it('fails loudly from the root scope or without SessionsService', async () => { const b = await bench() - const s = b.scopedSvc(sid('s1')) - await s.cancel() - const double = b.sessionDoubles.get(sid('s1'))! - expect(double.cancel).toHaveBeenCalledTimes(1) - double.cancel.mockResolvedValue({ ok: false, error: { code: 'internal', message: 'nope' } }) - await expect(s.cancel()).rejects.toThrow(/cancel failed: internal: nope/) - }) - - it('root-context send and cancel throw the addressing hint', async () => { - const b = await bench() - await expect(b.svc.send('x', 'queue')).rejects.toThrow(/requires a session scope/) - await expect(b.svc.cancel()).rejects.toThrow(/requires a session scope/) - }) -}) - -describe('startSession chain', () => { - it('creates, navigates through sessions.open, then sends through the new scope', async () => { - const b = await bench() - await b.svc.startSession({ cwd: '/proj', text: 'first', mode: 'queue' }) - expect(b.createMock).toHaveBeenCalledWith({ cwd: '/proj' }) - expect(b.openMock).toHaveBeenCalledWith(sid('new-1')) - expect(b.sessionDoubles.get(sid('new-1'))!.prompt).toHaveBeenCalledWith( - [{ type: 'text', text: 'first' }], 'queue') - }) - - it('omits cwd from create when not chosen', async () => { - const b = await bench() - await b.svc.startSession({ text: 't', mode: 'steer' }) - expect(b.createMock).toHaveBeenCalledWith({}) - }) - - it('fails loud when the created session resolves no scope', async () => { - const b = await bench() - ;(b.sessionsFake.create as ReturnType).mockResolvedValue(sid('ghost')) - await expect(b.svc.startSession({ text: 't', mode: 'queue' })).rejects.toThrow(/resolved no scope/) - }) -}) - -describe('service-unavailable loud failures', () => { - it('throws when sessions is missing', async () => { - const b = await bench({ sessions: false }) - await expect(b.svc.startSession({ text: 't', mode: 'queue' })).rejects.toThrow(/sessions service unavailable/) - }) - - it('startSession fails loud when the new scope cannot resolve conversation', async () => { - const b = await bench() - // A scope minted outside the service tree: scoped.get('conversation') finds nothing. - const foreign = new Context() - const foreignScope = foreign.plugin(() => {}).ctx.extend({}) - ;(b.sessionsFake.scope as unknown) = () => foreignScope - await expect(b.svc.startSession({ text: 't', mode: 'queue' })) - .rejects.toThrow(/conversation service unavailable through the new scope/) + await expect(b.root.send('x', 'queue')).rejects.toThrow(/requires a session scope/) + const missing = await bench(false) + await expect(missing.root.send('x', 'queue')).rejects.toThrow(/sessions service unavailable/) }) }) diff --git a/packages/client/ui-conversation/tests/skeleton-branches.spec.tsx b/packages/client/ui-conversation/tests/skeleton-branches.spec.tsx deleted file mode 100644 index 4eb70ea39f..0000000000 --- a/packages/client/ui-conversation/tests/skeleton-branches.spec.tsx +++ /dev/null @@ -1,318 +0,0 @@ -// @vitest-environment jsdom -// Skeleton branch tails for the coverage gate (complements skeleton.spec.tsx -// acceptance flows), four-share props form: breadcrumb ancestry derivation + -// error strip in ConversationRoot, DetailsPanel non-JSON args / non-text -// result blocks / error-only results over the shared store, EmptyState -// failure surface and path-modal confirm with in-component cwd derivation. - -import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, fireEvent, render, waitFor } from '@testing-library/react' -import { hookOf } from './hook.ts' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' -import type { UseSession } from '@deepseek-ai/dsh-client-ui-slots' -import type { ConversationSnapshot, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client' -import type { SelectionTarget, ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' -// Export discipline: packages/client/AGENTS.md. -import { createChatStore } from '../src/client/stores.ts' -import { ConversationRoot, type ConversationRootProps } from '../src/client/skeleton/ConversationRoot.tsx' -import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx' -import { EmptyState } from '../src/client/skeleton/EmptyState.tsx' - -afterEach(cleanup) - -const SID = 's1' as SessionId -/** Fallback-only chain stub (no takeover registered in these benches). */ -const fallbackRenderSlotChain: ConversationRootProps['renderSlotChain'] = - (_key, _owner, opts) => opts?.fallback ?? null - -function snapshotBase(): ConversationSnapshot { - return { - sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], - pending: [], running: false, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, lastAgentError: null, - } as ConversationSnapshot -} - -function sessionSource(over?: Partial) { - const snap = { ...snapshotBase(), ...over } - return { - getSnapshot: () => snap, - subscribe: () => () => {}, - } -} - -/** Sessions-list stub over a snapshot store (the standard useSessions hook shape). */ -function listHook(rows: { id: string; title: string; cwd?: string; parentId?: string }[]) { - const store = createSnapshotStore({ - ids: rows.map(r => r.id as SessionId), - byId: Object.fromEntries(rows.map(r => [r.id, { - id: r.id as SessionId, title: `durable ${r.title}`, displayTitle: r.title, running: false, updatedAt: 1, - ...(r.cwd !== undefined ? { cwd: r.cwd } : {}), - ...(r.parentId !== undefined ? { parentId: r.parentId as SessionId } : {}), - }])), - current: undefined, - } as SessionListState) - return hookOf(store) -} - -describe('ConversationRoot branches', () => { - const chatTab: ViewTab = { id: 'chat', label: 'Chat' } - /** renderSlot stub in the outlet's baked shape (ring key + only filter marker). */ - const stubRenderSlot = (() =>
) as unknown as ConversationRootProps['renderSlot'] - /** SessionProvider seat stub (render-prop pass-through; ConversationRoot never invokes it). */ - const SessionProviderStub: ConversationRootProps['SessionProvider'] = ({ children }) => <>{children(SID)} - - function rootProps(over?: { - rows?: { id: string; title: string; parentId?: string }[] - snapshot?: Partial - }) { - const open = vi.fn() - const chat = createChatStore().create() - const view = render( - } - useSessions={listHook(over?.rows ?? [])} - useStore={hookOf(chat)} - actions={chat.actions} - renderSlot={stubRenderSlot} - renderSlotChain={fallbackRenderSlotChain} - SessionProvider={SessionProviderStub} - views={{ list: () => [chatTab], subscribe: () => () => {}, version: () => 1 }} - send={vi.fn()} - stop={vi.fn()} - open={open} - />, - ) - return { view, open, chat } - } - - it('derives the ancestry breadcrumb from the sessions list and navigates on ancestor click', () => { - const { view, open } = rootProps({ - rows: [{ id: 'root-1', title: 'Workspace' }, { id: 's1', title: 'Current', parentId: 'root-1' }], - }) - expect(view.getByText('Workspace')).toBeTruthy() - expect(view.getByText('/')).toBeTruthy() - fireEvent.click(view.getByText('Workspace')) - expect(open).toHaveBeenCalledWith('root-1' as SessionId) - // The last crumb is the current session: disabled, no navigation. - fireEvent.click(view.getByText('Current')) - expect(open).toHaveBeenCalledTimes(1) - }) - - it('a broken parent link stops the ancestry walk at the known chain', () => { - const { view } = rootProps({ - rows: [{ id: 's1', title: 'Orphan', parentId: 'vanished' }], - }) - // The walk keeps s1 itself and stops where the parent is unknown. - expect(view.getByText('Orphan')).toBeTruthy() - }) - - it('falls back to the raw session id without ancestry and counts user turns', () => { - const { view } = rootProps({ - snapshot: { nodes: [{ kind: 'user', seq: 1 } as never, { kind: 'assistant', seq: 2 } as never] }, - }) - expect(view.getByText(SID)).toBeTruthy() - expect(view.getByText(/1 turns/)).toBeTruthy() - }) - - it('surfaces promptError through the composer error strip', () => { - const { view } = rootProps({ - snapshot: { promptError: { op: 'stop', error: { message: 'halt', code: 'internal' } } as never }, - }) - expect(view.getByText(/停止失败:halt(internal)/)).toBeTruthy() - }) - - it('an unknown stored view id falls back to the first registered view', () => { - const { chat } = rootProps({}) - cleanup() - chat.actions.setView('gone') - const view = render( - } - useSessions={listHook([])} - useStore={hookOf(chat)} - actions={chat.actions} - renderSlot={stubRenderSlot} - renderSlotChain={fallbackRenderSlotChain} - SessionProvider={SessionProviderStub} - views={{ list: () => [chatTab], subscribe: () => () => {}, version: () => 1 }} - send={vi.fn()} - stop={vi.fn()} - open={vi.fn()} - />, - ) - expect(view.getByTestId('view-body')).toBeTruthy() - }) -}) - -describe('DetailsPanel branches', () => { - function panel(selection: SelectionTarget | null, snapshot?: Partial) { - const chat = createChatStore().create() - if (selection !== null) chat.actions.select(selection) - return render( - } - useSessions={listHook([])} - useStore={hookOf(chat)} - actions={chat.actions} - closeDetails={vi.fn()} - />, - ) - } - - it('shows non-JSON args verbatim (streaming fragment path)', () => { - const view = panel({ turnSeq: 1, callId: 'c1', toolName: 'bash' }, { - runningCalls: [{ callId: 'c1', name: 'bash', argsRaw: '{"cmd": tru', turn: 1, step: 1, time: 1_000, callView: null }], - }) - expect(view.getByText('{"cmd": tru')).toBeTruthy() - }) - - it('a selection without callId renders the empty hint (selector null arm)', () => { - const view = panel({ turnSeq: 2 }) - expect(view.getByText(/点击消息流中的工具行查看详情/)).toBeTruthy() - }) - - it('snapshot updates re-run the material selector through the shallow equality arm', () => { - let snap = { ...snapshotBase(), runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{"a":1}', turn: 1, step: 1, time: 1_000, callView: null }] } as ConversationSnapshot - const subs = new Set<() => void>() - const source = { - getSnapshot: () => snap, - subscribe: (fn: () => void) => { - subs.add(fn) - return () => subs.delete(fn) - }, - } - const chat = createChatStore().create() - chat.actions.select({ turnSeq: 1, callId: 'c9' }) - const view = render( - } - useSessions={listHook([])} - useStore={hookOf(chat)} - actions={chat.actions} - closeDetails={vi.fn()} - />, - ) - expect(view.getByText(/"a": 1/)).toBeTruthy() - // Top-level swap with identical material members: the eq arm short-circuits. - snap = { ...snap } - for (const fn of [...subs]) fn() - expect(view.getByText(/"a": 1/)).toBeTruthy() - }) - - it('windowless call material: no name/args fallback to callId, mixed node walk skips non-matches', () => { - // A tool-result whose call head fell outside the window (call === null), - // preceded by non-matching nodes so the walk exercises both filter arms. - const view = panel({ turnSeq: 1, callId: 'c8' }, { - nodes: [ - { kind: 'user', seq: 1, content: [], source: null } as never, - { kind: 'tool-result', seq: 2, callId: 'other', call: { name: 'x', argsRaw: '{}' }, content: [], isError: false, callView: null, resultView: null } as never, - { kind: 'tool-result', seq: 3, callId: 'c8', call: null, content: [], isError: false, callView: null, resultView: null } as never, - ], - }) - expect(view.getByText('c8')).toBeTruthy() - }) - - it('stringifies non-text result blocks and renders error-only results', () => { - const withBlocks = panel({ turnSeq: 1, callId: 'c2' }, { - nodes: [{ - kind: 'tool-result', seq: 3, callId: 'c2', call: { name: 'read', argsRaw: '{}' }, - content: [{ type: 'image', data: 'x' } as never], - isError: false, callView: null, resultView: null, - } as never], - }) - expect(withBlocks.getByText(/"type": "image"/)).toBeTruthy() - const errorOnly = panel({ turnSeq: 1, callId: 'c3' }, { - nodes: [{ - kind: 'tool-result', seq: 4, callId: 'c3', call: { name: 'bash', argsRaw: '{}' }, - content: [], isError: true, error: { name: 'ToolError', code: 'timeout' }, - callView: null, resultView: null, - } as never], - }) - expect(errorOnly.getByText(/ToolError: timeout/)).toBeTruthy() - }) -}) - -describe('EmptyState branches', () => { - const noopCreate = () => Promise.resolve() - - it('keeps the draft and surfaces a local error strip when startSession rejects', async () => { - const startSession = vi.fn(() => Promise.reject(new Error('create down'))) - const view = render( - , - ) - const textarea = view.container.querySelector('textarea')! - fireEvent.change(textarea, { target: { value: 'first task' } }) - fireEvent.keyDown(textarea, { key: 'Enter' }) - await waitFor(() => expect(view.getByText(/发送失败:create down/)).toBeTruthy()) - expect((textarea as HTMLTextAreaElement).value).toBe('first task') - }) - - it('non-Error rejection reasons stringify into the error strip', async () => { - const startSession = vi.fn(() => Promise.reject('plain-string')) - const view = render( - , - ) - const textarea = view.container.querySelector('textarea')! - fireEvent.change(textarea, { target: { value: 'go' } }) - fireEvent.keyDown(textarea, { key: 'Enter' }) - await waitFor(() => expect(view.getByText(/发送失败:plain-string/)).toBeTruthy()) - }) - - it('cwd derivation skips blank cwds; menu picks, path modal confirms, submits the typed path', async () => { - const startSession = vi.fn(() => Promise.resolve()) - const view = render( - , - ) - fireEvent.click(view.getByRole('button', { name: '项目目录' })) - expect([...view.getByRole('menu').querySelectorAll('[role="menuitem"]')].map(el => el.textContent)) - .toEqual(['proj', 'New Workspace']) - fireEvent.click(view.getByRole('menuitem', { name: 'proj' })) - expect(view.getByRole('button', { name: '项目目录' }).textContent).toContain('proj') - fireEvent.click(view.getByRole('button', { name: '项目目录' })) - fireEvent.mouseEnter(view.getByRole('menuitem', { name: 'New Workspace' }).parentElement as HTMLElement) - fireEvent.click(view.getByRole('menuitem', { name: 'Use a existing folder' })) - const custom = view.getByLabelText('Folder path') - fireEvent.change(custom, { target: { value: '/typed/dir' } }) - fireEvent.click(view.getByRole('button', { name: 'Open Folder' })) - const textarea = view.container.querySelector('textarea')! - fireEvent.change(textarea, { target: { value: 'task' } }) - fireEvent.keyDown(textarea, { key: 'Enter' }) - await waitFor(() => expect(startSession).toHaveBeenCalledWith({ text: 'task', mode: 'queue', cwd: '/typed/dir' })) - }) - - it('Create modal surfaces inject failures inline', async () => { - const createWorkspaceSession = vi.fn(() => Promise.reject(new Error('mkdir blocked'))) - const view = render( - Promise.resolve()} - createWorkspaceSession={createWorkspaceSession} - />, - ) - fireEvent.click(view.getByRole('button', { name: '项目目录' })) - fireEvent.mouseEnter(view.getByRole('menuitem', { name: 'New Workspace' }).parentElement as HTMLElement) - fireEvent.click(view.getByRole('menuitem', { name: 'Create new' })) - fireEvent.click(view.getByRole('button', { name: 'Create' })) - await waitFor(() => expect(view.getByRole('alert').textContent).toContain('mkdir blocked')) - }) -}) diff --git a/packages/client/ui-conversation/tests/skeleton.spec.tsx b/packages/client/ui-conversation/tests/skeleton.spec.tsx index a598803a25..fc596ec821 100644 --- a/packages/client/ui-conversation/tests/skeleton.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.spec.tsx @@ -1,344 +1,203 @@ // @vitest-environment jsdom -/** - * Skeleton acceptance over the four-share props form: empty-state transition - * (same InputBar component in hero position, startSession submit, in-component - * cwd derivation), ConversationRoot view switching through the store's view - * field, DetailsPanel selection through the shared store. Components stay - * pure — the framework shares are stubbed (useSession/useSessions), the store - * share is a REAL createChatStore().create() instance (same construction path - * as production), injected callbacks are spies. - */ -import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' -import type { UseSession } from '@deepseek-ai/dsh-client-web-react' -import type { ConversationSnapshot, PendingInteraction, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client' -import { PendingWait } from '@deepseek-ai/dsh-client-runtime/client' -import { RpcId } from '@deepseek-ai/dsh-client-connection/client' -import type { SelectionTarget, ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { + ConversationSnapshot, SessionId, SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' +import type { EmptyStateProps } from '../src/client/skeleton/EmptyState.tsx' import type { ConversationRootProps } from '../src/client/skeleton/ConversationRoot.tsx' -// Export discipline: packages/client/AGENTS.md. import { createChatStore } from '../src/client/stores.ts' import { ConversationRoot } from '../src/client/skeleton/ConversationRoot.tsx' -import { DetailsPanel } from '../src/client/skeleton/DetailsPanel.tsx' import { EmptyState } from '../src/client/skeleton/EmptyState.tsx' -const sid = (s: string): SessionId => s as SessionId - afterEach(cleanup) -beforeEach(() => { - // jsdom normally provides localStorage; some host Node builds surface it as undefined. - globalThis.localStorage?.clear() +beforeEach(() => { localStorage.clear() }) + +const sid = (id: string) => id as SessionId +const wid = (id: string) => id as WorkspaceId +const SID = sid('s1') + +function workspace(id = 'w1'): WorkspaceView { + return { + workspaceId: wid(id), path: `/projects/${id}`, title: id, sessionIds: [], + createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', + } +} + +type SessionIntent = NonNullable +type WorkspaceIntent = NonNullable + +const workspaceState = ( + items: readonly WorkspaceView[], workspaceIntent?: WorkspaceIntent, +): WorkspaceListState => ({ + items, intent: workspaceIntent, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, }) +const hook = (snapshot: T) => (selector: (state: T) => S): S => selector(snapshot) -/** Minimal conversation snapshot slice the skeleton reads. */ -interface FakeSnapshot { - nodes: readonly { - kind: string - seq?: number - time?: number - callId?: string - call?: { name: string; argsRaw: string } | null - callTime?: number | null - content?: readonly { type: string; text?: string }[] - isError?: boolean - callView?: null - resultView?: null - }[] - runningCalls: readonly { - callId: string - name: string - argsRaw: string - turn?: number - step?: number - time?: number - callView?: null - }[] - running: boolean - removed: boolean - promptError: { op: 'send' | 'stop'; error: { message: string; code: string } } | null - pending: readonly PendingInteraction[] +function mountEmpty( + intent: SessionIntent, + items: readonly WorkspaceView[] = [], + localWorkspace?: WorkspaceIntent, +) { + const updateSessionPrompt = vi.fn() + const sendSession = vi.fn() + const startSession = vi.fn() + let pickerOwner: unknown + const sessionState: SessionListState = { + ids: [], byId: {}, current: intent.sessionId, intent, phase: 'ready', + } + const workspaceIntent = intent.target.kind === 'workspace-intent' + ? localWorkspace ?? { name: 'workspace', phase: 'ready' as const } + : undefined + const view = render( + { pickerOwner = owner; return null }) as EmptyStateProps['renderSlot']} + />, + ) + return { view, updateSessionPrompt, sendSession, startSession, pickerOwner: () => pickerOwner } } -function fakeSession(init: Partial = {}) { - const store = createSnapshotStore({ - nodes: [], runningCalls: [], running: false, removed: false, promptError: null, pending: [], ...init, - }) - return { store, useSession: bindSnapshotSelector(store) as unknown as UseSession } -} - -/** Sessions-list stub: the standard useSessions hook over a snapshot store. */ -function fakeSessions(rows: { id: string; title: string; cwd?: string; parentId?: string }[]) { - const store = createSnapshotStore({ - ids: rows.map(r => sid(r.id)), - byId: Object.fromEntries(rows.map(r => [r.id, { - id: sid(r.id), title: `durable ${r.title}`, displayTitle: r.title, running: false, updatedAt: 1, - ...(r.cwd !== undefined ? { cwd: r.cwd } : {}), - ...(r.parentId !== undefined ? { parentId: sid(r.parentId) } : {}), - }])), - current: undefined, - } as SessionListState) - return { store, useSessions: bindSnapshotSelector(store) } -} - -/** SessionProvider seat stub (render-prop pass-through; ConversationRoot never invokes it). */ -const SessionProviderStub: ConversationRootProps['SessionProvider'] = ({ children }) => <>{children(sid('s1'))} - describe('EmptyState', () => { - const noopCreate = () => Promise.resolve() - - it('derives cwd options from the sessions list, submits startSession, failure surfaces locally', async () => { - const { useSessions } = fakeSessions([ - { id: 'a', title: 'a', cwd: '/w/app' }, - { id: 'b', title: 'b', cwd: '/w/lib' }, - { id: 'c', title: 'c', cwd: '/w/app' }, // duplicate cwd dedupes - ]) - let reject!: (e: Error) => void - const startSession = vi.fn(() => new Promise((_res, rej) => { reject = rej })) - render( - , - ) - - const trigger = screen.getByRole('button', { name: '项目目录' }) - fireEvent.click(trigger) - const menu = screen.getByRole('menu') - expect([...menu.querySelectorAll('[role="menuitem"]')].map(el => el.textContent)) - .toEqual(['app', 'lib', 'New Workspace']) - fireEvent.click(screen.getByRole('menuitem', { name: 'app' })) - const box = screen.getByPlaceholderText('Message to run task, plan and build, enter for / commands') - fireEvent.change(box, { target: { value: '造一个轮子' } }) - fireEvent.keyDown(box, { key: 'Enter' }) - expect(startSession).toHaveBeenCalledWith({ text: '造一个轮子', mode: 'queue', cwd: '/w/app' }) - - reject(new Error('后端拒收')) - expect(await screen.findByText(/后端拒收/)).toBeTruthy() - // Draft survives the failure for retry. - expect((box as HTMLTextAreaElement).value).toBe('造一个轮子') + it('reads the Workspace and Session intents from runtime projections', () => { + const b = mountEmpty({ + sessionId: sid('local-1'), target: { kind: 'workspace-intent' }, + prompt: 'draft', phase: 'ready', + }) + expect(b.view.getByRole('button', { name: 'Choose workspace' }).textContent).toContain('workspace') + fireEvent.change(b.view.getByPlaceholderText('Describe what you want to build'), { target: { value: 'build it' } }) + expect(b.updateSessionPrompt).toHaveBeenCalledWith('build it') + fireEvent.click(b.view.getByRole('button', { name: 'Send message' })) + expect(b.sendSession).toHaveBeenCalledOnce() }) - it('Use a existing folder opens the path modal and Open Folder sets the chip', () => { - const { useSessions } = fakeSessions([]) - render( - Promise.resolve()} - createWorkspaceSession={noopCreate} - />, - ) - fireEvent.click(screen.getByRole('button', { name: '项目目录' })) - const newWs = screen.getByRole('menuitem', { name: 'New Workspace' }) - fireEvent.mouseEnter(newWs.parentElement as HTMLElement) - fireEvent.click(screen.getByRole('menuitem', { name: 'Use a existing folder' })) - expect(screen.getByRole('dialog', { name: 'Enter an existing folder path' })).toBeTruthy() - const path = screen.getByLabelText('Folder path') as HTMLInputElement - fireEvent.change(path, { target: { value: '/tmp/fresh' } }) - fireEvent.click(screen.getByRole('button', { name: 'Open Folder' })) - expect(screen.queryByRole('dialog')).toBeNull() - expect(screen.getByRole('button', { name: '项目目录' }).textContent).toContain('fresh') + it('uses useWorkspaces for the selected label and preserves the prompt when retargeting', () => { + const first = workspace('first') + const b = mountEmpty({ + sessionId: sid('local-2'), target: { kind: 'workspace', workspaceId: first.workspaceId }, + prompt: 'keep me', phase: 'ready', + }, [first]) + expect(b.view.getByRole('button', { name: 'Choose workspace' }).textContent).toContain('first') + fireEvent.click(b.view.getByRole('button', { name: 'Choose workspace' })) + const owner = b.pickerOwner() as { onPick(id: WorkspaceId): void } + owner.onPick(wid('second')) + expect(b.startSession).toHaveBeenCalledWith(wid('second'), 'keep me') }) - it('Create new opens the modal and createWorkspaceSession succeeds', async () => { - const { useSessions } = fakeSessions([]) - const createWorkspaceSession = vi.fn(() => Promise.resolve()) - render( - Promise.resolve()} - createWorkspaceSession={createWorkspaceSession} - />, - ) - fireEvent.click(screen.getByRole('button', { name: '项目目录' })) - fireEvent.mouseEnter(screen.getByRole('menuitem', { name: 'New Workspace' }).parentElement as HTMLElement) - fireEvent.click(screen.getByRole('menuitem', { name: 'Create new' })) - expect(screen.getByRole('dialog', { name: 'Create new workspace' })).toBeTruthy() - const name = screen.getByLabelText('Workspace name') as HTMLInputElement - expect(name.value).toBe('New WorkSpace') - fireEvent.change(name, { target: { value: 'My Proj' } }) - fireEvent.keyDown(name, { key: 'Enter' }) - await vi.waitFor(() => expect(createWorkspaceSession).toHaveBeenCalledWith('My Proj')) - }) - - it('Create modal Cancel dismisses without calling createWorkspaceSession', () => { - const { useSessions } = fakeSessions([]) - const createWorkspaceSession = vi.fn(() => Promise.resolve()) - render( - Promise.resolve()} - createWorkspaceSession={createWorkspaceSession} - />, - ) - fireEvent.click(screen.getByRole('button', { name: '项目目录' })) - fireEvent.mouseEnter(screen.getByRole('menuitem', { name: 'New Workspace' }).parentElement as HTMLElement) - fireEvent.click(screen.getByRole('menuitem', { name: 'Create new' })) - fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) - expect(screen.queryByRole('dialog')).toBeNull() - expect(createWorkspaceSession).not.toHaveBeenCalled() + it('exposes materialization phase and failure text', () => { + const creating = mountEmpty({ + sessionId: sid('local-3'), target: { kind: 'workspace-intent' }, + prompt: 'x', phase: 'ready', + }, [], { name: 'workspace', phase: 'creating' }) + expect(creating.view.getByRole('status').textContent).toBe('Creating workspace…') + cleanup() + const workspaceFailed = mountEmpty({ + sessionId: sid('local-3'), target: { kind: 'workspace-intent' }, + prompt: 'x', phase: 'ready', + }, [], { name: 'workspace', phase: 'ready', error: 'offline' }) + expect(workspaceFailed.view.getByRole('alert').textContent).toBe('Workspace creation failed: offline') + cleanup() + const failed = mountEmpty({ + sessionId: sid('local-3'), target: { kind: 'workspace', workspaceId: wid('w1') }, + prompt: 'x', phase: 'ready', error: { step: 'session', message: 'offline' }, + }, [workspace()]) + expect(failed.view.getByRole('alert').textContent).toBe('Session creation failed: offline') }) }) -describe('ConversationRoot', () => { - function bench( - tabs: ViewTab[], activeView?: string, init: Partial = {}, - renderSlotChain?: ConversationRootProps['renderSlotChain'], - ) { - const { useSession } = fakeSession({ nodes: [{ kind: 'user' }, { kind: 'user' }], ...init }) - const { useSessions } = fakeSessions([ - { id: 'root', title: 'proj' }, - { id: 's1', title: 'child', parentId: 'root' }, - ]) - const chat = createChatStore().create() - if (activeView !== undefined) chat.actions.setView(activeView) - const send = vi.fn() - const stop = vi.fn() - const open = vi.fn() - // The renderSlot share as the outlet would bake it: renders a marker for - // the ring key carrying the active-id filter (a Mock cannot satisfy the - // generic method type directly — cast once at the prop seam). - const renderSlot = vi.fn((key: string, _owner: object, opts?: { only?: string }) => ( -
- )) - const ui = render( - opts?.fallback ?? null)} - SessionProvider={SessionProviderStub} - views={{ - list: () => tabs, - subscribe: () => () => {}, - version: () => 1, - }} - send={send} - stop={stop} - open={open} - />) - return { ui, chat, send, stop, open, renderSlot } +function conversationSnapshot( + composerPhase: ConversationSnapshot['composerPhase'], + pendingPrompt: ConversationSnapshot['pendingPrompt'] = null, +): ConversationSnapshot { + return { + sessionId: SID, nodes: [], foldDegraded: false, partial: null, runningCalls: [], + pending: [], running: false, composerPhase, removed: false, openState: 'open', openError: null, + hasMore: false, loadingOlder: false, promptError: null, intent: null, pendingPrompt, lastAgentError: null, } +} - const tab = (id: string, label: string): ViewTab => ({ id, label }) - - it('renders breadcrumb chain (useSessions-derived), meta turns, and the default chat view', () => { - const { open } = bench([tab('chat', 'Chat'), tab('trajectory', 'Trajectory')]) - expect(screen.getByText('proj')).toBeTruthy() - expect(screen.getByText('child')).toBeTruthy() - expect(screen.getByText(/2 turns/)).toBeTruthy() - expect(screen.getByTestId('view-chat')).toBeTruthy() - // Ancestor crumb navigates; current crumb is disabled. - fireEvent.click(screen.getByRole('button', { name: 'proj' })) - expect(open).toHaveBeenCalledWith('root') - expect((screen.getByRole('button', { name: 'child' }) as HTMLButtonElement).disabled).toBe(true) +function mountConversation(pendingPrompt: ConversationSnapshot['pendingPrompt'] = null) { + const root = sid('root') + const sessions = createSnapshotStore({ + ids: [root, SID], + byId: { + [root]: { id: root, displayTitle: 'Root', running: false, updatedAt: 1 }, + [SID]: { id: SID, displayTitle: 'Child', parentId: root, cwd: '/projects/one', running: false, updatedAt: 2 }, + }, + current: SID, + intent: undefined, + phase: 'ready', }) - - it('switches views through the store view field and falls back on unknown ids', () => { - const { chat } = bench([tab('chat', 'Chat'), tab('trajectory', 'Trajectory')]) - fireEvent.click(screen.getByRole('tab', { name: 'Trajectory' })) - expect(chat.store.getSnapshot().view).toBe('trajectory') - expect(screen.getByTestId('view-trajectory')).toBeTruthy() - cleanup() - // A stale persisted id (its view plugin unloaded) falls to the first view. - bench([tab('chat', 'Chat'), tab('trajectory', 'Trajectory')], 'ghost-view') - expect(screen.getByTestId('view-chat')).toBeTruthy() - }) - - it('renders the active view through the declared ring slot with the only filter', () => { - const { renderSlot } = bench([tab('chat', 'Chat')]) - // No owner share: views take everything from the standard kit (contract). - expect(renderSlot).toHaveBeenCalledWith('conversation.view', {}, { only: 'chat' }) - expect(screen.getByTestId('view-chat').getAttribute('data-slot')).toBe('conversation.view') - }) - - it('hides the tab strip with a single view; composer writes the store draft and sends it', () => { - const { chat, send } = bench([tab('chat', 'Chat')]) - expect(screen.queryByRole('tablist')).toBeNull() - const box = screen.getByPlaceholderText(/输入消息/) - fireEvent.change(box, { target: { value: 'hi' } }) - // Typing goes through actions.setDraft into the shared store. - expect(chat.store.getSnapshot().draft).toBe('hi') - fireEvent.keyDown(box, { key: 'Enter' }) - expect(send).toHaveBeenCalledWith('hi', 'queue') - }) - - it('dispatches the pending list to the composer chain; all-decline falls back to InputBar', () => { - const wait = new PendingWait('question', RpcId('rq'), sid('s1'), - { questions: [{ id: 'mode', question: 'Choose?', options: [{ label: 'Fast' }] }] } as PendingWait<'question'>['payload'], vi.fn()) - // A matching entry takes the composer over. - const renderSlotChain = vi.fn(() =>
question takeover
) as unknown as ConversationRootProps['renderSlotChain'] - bench([tab('chat', 'Chat')], undefined, { pending: [wait] }, renderSlotChain) - expect(screen.getByText('question takeover')).toBeTruthy() - expect(screen.queryByPlaceholderText(/输入消息/)).toBeNull() - // The owner dispatches the raw pending list (chain currency); routing - // lives in entry selectors, not here. - expect(renderSlotChain).toHaveBeenCalledWith( - 'conversation.composer', - expect.objectContaining({ - interactions: expect.arrayContaining([expect.objectContaining({ key: 'q:rq' })]), - }), - expect.objectContaining({ fallback: expect.anything() }), - ) - cleanup() - // Zero registered entries (default all-decline stub): the fallback IS the - // default InputBar — behavior equals the pre-chain composer. - bench([tab('chat', 'Chat')], undefined, { pending: [wait] }) - expect(screen.getByPlaceholderText(/输入消息/)).toBeTruthy() - }) -}) - -describe('DetailsPanel', () => { - function benchDetails(snapshot: Partial, selection: SelectionTarget | null) { - const { useSession } = fakeSession(snapshot) - const { useSessions } = fakeSessions([]) - const chat = createChatStore().create() - if (selection !== null) chat.actions.select(selection) - const closeDetails = vi.fn() - render( - ) - return { closeDetails, chat } + const workspaces = createSnapshotStore(workspaceState([{ ...workspace('one'), sessionIds: [SID] }])) + const session = createSnapshotStore(conversationSnapshot( + pendingPrompt === null ? 'active' : 'blank', pendingPrompt, + )) + const chat = createChatStore().create() + chat.actions.setDraft('ordinary draft') + const send = vi.fn() + const stop = vi.fn() + const open = vi.fn() + const updateSessionPrompt = vi.fn() + const retrySessionPrompt = vi.fn() + const renderSlot = ((_key: string, _owner: object, opts?: { only?: string }) => ( +
+ )) as ConversationRootProps['renderSlot'] + const renderSlotChain = ((_key, _owner, opts) => opts?.fallback ?? null) as ConversationRootProps['renderSlotChain'] + const SessionProvider: ConversationRootProps['SessionProvider'] = ({ children }) => <>{children(SID)} + const props: ConversationRootProps = { + sessionId: SID, + useSession: bindSnapshotSelector(session), + useSessions: bindSnapshotSelector(sessions), + useWorkspaces: bindSnapshotSelector(workspaces), + useStore: bindSnapshotSelector(chat), + actions: chat.actions, + renderSlot, + renderSlotChain, + SessionProvider, + views: { list: () => [{ id: 'chat', label: 'Chat' }], subscribe: () => () => {}, version: () => 1 }, + send, + stop, + open, + updateSessionPrompt, + retrySessionPrompt, } + const view = render() + return { view, chat, send, open, updateSessionPrompt, retrySessionPrompt } +} - it('renders the selected call args and result off the shared store; close fires the injected callback', () => { - const { closeDetails } = benchDetails({ - nodes: [{ - kind: 'tool-result', seq: 1, time: 1_000, callId: 'c1', - call: { name: 'bash', argsRaw: '{"cmd":"ls"}' }, - callTime: 500, - content: [{ type: 'text', text: 'file-a\nfile-b' }], - isError: false, callView: null, resultView: null, - }], - }, { turnSeq: 1, callId: 'c1' }) - expect(screen.getByText('bash')).toBeTruthy() - expect(screen.getByText(/"cmd": "ls"/)).toBeTruthy() - expect(screen.getByText(/file-a/)).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: '关闭详情' })) - expect(closeDetails).toHaveBeenCalledTimes(1) +describe('ConversationRoot draft ownership', () => { + it('keeps ordinary per-Session composer text in the chat store and selects through runtime actions', () => { + const b = mountConversation() + const box = b.view.getByRole('textbox') + expect((box as HTMLTextAreaElement).value).toBe('ordinary draft') + fireEvent.change(box, { target: { value: 'ordinary revised' } }) + expect(b.chat.store.getSnapshot().draft).toBe('ordinary revised') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(b.send).toHaveBeenCalledWith('ordinary revised', 'queue') + fireEvent.click(b.view.getByRole('button', { name: 'Root' })) + expect(b.open).toHaveBeenCalledWith(sid('root')) }) - it('shows the empty hint without a selection and the running state for open calls', () => { - benchDetails({ runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{}', turn: 1, step: 1, time: 1_000, callView: null }] }, null) - expect(screen.getByText(/点击消息流中的工具行/)).toBeTruthy() - cleanup() - benchDetails({ runningCalls: [{ callId: 'c9', name: 'bash', argsRaw: '{}', turn: 1, step: 1, time: 1_000, callView: null }] }, { turnSeq: 1, callId: 'c9' }) - expect(screen.getByText('运行中…')).toBeTruthy() - }) - - it('reports an out-of-window call distinctly', () => { - benchDetails({}, { turnSeq: 1, callId: 'ghost' }) - expect(screen.getByText(/不在当前窗口内/)).toBeTruthy() + it('reads a retained prompt from useSession and edits/retries it through the scoped Session', () => { + const b = mountConversation({ + workspaceId: wid('one'), text: 'retry me', phase: 'failed', + retry: 'send', error: 'offline', + }) + const box = b.view.getByRole('textbox') + expect((box as HTMLTextAreaElement).value).toBe('retry me') + expect(b.view.getByRole('alert').textContent).toBe('Message send failed: offline') + fireEvent.change(box, { target: { value: 'revised prompt' } }) + expect(b.updateSessionPrompt).toHaveBeenCalledWith('revised prompt') + expect(b.chat.store.getSnapshot().draft).toBe('ordinary draft') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(b.retrySessionPrompt).toHaveBeenCalledOnce() + expect(b.send).not.toHaveBeenCalled() }) }) diff --git a/packages/client/ui-layout/README.md b/packages/client/ui-layout/README.md index 9c31e4cc7a..4a9f5e9bd5 100644 --- a/packages/client/ui-layout/README.md +++ b/packages/client/ui-layout/README.md @@ -1,10 +1,10 @@ # @deepseek-ai/dsh-client-ui-layout -Shell plugin: three-column AppFrame (drag handles, concession chain) + ctx.layout viewing-state service (nav, panel widths, persist); defines the sidebar/conversation/details/conversation.empty slots. The sidebar is fixed-width (it never concedes to viewport pressure — only details shrinks, then auto-closes); a closed sidebar retains a 56px control rail while details closes to zero width; collapse/expand animates the grid tracks on the deepsuite sider curve. Contract: api-contracts v3 §5. +Shell plugin: three-column AppFrame (drag handles and concession chain) plus the `ctx.layout` panel-geometry service; it registers into the runtime-owned `root` slot and declares `sidebar`, `conversation`, `details`, and `conversation.empty`. The sidebar is fixed-width (only details shrinks, then auto-closes); a closed sidebar retains a 56px control rail while details closes to zero width. -Slot declarations use the composed-props entry form (`owner` share, no full `props`): the exported OwnerShare contracts are `SidebarOwnerProps` / `ConvOwnerProps` / `DetailsOwnerProps` / `EmptyOwnerProps` — registrants reference them via `OwnerOf<'sidebar' | ...>` and compose their own injected share locally. No entry declares `children` (declaring it requires the registered component to carry the slots face — reserved for future business slots): delegation authority is the component-side whitelist, i.e. AppFrame's `ScopedSlots` face over sidebar/conversation/details/conversation.empty. Since the root-slot rework the frame itself registers into 'root' and renders those child slots at its own render sites; the shell only renders 'root'. +AppFrame reads the runtime Session projection: `baselinesReady` selects loading, a page-local `SessionListState.intent` selects the empty composer, and a connected Session renders through `SessionProvider`. The conversation and empty-state owner shares are empty; each registrant obtains business data from standard hooks and actions from its own inject face. The sidebar owner share contains only `collapsed` and `width`; navigation actions belong to sidebar's own injected service face. -The export surface is the cross-package contract only: the AppFrame trio (+ `AppFrameProps`) consumed by the web shell's assembly, `LayoutService` with its store shapes (`NavState`/`PanelState`/`ViewId`), and the OwnerShare contracts. The concession-chain solver (`computeColumns`) and its geometry constants are package-internal; tests import them from `/src`. +The `/client` export surface is the plugin body (`apply`/`inject`), `LayoutService`, and the four owner-share interfaces. AppFrame, the panel store, and the concession solver remain package-internal; tests import internals through `/src`. ## Model Experience diff --git a/packages/client/ui-layout/src/client/AppFrame.tsx b/packages/client/ui-layout/src/client/AppFrame.tsx index dfa8271075..27a4af0386 100644 --- a/packages/client/ui-layout/src/client/AppFrame.tsx +++ b/packages/client/ui-layout/src/client/AppFrame.tsx @@ -6,10 +6,10 @@ * renders HERE with live parameters from the concession solve, and the * session pair renders under the SessionProvider standard seat (render-prop * form, injected by the renderer because the children declaration contains - * session-scope slots; session slots get sessionId as a framework-standard - * prop, so the owner shares stay empty). Pure component: everything arrives - * through the four prop shares — zero cordis or framework imports, zero - * self-made hooks. + * session-scope slots; session data arrives through framework-standard props + * and each registrant's inject face). Pure component: everything arrives + * through the three framework shares — zero cordis or framework imports, + * zero self-made hooks. */ import { useCallback, useEffect, useRef, useState } from 'react' import type { ReactNode } from 'react' @@ -18,7 +18,7 @@ import { computeColumns } from './columns.ts' import type { createLayoutStore } from './stores.ts' import css from './AppFrame.module.css' -/** Full composed props: runtime share + child-slot render share + store share (no business face). */ +/** Full composed props: runtime share + child-slot render share + store share. */ export type AppFrameProps = & PropsRuntime<'root'> & PropsRenderSlots<'sidebar' | 'conversation' | 'details' | 'conversation.empty'> @@ -82,8 +82,17 @@ function DragHandle(props: { side: 'sidebar' | 'details'; left: number; onStart: } /** The three-column frame (see module doc). SessionProvider arrives as a standard seat (declaring a session-scope child summons it — no framework import). */ -export function AppFrame({ useStore, actions, renderSlot, SessionProvider }: AppFrameProps) { +export function AppFrame({ + useStore, + actions, + renderSlot, + SessionProvider, + useSessions, + useWorkspaces, +}: AppFrameProps) { const panels = useStore((s) => s) + const sessions = useSessions(s => s) + const baselinesReady = useWorkspaces(s => s.baselinesReady) const frameRef = useRef(null) const [viewport, setViewport] = useState(() => window.innerWidth) @@ -143,24 +152,47 @@ export function AppFrame({ useStore, actions, renderSlot, SessionProvider }: App sidebar keeps the mounted slot at the compact-rail width, and the component sees its rendered state as owner params decided here (collapsed follows the preference, not the resolved width). */} - {renderSlot('sidebar', { collapsed: panels.sidebar === 0, width: cols.sidebar })} + {renderSlot('sidebar', { + collapsed: panels.sidebar === 0, + width: cols.sidebar, + })}
- ( + {!baselinesReady + ? ( <> - {renderSlot('conversation.empty', {})} + +
Loading workspaces and sessions…
+
- )} - > - {() => ( - <> - {/* sessionId is a framework-standard prop on session slots — the owner passes nothing. */} - {renderSlot('conversation', {})} - {renderSlot('details', {})} - - )} -
+ ) + : sessions.intent !== undefined + ? ( + <> + + {renderSlot('conversation.empty', {})} + + + + ) + : ( + ( + <> +
Opening session…
+ + + )} + > + {() => ( + <> + {/* Session data and actions arrive from standard hooks and the registrant's inject face. */} + {renderSlot('conversation', {})} + {renderSlot('details', {})} + + )} +
+ )} {/* The collapsed rail is fixed-width: no resize handle while closed. */} {panels.sidebar > 0 && } {cols.details > 0 && } diff --git a/packages/client/ui-layout/src/client/index.ts b/packages/client/ui-layout/src/client/index.ts index 1aeb04593b..6ecb6f6b1d 100644 --- a/packages/client/ui-layout/src/client/index.ts +++ b/packages/client/ui-layout/src/client/index.ts @@ -29,8 +29,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { // The 'root' entry itself is the runtime's built-in slot (declared // there); these four are the frame's children, declared by the same - // register() call that contributes AppFrame. Session slots carry no - // owner share: the framework injects sessionId as a standard prop. + // register() call that contributes AppFrame. Session owners never pass + // sessionId: the framework injects it as a standard prop. 'sidebar': { kind: 'single'; scope: 'root'; owner: SidebarOwnerProps } 'conversation': { kind: 'single'; scope: 'session'; owner: ConvOwnerProps } 'details': { kind: 'single'; scope: 'session'; owner: DetailsOwnerProps } @@ -41,12 +41,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { // OwnerShare contracts — the render-side share the slot owner supplies at // renderSlot. Registrants IMPORT these and compose their full component props // through the four-share intersection (PropsRuntime & PropsRenderSlots & -// PropsStore & I). Session owner shares stay literally empty: a phantom -// `sessionId?: never` would intersect with the framework's mandatory -// SessionStandardProps.sessionId and collapse the composed props to never — -// the anti-smuggling guard is mutually exclusive with standard injection, so -// the standard member's own type is the only guard on standard keys. Phantom -// members remain fine on keys the standards never claim (EmptyOwnerProps). +// PropsStore & I). Conversation business state and actions arrive through +// framework-standard hooks and each registrant's inject face, not owner props. /** Sidebar owner share: live column state from the frame's concession solve. */ export interface SidebarOwnerProps { @@ -56,13 +52,13 @@ export interface SidebarOwnerProps { width: number } -/** Conversation owner share: empty — sessionId arrives as a framework-standard prop. */ +/** Conversation owner share: business state and actions belong to the registrant. */ export interface ConvOwnerProps {} /** Details owner share: empty — sessionId arrives as a framework-standard prop. */ export interface DetailsOwnerProps {} -/** Empty-state owner share (ui-conversation registers EmptyState here). */ +/** Empty-state owner share: business state and actions belong to the registrant. */ export interface EmptyOwnerProps { children?: never } /** Required services (cordis fiber inject — the loader passes the whole export surface as an object plugin). */ @@ -89,9 +85,8 @@ export function apply(ctx: ClientContext): void { // Exclusive store: the factory itself — the framework instantiates per // entry and delivers useStore/actions to AppFrame as standard props. store: createLayoutStore, - // No business face for the frame (I = {}): the hook's job is the - // assembly side effect wiring the entry's bound actions into the - // cross-plugin service seam. + // The hook's only side effect connects the root store to ctx.layout; + // conversation business actions belong to their registrants. inject: (actions: PanelActions) => { layout.attachPanels(actions) return {} diff --git a/packages/client/ui-layout/src/client/stores.ts b/packages/client/ui-layout/src/client/stores.ts index 688a5fa2b7..06bcbe5ae3 100644 --- a/packages/client/ui-layout/src/client/stores.ts +++ b/packages/client/ui-layout/src/client/stores.ts @@ -13,19 +13,19 @@ import { SIDEBAR_DEFAULT, SIDEBAR_MAX, SIDEBAR_MIN, } from './columns.ts' -/** Panel width preferences in px (0 = closed) — the layout store's state. */ -type PanelWidths = { sidebar: number; details: number } +/** Layout store state: panel width preferences in px (0 = closed). */ +type LayoutState = { sidebar: number; details: number } /** * Annotation twin of the actions literal below (the export needs a declared * return type); drift fails assignability at the defineStore call. */ type LayoutActions = { - setSidebar: (draft: PanelWidths, px: number) => void - setDetails: (draft: PanelWidths, px: number) => void - toggleSidebar: (draft: PanelWidths) => void - openDetails: (draft: PanelWidths) => void - closeDetails: (draft: PanelWidths) => void + setSidebar: (draft: LayoutState, px: number) => void + setDetails: (draft: LayoutState, px: number) => void + toggleSidebar: (draft: LayoutState) => void + openDetails: (draft: LayoutState) => void + closeDetails: (draft: LayoutState) => void } /** @@ -36,9 +36,9 @@ type LayoutActions = { * open/close transitions write 0 / the default explicitly. * @returns the store handle (spec + type + identity + factory in one). */ -export function createLayoutStore(): EngineStoreHandle { - return defineStore({ - init: () => ({ sidebar: SIDEBAR_DEFAULT, details: 0 }), +export function createLayoutStore(): EngineStoreHandle { + const handle = defineStore({ + init: (): LayoutState => ({ sidebar: SIDEBAR_DEFAULT, details: 0 }), persist: 'dsh.layout.panels', actions: { setSidebar: (d, px: number) => { d.sidebar = clampWidth(px, SIDEBAR_MIN, SIDEBAR_MAX) }, @@ -48,4 +48,5 @@ export function createLayoutStore(): EngineStoreHandle { d.details = 0 }, }, }) + return handle } diff --git a/packages/client/ui-layout/tests/app-frame.spec.tsx b/packages/client/ui-layout/tests/app-frame.spec.tsx index 9f8653739d..beebe0aeea 100644 --- a/packages/client/ui-layout/tests/app-frame.spec.tsx +++ b/packages/client/ui-layout/tests/app-frame.spec.tsx @@ -17,9 +17,13 @@ import { AppFrame } from '@deepseek-ai/dsh-client-ui-layout/src/client/AppFrame. import type { AppFrameProps } from '@deepseek-ai/dsh-client-ui-layout/src/client/AppFrame.tsx' import { SIDEBAR_COLLAPSED } from '@deepseek-ai/dsh-client-ui-layout/src/client/columns.ts' import { createLayoutStore } from '@deepseek-ai/dsh-client-ui-layout/src/client/stores.ts' +import type { + SessionId, SessionListState, WorkspaceId, WorkspaceListState, +} from '@deepseek-ai/dsh-client-runtime/client' // Session-mode switch for the SessionProvider stub prop. const sessionMode = { current: true } +const baselinesReady = { current: true } // Render-prop contract stub fed through the standard seat prop (the renderer // injects the real one in production): session mode runs children(id), empty @@ -59,13 +63,31 @@ function mountFrame() { if (key === 'details') return
return
}) as AppFrameProps['renderSlot'] - const useSessions = ((sel: (s: unknown) => unknown) => sel({ ids: [], byId: {} })) as never + const sessionId = 's-test' as SessionId + const workspaceId = 'w-test' as WorkspaceId + const sessionState = { + ids: sessionMode.current ? [sessionId] : [], + byId: sessionMode.current + ? { [sessionId]: { id: sessionId, displayTitle: 'Test', running: false, updatedAt: 1 } } + : {}, + current: sessionMode.current ? sessionId : undefined, + phase: 'ready', + intent: sessionMode.current + ? undefined + : { sessionId: 'intent' as SessionId, target: { kind: 'workspace', workspaceId }, prompt: '', phase: 'connecting' }, + } as SessionListState + const useSessions = ((sel: (s: SessionListState) => unknown) => sel(sessionState)) as never + const workspaceState: WorkspaceListState = { + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: baselinesReady.current, recentWorkspaceId: undefined, + } const utils = render( unknown) => sel(workspaceState)) as never} SessionProvider={SessionProviderStub} />, ) @@ -91,6 +113,7 @@ function drag(handle: Element, fromX: number, toX: number): void { beforeEach(() => { frameWidth = 1920 sessionMode.current = true + baselinesReady.current = true localStorage.clear() // the layout store persists; instances must not bleed across tests vi.useFakeTimers() vi.stubGlobal('ResizeObserver', ResizeObserverStub) @@ -131,13 +154,22 @@ describe('AppFrame', () => { expect(slotCalls.find((c) => c.key === 'details')!.props).toEqual({}) }) - it('renders the empty branch through conversation.empty when no session is current', () => { + it('keeps a connecting page-local Session intent in conversation.empty', () => { sessionMode.current = false const { slotCalls, getByTestId, queryByTestId } = mountFrame() expect(getByTestId('empty-content')).toBeTruthy() expect(queryByTestId('center-content')).toBeNull() expect(slotCalls.map((c) => c.key)).toContain('conversation.empty') expect(slotCalls.map((c) => c.key)).not.toContain('conversation') + expect(slotCalls.find((c) => c.key === 'conversation.empty')!.props).toEqual({}) + }) + + it('keeps the loading branch until both object-layer baselines are ready', () => { + baselinesReady.current = false + const { slotCalls, getByRole } = mountFrame() + expect(getByRole('status').textContent).toContain('Loading workspaces and sessions') + expect(slotCalls.map((c) => c.key)).not.toContain('conversation') + expect(slotCalls.map((c) => c.key)).not.toContain('conversation.empty') }) it('sidebar slot receives live concession output as owner props', () => { diff --git a/packages/client/ui-layout/tests/apply.spec.ts b/packages/client/ui-layout/tests/apply.spec.ts index b9682193fb..bed0987f62 100644 --- a/packages/client/ui-layout/tests/apply.spec.ts +++ b/packages/client/ui-layout/tests/apply.spec.ts @@ -22,12 +22,12 @@ async function bench() { describe('ui-layout client apply', () => { it('declares its service dependencies', () => { - expect(inject).toContain('slots') + expect(inject).toEqual(['slots']) }) it('provides ctx.layout and registers AppFrame into root with the four child declarations', async () => { const { ctx, slots } = await bench() - const fiber = ctx.plugin({ inject: ['slots'], apply }) + const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() expect(ctx.get('layout')).toBeInstanceOf(LayoutService) // The one register() call occupied 'root'… @@ -39,9 +39,23 @@ describe('ui-layout client apply', () => { expect(slots.spec('conversation.empty')).toEqual({ kind: 'single', scope: 'root' }) }) + it('injects no business face and attaches the layout actions', async () => { + const { ctx, slots } = await bench() + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + const actions = { + setSidebar: vi.fn(), setDetails: vi.fn(), toggleSidebar: vi.fn(), openDetails: vi.fn(), closeDetails: vi.fn(), + } + const injected = (slots.entries('root')[0]!.inject as (actions: never) => object)(actions as never) + expect(injected).toEqual({}) + const layout = ctx.get('layout') as LayoutService + layout.toggleSidebar() + expect(actions.toggleSidebar).toHaveBeenCalledOnce() + }) + it('teardown unwinds the service, the root registration, and the child declarations', async () => { const { ctx, slots } = await bench() - const fiber = ctx.plugin({ inject: ['slots'], apply }) + const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() await fiber.dispose() expect(ctx.get('layout')).toBeUndefined() diff --git a/packages/client/ui-primitives/package.json b/packages/client/ui-primitives/package.json index 44c35eb517..7f5c3555bd 100644 --- a/packages/client/ui-primitives/package.json +++ b/packages/client/ui-primitives/package.json @@ -22,12 +22,14 @@ "dependencies": { "clsx": "^2.0.0", "react": "^18.2.0", + "react-dom": "^18.2.0", "react-markdown": "^10.1.0", "remark-gfm": "^4.0.1" }, "devDependencies": { "@deepseek-ai/dsh-invariants": "workspace:^", "@types/react": "~18.3.1", + "@types/react-dom": "~18.3.0", "cordis": "^4.0.0-rc.7" }, "files": [ diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index 3cbcb62d29..b55abe094d 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -7,6 +7,8 @@ * r12, inverted hairline border, shadow-lv3, 4px inset padding. */ .list, .submenu { + /* min-widths below are the design's outer card widths — include the pad. */ + box-sizing: border-box; padding: 4px; display: flex; flex-direction: column; @@ -17,12 +19,22 @@ box-shadow: var(--dsw-shadow-lv3); } +/* Primary card is 218 wide in the design across both hosts. */ .list { position: absolute; top: calc(100% + 4px); left: 0; z-index: 100; - min-width: 130px; + min-width: 218px; +} + +/* Portal mode: fixed in the viewport, coordinates supplied inline from the + * anchor rect (side/align resolved in JS, the in-place offset rules above + * don't apply). */ +.portal { + position: fixed; + top: auto; + left: auto; } /* Open above the anchor (empty-state workspace chip: figma 122:9481). */ @@ -116,7 +128,7 @@ bottom: -4px; left: calc(100% + 10px); z-index: 101; - min-width: 160px; + min-width: 163px; } .submenu::before { diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index 0b07c26357..de015ee534 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -1,10 +1,13 @@ // Menu: minimal controlled dropdown (group-by pickers, project selectors). -// Pure CSS positioning relative to the anchor wrapper — no portal, no popper. +// Default: pure CSS positioning relative to the anchor wrapper — no popper. +// Opt-in `portal` renders the list into document.body, fixed-positioned from +// the anchor rect, for anchors inside overflow-clipping containers (sidebar). // The owner controls `open`; outside-click closing uses one document listener // active only while open. Submenus open on hover/focus inside the same root. -import { useEffect, useRef, useState } from 'react' -import type { ReactNode } from 'react' +import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import type { CSSProperties, ReactNode } from 'react' +import { createPortal } from 'react-dom' import clsx from 'clsx' import { IconCheckOutline16 } from './icons/index.tsx' import css from './Menu.module.css' @@ -43,9 +46,19 @@ function isSeparator(entry: MenuEntry): entry is MenuSeparator { * @param props.onClose - invoked on outside click or Escape. * @param props.align - list alignment against the anchor (default 'start'). * @param props.side - open below (`bottom`, default) or above (`top`) the anchor. + * @param props.portal - render the list into document.body, fixed-positioned + * from the anchor rect (repositions on scroll/resize while open). Use when an + * ancestor's overflow clipping would crop the in-place list; default false + * keeps the pure-CSS in-place behavior. + * @param props.getAnchorRect - portal mode only: supply the anchor rect + * directly (e.g. from a host-owned trigger button) instead of measuring the + * Menu's own wrapper span. Required when the wrapper isn't itself laid out at + * the trigger (render-prop anchors, effect-positioned proxies — measuring the + * wrapper there races the host's layout effects). Called on open and on every + * scroll/resize; return null to skip placement for that frame. * @returns anchor wrapper with the conditional list. */ -export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align = 'start', side = 'bottom', className }: { +export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align = 'start', side = 'bottom', portal = false, getAnchorRect, className }: { open: boolean anchor: ReactNode items: readonly MenuEntry[] @@ -54,10 +67,44 @@ export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align onClose: () => void align?: 'start' | 'end' side?: 'bottom' | 'top' + portal?: boolean + getAnchorRect?: () => DOMRect | null className?: string }) { const rootRef = useRef(null) + const listRef = useRef(null) const [openSubmenuId, setOpenSubmenuId] = useState(null) + const [fixedPos, setFixedPos] = useState(null) + + // Portal mode: fixed-position the list from the anchor rect before paint; + // track the anchor while open (capture-phase scroll catches nested panes). + // getAnchorRect trumps measuring the wrapper span: a child layout effect + // runs before the parent's, so a wrapper the host positions in its own + // effect measures stale here — the host callback owns the truth instead. + useLayoutEffect(() => { + if (!open || !portal) { setFixedPos(null); return } + const place = () => { + let r: DOMRect | null + if (getAnchorRect !== undefined) { + r = getAnchorRect() + } else { + /* v8 ignore next 2 -- the ref is attached before the layout effect runs and the listeners die with it. */ + r = rootRef.current?.getBoundingClientRect() ?? null + } + if (r === null) return + setFixedPos({ + ...(align === 'start' ? { left: r.left } : { right: window.innerWidth - r.right }), + ...(side === 'bottom' ? { top: r.bottom + 4 } : { bottom: window.innerHeight - r.top + 4 }), + }) + } + place() + window.addEventListener('scroll', place, true) + window.addEventListener('resize', place) + return () => { + window.removeEventListener('scroll', place, true) + window.removeEventListener('resize', place) + } + }, [open, portal, align, side, getAnchorRect]) useEffect(() => { if (!open) { @@ -65,7 +112,11 @@ export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align return } const onPointerDown = (e: PointerEvent) => { - if (rootRef.current && e.target instanceof Node && !rootRef.current.contains(e.target)) onClose() + if (!(e.target instanceof Node)) return + // The portaled list is outside the anchor subtree; check both. + if (rootRef.current?.contains(e.target) === true) return + if (listRef.current?.contains(e.target) === true) return + onClose() } const onKeyDown = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() @@ -78,11 +129,13 @@ export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align } }, [open, onClose]) - return ( - - {anchor} - {open && ( -
+ const list = open && (!portal || fixedPos !== null) && ( +
{items.map(entry => { if (isSeparator(entry)) { return
@@ -137,8 +190,13 @@ export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align
) })} -
- )} +
+ ) + + return ( + + {anchor} + {portal ? (list !== false && createPortal(list, document.body)) : list} ) } diff --git a/packages/client/ui-primitives/src/Modal.module.css b/packages/client/ui-primitives/src/Modal.module.css index 49026f7a5f..02c075803e 100644 --- a/packages/client/ui-primitives/src/Modal.module.css +++ b/packages/client/ui-primitives/src/Modal.module.css @@ -40,10 +40,12 @@ width: 100%; } -/* Header pad (figma Title row): pt 22 / pl 24 / pr 14 / pb 12. */ +/* Header row (figma Title row): pad l24/t22/r14/b12, SPACE_BETWEEN — + * title left, close button right. */ .header { display: flex; - flex-direction: column; + align-items: center; + justify-content: space-between; gap: 8px; padding: 22px 14px 12px 24px; } @@ -52,21 +54,43 @@ margin: 0; font-size: 16px; line-height: 24px; - font-weight: 500; + font-weight: 510; color: var(--dsw-alias-label-primary); } +.close { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border: none; + border-radius: 8px; + background: transparent; + cursor: pointer; + color: var(--dsw-alias-label-secondary); +} + +.close:hover { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* Description and body share the 332px content column (24px side pads). */ .description { margin: 0; + padding: 0 24px; font-size: 14px; line-height: 22px; - color: var(--dsw-alias-label-secondary); + font-weight: 400; + color: var(--dsw-alias-label-primary); } .body { display: flex; flex-direction: column; min-width: 0; + margin-top: 20px; padding: 0 24px; } diff --git a/packages/client/ui-primitives/src/Modal.tsx b/packages/client/ui-primitives/src/Modal.tsx index cdbe1060bf..820ff3d7a3 100644 --- a/packages/client/ui-primitives/src/Modal.tsx +++ b/packages/client/ui-primitives/src/Modal.tsx @@ -5,6 +5,7 @@ import { useEffect } from 'react' import type { ReactNode } from 'react' import clsx from 'clsx' +import { IconCloseOutline16 } from './icons/index.tsx' import css from './Modal.module.css' /** @@ -49,10 +50,13 @@ export function Modal({ open, onClose, title, description, children, footer, cla

{title}

- {description !== undefined && description !== '' && ( -

{description}

- )} +
+ {description !== undefined && description !== '' && ( +

{description}

+ )} {children !== undefined &&
{children}
}
{footer !== undefined &&
{footer}
} diff --git a/packages/client/ui-primitives/src/Tooltip.tsx b/packages/client/ui-primitives/src/Tooltip.tsx index f62a397535..e2a49f6579 100644 --- a/packages/client/ui-primitives/src/Tooltip.tsx +++ b/packages/client/ui-primitives/src/Tooltip.tsx @@ -7,8 +7,8 @@ // it escapes ancestor overflow clipping (the sidebar rail clips its column) // without a portal. -import { cloneElement, useEffect, useRef, useState } from 'react' -import type { FocusEventHandler, MouseEventHandler, ReactElement, Ref } from 'react' +import { cloneElement, useCallback, useEffect, useRef, useState } from 'react' +import type { FocusEventHandler, MouseEventHandler, MutableRefObject, ReactElement, Ref } from 'react' import css from './Tooltip.module.css' /** Bubble placement relative to the anchor. */ @@ -28,11 +28,19 @@ interface AnchorProps { * @param props.label - bubble text. * @param props.side - placement relative to the anchor (default 'right'). * @param props.disabled - suppress the bubble while true; the anchor renders identically so toggling never remounts it (which would cut its CSS transitions). - * @param props.children - a single anchor element. Tooltip owns its ref (no current consumer passes one). + * @param props.children - a single anchor element; its own ref (callback or object) is forwarded alongside the tooltip's. * @returns the cloned anchor plus a fixed-position bubble while hovered/focused. */ export function Tooltip({ label, side = 'right', disabled = false, children }: { label: string; side?: TooltipSide; disabled?: boolean; children: ReactElement }) { const anchor = useRef(null) + // React 18 keeps the element's ref outside props; forward it so wrapping an + // anchor in Tooltip never silently severs the owner's ref. + const childRef = (children as ReactElement & { ref?: Ref }).ref + const mergedRef = useCallback((el: HTMLElement | null) => { + anchor.current = el + if (typeof childRef === 'function') childRef(el) + else if (childRef != null) (childRef as MutableRefObject).current = el + }, [childRef]) const [pos, setPos] = useState<{ x: number; y: number } | null>(null) // Hover and focus are independent triggers: the bubble hides only after // BOTH clear (hovering away from a focused anchor must not drop it). @@ -61,7 +69,7 @@ export function Tooltip({ label, side = 'right', disabled = false, children }: { return ( <> {cloneElement(children, { - ref: anchor, + ref: mergedRef, onMouseEnter: (e) => { children.props.onMouseEnter?.(e); triggers.current.hover = true; show() }, onMouseLeave: (e) => { children.props.onMouseLeave?.(e); triggers.current.hover = false; hide() }, onFocus: (e) => { children.props.onFocus?.(e); triggers.current.focus = true; show() }, diff --git a/packages/client/ui-primitives/tests/atoms.spec.tsx b/packages/client/ui-primitives/tests/atoms.spec.tsx index a4b286ced7..440f4ba6ef 100644 --- a/packages/client/ui-primitives/tests/atoms.spec.tsx +++ b/packages/client/ui-primitives/tests/atoms.spec.tsx @@ -170,6 +170,71 @@ describe('Menu', () => { fireEvent.mouseLeave(wrap) expect(screen.queryByRole('menuitem', { name: 'Create ok' })).toBeNull() }) + + it('portal mode prefers getAnchorRect over measuring its own wrapper', () => { + const rect = { left: 40, right: 72, top: 100, bottom: 128, width: 32, height: 28, x: 40, y: 100, toJSON: () => ({}) } as DOMRect + render( + rect} + anchor={null} + items={items} + onSelect={() => {}} + onClose={() => {}} + />) + const menu = screen.getByRole('menu') + // side=bottom, align=start: below the host-supplied rect, left-aligned. + expect(menu.style.left).toBe('40px') + expect(menu.style.top).toBe('132px') + }) + + it('portal mode skips the frame when getAnchorRect returns null (no menu until a rect exists)', () => { + render( + null} + anchor={null} + items={items} + onSelect={() => {}} + onClose={() => {}} + />) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('portal mode renders the list under body, positions it fixed, and still closes on outside pointerdown', () => { + const onSelect = vi.fn() + const onClose = vi.fn() + const { container } = render( + trigger} items={items} onSelect={onSelect} onClose={onClose} />) + const menu = screen.getByRole('menu') + // Outside the anchor wrapper subtree — overflow-clipping ancestors can't crop it. + expect(container.contains(menu)).toBe(false) + expect(menu.parentElement).toBe(document.body) + expect(menu.style.top).not.toBe('') + fireEvent.click(screen.getByRole('menuitem', { name: 'Alpha' })) + expect(onSelect).toHaveBeenCalledWith('a') + fireEvent.pointerDown(menu) + expect(onClose).not.toHaveBeenCalled() + // Non-Node targets (e.g. window itself) are ignored, not treated as outside. + const nonNodeTarget = new Event('pointerdown', { bubbles: true }) + Object.defineProperty(nonNodeTarget, 'target', { value: window }) + document.dispatchEvent(nonNodeTarget) + expect(onClose).not.toHaveBeenCalled() + fireEvent.pointerDown(document.body) + expect(onClose).toHaveBeenCalledTimes(1) + }) + + it('portal mode positions from the opposite edges for align=end / side=top', () => { + render( + trigger} items={items} onSelect={() => {}} onClose={() => {}} />) + const menu = screen.getByRole('menu') + expect(menu.style.right).not.toBe('') + expect(menu.style.bottom).not.toBe('') + expect(menu.style.left).toBe('') + expect(menu.style.top).toBe('') + }) }) describe('Modal', () => { diff --git a/packages/client/ui-primitives/tests/tooltip.spec.tsx b/packages/client/ui-primitives/tests/tooltip.spec.tsx index 3b3af8373c..6741921c66 100644 --- a/packages/client/ui-primitives/tests/tooltip.spec.tsx +++ b/packages/client/ui-primitives/tests/tooltip.spec.tsx @@ -104,6 +104,26 @@ describe('Tooltip', () => { expect(screen.queryByRole('tooltip')).toBeNull() }) + it('forwards the anchor element to the child ref (object and callback)', () => { + const objectRef = { current: null as HTMLButtonElement | null } + const callbackRef = vi.fn() + const { rerender } = render( + + + , + ) + expect(objectRef.current).toBe(screen.getByText('anchor')) + // Tooltip's own positioning still works through the merged ref. + fireEvent.mouseEnter(screen.getByText('anchor')) + expect(screen.getByRole('tooltip')).toBeTruthy() + rerender( + + + , + ) + expect(callbackRef).toHaveBeenCalledWith(screen.getByText('anchor')) + }) + it('drops an already-visible bubble when disabled flips mid-hover', () => { const { rerender } = render( diff --git a/packages/client/ui-question/tests/question-composer.spec.tsx b/packages/client/ui-question/tests/question-composer.spec.tsx index 9a8ac9bb57..2e08aa61b3 100644 --- a/packages/client/ui-question/tests/question-composer.spec.tsx +++ b/packages/client/ui-question/tests/question-composer.spec.tsx @@ -1,7 +1,9 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import type { ConversationSnapshot, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client' +import type { + ConversationSnapshot, SessionId, SessionListState, WorkspaceListState, +} from '@deepseek-ai/dsh-client-runtime/client' import { PendingWait } from '@deepseek-ai/dsh-client-runtime/client' import type { RpcReceipt } from '@deepseek-ai/dsh-client-connection/client' import { RpcId } from '@deepseek-ai/dsh-client-connection/client' @@ -22,6 +24,7 @@ const kit = { sessionId: SID, useSession: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook, useSessions: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook, + useWorkspaces: (() => { throw new Error('unused') }) as unknown as SnapshotSelectorHook, } const QUESTIONS = [ diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index c165455b1a..d8c2f61ee0 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -1,10 +1,10 @@ # @deepseek-ai/dsh-client-ui-sidebar -Sidebar plugin: session multi-level tree (cwd grouping + parentId nesting), search, by-workspace grouping, state dots, three creation entries. Top-level New Session / New Workspace clear the selection onto `conversation.empty`; per-project "+" still create-then-opens. Collapse is a slide + crossfade into the layout-owned 56px rail (open / new session / new workspace / search — search expands and focuses the search box — plus the settings foot): the expanded content freezes at its width and fades in place while the column slides over it, then the rail — whale mark resting, panel icon on hover, tooltips on every control — crossfades in at settle as the wide content unmounts. Contract: the [slot system standard](../../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md). +Sidebar plugin: real Host Workspaces in stable Host order, each containing its `sessionIds` in Workspace order with `parentId` nesting; Sessions outside every Workspace appear in a trailing `Ungrouped` section. Search, state dots, and collapse into the layout-owned 56px rail are presentation-local. Contract: the [slot system standard](../../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md). -`src/client/contract/slots.ts` is the single-domain contract file: `SidebarRootInjected` (the registrant's own injected share — plain service callbacks: onOpen/onCreate/onToggleSidebar) and `SidebarRootComponentProps = PropsRuntime<'sidebar'> & SidebarRootInjected` (owner `{collapsed,width}` plus the standard `useSessions` hook, resolved off ui-layout's SlotMap declaration, never re-stated). `apply` registers SidebarRoot cast-free against that composition; the inject factory closes over the plugin's own ctx. +New Session starts the runtime's page-local frontend Session Intent; a real Workspace's "+" starts one targeted to that Workspace. The Workspace header "+" opens ui-workspace's shared picker, whose selection also targets a frontend Session. A Workspace Intent does not appear in the sidebar. -There is no plugin store: rows derive in the component (`useMemo` over the `useSessions` snapshot + local expansion/search state) through the pure `deriveRows` in `tree.ts`. +`SidebarRootComponentProps` composes the layout owner share, the global `useSessions` and `useWorkspaces` hooks, the declared `sidebar.workspace` child slot, and injected `startSession`, `open`, and sidebar-toggle callbacks. There is no plugin store: `deriveGroups` consumes object-layer snapshots and component-local expansion/search state. The `/client` export surface is the plugin body (`apply`/`inject`) plus the contract types only — SidebarRoot, the row components, and the tree derivation are internal (the slot registration closes over them; tests import src paths directly). diff --git a/packages/client/ui-sidebar/src/client/Rows.module.css b/packages/client/ui-sidebar/src/client/Rows.module.css index 18539a5f61..f996f03348 100644 --- a/packages/client/ui-sidebar/src/client/Rows.module.css +++ b/packages/client/ui-sidebar/src/client/Rows.module.css @@ -104,6 +104,18 @@ line-height: 20px; } +.renameInput { + min-width: 0; + font-size: 14px; + line-height: 20px; + padding: 0 2px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 4px; + background: var(--dsw-alias-button-elevated-fill); + color: inherit; + outline: none; +} + .sessionRow .title { flex: 1; } diff --git a/packages/client/ui-sidebar/src/client/Rows.tsx b/packages/client/ui-sidebar/src/client/Rows.tsx index 53f8bbe14f..6535a9a08a 100644 --- a/packages/client/ui-sidebar/src/client/Rows.tsx +++ b/packages/client/ui-sidebar/src/client/Rows.tsx @@ -5,10 +5,10 @@ */ import clsx from 'clsx' import { - IconEllipsisOutline16, IconFolderClose16, IconFolderOpen16, IconPlusOutline16, + IconFolderClose16, IconFolderOpen16, IconPlusOutline16, IconTriangleRightFill14, StateDot, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { ProjectRow, SessionRow } from './tree.ts' +import type { GroupNode, SessionNode } from './tree.ts' import { formatRelativeTime } from './tree.ts' import css from './Rows.module.css' @@ -16,20 +16,21 @@ import css from './Rows.module.css' const INDENT_STEP = 16 /** - * Project (workspace) row: 54px, folder + title + session count; hover - * reveals the chevron and the more/create buttons. - * @param props.row - derived project row. - * @param props.active - group contains the selected session (blue open folder). + * Project (workspace) header row: 54px, folder + title + session count; + * hover reveals the chevron and create button. `containsCurrent` arrives on + * the node (derivation fact, no renderer scan). + * @param props.group - derived group node. * @param props.onToggle - expand/collapse the group. - * @param props.onCreate - create a session inside this group. + * @param props.onCreate - start a frontend Session inside this Workspace. * @returns the row element. */ -export function ProjectRowItem({ row, active, onToggle, onCreate }: { - row: ProjectRow - active: boolean +export function ProjectRowItem({ group, onToggle, onCreate }: { + group: GroupNode onToggle: () => void onCreate: () => void }) { + const row = group + const active = group.expanded && group.containsCurrent const count = `${row.sessionCount} ${row.sessionCount === 1 ? 'session' : 'sessions'}` return (
@@ -44,14 +45,10 @@ export function ProjectRowItem({ row, active, onToggle, onCreate }: { {count} - {/* Row menu contents are not designed yet (figma draft notes); the button is the reserved anchor. */} - @@ -105,11 +122,22 @@ export function SessionRowItem({ row, selected, now, onOpen, onToggle }: { {row.running && } {row.title} {formatRelativeTime(row.updatedAt, now)} - - -
) + return ( + <> + {ownRow} + {node.children.map(child => ( + + ))} + + ) } diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css index 621b33fc66..591aef2330 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css @@ -339,24 +339,33 @@ pointer-events: none; } -/* Batch separator (figma 133:7661): 20px spacer after an expanded project's - session run, before the next project row. */ -.batchGap { - flex: none; - height: 20px; -} - -/* Tree list: the only scrolling region. */ +/* Tree list: the only scrolling region. Block, not a flex column: as flex + items the 54/34 rows would shrink under content overflow (scrollHeight + collapses onto clientHeight and wheel scrolling dies); block children keep + their design heights and the 4px rhythm rides margins instead of gap. */ .list { flex: 1; min-height: 0; overflow-y: auto; - display: flex; - flex-direction: column; - gap: 4px; padding-bottom: 12px; } +/* One workspace section: header row + expanded session run. Rows inside + keep the former flat-list 4px gap as sibling margins; the inter-group + breathing room (figma 133:7661 batch separator, 20px after an expanded + run) rides the NEXT section's top margin so the last group adds none. */ +.groupSection > * + * { + margin-top: 4px; +} + +.groupSection + .groupSection { + margin-top: 4px; +} + +.groupSection:has([aria-expanded='true']) + .groupSection { + margin-top: 20px; +} + .empty { padding: 16px 12px; color: var(--dsw-alias-label-tertiary); diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx index ac1e33866b..931eb1ba17 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx @@ -7,7 +7,7 @@ * (one icon each, same top-down order) fading in as the slide ends. Rail * search expands and focuses the search box. */ -import { Fragment, useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import clsx from 'clsx' import { BrandWordmark, FishLogo, @@ -15,9 +15,10 @@ import { IconProjectAddOutline16, IconSearchOutline16, IconSettingsOutline14, Menu, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' +import type { WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' import type { SidebarRootComponentProps } from './contract/slots.ts' -import { deriveRows } from './tree.ts' -import { ProjectRowItem, SessionRowItem } from './Rows.tsx' +import { deriveGroups, UNGROUPED_KEY } from './tree.ts' +import { IntentRowItem, ProjectRowItem, SessionNodeItem } from './Rows.tsx' import css from './SidebarRoot.module.css' /** Wide-content unmount delay; matches the 150ms wide-content fade-out. */ @@ -27,7 +28,7 @@ const COLLAPSE_SETTLE_MS = 150 const EXPAND_SLIDE_MS = 300 const GROUP_BY_ITEMS = [ - { id: 'workspace', label: 'WorkSpace' }, + { id: 'workspace', label: 'Workspace' }, // Only workspace grouping is implemented. { id: 'update', label: 'Update', disabled: true }, { id: 'status', label: 'Status', disabled: true }, @@ -63,62 +64,74 @@ function GroupByMenu() { ) } -type SessionTreeProps = Pick & { +type SessionTreeProps = Pick< + SidebarRootComponentProps, + 'useSessions' | 'startSession' | 'open' +> & { + workspaces: readonly WorkspaceView[] /** Live search filter owned by the root (the query outlives the tree). */ query: string } /** The scrolling session tree; unmounting at collapse settle drops the sessions subscription and expansion state. */ -function SessionTree({ useSessions, onOpen, onCreate, query }: SessionTreeProps) { +function SessionTree({ useSessions, startSession, open, workspaces, query }: SessionTreeProps) { const list = useSessions((s) => s) - // Selection belongs to the sessions snapshot, not layout state. - const current = useSessions((s) => s.current) + const current = list.current const [expandedProjects, setExpandedProjects] = useState([]) const [expandedSessions, setExpandedSessions] = useState([]) - const rows = useMemo( - () => deriveRows(list, { expandedProjects, expandedSessions, query }), - [list, expandedProjects, expandedSessions, query], + // Re-expand when publication moves the selected intent into a real Workspace. + const intent = list.intent + const intentWorkspaceId = intent?.target.kind === 'workspace' + ? intent.target.workspaceId + : undefined + const currentGroup = current === undefined + ? undefined + : intent?.sessionId === current + ? intentWorkspaceId + : (workspaces.find(w => w.sessionIds.includes(current))?.workspaceId as string | undefined) + ?? UNGROUPED_KEY + useEffect(() => { + if (current === undefined || currentGroup === undefined) return + setExpandedProjects((l) => (l.includes(currentGroup) ? l : [...l, currentGroup])) + }, [current, currentGroup]) + const groups = useMemo( + () => deriveGroups(list, workspaces, { expandedProjects, expandedSessions, query }), + [list, workspaces, expandedProjects, expandedSessions, query], ) const now = Date.now() - // Presentational lookup (not tree derivation): the group holding the - // selected session gets the active folder; only expanded groups can show it. - let activeGroup: string | undefined - if (current !== undefined) { - for (const row of rows) { - if (row.type === 'session' && row.id === current) { activeGroup = row.groupKey; break } - } - } - return (
- {rows.length === 0 && ( + {groups.length === 0 && (
{query === '' ? 'No sessions yet' : 'No matches'}
)} - {rows.map((row, i) => row.type === 'project' - ? ( - - {/* Batch separator: a project row closing an expanded session run (figma 133:7661). */} - {i > 0 && rows[i - 1]!.type === 'session' && } - { setExpandedProjects((l) => toggled(l, row.key)) }} - onCreate={() => { onCreate(row.cwd) }} - /> - - ) - : ( - ( + // Group section: header row + expanded session subtree. The + // inter-group breathing room (former flat-list batch separator) + // is the section's own margin (SidebarRoot.module.css). +
+ { setExpandedProjects((l) => toggled(l, group.key)) }} + onCreate={() => { + if (group.workspaceId !== undefined) startSession(group.workspaceId) + }} + /> + {group.intentHere && } + {group.sessions.map(node => ( + { onOpen(row.id) }} - onToggle={() => { setExpandedSessions((l) => toggled(l, row.id)) }} + onOpen={open} + onToggle={(id) => { setExpandedSessions((l) => toggled(l, id)) }} /> ))} +
+ ))}
@@ -130,11 +143,27 @@ function SessionTree({ useSessions, onOpen, onCreate, query }: SessionTreeProps) * @param props - composed slot props (runtime share + injected callbacks, contract/slots.ts). * @returns the sidebar element tree. */ -export function SidebarRoot({ collapsed, width, useSessions, onOpen, onCreate, onToggleSidebar }: SidebarRootComponentProps) { +export function SidebarRoot({ + collapsed, + width, + useSessions, + useWorkspaces, + startSession, + open, + toggleSidebar, + renderSlot, +}: SidebarRootComponentProps) { + const workspaces = useWorkspaces(state => state.items) // The query outlives the tree and the input (both wide-only) so collapsing // does not silently drop an in-progress filter. const [query, setQuery] = useState('') const searchInput = useRef(null) + // Section-header + opens the workspace picker (same popover in wide and + // rail states; the hole sits beside the button and opens rightward). + const [wsPickerOpen, setWsPickerOpen] = useState(false) + // Placement anchor for the picker popover: the slot span renders elsewhere + // in the DOM, so the picker positions off this button's rect. + const wsPlusRef = useRef(null) // Wide content stays mounted while the collapse animates (fading via // .collapsed .wide), unmounts at settle, and remounts right away on expand. @@ -188,7 +217,7 @@ export function SidebarRoot({ collapsed, width, useSessions, onOpen, onCreate, o type="button" className={clsx(css.iconButton, css.toggle)} aria-label={collapsed ? 'Open sidebar' : 'Collapse sidebar'} - onClick={() => { onToggleSidebar() }} + onClick={() => { toggleSidebar() }} > {!wide && } {/* Rail icons render at 18 (figma rail spec); expanded keeps the glyph-native sizes. */} @@ -202,7 +231,7 @@ export function SidebarRoot({ collapsed, width, useSessions, onOpen, onCreate, o type="button" className={css.newSession} aria-label="New session" - onClick={() => { onCreate() }} + onClick={() => { startSession() }} > {wide && New Session} @@ -210,18 +239,29 @@ export function SidebarRoot({ collapsed, width, useSessions, onOpen, onCreate, o
- {wide && WorkSpace} + {wide && Workspaces} {wide && } + {/* Picker hole beside the + (same site in wide and rail states). */} + {renderSlot('sidebar.workspace', { + open: wsPickerOpen, + anchorRef: wsPlusRef, + onPick: (workspaceId) => { + setWsPickerOpen(false) + startSession(workspaceId) + }, + onClose: () => { setWsPickerOpen(false) }, + })}
{/* Expanded: the row is a click-to-focus field (the leading icon is @@ -233,7 +273,7 @@ export function SidebarRoot({ collapsed, width, useSessions, onOpen, onCreate, o className={css.searchButton} aria-label="Search sessions" tabIndex={collapsed ? 0 : -1} - onClick={() => { if (collapsed) { setSearchOnExpand(true); onToggleSidebar() } }} + onClick={() => { if (collapsed) { setSearchOnExpand(true); toggleSidebar() } }} > @@ -263,7 +303,15 @@ export function SidebarRoot({ collapsed, width, useSessions, onOpen, onCreate, o {/* Always-mounted seat: its flex slot pins the foot to the bottom in both states while the tree itself is wide-only. */}
- {wide && } + {wide && ( + + )}
diff --git a/packages/client/ui-sidebar/src/client/contract/slots.ts b/packages/client/ui-sidebar/src/client/contract/slots.ts index a5ce65ef59..0334ca88c9 100644 --- a/packages/client/ui-sidebar/src/client/contract/slots.ts +++ b/packages/client/ui-sidebar/src/client/contract/slots.ts @@ -1,42 +1,69 @@ /** * Sidebar slot contract: the registrant-side props composition for the - * layout-owned `sidebar` slot. The own injected share is declared here (a - * share's type lives with whoever wires it); the runtime share — owner - * props {collapsed,width} plus the standard useSessions hook — is - * PropsRuntime<'sidebar'>, resolved off ui-layout's SlotMap declaration and - * never re-stated. Single domain — this is the package's whole contract - * surface. + * layout-owned `sidebar` slot and the Workspace picker hole declared here. + * The runtime share combines layout-owned page state and actions with the + * global useSessions and useWorkspaces hooks; the injected share adds the + * runtime navigation actions and sidebar toggle. */ -import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { RefObject } from 'react' +import type { PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls ui-layout's SlotMap merge (the 'sidebar' entry) into every // program that sees this contract, so PropsRuntime<'sidebar'> resolves. import type {} from '@deepseek-ai/dsh-client-ui-layout/client' -import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client' +import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' -/** - * Registrant-private injected share (arrives via the register inject - * factory): plain cross-service callbacks only — tree data rides the - * standard useSessions hook and viewing state is component-local. A type - * alias, not an interface: the alias carries an implicit index signature, - * so the factory's return crosses the registry's `Record` - * boundary uncast. - */ -export type SidebarRootInjected = { - /** Open (switch to) a session. */ - onOpen: (id: SessionId) => void - /** - * New-session affordance: no cwd clears selection onto the empty-state - * launch; a cwd create-then-opens a session in that project group. - */ - onCreate: (cwd?: string) => void - /** Collapse the sidebar column (layout service action; owner share stays {collapsed,width}). */ - onToggleSidebar: () => void +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** + * The workspace picker hole in the sidebar section header (anchored at + * the + button). Declared by this package's 'sidebar' entry (declaring + * is claiming); ui-workspace registers the picker. + */ + 'sidebar.workspace': { kind: 'single'; scope: 'root'; owner: SidebarWorkspaceOwnerProps } + } } /** - * Full component props: the framework runtime share (owner {collapsed,width} - * + standard useSessions) plus the own injected share. No children are - * declared and no store is registered, so no PropsRenderSlots/PropsStore - * term appears. + * Owner share of the sidebar workspace hole: popover geometry plus the + * sidebar's pick semantics. The picked Host Workspace is already real; the + * callback starts a frontend Session Intent targeted to it. */ -export type SidebarRootComponentProps = PropsRuntime<'sidebar'> & SidebarRootInjected +export interface SidebarWorkspaceOwnerProps { + /** Popover visibility (+ button toggle state, host-local). */ + open: boolean + /** + * The + button element — the popover's placement anchor. The picker's + * slot span renders elsewhere in the DOM, so without this the menu + * positions off the zero-size placement span (order-dependent). Optional + * only until the host passes it; absent falls back to in-place placement. + */ + anchorRef?: RefObject + /** Start a frontend Session in a selected or newly created real Workspace. */ + onPick: (workspaceId: WorkspaceId) => void + /** Close the popover (outside click / Escape / post-pick). */ + onClose: () => void +} + +/** + * Registrant-private injected share (arrives via the register inject + * factory). Host Workspace and Session data use the global framework hooks; + * navigation and panel actions are plain callbacks, and viewing state remains + * component-local. A type alias supplies the implicit index signature required + * by the registry. + */ +export type SidebarRootInjected = { + /** Start or replace the current frontend Session Intent. */ + startSession: (workspaceId?: WorkspaceId, prompt?: string) => void + /** Open a real Session. */ + open: (sessionId: SessionId) => void + /** Toggle the sidebar column through the layout service. */ + toggleSidebar: () => void +} + +/** + * Full component props: layout owner state/actions plus global useSessions + * and useWorkspaces, the declared Workspace picker render share, and this + * package's injected callback. No store is registered. + */ +export type SidebarRootComponentProps = + PropsRuntime<'sidebar'> & PropsRenderSlots<'sidebar.workspace'> & SidebarRootInjected diff --git a/packages/client/ui-sidebar/src/client/index.ts b/packages/client/ui-sidebar/src/client/index.ts index e0c3a4b37d..0a1c8ebb12 100644 --- a/packages/client/ui-sidebar/src/client/index.ts +++ b/packages/client/ui-sidebar/src/client/index.ts @@ -1,36 +1,30 @@ /** Registers the sidebar UI into the layout-owned slot. */ -import type { ClientContext, SessionId } from '@deepseek-ai/dsh-client-runtime/client' +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import type { SidebarRootInjected } from './contract/slots.ts' import { SidebarRoot } from './SidebarRoot.tsx' -export type { SidebarRootComponentProps, SidebarRootInjected } from './contract/slots.ts' +export type { SidebarRootComponentProps, SidebarRootInjected, SidebarWorkspaceOwnerProps } from './contract/slots.ts' /** Services required by the sidebar plugin. */ -export const inject = ['slots', 'layout', 'sessions'] +export const inject = ['slots', 'layout', 'sessions', 'workspaces'] /** Registers the sidebar component and its service callbacks. * @param ctx - Client root context. */ export function apply(ctx: ClientContext): void { const injectProps = (): SidebarRootInjected => ({ - // Selection belongs to the sessions service; layout owns only panel geometry. - onOpen: (id) => { ctx.sessions.open(id) }, - onCreate: (cwd) => { - // Top-level New Session / New Workspace: clear selection so AppFrame - // shows conversation.empty (EmptyState + shared InputBar). Per-project - // "+" still create-then-opens into that cwd until workspace seeding - // reaches the empty-state picker. - if (cwd === undefined) { - ctx.sessions.clear() - return - } - void ctx.sessions.create({ cwd }) - .then((id: SessionId) => { ctx.sessions.open(id) }) - }, - onToggleSidebar: () => { ctx.layout.toggleSidebar() }, + startSession: (workspaceId, prompt) => { ctx.workspaces.startSession(workspaceId, prompt) }, + open: (sessionId) => { ctx.sessions.open(sessionId) }, + toggleSidebar: () => { ctx.layout.toggleSidebar() }, }) ctx.effect( - () => ctx.slots.register({ name: 'sidebar', inject: injectProps }, SidebarRoot), + () => ctx.slots.register({ + name: 'sidebar', + // SidebarRoot owns this picker site; ui-workspace registers the shared + // picker that selects a Host Workspace for a frontend Session Intent. + children: { 'sidebar.workspace': { kind: 'single', scope: 'root' } }, + inject: injectProps, + }, SidebarRoot), 'ui-sidebar: slot registration', ) } diff --git a/packages/client/ui-sidebar/src/client/tree.ts b/packages/client/ui-sidebar/src/client/tree.ts index 1d5782cb3c..64fda519e6 100644 --- a/packages/client/ui-sidebar/src/client/tree.ts +++ b/packages/client/ui-sidebar/src/client/tree.ts @@ -1,41 +1,46 @@ -/** Pure derivation of flat sidebar rows from sessions and local view state. */ -import type { SessionId, SessionListState, SessionSummary } from '@deepseek-ai/dsh-client-runtime/client' +/** + * Derives the sidebar tree from Host Workspace order and membership. + * Unassigned Sessions trail under Ungrouped; only Intents targeting real Workspaces render. + */ +import type { SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' -/** Group key for sessions without a project directory. */ +/** Group key for Sessions outside every Workspace. */ export const UNGROUPED_KEY = '' -/** Display label for the ungrouped project row. */ +/** Display label for the ungrouped bucket row. */ export const UNGROUPED_LABEL = 'Ungrouped' -/** Project (workspace) row: 54px, two lines (label + session count). */ -export interface ProjectRow { - type: 'project' - /** Group key: the cwd, or {@link UNGROUPED_KEY}. */ - key: string - cwd: string | undefined - label: string - /** Total sessions in the group, including hidden ones. */ - sessionCount: number - expanded: boolean -} - -/** Session row: 34px single line; depth drives the 22px indent steps. */ -export interface SessionRow { - type: 'session' +/** One session node of a group's visible tree (34px row; children render indented one step). */ +export interface SessionNode { id: SessionId - /** Owning project group key (selection -> active-folder lookup). */ - groupKey: string title: string - /** 0 = directly under the project row. */ - depth: number + /** Visible children, already expansion/search-filtered (empty when folded). */ + children: readonly SessionNode[] + /** The session HAS children in the data (the twist renders even while folded). */ hasChildren: boolean expanded: boolean running: boolean updatedAt: number } -/** One flat sidebar list row. */ -export type SidebarRow = ProjectRow | SessionRow +/** One workspace group section: header row facts + the visible session tree. */ +export interface GroupNode { + /** Group key: the workspace id or {@link UNGROUPED_KEY}. */ + key: string + /** Backing Workspace id; absent only for the ungrouped bucket. */ + workspaceId: WorkspaceId | undefined + cwd: string | undefined + label: string + /** Total sessions in the group, including hidden ones. */ + sessionCount: number + expanded: boolean + /** The group contains the selected session (active folder tint; supplied here so the renderer never scans). */ + containsCurrent: boolean + /** The frontend Session Intent points here: render one "New session" row. */ + intentHere: boolean + /** Visible roots (empty while the group is folded). */ + sessions: readonly SessionNode[] +} /** Viewing state consumed by the derivation — the component's local useState arrays, taken as-is. */ export interface TreeView { @@ -46,17 +51,18 @@ export interface TreeView { interface Group { key: string + workspaceId: WorkspaceId | undefined cwd: string | undefined label: string summaries: Map roots: SessionId[] children: Map - latest: number } /** - * Project display label: basename of the group directory. - * @param cwd - project directory, or undefined for the ungrouped bucket. + * Directory display label: basename of the path (both separators accepted). + * Ungrouped-bucket fallback for surfaces without a workspace title. + * @param cwd - directory path, or undefined for the ungrouped bucket. * @returns basename, the raw cwd when it has no basename, or the ungrouped label. */ export function projectLabel(cwd: string | undefined): string { @@ -71,32 +77,32 @@ function byRecency(a: SessionSummary, b: SessionSummary): number { return a.id < b.id ? -1 : 1 } -function groupByCwd(list: SessionListState): Group[] { - const byKey = new Map() - for (const id of list.ids) { - const s = list.byId[id] - if (s === undefined) continue - const key = s.cwd ?? UNGROUPED_KEY - const members = byKey.get(key) - if (members === undefined) byKey.set(key, [s]) - else members.push(s) - } - const groups: Group[] = [] - for (const [key, members] of byKey) { - const summaries = new Map(members.map(m => [m.id, m])) - const children = new Map() - const roots: SessionSummary[] = [] - for (const m of members) { - // A session is a tree child only when its parent lives in the same - // group; cross-group or unknown parents degrade to group roots. - if (m.parentId !== undefined && m.parentId !== m.id && summaries.has(m.parentId)) { - const kids = children.get(m.parentId) - if (kids === undefined) children.set(m.parentId, [m.id]) - else kids.push(m.id) - } else { - roots.push(m) - } +/** Build one group's parent/child tree from an ordered member list. */ +function buildGroup( + key: string, + workspaceId: WorkspaceId | undefined, + cwd: string | undefined, + label: string, + members: readonly SessionSummary[], + order: 'account' | 'recency', +): Group { + const summaries = new Map(members.map(m => [m.id, m])) + const children = new Map() + const roots: SessionSummary[] = [] + for (const m of members) { + // A session is a tree child only when its parent lives in the same + // group; cross-group or unknown parents degrade to group roots. + if (m.parentId !== undefined && m.parentId !== m.id && summaries.has(m.parentId)) { + const kids = children.get(m.parentId) + if (kids === undefined) children.set(m.parentId, [m.id]) + else kids.push(m.id) + } else { + roots.push(m) } + } + // Workspace order is the member iteration order (workspace.sessionIds), so + // attached groups keep insertion order; Ungrouped sorts by recency. + if (order === 'recency') { roots.sort(byRecency) for (const kids of children.values()) { kids.sort((a, b) => { @@ -107,48 +113,63 @@ function groupByCwd(list: SessionListState): Group[] { return byRecency(sa, sb) }) } - const rootIds = roots.map(r => r.id) - // parentId cycles (host bug) leave members unreachable from any root; - // surface them as extra roots — the flatten walk's visited set stops - // loops. Each node sits in at most one kids list and roots have no - // in-group parent, so the scan pushes every reachable node exactly once. - const reachable = new Set(rootIds) - const stack = [...rootIds] - while (stack.length > 0) { - const top = stack.pop() - /* v8 ignore next -- unreachable: the loop condition guarantees a non-empty stack. */ - if (top === undefined) break - for (const kid of children.get(top) ?? []) { - reachable.add(kid) - stack.push(kid) - } - } - for (const m of [...members].sort(byRecency)) { - if (!reachable.has(m.id)) rootIds.push(m.id) - } - let latest = 0 - for (const m of members) latest = Math.max(latest, m.updatedAt) - groups.push({ - key, - cwd: key === UNGROUPED_KEY ? undefined : key, - label: projectLabel(key === UNGROUPED_KEY ? undefined : key), - summaries, - roots: rootIds, - children, - latest, - }) } - groups.sort((a, b) => b.latest - a.latest || (a.label < b.label ? -1 : a.label > b.label ? 1 : 0)) + const rootIds = roots.map(r => r.id) + // parentId cycles (host bug) leave members unreachable from any root; + // surface them as extra roots — the flatten walk's visited set stops + // loops. Each node sits in at most one kids list and roots have no + // in-group parent, so the scan pushes every reachable node exactly once. + const reachable = new Set(rootIds) + const stack = [...rootIds] + while (stack.length > 0) { + const top = stack.pop() + /* v8 ignore next -- unreachable: the loop condition guarantees a non-empty stack. */ + if (top === undefined) break + for (const kid of children.get(top) ?? []) { + reachable.add(kid) + stack.push(kid) + } + } + for (const m of members) { + if (!reachable.has(m.id)) rootIds.push(m.id) + } + return { key, workspaceId, cwd, label, summaries, roots: rootIds, children } +} + +/** + * Group Sessions by Host Workspace: one group per entity in stable Host + * order, with members resolved from sessionIds in their stored order. Sessions + * outside every Workspace trail in the recency-ordered Ungrouped bucket. + */ +function groupByWorkspace(list: SessionListState, workspaces: readonly WorkspaceView[]): Group[] { + const groups: Group[] = [] + const accounted = new Set() + for (const workspace of workspaces) { + const members: SessionSummary[] = [] + for (const id of workspace.sessionIds) { + const summary = list.byId[id] + if (summary === undefined) continue // account may lead the list pull; the row appears when the summary lands + members.push(summary) + accounted.add(id) + } + groups.push(buildGroup( + workspace.workspaceId, workspace.workspaceId, workspace.path, workspace.title, members, 'account', + )) + } + const stray = list.ids + .map(id => list.byId[id]) + .filter((s): s is SessionSummary => s !== undefined && !accounted.has(s.id)) + if (stray.length > 0) { + groups.push(buildGroup(UNGROUPED_KEY, undefined, undefined, UNGROUPED_LABEL, stray, 'recency')) + } return groups } -function sessionRow(g: Group, s: SessionSummary, depth: number, hasChildren: boolean, expanded: boolean): SessionRow { +function sessionNode(s: SessionSummary, children: readonly SessionNode[], hasChildren: boolean, expanded: boolean): SessionNode { return { - type: 'session', id: s.id, - groupKey: g.key, title: s.displayTitle, - depth, + children, hasChildren, expanded, running: s.running, @@ -156,20 +177,20 @@ function sessionRow(g: Group, s: SessionSummary, depth: number, hasChildren: boo } } -function flattenVisible(g: Group, expandedSessions: ReadonlySet, rows: SidebarRow[]): void { +function buildVisible(g: Group, expandedSessions: ReadonlySet): SessionNode[] { const visited = new Set() - const walk = (id: SessionId, depth: number): void => { - if (visited.has(id)) return + const walk = (id: SessionId): SessionNode | null => { + if (visited.has(id)) return null visited.add(id) const s = g.summaries.get(id) /* v8 ignore next -- unreachable: walked ids come from the grouped summaries. */ - if (s === undefined) return + if (s === undefined) return null const kids = g.children.get(id) ?? [] const expanded = expandedSessions.has(id) - rows.push(sessionRow(g, s, depth, kids.length > 0, expanded)) - if (expanded) for (const kid of kids) walk(kid, depth + 1) + const children = expanded ? kids.map(walk).filter((n): n is SessionNode => n !== null) : [] + return sessionNode(s, children, kids.length > 0, expanded) } - for (const root of g.roots) walk(root, 0) + return g.roots.map(walk).filter((n): n is SessionNode => n !== null) } /** Matched sessions plus their ancestor chains (forced visible under search). */ @@ -186,66 +207,98 @@ function searchVisible(g: Group, q: string): Set { return visible } -function flattenSearch(g: Group, visible: ReadonlySet, rows: SidebarRow[]): void { +function buildSearch(g: Group, visible: ReadonlySet): SessionNode[] { const visited = new Set() - const walk = (id: SessionId, depth: number): void => { - if (visited.has(id) || !visible.has(id)) return + const walk = (id: SessionId): SessionNode | null => { + if (visited.has(id) || !visible.has(id)) return null visited.add(id) const s = g.summaries.get(id) /* v8 ignore next -- unreachable: walked ids come from the grouped summaries. */ - if (s === undefined) return + if (s === undefined) return null const kids = (g.children.get(id) ?? []).filter(kid => visible.has(kid)) - rows.push(sessionRow(g, s, depth, kids.length > 0, kids.length > 0)) - for (const kid of kids) walk(kid, depth + 1) + const children = kids.map(walk).filter((n): n is SessionNode => n !== null) + return sessionNode(s, children, kids.length > 0, kids.length > 0) } - for (const root of g.roots) walk(root, 0) + return g.roots.map(walk).filter((n): n is SessionNode => n !== null) } /** - * Derive the flat sidebar row list. + * Derive the nested sidebar group structure. * - * Normal mode: every project row shows; sessions show under expanded - * projects, descending only into expanded sessions. Search mode (non-blank - * query, case-insensitive display-title substring): expansion state is ignored — + * Normal mode: every group shows; sessions populate under expanded groups, + * descending only into expanded sessions. A frontend Session Intent targeting + * a real Workspace marks that group `intentHere` and forces it expanded. Search mode (non-blank query, + * case-insensitive display-title substring): expansion state is ignored — * matched sessions and their ancestor chains are forced visible, groups - * without a display-title or label hit are dropped, and a label-only hit keeps the - * bare project row. - * @param list - sessions list snapshot. + * without a display-title or label hit are dropped, a label-only hit keeps + * the bare group header, and Intent rows do not participate. + * @param list - sessions list snapshot (`current` feeds containsCurrent). + * @param workspaces - real workspaces in stable Host order. * @param view - local expansion arrays and search query. - * @returns rows in render order. + * @returns group sections in render order. */ -export function deriveRows(list: SessionListState, view: TreeView): SidebarRow[] { +export function deriveGroups( + list: SessionListState, + workspaces: readonly WorkspaceView[], + view: TreeView, +): GroupNode[] { const q = view.query.trim().toLowerCase() const expandedProjects = new Set(view.expandedProjects) const expandedSessions = new Set(view.expandedSessions) - const rows: SidebarRow[] = [] - for (const g of groupByCwd(list)) { + const intent = list.intent + const intentWorkspaceId = intent?.target.kind === 'workspace' + ? intent.target.workspaceId + : undefined + const currentAccount = list.current === undefined + ? undefined + : workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId as string | undefined + const currentGroup = list.current === undefined + ? undefined + : intent?.sessionId === list.current + ? intentWorkspaceId + : currentAccount ?? UNGROUPED_KEY + const groups: GroupNode[] = [] + for (const g of groupByWorkspace(list, workspaces)) { + const hasIntent = intentWorkspaceId !== undefined + && g.workspaceId !== undefined && intentWorkspaceId === g.workspaceId + const intentHere = q === '' && hasIntent if (q === '') { - const expanded = expandedProjects.has(g.key) - rows.push({ type: 'project', key: g.key, cwd: g.cwd, label: g.label, sessionCount: g.summaries.size, expanded }) - if (expanded) flattenVisible(g, expandedSessions, rows) + const expanded = intentHere || expandedProjects.has(g.key) + groups.push({ + key: g.key, + workspaceId: g.workspaceId, + cwd: g.cwd, + label: g.label, + sessionCount: g.summaries.size + (hasIntent ? 1 : 0), + expanded, + containsCurrent: g.key === currentGroup, + intentHere, + sessions: expanded ? buildVisible(g, expandedSessions) : [], + }) } else { const visible = searchVisible(g, q) if (visible.size === 0 && !g.label.toLowerCase().includes(q)) continue - rows.push({ - type: 'project', + groups.push({ key: g.key, + workspaceId: g.workspaceId, cwd: g.cwd, label: g.label, - sessionCount: g.summaries.size, + sessionCount: g.summaries.size + (hasIntent ? 1 : 0), expanded: visible.size > 0, + containsCurrent: g.key === currentGroup, + intentHere: false, + sessions: buildSearch(g, visible), }) - flattenSearch(g, visible, rows) } } - return rows + return groups } /** - * Relative time label for session rows (figma samples: now / 2min / 1h / 2d / 18d / 2mo). - * @param updatedAt - epoch ms of the last update. - * @param now - current epoch ms. - * @returns compact age label. + * Compact relative time for session rows ("now", "5min", "3h", "2d", "4mo", "1y"). + * @param updatedAt - epoch ms of the session's last activity. + * @param now - current epoch ms (injected for pure rendering). + * @returns the row's trailing time label. */ export function formatRelativeTime(updatedAt: number, now: number): string { const MIN = 60_000 diff --git a/packages/client/ui-sidebar/tests/apply.spec.tsx b/packages/client/ui-sidebar/tests/apply.spec.tsx index 51976d95bf..5d285bd20c 100644 --- a/packages/client/ui-sidebar/tests/apply.spec.tsx +++ b/packages/client/ui-sidebar/tests/apply.spec.tsx @@ -1,117 +1,60 @@ -/** - * apply wiring on a real cordis Context + SlotsService (terminal register - * form): SidebarRoot registered into the layout-declared sidebar slot, the - * thin inject surface (three plain service callbacks closed over the plugin - * ctx — no hooks, no store lines), load-order fail-loud, and fiber-teardown - * unregistration. Component behavior is covered props-direct in - * sidebar-root.spec.tsx; no renderer machinery here. - */ +/** Sidebar slot registration and its plain runtime/layout callbacks. */ import { Context } from 'cordis' import { describe, expect, it, vi } from 'vitest' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' -import type { SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-sidebar/client' import type { SidebarRootInjected } from '@deepseek-ai/dsh-client-ui-sidebar/client' -// Type-only: ui-layout's SlotMap merge so the sidebar slot key typechecks. -import type {} from '@deepseek-ai/dsh-client-ui-layout/client' -const sid = (s: string) => s as SessionId - -async function bench() { +async function bench(declare = true) { const ctx = new Context() await ctx.plugin(SlotsService).await() - const list = createSnapshotStore({ - ids: [sid('a')], - byId: { [sid('a')]: { id: sid('a'), title: 'alpha', displayTitle: 'alpha', cwd: '/proj', running: false, updatedAt: 1 } }, - current: undefined, - }) - const sessions = { - list, - create: vi.fn(async () => sid('minted')), - open: vi.fn(), - clear: vi.fn(), - } const layout = { toggleSidebar: vi.fn() } - ctx.provide('sessions', sessions) + const sessions = { open: vi.fn() } + const workspaces = { startSession: vi.fn() } ctx.provide('layout', layout) + ctx.provide('sessions', sessions as never) + ctx.provide('workspaces', workspaces as never) const slots = ctx.get('slots') as SlotsService - // The sidebar slot exists only while its declaring entry is live. - slots.register( - { name: 'root', children: { 'sidebar': { kind: 'single', scope: 'root' } } } as never, - () => null, - ) - return { ctx, slots, sessions, layout } + if (declare) { + slots.register( + { name: 'root', children: { 'sidebar': { kind: 'single', scope: 'root' } } } as never, + () => null, + ) + } + return { ctx, slots, layout, sessions, workspaces } } -/** The sidebar entry's injected share, read off the stored entry. */ -function injectedOf(slots: SlotsService): SidebarRootInjected { - const entries = slots.entries('sidebar') - expect(entries).toHaveLength(1) - // The typed StoredEntry.inject is declaration-derived ((...args: never[]) - // shape); the sidebar factory is parameterless, so the call is safe here. - const inject = entries[0]!.inject as (() => SidebarRootInjected) | undefined - return inject!() -} - -describe('apply', () => { - it('declares the services it binds', () => { - expect(inject).toEqual(['slots', 'layout', 'sessions']) +describe('ui-sidebar apply', () => { + it('declares only the services it uses', () => { + expect(inject).toEqual(['slots', 'layout', 'sessions', 'workspaces']) }) - it('fails loud when mounted without the inject declaration', async () => { - // ctx.slots rides the cordis property proxy: reading it from a plugin - // that never declared the dependency throws instead of yielding undefined. - const ctx = new Context() - await ctx.plugin(SlotsService).await() - await expect(ctx.plugin({ apply })).rejects.toThrow(/without inject/) + it('registers the sidebar and declares its Workspace picker hole', async () => { + const b = await bench() + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries('sidebar')).toHaveLength(1) + expect(b.slots.spec('sidebar.workspace')).toEqual({ kind: 'single', scope: 'root' }) + const injected = (b.slots.entries('sidebar')[0]!.inject as () => SidebarRootInjected)() + expect(Object.keys(injected)).toEqual(['startSession', 'open', 'toggleSidebar']) + injected.startSession('workspace' as never, 'prompt') + expect(b.workspaces.startSession).toHaveBeenCalledWith('workspace', 'prompt') + injected.open('session' as never) + expect(b.sessions.open).toHaveBeenCalledWith('session') + injected.toggleSidebar() + expect(b.layout.toggleSidebar).toHaveBeenCalledOnce() }) - it('fails loud when no live entry has declared the sidebar slot', async () => { - const ctx = new Context() - await ctx.plugin(SlotsService).await() - ctx.provide('sessions', {}) - ctx.provide('layout', {}) - await expect(ctx.plugin({ inject: [...inject], apply })).rejects.toThrow(/slot "sidebar" is not declared/) + it('fails when no live owner declared the sidebar slot', async () => { + const b = await bench(false) + await expect(b.ctx.plugin({ inject: [...inject], apply })).rejects.toThrow(/not declared/) }) - it('registers SidebarRoot with the thin three-callback inject surface', async () => { - const { ctx, slots } = await bench() - await ctx.plugin({ inject: [...inject], apply }).await() - const injected = injectedOf(slots) - // The whole business face: three plain callbacks, no hooks, no store lines. - expect(Object.keys(injected).sort()).toEqual(['onCreate', 'onOpen', 'onToggleSidebar']) - }) - - it('routes the callbacks to the layout/sessions services', async () => { - const { ctx, slots, sessions, layout } = await bench() - await ctx.plugin({ inject: [...inject], apply }).await() - const injected = injectedOf(slots) - - injected.onToggleSidebar() - expect(layout.toggleSidebar).toHaveBeenCalledOnce() - - injected.onOpen(sid('a')) - expect(sessions.open).toHaveBeenCalledWith('a') - - injected.onCreate() - expect(sessions.clear).toHaveBeenCalledOnce() - expect(sessions.create).not.toHaveBeenCalled() - - injected.onCreate('/proj') - expect(sessions.create).toHaveBeenCalledWith({ cwd: '/proj' }) - // create-then-open lands after the create promise resolves. - await Promise.resolve() - await Promise.resolve() - expect(sessions.open).toHaveBeenCalledWith('minted') - }) - - it('teardown unregisters the slot entry', async () => { - const { ctx, slots } = await bench() - const fiber = ctx.plugin({ inject: [...inject], apply }) + it('removes the entry and child declaration on teardown', async () => { + const b = await bench() + const fiber = b.ctx.plugin({ inject: [...inject], apply }) await fiber.await() - expect(slots.entries('sidebar')).toHaveLength(1) await fiber.dispose() - expect(slots.entries('sidebar')).toHaveLength(0) + expect(b.slots.entries('sidebar')).toHaveLength(0) + expect(b.slots.spec('sidebar.workspace')).toBeUndefined() }) }) diff --git a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx index a76b86c106..bae2ed69ee 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx @@ -1,292 +1,82 @@ // @vitest-environment jsdom -/** - * SidebarRoot interaction spec, props-direct (slot-parity test doctrine: - * components are fed composed props, no assembly machinery). The standard - * useSessions hook is stubbed with a real web-react SnapshotStore selector; - * expansion/search live inside the component, so all viewing behavior is - * driven through the DOM. Covers expand/collapse, subtree unfold, search - * filtering, row activation, and the creation entries. - */ import { afterEach, describe, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' -import { act, useSyncExternalStore } from 'react' -// Runtime is React-free, so the spec binds its selector locally. -import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' -import type { SessionId, SessionListState, SessionSummary } from '@deepseek-ai/dsh-client-runtime/client' +import type { + SessionId, SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' +import type { SidebarRootComponentProps } from '../src/client/contract/slots.ts' import { SidebarRoot } from '../src/client/SidebarRoot.tsx' -/** Minimal selector hook over an engine store (production binding lives in the renderer). */ -function hookOf(src: { getSnapshot(): T; subscribe(fn: () => void): () => void }) { - return (sel: (s: T) => S, _eq?: (a: S, b: S) => boolean): S => - sel(useSyncExternalStore(src.subscribe.bind(src), src.getSnapshot.bind(src))) -} - -const sid = (s: string) => s as SessionId - -/** Bare-string init; brands ids and omits absent optional keys (exactOptionalPropertyTypes). */ -interface SummaryInit { - id: string - title?: string - cwd?: string - parentId?: string - running?: boolean - updatedAt?: number -} - -function summary(init: SummaryInit): SessionSummary { - const s: SessionSummary = { - id: sid(init.id), - title: init.title ?? init.id, - displayTitle: init.title ?? init.id, - running: init.running ?? false, - updatedAt: init.updatedAt ?? 0, - } - if (init.cwd !== undefined) s.cwd = init.cwd - if (init.parentId !== undefined) s.parentId = sid(init.parentId) - return s -} - -function listStateOf(...summaries: SessionSummary[]): SessionListState { - const byId: Record = {} - for (const s of summaries) byId[s.id] = s - return { ids: summaries.map((s) => s.id), byId, current: undefined } -} - afterEach(cleanup) - -function mount(...summaries: SessionSummary[]) { - // Real engine store as the useSessions stub: same uSES selector shape the - // framework delivers, so list updates re-render exactly like production. - const sessions = createSnapshotStore(listStateOf(...summaries)) - const onOpen = vi.fn((id: SessionId) => { sessions.update((d) => { d.current = id }) }) - const onCreate = vi.fn() - // The owner decides collapsed in production (AppFrame maps the preference); - // the harness mirrors that loop so the toggle drives a re-render. - let collapsed = false - const view = (width: number) => ( - - ) - const onToggleSidebar = vi.fn(() => { - collapsed = !collapsed - utils.rerender(view(collapsed ? 56 : 300)) - }) - const utils = render(view(300)) - return { sessions, onOpen, onCreate, onToggleSidebar, ...utils } +const sid = (id: string) => id as SessionId +const wid = (id: string) => id as WorkspaceId +const hook = (snapshot: T) => (selector: (state: T) => S): S => selector(snapshot) +const workspace: WorkspaceView = { + workspaceId: wid('project'), path: '/projects/project', title: 'Project', sessionIds: [sid('s1')], + createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', +} +const sessions: SessionListState = { + ids: [sid('s1')], + byId: { [sid('s1')]: { id: sid('s1'), displayTitle: 'First session', running: false, updatedAt: 1 } }, + current: undefined, phase: 'ready', + intent: undefined, +} +const workspaces: WorkspaceListState = { + items: [workspace], state: 'idle', phase: 'ready', error: null, + intent: undefined, baselinesReady: true, recentWorkspaceId: workspace.workspaceId, } -const projectData = () => [ - summary({ id: 'root', title: 'root work', cwd: '/proj', updatedAt: 5 }), - summary({ id: 'kid', title: 'forked child', cwd: '/proj', parentId: sid('root'), updatedAt: 4 }), - summary({ id: 'lone', title: 'elsewhere', cwd: '/other', updatedAt: 3 }), -] - -/** Flush the store's microtask-batched notification into React. */ -const flush = async () => { await act(async () => { await Promise.resolve() }) } - -/** The brand wordmark is decorative svg (aria-hidden, no text); locate it by its native viewBox. */ -const wordmark = () => document.querySelector('svg[viewBox="0 0 182 24"]') +function mount(sessionState: SessionListState = sessions) { + const startSession = vi.fn() + const open = vi.fn() + let pickerOwner: unknown + const view = render( + { pickerOwner = owner; return null }) as SidebarRootComponentProps['renderSlot']} + />, + ) + return { view, startSession, open, pickerOwner: () => pickerOwner } +} describe('SidebarRoot', () => { - it('renders chrome and collapsed project rows', () => { - mount(...projectData()) - expect(wordmark()).not.toBeNull() - expect(screen.getByText('New Session')).toBeTruthy() - expect(screen.getByText('proj')).toBeTruthy() - expect(screen.getByText('2 sessions')).toBeTruthy() - expect(screen.getByText('1 session')).toBeTruthy() - expect(screen.queryByText('root work')).toBeNull() + it('renders real Workspaces from useWorkspaces and routes New Session', () => { + const b = mount() + expect(screen.getByText('Project')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'New session' })) + expect(b.startSession).toHaveBeenCalledWith() }) - it('expands a project on click and unfolds a subtree via the twist', () => { - mount(...projectData()) - act(() => { fireEvent.click(screen.getByText('proj')) }) - expect(screen.getByText('root work')).toBeTruthy() - expect(screen.queryByText('forked child')).toBeNull() - act(() => { fireEvent.click(screen.getByLabelText('Expand')) }) - expect(screen.getByText('forked child')).toBeTruthy() - act(() => { fireEvent.click(screen.getByLabelText('Collapse')) }) - expect(screen.queryByText('forked child')).toBeNull() - }) - - it('opens a session on row click and marks it selected', async () => { - const { onOpen } = mount(...projectData()) - act(() => { fireEvent.click(screen.getByText('proj')) }) - act(() => { fireEvent.click(screen.getByText('root work')) }) - expect(onOpen).toHaveBeenCalledWith('root') - // The mock routed the open into sessions.current — highlight follows. - await flush() - expect(screen.getByText('root work').closest('[role="treeitem"]')!.getAttribute('aria-selected')).toBe('true') - }) - - it('search filters across groups and forces ancestor chains visible', () => { - mount(...projectData()) - const input = screen.getByPlaceholderText('Search name, keywords...') - act(() => { fireEvent.change(input, { target: { value: 'forked' } }) }) - expect(screen.getByText('forked child')).toBeTruthy() - expect(screen.getByText('root work')).toBeTruthy() - expect(screen.queryByText('elsewhere')).toBeNull() - expect(screen.queryByText(/^other$/)).toBeNull() - act(() => { fireEvent.click(screen.getByLabelText('Clear search')) }) - expect(screen.queryByText('root work')).toBeNull() - expect(screen.getByText('proj')).toBeTruthy() - }) - - it('shows the blank-list empty state without a query', () => { - mount() - expect(screen.getByText('No sessions yet')).toBeTruthy() - }) - - it('shows the no-match empty state', () => { - mount(...projectData()) - const input = screen.getByPlaceholderText('Search name, keywords...') - act(() => { fireEvent.change(input, { target: { value: 'zzz-none' } }) }) - expect(screen.getByText('No matches')).toBeTruthy() - }) - - it('routes the three creation entries with the right cwd', () => { - const { onCreate } = mount(...projectData()) - act(() => { fireEvent.click(screen.getByText('New Session')) }) - expect(onCreate).toHaveBeenLastCalledWith() - act(() => { fireEvent.click(screen.getByLabelText('New workspace')) }) - expect(onCreate).toHaveBeenLastCalledWith() - // Per-project "+" is hover-revealed by CSS; still clickable in jsdom. - act(() => { fireEvent.click(screen.getAllByLabelText('New session here')[0]!) }) - expect(onCreate).toHaveBeenLastCalledWith('/proj') - }) - - it('collapse fades the wide content out, then the rail keeps the four controls', () => { - vi.useFakeTimers() - try { - const { onToggleSidebar, onCreate } = mount(...projectData()) - act(() => { fireEvent.click(screen.getByLabelText('Collapse sidebar')) }) - expect(onToggleSidebar).toHaveBeenCalledOnce() - // Fade window: the wide chrome is still mounted while it fades. - expect(wordmark()).not.toBeNull() - expect(screen.getByRole('tree')).toBeTruthy() - // Settle: wide content unmounts, the rail controls remain. - act(() => { vi.advanceTimersByTime(300) }) - expect(wordmark()).toBeNull() - expect(screen.queryByText('New Session')).toBeNull() - expect(screen.queryByRole('tree')).toBeNull() - // Rail order mirrors the expanded rows: open, new session, new workspace, search. - const rail = ['Open sidebar', 'New session', 'New workspace', 'Search sessions', 'Settings'] - .map((label) => screen.getByLabelText(label)) - for (let i = 1; i < rail.length; i++) { - expect(rail[i - 1]!.compareDocumentPosition(rail[i]!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - } - // Rail creation entries route like their expanded counterparts. - act(() => { fireEvent.click(screen.getByLabelText('New session')) }) - expect(onCreate).toHaveBeenLastCalledWith() - act(() => { fireEvent.click(screen.getByLabelText('Open sidebar')) }) - expect(onToggleSidebar).toHaveBeenCalledTimes(2) - expect(screen.getByLabelText('Collapse sidebar')).toBeTruthy() - expect(screen.getByText('New Session')).toBeTruthy() - } finally { - vi.useRealTimers() - } - }) - - it('rail search expands the sidebar and focuses the search box', () => { - vi.useFakeTimers() - try { - const { onToggleSidebar } = mount(...projectData()) - // While expanded the search control is inert (the row click focuses instead). - act(() => { fireEvent.click(screen.getByLabelText('Search sessions')) }) - expect(onToggleSidebar).not.toHaveBeenCalled() - act(() => { fireEvent.click(screen.getByLabelText('Collapse sidebar')) }) - act(() => { vi.advanceTimersByTime(300) }) - act(() => { fireEvent.click(screen.getByLabelText('Search sessions')) }) - expect(onToggleSidebar).toHaveBeenCalledTimes(2) - // Focus waits out the 300ms column slide (EXPAND_SLIDE_MS). - act(() => { vi.advanceTimersByTime(300) }) - const input = screen.getByPlaceholderText('Search name, keywords...') - expect(document.activeElement).toBe(input) - } finally { - vi.useRealTimers() - } - }) - - it('expanded search focuses without toggling the sidebar', () => { - const { onToggleSidebar } = mount(...projectData()) - const input = screen.getByPlaceholderText('Search name, keywords...') - act(() => { fireEvent.click(screen.getByLabelText('Search sessions')) }) - expect(document.activeElement).toBe(input) - expect(onToggleSidebar).not.toHaveBeenCalled() - }) - - it('the search query survives a collapse/expand round trip', () => { - vi.useFakeTimers() - try { - mount(...projectData()) - const input = screen.getByPlaceholderText('Search name, keywords...') - act(() => { fireEvent.change(input, { target: { value: 'forked' } }) }) - act(() => { fireEvent.click(screen.getByLabelText('Collapse sidebar')) }) - act(() => { vi.advanceTimersByTime(300) }) - act(() => { fireEvent.click(screen.getByLabelText('Open sidebar')) }) - const restored = screen.getByPlaceholderText('Search name, keywords...') as HTMLInputElement - expect(restored.value).toBe('forked') - expect(screen.getByText('forked child')).toBeTruthy() - expect(screen.queryByText('elsewhere')).toBeNull() - } finally { - vi.useRealTimers() - } - }) - - it('group-by menu behaves', () => { - mount(...projectData()) - expect(screen.queryByText('Update')).toBeNull() - act(() => { fireEvent.click(screen.getByLabelText('Group by')) }) - expect(screen.getByText('Update')).toBeTruthy() - expect(screen.getByText('Status')).toBeTruthy() - // Selecting the active strategy closes the list (only workspace is enabled). - act(() => { fireEvent.click(screen.getByText('WorkSpace', { selector: 'button *' })) }) - expect(screen.queryByText('Update')).toBeNull() - // Reopen and dismiss via Escape (Menu onClose channel). - act(() => { fireEvent.click(screen.getByLabelText('Group by')) }) - act(() => { fireEvent.keyDown(document, { key: 'Escape' }) }) - expect(screen.queryByText('Update')).toBeNull() - }) - - it('re-renders when the sessions list gains a session', async () => { - const { sessions } = mount(...projectData()) - act(() => { - sessions.update((draft) => { - draft.ids.push(sid('fresh')) - draft.byId[sid('fresh')] = summary({ id: 'fresh', title: 'brand new', cwd: '/fresh', updatedAt: 99 }) - }) + it('shows a frontend Session under its real Workspace and routes its row plus', () => { + const intent = { sessionId: sid('intent'), target: { kind: 'workspace' as const, workspaceId: workspace.workspaceId }, prompt: '', phase: 'connecting' as const } + const b = mount({ + ...sessions, + current: intent.sessionId, + intent, }) - // Store notifications are microtask-batched. - await flush() - expect(screen.getByText('fresh')).toBeTruthy() + expect(screen.getByText('New session')).toBeTruthy() + expect(screen.getByText('2 sessions')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'New session in Project' })) + expect(b.startSession).toHaveBeenCalledWith(workspace.workspaceId) }) - it('row "More" anchors swallow the click without opening or toggling', () => { - const { onOpen } = mount(...projectData()) - act(() => { fireEvent.click(screen.getByText('proj')) }) - // Project-row anchor: must not collapse the project (rows stay visible). - act(() => { fireEvent.click(screen.getAllByLabelText('More')[0]!) }) - expect(screen.getByText('root work')).toBeTruthy() - // Session-row anchor: must not open the session. - act(() => { fireEvent.click(screen.getAllByLabelText('More')[1]!) }) - expect(onOpen).not.toHaveBeenCalled() + it('forwards Workspace picker selection and closes the picker', () => { + const b = mount() + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + const owner = b.pickerOwner() as { open: boolean; onPick(id: WorkspaceId): void } + expect(owner.open).toBe(true) + owner.onPick(workspace.workspaceId) + expect(b.startSession).toHaveBeenCalledWith(workspace.workspaceId) }) - it('shows the running state dot only for running sessions', () => { - mount( - summary({ id: 'busy', title: 'busy one', cwd: '/p', running: true, updatedAt: 2 }), - summary({ id: 'idle', title: 'idle one', cwd: '/p', updatedAt: 1 }), - ) - act(() => { fireEvent.click(screen.getByText('p')) }) - const busyRow = screen.getByText('busy one').closest('[role="treeitem"]')! - const idleRow = screen.getByText('idle one').closest('[role="treeitem"]')! - expect(busyRow.querySelector('[data-state="ongoing"]')).toBeTruthy() - expect(idleRow.querySelector('[data-state="ongoing"]')).toBeNull() + it('opens a real Session through the owner action', () => { + const b = mount({ ...sessions, current: sid('intent'), intent: { + sessionId: sid('intent'), target: { kind: 'workspace', workspaceId: workspace.workspaceId }, prompt: '', phase: 'ready', + } }) + fireEvent.click(screen.getByText('Project')) + fireEvent.click(screen.getByText('First session')) + expect(b.open).toHaveBeenCalledWith(sid('s1')) }) }) diff --git a/packages/client/ui-sidebar/tests/tree.spec.ts b/packages/client/ui-sidebar/tests/tree.spec.ts index 037a2a82ac..76d68db4ee 100644 --- a/packages/client/ui-sidebar/tests/tree.spec.ts +++ b/packages/client/ui-sidebar/tests/tree.spec.ts @@ -1,245 +1,74 @@ import { describe, expect, it } from 'vitest' -import type { SessionId, SessionListState, SessionSummary } from '@deepseek-ai/dsh-client-runtime/client' -import { - deriveRows, formatRelativeTime, projectLabel, UNGROUPED_KEY, UNGROUPED_LABEL, - type SessionRow, type TreeView, -} from '../src/client/tree.ts' +import type { + SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' +import { deriveGroups, formatRelativeTime, UNGROUPED_KEY } from '../src/client/tree.ts' -const sid = (s: string) => s as SessionId - -/** Bare-string init; brands ids and omits absent optional keys (exactOptionalPropertyTypes). */ -interface SummaryInit { - id: string - title?: string - displayTitle?: string - cwd?: string - parentId?: string - running?: boolean - updatedAt?: number -} - -function summary(init: SummaryInit): SessionSummary { - const s: SessionSummary = { - id: sid(init.id), - displayTitle: init.displayTitle ?? init.title ?? init.id, - running: init.running ?? false, - updatedAt: init.updatedAt ?? 0, - } - if (init.title !== undefined) s.title = init.title - if (init.cwd !== undefined) s.cwd = init.cwd - if (init.parentId !== undefined) s.parentId = sid(init.parentId) - return s -} - -function listOf(...summaries: SessionSummary[]): SessionListState { - const byId: Record = {} - for (const s of summaries) byId[s.id] = s - return { ids: summaries.map(s => s.id), byId, current: undefined } -} - -const view = (partial: Partial = {}): TreeView => ({ - expandedProjects: partial.expandedProjects ?? [], - expandedSessions: partial.expandedSessions ?? [], - query: partial.query ?? '', +const sid = (id: string) => id as SessionId +const wid = (id: string) => id as WorkspaceId +const summary = (id: string, updatedAt: number, cwd?: string): SessionSummary => ({ + id: sid(id), displayTitle: id, running: false, updatedAt, ...(cwd === undefined ? {} : { cwd }), +}) +const list = (...items: SessionSummary[]): SessionListState => ({ + ids: items.map(item => item.id), + byId: Object.fromEntries(items.map(item => [item.id, item])), + current: undefined, + phase: 'ready', + intent: undefined, +}) +const workspace = (id: string, sessionIds: string[]): WorkspaceView => ({ + workspaceId: wid(id), path: `/projects/${id}`, title: id, + sessionIds: sessionIds.map(sid), createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', +}) +const view = (expandedProjects: readonly string[] = [], query = '') => ({ + expandedProjects, expandedSessions: [] as string[], query, }) -describe('projectLabel', () => { - it('takes the basename and survives trailing separators', () => { - expect(projectLabel('/home/me/proj')).toBe('proj') - expect(projectLabel('/home/me/proj/')).toBe('proj') - expect(projectLabel('C:\\work\\thing')).toBe('thing') +describe('deriveGroups', () => { + it('keeps Host Workspace and sessionIds order without Client recency sorting', () => { + const sessions = list(summary('newer', 20), summary('older', 10)) + const workspaces = [workspace('first', ['older', 'newer']), workspace('empty', [])] + const groups = deriveGroups(sessions, workspaces, view(['first'])) + expect(groups.map(group => group.key)).toEqual(['first', 'empty']) + expect(groups[0]!.sessions.map(session => session.id)).toEqual([sid('older'), sid('newer')]) }) - it('falls back for empty and root-only paths', () => { - expect(projectLabel(undefined)).toBe(UNGROUPED_LABEL) - expect(projectLabel('')).toBe(UNGROUPED_LABEL) - expect(projectLabel('///')).toBe('///') - }) -}) - -describe('deriveRows grouping', () => { - it('groups by cwd into project rows with counts, newest group first', () => { - const rows = deriveRows(listOf( - summary({ id: 'a', cwd: '/x/alpha', updatedAt: 10 }), - summary({ id: 'b', cwd: '/x/beta', updatedAt: 30 }), - summary({ id: 'c', cwd: '/x/alpha', updatedAt: 20 }), - ), view()) - expect(rows).toEqual([ - expect.objectContaining({ type: 'project', key: '/x/beta', label: 'beta', sessionCount: 1, expanded: false }), - expect.objectContaining({ type: 'project', key: '/x/alpha', label: 'alpha', sessionCount: 2 }), - ]) + it('puts only real unaccounted Sessions in the trailing Ungrouped group', () => { + const sessions = list(summary('owned', 1, '/projects/first'), summary('loose', 9, '/other')) + const groups = deriveGroups(sessions, [workspace('first', ['owned'])], view([UNGROUPED_KEY])) + expect(groups.map(group => group.key)).toEqual(['first', UNGROUPED_KEY]) + expect(groups[1]!.sessions.map(session => session.id)).toEqual([sid('loose')]) }) - it('orders equally-recent groups by label and skips ids missing from byId', () => { - const list = listOf( - summary({ id: 'b1', cwd: '/x/beta', updatedAt: 5 }), - summary({ id: 'a1', cwd: '/x/alpha', updatedAt: 5 }), - // Same basename and same recency as beta: label comparator returns 0, - // insertion order breaks the tie. - summary({ id: 'b2', cwd: '/y/beta', updatedAt: 5 }), - ) - list.ids.push(sid('ghost')) - const rows = deriveRows(list, view()) - expect(rows.map(r => r.type === 'project' && r.key)).toEqual(['/x/alpha', '/x/beta', '/y/beta']) - }) - - it('buckets cwd-less sessions under the ungrouped project row', () => { - const rows = deriveRows(listOf(summary({ id: 'a' })), view()) - expect(rows).toEqual([ - expect.objectContaining({ type: 'project', key: UNGROUPED_KEY, cwd: undefined, label: UNGROUPED_LABEL }), - ]) - }) - - it('hides sessions under collapsed projects and shows them when expanded', () => { - const list = listOf( - summary({ id: 'a', cwd: '/p', updatedAt: 1 }), - summary({ id: 'b', cwd: '/p', updatedAt: 2 }), - ) - expect(deriveRows(list, view()).filter(r => r.type === 'session')).toHaveLength(0) - const rows = deriveRows(list, view({ expandedProjects: ['/p'] })) - expect(rows.slice(1)).toEqual([ - expect.objectContaining({ type: 'session', id: 'b', depth: 0 }), - expect.objectContaining({ type: 'session', id: 'a', depth: 0 }), - ]) - }) -}) - -describe('deriveRows session tree', () => { - const treeList = listOf( - summary({ id: 'root', cwd: '/p', updatedAt: 5 }), - summary({ id: 'kid', cwd: '/p', parentId: sid('root'), updatedAt: 4 }), - summary({ id: 'grandkid', cwd: '/p', parentId: sid('kid'), updatedAt: 3 }), - summary({ id: 'other', cwd: '/p', updatedAt: 9 }), - ) - - it('nests children under expanded parents with increasing depth', () => { - const rows = deriveRows(treeList, view({ - expandedProjects: ['/p'], - expandedSessions: ['root', 'kid'], + it('shows one frontend Session row only under a real target Workspace', () => { + const intent = { sessionId: sid('intent'), target: { kind: 'workspace' as const, workspaceId: wid('first') }, prompt: '', phase: 'connecting' as const } + const target = workspace('first', []) + expect(deriveGroups({ ...list(), current: intent.sessionId, intent }, [target], view())[0]).toEqual(expect.objectContaining({ + intentHere: true, + sessionCount: 1, + containsCurrent: true, })) - expect(rows.slice(1)).toEqual([ - expect.objectContaining({ id: 'other', depth: 0, hasChildren: false }), - expect.objectContaining({ id: 'root', depth: 0, hasChildren: true, expanded: true }), - expect.objectContaining({ id: 'kid', depth: 1, hasChildren: true, expanded: true }), - expect.objectContaining({ id: 'grandkid', depth: 2, hasChildren: false }), - ]) + const hiddenIntent = { sessionId: sid('zero'), target: { kind: 'workspace-intent' as const }, prompt: '', phase: 'ready' as const } + expect(deriveGroups({ ...list(), intent: hiddenIntent }, [target], view())[0]!.intentHere).toBe(false) }) - it('collapses subtrees at unexpanded sessions', () => { - const rows = deriveRows(treeList, view({ expandedProjects: ['/p'] })) - const ids = rows.filter((r): r is SessionRow => r.type === 'session').map(r => r.id) - expect(ids).toEqual(['other', 'root']) - }) - - it('degrades a cross-group parent link to a group root', () => { - const rows = deriveRows(listOf( - summary({ id: 'p1', cwd: '/a', updatedAt: 2 }), - summary({ id: 'stray', cwd: '/b', parentId: sid('p1'), updatedAt: 1 }), - ), view({ expandedProjects: ['/a', '/b'] })) - expect(rows).toEqual([ - expect.objectContaining({ type: 'project', key: '/a' }), - expect.objectContaining({ id: 'p1', depth: 0 }), - expect.objectContaining({ type: 'project', key: '/b' }), - expect.objectContaining({ id: 'stray', depth: 0 }), - ]) - }) - - it('keeps cycle members visible as extra roots without looping', () => { - const rows = deriveRows(listOf( - summary({ id: 'x', cwd: '/p', parentId: sid('y'), updatedAt: 2 }), - summary({ id: 'y', cwd: '/p', parentId: sid('x'), updatedAt: 1 }), - summary({ id: 'self', cwd: '/p', parentId: sid('self'), updatedAt: 3 }), - ), view({ expandedProjects: ['/p'], expandedSessions: ['x', 'y', 'self'] })) - const ids = rows.filter((r): r is SessionRow => r.type === 'session').map(r => r.id) - expect(ids).toContain('self') - expect(ids).toContain('x') - expect(ids).toContain('y') - expect(ids).toHaveLength(3) - }) - - it('breaks updatedAt ties deterministically by id', () => { - const rows = deriveRows(listOf( - summary({ id: 'b', cwd: '/p', updatedAt: 7 }), - summary({ id: 'a', cwd: '/p', updatedAt: 7 }), - summary({ id: 'c', cwd: '/p', updatedAt: 7 }), - ), view({ expandedProjects: ['/p'] })) - const ids = rows.filter((r): r is SessionRow => r.type === 'session').map(r => r.id) - expect(ids).toEqual(['a', 'b', 'c']) - }) - - it('collects multiple children under one parent in recency order', () => { - const rows = deriveRows(listOf( - summary({ id: 'p', cwd: '/p', updatedAt: 9 }), - summary({ id: 'old', cwd: '/p', parentId: sid('p'), updatedAt: 1 }), - summary({ id: 'new', cwd: '/p', parentId: sid('p'), updatedAt: 5 }), - ), view({ expandedProjects: ['/p'], expandedSessions: ['p'] })) - const ids = rows.filter((r): r is SessionRow => r.type === 'session').map(r => r.id) - expect(ids).toEqual(['p', 'new', 'old']) - }) - - it('carries the running flag onto rows', () => { - const rows = deriveRows( - listOf(summary({ id: 'a', cwd: '/p', running: true })), - view({ expandedProjects: ['/p'] })) - expect(rows[1]).toEqual(expect.objectContaining({ id: 'a', running: true })) - }) -}) - -describe('deriveRows search', () => { - const list = listOf( - summary({ id: 'root', title: 'alpha work', cwd: '/p', updatedAt: 5 }), - summary({ id: 'kid', title: 'deep needle here', cwd: '/p', parentId: sid('root'), updatedAt: 4 }), - summary({ id: 'noise', title: 'unrelated', cwd: '/p', updatedAt: 3 }), - summary({ id: 'q', title: 'quiet', cwd: '/other', updatedAt: 2 }), - ) - - it('forces matched sessions and their ancestor chains visible, ignoring expansion', () => { - const rows = deriveRows(list, view({ query: 'NEEDLE' })) - expect(rows).toEqual([ - expect.objectContaining({ type: 'project', key: '/p', expanded: true }), - expect.objectContaining({ id: 'root', depth: 0, expanded: true }), - expect.objectContaining({ id: 'kid', depth: 1 }), - ]) - }) - - it('drops groups without a hit and keeps a bare project row on label-only hits', () => { - const rows = deriveRows(list, view({ query: 'other' })) - expect(rows).toEqual([ - expect.objectContaining({ type: 'project', key: '/other', expanded: false }), - ]) - }) - - it('blank query means normal mode', () => { - const rows = deriveRows(list, view({ query: ' ' })) - expect(rows.every(r => r.type === 'project')).toBe(true) - }) - - it('matches the effective display title when no durable title is available', () => { - const fallback = listOf(summary({ id: 'raw-id', displayTitle: 'project fallback', cwd: '/elsewhere' })) - const rows = deriveRows(fallback, view({ query: 'fallback' })) - expect(rows).toEqual([ - expect.objectContaining({ type: 'project', key: '/elsewhere' }), - expect.objectContaining({ type: 'session', id: 'raw-id', title: 'project fallback' }), - ]) + it('search filters real Sessions and omits the Intent placeholder', () => { + const intent = { sessionId: sid('intent'), target: { kind: 'workspace' as const, workspaceId: wid('first') }, prompt: '', phase: 'ready' as const } + const groups = deriveGroups({ ...list(summary('match', 1)), intent }, [workspace('first', ['match'])], view([], 'match')) + expect(groups[0]!.sessions.map(session => session.id)).toEqual([sid('match')]) + expect(groups[0]!.intentHere).toBe(false) + expect(groups[0]!.sessionCount).toBe(2) }) }) describe('formatRelativeTime', () => { - const now = 1_000_000_000_000 - it.each([ - [now, 'now'], - [now - 30_000, 'now'], - [now - 2 * 60_000, '2min'], - [now - 3_600_000, '1h'], - [now - 2 * 86_400_000, '2d'], - [now - 18 * 86_400_000, '18d'], - [now - 65 * 86_400_000, '2mo'], - [now - 400 * 86_400_000, '1y'], - ])('%d -> %s', (at, label) => { - expect(formatRelativeTime(at, now)).toBe(label) - }) - - it('clamps future timestamps to now', () => { - expect(formatRelativeTime(now + 5_000, now)).toBe('now') + it('formats current, minute, hour, day, month, and year buckets', () => { + const now = 400 * 24 * 60 * 60 * 1_000 + expect(formatRelativeTime(now, now)).toBe('now') + expect(formatRelativeTime(now - 5 * 60_000, now)).toBe('5min') + expect(formatRelativeTime(now - 3 * 3_600_000, now)).toBe('3h') + expect(formatRelativeTime(now - 2 * 86_400_000, now)).toBe('2d') + expect(formatRelativeTime(now - 60 * 86_400_000, now)).toBe('2mo') + expect(formatRelativeTime(0, now)).toBe('1y') }) }) diff --git a/packages/client/ui-slots/README.md b/packages/client/ui-slots/README.md index 16d6380639..4057691295 100644 --- a/packages/client/ui-slots/README.md +++ b/packages/client/ui-slots/README.md @@ -13,7 +13,7 @@ One `register({ name, children?, store?, inject?, ...kind }, Component)` call co Chain-kind slots invert keyed routing — entries self-nominate instead of the dispatch site picking an `entryKey`: each registration carries a pure `ChainSelect` selector (plus optional ascending `priority`, ties in registration order), the first non-null return elects its entry and becomes the component's `matched` prop, and all-null falls to the owner's `renderSlotChain` fallback (`ChainRenderOpts`). -The standard-kit interfaces (`SessionStandardProps`, `GlobalStandardProps`) are declared empty here and merged by the runtime package (same declare-merge pattern as SlotMap keys). Inject factory parameters derive from the declaration (`InjectParams`): session slots get `sessionId`, a declared store appends baked `actions`, nothing else — data access lives in the apply closure's ctx. +The standard-kit interfaces (`SessionStandardProps`, `GlobalStandardProps`) are declared empty here and merged by the runtime package (same declare-merge pattern as SlotMap keys). The renderer binds the runtime's session and workspace observable sources into selector hooks. Inject factory parameters derive from the declaration (`InjectParams`): session slots get `sessionId`, a declared store appends baked `actions`, nothing else — data access lives in the apply closure's ctx. The store family (`defineStore` spec in / `StoreHandle` out) types the store seat: `init` infers the state schema, `actions` is the complete draft-transform write set, `BakedActions` strips the draft parameter into the callbacks components and inject factories receive. The `defineStore` value implementation lives in the runtime package (the engine's home) and satisfies the `DefineStore` contract exported here. Engine products and the renderer host contract carry bare snapshot sources (`getSnapshot`/`subscribe`), never React hooks — hook binding is the render machinery's side of the seam; only the props-contract hook type (`SnapshotSelectorHook`) lives here. diff --git a/packages/client/ui-slots/src/index.ts b/packages/client/ui-slots/src/index.ts index e6a85664b0..677bc4e0df 100644 --- a/packages/client/ui-slots/src/index.ts +++ b/packages/client/ui-slots/src/index.ts @@ -74,8 +74,8 @@ export interface SessionStandardProps {} /** * Framework standard kit delivered to EVERY slot component (the global seat). - * Declared empty here; the runtime package merges `useSessions` (the session - * list selector hook — the sidebar tree's single derivation source). + * Declared empty here; the runtime package merges the global object-layer + * selector hooks that shared page composition consumes. */ export interface GlobalStandardProps {} diff --git a/packages/client/ui-slots/src/renderer.ts b/packages/client/ui-slots/src/renderer.ts index 49d64205c7..058929b1ff 100644 --- a/packages/client/ui-slots/src/renderer.ts +++ b/packages/client/ui-slots/src/renderer.ts @@ -98,6 +98,11 @@ export interface SlotRendererHost { */ cell(id: string): SessionCell | undefined } + /** Workspace-side standard-kit sources. */ + workspaces: { + /** Workspace list source backing the useWorkspaces standard hook. */ + list: HostObservable + } } /** The install seam: runtime owns install()/renderSlot(); web-react implements rendering. */ diff --git a/packages/client/ui-trajectory/tests/views.spec.tsx b/packages/client/ui-trajectory/tests/views.spec.tsx index dcc1ba6855..c1e6331ef6 100644 --- a/packages/client/ui-trajectory/tests/views.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.spec.tsx @@ -15,7 +15,7 @@ import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' import type { UseSession } from '@deepseek-ai/dsh-client-web-react' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' -import type { ConversationSnapshot, SessionId, SessionListState } from '@deepseek-ai/dsh-client-runtime/client' +import type { ConversationSnapshot, SessionId, SessionListState, WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client' import type { ConvViewProps, ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' // Export discipline: packages/client/AGENTS.md. import { ConversationRoot, type ConversationRootProps } from '@deepseek-ai/dsh-client-ui-conversation/src/client/skeleton/ConversationRoot.tsx' @@ -62,7 +62,15 @@ function fakeSession(nodes: ConversationSnapshot['nodes']) { /** Empty sessions-list hook; breadcrumbs therefore fall back to the raw id. */ function emptySessions() { const store = createSnapshotStore( - { ids: [], byId: {}, current: undefined } as SessionListState) + { ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' }) + return bindSnapshotSelector(store) +} + +function emptyWorkspaces() { + const store = createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, baselinesReady: true, + recentWorkspaceId: undefined, + }) return bindSnapshotSelector(store) } @@ -75,6 +83,7 @@ function standaloneProps(nodes: ConversationSnapshot['nodes']): ConvViewProps { sessionId: SID, useSession: fakeSession(nodes).useSession, useSessions: emptySessions(), + useWorkspaces: emptyWorkspaces(), } as unknown as ConvViewProps } @@ -121,7 +130,7 @@ function mount(slots: SlotsService, nodes: ConversationSnapshot['nodes'] = NODES const View = entry.component as FC return ( ) @@ -131,6 +140,7 @@ function mount(slots: SlotsService, nodes: ConversationSnapshot['nodes'] = NODES sessionId={SID} useSession={useSession} useSessions={emptySessions()} + useWorkspaces={emptyWorkspaces()} useStore={bindSnapshotSelector(chat)} actions={chat.actions} renderSlot={renderSlot} @@ -144,6 +154,8 @@ function mount(slots: SlotsService, nodes: ConversationSnapshot['nodes'] = NODES send={vi.fn()} stop={vi.fn()} open={vi.fn()} + updateSessionPrompt={vi.fn()} + retrySessionPrompt={vi.fn()} />, ) } diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md new file mode 100644 index 0000000000..b2a024fc5e --- /dev/null +++ b/packages/client/ui-workspace/README.md @@ -0,0 +1,20 @@ +# @deepseek-ai/dsh-client-ui-workspace + +Shared Workspace picker plugin. `WorkspacePicker` is registered into the sidebar's `sidebar.workspace` slot and the page-local Session Intent hero's `conversation.empty.workspace` slot, so both surfaces use the same menu and creation modals. + +The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object; the existing-folder and create-new actions first create a real Workspace through the object layer, then select it. Create-new disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. + +Both target slots are declared by other plugins, so `apply` registers through declaration-aware deferral and re-registers after a declaring slot is restored. + +## Model Experience + +None, as the picker is browser chrome; nothing here reaches a model request. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + +- **No Workspace rename/delete controls** — the picker supports selection and creation only. +- **Existing-folder entry is manual path input only** — Host creation failures are shown in the modal. diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json new file mode 100644 index 0000000000..0a6c82c0cf --- /dev/null +++ b/packages/client/ui-workspace/package.json @@ -0,0 +1,65 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-workspace", + "description": "Workspace picker plugin: one WorkspacePicker registered into the sidebar and empty-state workspace slots", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "dshClient": { + "inject": [ + "@deepseek-ai/dsh-client-runtime", + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-sidebar" + ], + "platform": "web" + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-client-runtime": "^0.0.1", + "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", + "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-client-ui-conversation": "workspace:^", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", + "@deepseek-ai/dsh-client-ui-sidebar": "workspace:^", + "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@types/react": "~18.3.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ] +} diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.module.css b/packages/client/ui-workspace/src/client/WorkspacePicker.module.css new file mode 100644 index 0000000000..e439d30f27 --- /dev/null +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.module.css @@ -0,0 +1,46 @@ +/* Modal form styles mirror the empty state's path/create modals (same figma + * dialog family: field h44, r22, hairline border, pad 14/7) so the two + * entries stay visually identical. */ +.modalInput { + box-sizing: border-box; + width: 100%; + height: 44px; + padding: 7px 14px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 22px; + outline: none; + background: transparent; + font-size: 14px; + font-weight: 400; + line-height: 22px; + color: var(--dsw-alias-label-primary); +} + +.modalInput::placeholder { + color: var(--dsw-alias-label-caption); +} + +.modalInput:disabled { + color: var(--dsw-alias-label-dimmed); +} + +.modalAction { + min-width: 72px; +} + +.modalError, +.modalStatus, +.menuStatus { + margin-top: 8px; + font-size: 12px; + line-height: 18px; +} + +.modalError { + color: var(--dsw-alias-state-error-primary); +} + +.modalStatus, +.menuStatus { + color: var(--dsw-alias-label-secondary); +} diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx new file mode 100644 index 0000000000..8f6f483580 --- /dev/null +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -0,0 +1,196 @@ +/** Shared Workspace picker for the sidebar and New Session hero. */ +import { useCallback, useState } from 'react' +import { + Button, IconFolderClose16, IconPlusOutline16, Menu, Modal, type MenuEntry, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' +import type { WorkspacePickerProps } from './contract/slots.ts' +import css from './WorkspacePicker.module.css' + +const CREATE_WORKSPACE = '::create-workspace' +const USE_EXISTING = '::use-existing' +const CREATE_NEW = '::create-new' + +type ModalKind = 'path' | 'create' | null + +export function WorkspacePicker({ + open, + anchorRef, + useWorkspaces, + onPick, + onClose, + createWorkspace, +}: WorkspacePickerProps) { + const workspaceSnapshot = useWorkspaces(state => state) + const workspaces = workspaceSnapshot.items + const getAnchorRect = useCallback( + () => anchorRef?.current?.getBoundingClientRect() ?? null, + [anchorRef], + ) + const [modalKind, setModalKind] = useState(null) + const [pathDraft, setPathDraft] = useState('') + const [workspaceName, setWorkspaceName] = useState('') + const [creating, setCreating] = useState(false) + const [modalError, setModalError] = useState(null) + const normalizedWorkspaceName = workspaceName.trim() + const duplicateWorkspaceName = normalizedWorkspaceName !== '' + && workspaces.some(workspace => workspace.title === normalizedWorkspaceName) + + const items: MenuEntry[] = [ + ...workspaces.map(workspace => ({ + id: workspace.workspaceId as string, + label: workspace.title, + icon: , + })), + ...(workspaces.length > 0 ? [{ type: 'separator' as const, id: 'sep-create' }] : []), + { + id: CREATE_WORKSPACE, + label: 'Create workspace', + icon: , + submenu: [ + { id: USE_EXISTING, label: 'Use an existing folder' }, + { id: CREATE_NEW, label: 'Create a new workspace' }, + ], + }, + ] + + const closeModal = (): void => { + if (creating) return + setModalKind(null) + setModalError(null) + } + + const handleSelect = (id: string): void => { + if (id === USE_EXISTING) { + onClose() + setPathDraft('') + setModalError(null) + setModalKind('path') + return + } + if (id === CREATE_NEW) { + onClose() + setWorkspaceName('workspace') + setModalError(null) + setModalKind('create') + return + } + onPick(id as WorkspaceId) + } + + const create = (input: { name: string } | { path: string }): void => { + if (creating) return + setCreating(true) + setModalError(null) + void createWorkspace(input).then((workspace) => { + setCreating(false) + setModalKind(null) + onPick(workspace.workspaceId) + }).catch((reason: unknown) => { + const message = reason instanceof Error ? reason.message : String(reason) + setModalError(`Workspace creation failed: ${message}`) + setCreating(false) + }) + } + + const confirmPath = (): void => { + const path = pathDraft.trim() + if (path !== '') create({ path }) + } + + const confirmCreate = (): void => { + if (normalizedWorkspaceName !== '' && !duplicateWorkspaceName) { + create({ name: normalizedWorkspaceName }) + } + } + + return ( + <> + + {open && workspaceSnapshot.phase === 'pending' &&
Loading workspaces…
} + + + + + )} + > + { setPathDraft(event.target.value) }} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault() + confirmPath() + } + }} + /> + {creating &&
Creating workspace…
} + {modalError !== null &&
{modalError}
} +
+ + + + + )} + > + { setWorkspaceName(event.target.value); setModalError(null) }} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault() + confirmCreate() + } + }} + /> + {creating &&
Creating workspace…
} + {duplicateWorkspaceName && ( +
A workspace named “{normalizedWorkspaceName}” already exists.
+ )} + {modalError !== null &&
{modalError}
} +
+ + ) +} diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts new file mode 100644 index 0000000000..a3045e5070 --- /dev/null +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -0,0 +1,30 @@ +/** + * Shared Workspace picker contract for the sidebar and page-local Session Intent hero + * slots. Each runtime share provides its owner's popover controls plus the + * global useWorkspaces hook; this package adds the injected Host Workspace + * creation callback. + */ +import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only: pull both owner SlotMap merges into programs that resolve the +// picker runtime union below. +import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' + +/** + * Registrant-private injected share. Pick semantics remain in each owner's + * onPick callback; this callback creates only the real Host Workspace. A type + * alias supplies the implicit index signature required by the registry. + */ +export type WorkspacePickerInjected = { + /** Explicitly create or adopt a real Workspace before targeting a Session. */ + createWorkspace(input: { name: string } | { path: string }): Promise +} + +/** + * Full picker props: either owner's runtime share, including useWorkspaces, + * plus this package's injected creation callback. + */ +export type WorkspacePickerProps = + (PropsRuntime<'sidebar.workspace'> | PropsRuntime<'conversation.empty.workspace'>) + & WorkspacePickerInjected diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts new file mode 100644 index 0000000000..aa54587650 --- /dev/null +++ b/packages/client/ui-workspace/src/client/index.ts @@ -0,0 +1,54 @@ +/** + * Shared Workspace picker plugin, browser half. WorkspacePicker registers in + * the sidebar and page-local Session Intent hero slots, reads real Host Workspaces + * through the global useWorkspaces hook, and delegates selection semantics to + * each owner. Its injected share creates a Workspace without creating a + * Session. Export discipline: packages/client/AGENTS.md. + */ +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +import type { WorkspacePickerInjected } from './contract/slots.ts' +import { WorkspacePicker } from './WorkspacePicker.tsx' + +export type { WorkspacePickerInjected, WorkspacePickerProps } from './contract/slots.ts' + +/** + * Required services (cordis fiber inject). The target slot is declared by + * the ui-sidebar apply, whose activation order relative to this one is NOT + * constrained: dshClient.inject edges are informational (loading/prefetch + * metadata, never apply sequencing) and the sidebar provides no waitable + * service. apply therefore registers via declaration-aware deferral instead + * of assuming order. + */ +export const inject = ['slots', 'workspaces'] + +/** + * Register WorkspacePicker in both owner slots once their declarations are on + * the ledger. The inject factory returns a plain Workspace creation callback; + * data reads use the framework's global useWorkspaces hook. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + const injected = (): WorkspacePickerInjected => ({ + createWorkspace: input => ctx.workspaces.create(input), + }) + // Declaration-aware registration: the sidebar's declaring apply may + // activate after this one (entry activation order is unconstrained), and a + // register into an undeclared slot throws. Register once the declaration + // is on the ledger; the subscription also re-registers after an HMR + // collapse re-declares the slot (the cascade disposed our entry with it). + ctx.effect(() => { + const slotNames = ['sidebar.workspace', 'conversation.empty.workspace'] as const + const disposers = new Map<(typeof slotNames)[number], () => void>() + const tryRegister = (name: (typeof slotNames)[number]): void => { + if (ctx.slots.spec(name) === undefined) return + if (ctx.slots.entries(name).some(e => e.component === WorkspacePicker)) return + disposers.set(name, ctx.slots.register({ name, inject: injected }, WorkspacePicker)) + } + const unsubscribers = slotNames.map(name => ctx.slots.subscribe(name, () => { tryRegister(name) })) + for (const name of slotNames) tryRegister(name) + return () => { + for (const unsubscribe of unsubscribers) unsubscribe() + for (const dispose of disposers.values()) dispose() + } + }, 'ui-workspace: picker registrations') +} diff --git a/packages/client/ui-workspace/src/css-modules.d.ts b/packages/client/ui-workspace/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-workspace/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-workspace/src/index.ts b/packages/client/ui-workspace/src/index.ts new file mode 100644 index 0000000000..2af6a1023b --- /dev/null +++ b/packages/client/ui-workspace/src/index.ts @@ -0,0 +1,9 @@ +/** + * Workspace picker plugin, node half. Pure UI plugin: the empty apply exists + * so the plugin appears in the host cordis.yml / Loader (load and lifecycle + * follow the host; the browser half ships via exports["./client"], discovered + * through the package.json dshClient declaration). + */ + +/** Host plugin body — no host-side behavior for the workspace picker plugin. */ +export function apply(): void {} diff --git a/packages/client/ui-workspace/src/invariant.ts b/packages/client/ui-workspace/src/invariant.ts new file mode 100644 index 0000000000..4d3a52353c --- /dev/null +++ b/packages/client/ui-workspace/src/invariant.ts @@ -0,0 +1,32 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-workspace`. + * @module @deepseek-ai/dsh-client-ui-workspace/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-workspace' + +/** Cordis companion plugin name. */ +export const name = 'client-ui-workspace-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: a pure-consumer plugin registering one presentational + * component into two host-declared slots — its inject face is two stateless + * RPC wrappers plus a create-and-open call; it emits no cordis events and + * owns no cross-plugin mutable state. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/client/ui-workspace/tests/apply.spec.ts b/packages/client/ui-workspace/tests/apply.spec.ts new file mode 100644 index 0000000000..9352caa0b4 --- /dev/null +++ b/packages/client/ui-workspace/tests/apply.spec.ts @@ -0,0 +1,69 @@ +import { Context } from 'cordis' +import { describe, expect, it, vi } from 'vitest' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' +import type { WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client' +import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + const create = vi.fn(async (input: { name: string } | { path: string }) => ({ + workspaceId: 'ws-new' as never, + path: 'name' in input ? `/projects/${input.name}` : input.path, + title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0', + })) + ctx.provide('workspaces', { create }) + return { ctx, slots: ctx.get('slots') as SlotsService, create } +} + +function declare(slots: SlotsService, name: 'sidebar.workspace' | 'conversation.empty.workspace'): () => void { + return slots.register( + { name: 'root', children: { [name]: { kind: 'single', scope: 'root' } } } as never, + () => null, + ) +} + +function injectedOf(slots: SlotsService, name: 'sidebar.workspace' | 'conversation.empty.workspace'): WorkspacePickerInjected { + const entry = slots.entries(name)[0]! + return (entry.inject as () => WorkspacePickerInjected)() +} + +describe('ui-workspace apply', () => { + it('declares the independent Workspace service', () => { + expect(inject).toEqual(['slots', 'workspaces']) + }) + + it('registers the shared picker for declarations that arrive before or after apply', async () => { + const before = await bench() + declare(before.slots, 'sidebar.workspace') + await before.ctx.plugin({ inject: [...inject], apply }).await() + expect(before.slots.entries('sidebar.workspace')[0]!.component).toBe(WorkspacePicker) + + const after = await bench() + await after.ctx.plugin({ inject: [...inject], apply }).await() + declare(after.slots, 'conversation.empty.workspace') + await Promise.resolve() + expect(after.slots.entries('conversation.empty.workspace')[0]!.component).toBe(WorkspacePicker) + }) + + it('routes name and path creation to WorkspacesService', async () => { + const b = await bench() + declare(b.slots, 'sidebar.workspace') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const injected = injectedOf(b.slots, 'sidebar.workspace') + await injected.createWorkspace({ name: 'project' }) + await injected.createWorkspace({ path: '/tmp/project' }) + expect(b.create).toHaveBeenNthCalledWith(1, { name: 'project' }) + expect(b.create).toHaveBeenNthCalledWith(2, { path: '/tmp/project' }) + }) + + it('unregisters picker entries on teardown', async () => { + const b = await bench() + declare(b.slots, 'sidebar.workspace') + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + await fiber.dispose() + expect(b.slots.entries('sidebar.workspace')).toHaveLength(0) + }) +}) diff --git a/packages/client/ui-workspace/tests/invariant.spec.ts b/packages/client/ui-workspace/tests/invariant.spec.ts new file mode 100644 index 0000000000..0606c94e09 --- /dev/null +++ b/packages/client/ui-workspace/tests/invariant.spec.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import * as WorkspaceInvariant from '@deepseek-ai/dsh-client-ui-workspace/invariant' +import InvariantService from '@deepseek-ai/dsh-invariants' + +describe('invariant companion', () => { + it('registers under the package name with an empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + await expect(ctx.plugin(WorkspaceInvariant).await()).resolves.toBeDefined() + }) + + it('node-half apply is a no-op host placeholder', async () => { + const { apply } = await import('@deepseek-ai/dsh-client-ui-workspace') + apply() + expect(true).toBe(true) // reaching here without throw is the contract + }) +}) diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx new file mode 100644 index 0000000000..32d5be145b --- /dev/null +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -0,0 +1,123 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import type { + SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' +import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' + +afterEach(cleanup) + +const wid = (id: string) => id as WorkspaceId +function workspace(id: string, title = id): WorkspaceView { + return { + workspaceId: wid(id), path: `/projects/${id}`, title, sessionIds: [], + createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', + } +} +const hook = (snapshot: T) => (selector: (state: T) => S): S => selector(snapshot) +const sessions: SessionListState = { + ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready', +} +const workspaceState = (items: readonly WorkspaceView[]): WorkspaceListState => ({ + items, intent: undefined, state: 'idle', phase: 'ready', error: null, baselinesReady: true, + recentWorkspaceId: items[0]?.workspaceId, +}) +function anchor(): { current: HTMLElement } { + const element = document.createElement('button') + element.getBoundingClientRect = () => ({ + top: 10, left: 20, width: 30, height: 40, right: 50, bottom: 50, + x: 20, y: 10, toJSON: () => ({}), + }) + return { current: element } +} + +function mount(items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn()) { + const onPick = vi.fn() + const onClose = vi.fn() + const view = render( + , + ) + return { view, onPick, onClose, createWorkspace } +} + +function chooseCreateItem(name: 'Use an existing folder' | 'Create a new workspace'): void { + const parent = screen.getByRole('menuitem', { name: 'Create workspace' }) + fireEvent.mouseEnter(parent.parentElement as HTMLElement) + fireEvent.click(screen.getByRole('menuitem', { name })) +} + +describe('WorkspacePicker', () => { + it('lists real Workspaces from useWorkspaces and forwards a selected id', () => { + const b = mount() + fireEvent.click(screen.getByRole('menuitem', { name: 'Alpha' })) + expect(b.onPick).toHaveBeenCalledWith(wid('alpha')) + }) + + it('creates a real Workspace from a name and focuses its frontend Session target', async () => { + const created = workspace('new', 'New') + const createWorkspace = vi.fn(async () => created) + const b = mount([], createWorkspace) + chooseCreateItem('Create a new workspace') + const input = screen.getByLabelText('New workspace name') + fireEvent.change(input, { target: { value: 'project-one' } }) + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + expect(createWorkspace).toHaveBeenCalledWith({ name: 'project-one' }) + await waitFor(() => { expect(b.onPick).toHaveBeenCalledWith(created.workspaceId) }) + }) + + it('adopts an existing path through the same immediate create action', async () => { + const created = workspace('adopted') + const createWorkspace = vi.fn(async () => created) + const b = mount([], createWorkspace) + chooseCreateItem('Use an existing folder') + fireEvent.change(screen.getByLabelText('Existing folder path'), { target: { value: ' /tmp/project ' } }) + fireEvent.click(screen.getByRole('button', { name: 'Use folder' })) + expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) + await waitFor(() => { expect(b.onPick).toHaveBeenCalledWith(created.workspaceId) }) + }) + + it('blocks a create-new name already present in the Workspace list', () => { + const b = mount([workspace('alpha', 'Alpha')]) + chooseCreateItem('Create a new workspace') + fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: ' Alpha ' } }) + expect(screen.getByRole('alert').textContent).toBe('A workspace named “Alpha” already exists.') + expect((screen.getByRole('button', { name: 'Create workspace' }) as HTMLButtonElement).disabled).toBe(true) + fireEvent.keyDown(screen.getByLabelText('New workspace name'), { key: 'Enter' }) + expect(b.createWorkspace).not.toHaveBeenCalled() + }) + + it('exposes creation phase and error text while retaining the modal for retry', async () => { + let reject!: (reason: unknown) => void + const pending = new Promise((_resolve, rejectPromise) => { reject = rejectPromise }) + const b = mount([], vi.fn(() => pending)) + chooseCreateItem('Create a new workspace') + fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: 'broken' } }) + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + expect(screen.getByRole('status').textContent).toBe('Creating workspace…') + await act(async () => { reject(new Error('disk unavailable')); await pending.catch(() => {}) }) + expect(screen.getByRole('alert').textContent).toBe('Workspace creation failed: disk unavailable') + expect(b.view.getByRole('dialog')).toBeTruthy() + }) + + it('shows list loading through a stable status surface', () => { + const state: WorkspaceListState = { + ...workspaceState([]), phase: 'pending', state: 'loading', baselinesReady: false, + } + render( + , + ) + expect(screen.getByRole('status').textContent).toBe('Loading workspaces…') + }) +}) diff --git a/packages/client/ui-workspace/tsconfig.json b/packages/client/ui-workspace/tsconfig.json new file mode 100644 index 0000000000..a2679cccb4 --- /dev/null +++ b/packages/client/ui-workspace/tsconfig.json @@ -0,0 +1,33 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../runtime" + }, + { + "path": "../ui-sidebar" + }, + { + "path": "../ui-conversation" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/client/ui-workspace/tsdown.config.ts b/packages/client/ui-workspace/tsdown.config.ts new file mode 100644 index 0000000000..084fe49266 --- /dev/null +++ b/packages/client/ui-workspace/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-ui-workspace', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/web-react/src/scoped-slots.tsx b/packages/client/web-react/src/scoped-slots.tsx index f552236890..e15bc4d584 100644 --- a/packages/client/web-react/src/scoped-slots.tsx +++ b/packages/client/web-react/src/scoped-slots.tsx @@ -164,7 +164,7 @@ class SlotErrorBoundary extends Component< /** * Standard-kit synthesis shared by both scope branches: the global - * useSessions hook, the session pair, the store pair when declared, the + * useSessions/useWorkspaces hooks, the session pair, the store pair when declared, the * renderSlot binding when children are declared, and the SessionProvider * seat when the children declare a session-scope slot. Hosts hand out BARE * observable sources (hooks never cross the host contract); every hook is @@ -174,7 +174,10 @@ class SlotErrorBoundary extends Component< function standardKit(host: SlotRendererHost, entry: StoredEntry, cell: SessionCell | undefined): { kit: InjectedProps; actions: object | undefined } { - const kit: InjectedProps = { useSessions: observableHook(host.sessions.list) } + const kit: InjectedProps = { + useSessions: observableHook(host.sessions.list), + useWorkspaces: observableHook(host.workspaces.list), + } if (cell !== undefined) { kit['useSession'] = observableHook(cell.session) kit['sessionId'] = cell.sessionId diff --git a/packages/client/web-react/tests/scoped-slots-real-core.spec.tsx b/packages/client/web-react/tests/scoped-slots-real-core.spec.tsx index 647ef3a11a..3b333d1ba5 100644 --- a/packages/client/web-react/tests/scoped-slots-real-core.spec.tsx +++ b/packages/client/web-react/tests/scoped-slots-real-core.spec.tsx @@ -38,6 +38,9 @@ function hostOver(core: SlotCore): SlotRendererHost { current: { getSnapshot: () => undefined, subscribe: () => () => {} }, cell: () => undefined, }, + workspaces: { + list: { getSnapshot: () => ({}), subscribe: () => () => {} }, + }, } } diff --git a/packages/client/web-react/tests/scoped-slots.spec.tsx b/packages/client/web-react/tests/scoped-slots.spec.tsx index aab243ab47..326e01dd4a 100644 --- a/packages/client/web-react/tests/scoped-slots.spec.tsx +++ b/packages/client/web-react/tests/scoped-slots.spec.tsx @@ -81,6 +81,7 @@ function makeHost() { const live = new Set() const storeCache = new Map>() const list = observable<{ ids: string[] }>({ ids: [] }) + const workspaces = observable<{ ids: string[] }>({ ids: [] }) const current = observable(undefined) const cells = new Map() @@ -122,10 +123,12 @@ function makeHost() { current, cell: (id) => cells.get(id), }, + workspaces: { list: workspaces }, } return { host, list, + workspaces, current, declare: (key: string, spec: DeclaredSpec) => { specs.set(key, spec); bump(key) }, add: (key: string, partial: Omit & { options?: StoredEntry['options'] }) => { @@ -483,6 +486,19 @@ describe('standard-kit synthesis', () => { expect(view.container.textContent).toBe('2') }) + it('delivers a live useWorkspaces hook to every slot component', () => { + const h = makeHost() + h.declare('k.single', SINGLE_ROOT) + h.add('k.single', { + component: ({ useWorkspaces }: { useWorkspaces: (sel: (s: { ids: string[] }) => S) => S }) => + {useWorkspaces((s) => s.ids.length)}, + }) + const { view } = mountRoot(h, { 'k.single': SINGLE_ROOT }, (renderSlot) => renderSlot('k.single', {})) + expect(view.container.textContent).toBe('0') + act(() => { h.workspaces.set({ ids: ['w1'] }) }) + expect(view.container.textContent).toBe('1') + }) + it('delivers the session pair (bound useSession + sessionId) under SessionProvider', () => { const h = makeHost() h.declare('k.session', SINGLE_SESSION) @@ -710,6 +726,7 @@ describe('inject: execution point, parameter derivation, cache granularity', () (renderSlot) => renderSlot('k.single', { owner: 'owner', shared: 'owner' })) const props = seen.at(-1)! expect(typeof props['useSessions']).toBe('function') // kit always present + expect(typeof props['useWorkspaces']).toBe('function') expect(props['fromInject']).toBe('inject') expect(props['owner']).toBe('owner') expect(props['shared']).toBe('owner') // owner overrides inject diff --git a/packages/client/web-react/tests/session-provider.spec.tsx b/packages/client/web-react/tests/session-provider.spec.tsx index f4654b4ccd..7e73ccef28 100644 --- a/packages/client/web-react/tests/session-provider.spec.tsx +++ b/packages/client/web-react/tests/session-provider.spec.tsx @@ -52,6 +52,7 @@ function makeHost(bodies: { root: (rp: (key: string, owner: object) => React.Rea current, cell: (id) => cells.get(id), }, + workspaces: { list: observable({ items: [] }) }, } return { host, diff --git a/packages/client/web-react/tests/stale-authorization.spec.tsx b/packages/client/web-react/tests/stale-authorization.spec.tsx index c21555f76a..0f2726e708 100644 --- a/packages/client/web-react/tests/stale-authorization.spec.tsx +++ b/packages/client/web-react/tests/stale-authorization.spec.tsx @@ -42,6 +42,9 @@ function makeHost() { current: { getSnapshot: () => undefined, subscribe: () => () => {} }, cell: () => undefined, }, + workspaces: { + list: { getSnapshot: () => ({}), subscribe: () => () => {} }, + }, } return { host, diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 65bfaf7a20..2b76d407f7 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -696,6 +696,24 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'storageDomain', + summary: 'The mounted domain facility.', + methods: [ + { + signature: 'async open(spec: S): Promise>', + jsDoc: '/**\n * Open one declared domain. Steps, each failing the whole call: reject a\n * name that is already open (`already-open`); resolve the backend route\n * (`backend-not-found` passes through from the hub); require its `kv` facet\n * (`facet-unsupported`); open the unit projected from the spec (backend\n * `version-mismatch`/`malformed-medium` pass through); load and validate\n * every stored record against the spec\'s zod schemas (`invalid-record`\n * with the offending table and key); construct the domain.\n *\n * Lifecycle: the CALLER owns the returned handle and closes it via\n * `Domain.close()` (typically as its own `ctx.effect` disposer) — the\n * facility does not tie the domain to any consumer fiber. Domains still\n * open when the facility unmounts are closed by the plugin disposer.\n * @param spec - The domain declaration, typically from `defineDomain`.\n * @returns the opened domain handle, typed by the spec.\n */', + }, + { + signature: 'get(name: string): DomainImpl | undefined', + jsDoc: '/**\n * Look up an open domain by name, untyped. Diagnostic surface (the package\n * invariant cross-checks change events against live domain state); typed\n * consumers hold the handle returned by {@link open}.\n * @param name - Domain name.\n * @returns the open domain runtime, or `undefined` when not open.\n */', + }, + { + signature: 'async closeAll(): Promise', + jsDoc: '/**\n * Close every domain still open on this facility. The unmount path for\n * consumers that never called `Domain.close()` themselves; closing is\n * idempotent, so double-closing an already-closed domain is harmless.\n * @returns resolution after every unit is released.\n */', + }, + ], + }, { key: 'subagents', summary: 'Named provider registry and capability-checked start surface.', @@ -902,23 +920,27 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { key: 'workspace', - summary: 'The workspace registry service.', + summary: 'Durable workspace registry.', methods: [ { signature: 'async create(path: string, title?: string): Promise', - jsDoc: '/**\n * Create a workspace over an existing directory. The path is canonicalized\n * through `fs.realpath` first — a nonexistent path rejects with the\n * original `ENOENT`, a path resolving to anything but a directory rejects,\n * and a canonical path already owned by another workspace (including a\n * symlink resolving to it) rejects.\n * @param path - Directory the workspace points at; canonicalized before storing.\n * @param title - Display title; defaults to `basename` of the canonical path.\n * @returns the created workspace after durability.\n */', + jsDoc: '/**\n * Create or reuse a workspace for an existing directory. The path is\n * canonicalized through `fs.realpath`; a nonexistent path rejects with the\n * original error and a non-directory rejects. Repeated calls for the same\n * canonical path return the existing entity without changing its title.\n * A newly created workspace is prepended to the durable registry order.\n * A different canonical path cannot create a duplicate display title.\n * @param path - Existing directory to own, in any path spelling.\n * @param title - Display title used only when a new record is created.\n * @returns the existing or newly durable workspace.\n */', }, { signature: 'get(id: WorkspaceId): Workspace | undefined', - jsDoc: '/**\n * Look up a workspace by id.\n * @param id - The workspace id.\n * @returns the workspace, or `undefined` when unknown.\n */', + jsDoc: '/**\n * Look up a workspace by id.\n * @param id - Workspace id.\n * @returns the workspace, or `undefined` when unknown.\n */', }, { signature: 'list(): Workspace[]', - jsDoc: '/**\n * Snapshot of all workspaces, in load-then-creation order.\n * @returns a fresh array of the cached entities.\n */', + jsDoc: '/**\n * Synchronous workspace projection in durable registry order. Every\n * entity\'s `sessionIds` getter is already filtered by the startup/live\n * canonical-cwd header index; this method performs no persistence reads.\n * @returns a fresh ordered array of workspace entities.\n */', + }, + { + signature: 'async touchSession(sessionId: SessionId): Promise', + jsDoc: '/**\n * Move one accounted, cwd-validated session to the front of its workspace.\n * Ungrouped sessions and candidates filtered by the header check are\n * no-ops. The owning workspace\'s relative position never changes.\n * @param sessionId - Session whose activity was observed.\n * @returns resolution after the possible record write.\n */', }, { signature: 'async resolveByPath(path: string): Promise', - jsDoc: '/**\n * Resolve a workspace by directory path, through the same `fs.realpath`\n * canon as {@link create} (hence async). A path that does not exist rejects\n * with the original error — a missing directory has no canonical form to\n * compare (a workspace whose recorded directory vanished is only reachable\n * by id; see `Workspace.status`).\n * @param path - Directory path in any spelling (symlinks, `..`, trailing slash).\n * @returns the owning workspace, or `undefined` when none matches.\n */', + jsDoc: '/**\n * Resolve by canonical directory path without creating or mutating a\n * workspace. A missing path rejects during `realpath`; an existing unowned\n * directory returns `undefined`.\n * @param path - Existing directory path in any spelling.\n * @returns the workspace owning the canonical path, when one exists.\n */', }, ], }, @@ -1490,6 +1512,34 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'DiffResultView', declaration: 'export interface DiffResultView {\n card: \'diff\';\n title?: string;\n diffs: FileDiff[];\n}', }, + { + name: 'Domain', + declaration: 'export interface Domain {\n readonly name: string;\n readonly global: DomainGlobalHandleOf;\n table(name: N): KvTable, TableValueOf>;\n close(): Promise;\n}', + }, + { + name: 'DomainGlobal', + declaration: 'export interface DomainGlobal {\n get(): G;\n set(value: G): Promise;\n}', + }, + { + name: 'DomainGlobalHandleOf', + declaration: 'export type DomainGlobalHandleOf = S extends {\n readonly global: DomainGlobalSpec;\n} ? DomainGlobal : never;', + }, + { + name: 'DomainGlobalSpec', + declaration: 'export interface DomainGlobalSpec {\n readonly schema: ZodType;\n readonly initial: G;\n}', + }, + { + name: 'DomainImpl', + declaration: 'export class DomainImpl {\n readonly name: string;\n constructor(private readonly ctx: Context, spec: DomainSpec, private readonly unit: KvUnit, records: Map>, globalValue: unknown, private readonly onClosed: () => void);\n get global(): DomainGlobal;\n table(name: string): KvTable;\n close(): Promise;\n}', + }, + { + name: 'DomainSpec', + declaration: 'export interface DomainSpec {\n readonly name: string;\n readonly version: number;\n readonly global?: DomainGlobalSpec;\n readonly tables: Record;\n}', + }, + { + name: 'DomainTableSpec', + declaration: 'export interface DomainTableSpec {\n readonly valueSchema: ZodType;\n readonly __key?: K;\n}', + }, { name: 'DshEnvironment', declaration: 'export type DshEnvironment = Readonly>;', @@ -1634,6 +1684,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'JsonValue', declaration: 'export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n};', }, + { + name: 'KvTable', + declaration: 'export interface KvTable {\n get(key: K): V | undefined;\n entries(): IterableIterator<[\n K,\n V\n ]>;\n keys(): IterableIterator;\n readonly size: number;\n put(key: K, value: V): Promise;\n delete(key: K): Promise;\n update(key: K, fn: (current: V) => V): Promise;\n}', + }, + { + name: 'KvUnit', + declaration: 'export interface KvUnit {\n loadAll(): Promise<{\n tables: Record>;\n global: unknown;\n }>;\n putRecord(table: string, key: string, value: unknown): Promise;\n deleteRecord(table: string, key: string): Promise;\n setGlobal(value: unknown): Promise;\n close(): Promise;\n}', + }, { name: 'LlmAdapter', declaration: 'export abstract class LlmAdapter {\n providerInfo(provider: string): LlmProviderInfo;\n listModels(_provider: string): Promise;\n resolveModelContext(_provider: string, _model: string): Promise;\n abstract stream(options: GenerateOptions): AsyncIterable;\n}', @@ -2134,6 +2192,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'SurfaceOp', declaration: 'export type SurfaceOp = \'append\' | {\n op: \'replace\';\n start: number;\n end: number;\n};', }, + { + name: 'TableKeyOf', + declaration: 'export type TableKeyOf = S[\'tables\'][N] extends DomainTableSpec ? K : never;', + }, + { + name: 'TableValueOf', + declaration: 'export type TableValueOf = S[\'tables\'][N] extends DomainTableSpec ? V : never;', + }, { name: 'TaskDoneListener', declaration: 'export type TaskDoneListener = (snapshot: TaskSnapshot, owner: Agent | undefined) => void | PromiseLike;', @@ -2432,7 +2498,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Workspace', - declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', }, ] diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index c07ade2192..cc8b5a7237 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-host-apiproxy -The API gateway every client shape shares: the TS contract (`src/api/`, zero Node dependencies, importable from the browser), the fetch carrier pair (`src/fetch/`: `toFetchHandler` on the host side, `AbstractApiClient` plus platform subclasses on the client side), and the host-side implementation (`src/api-proxy.ts`: `createApiProxy` plus the default-exported `ApiProxyService` gateway plugin — config `{provider, model}`, provides `ctx.apiProxy`). Transport-agnostic by design: this package registers no routes; carriers (HTTP today, IPC later) wrap `ctx.apiProxy` themselves. The composition lives in `apps/cli/cordis.yml` (the `api-gateway` row). +The API gateway every client shape shares: the TS contract (`src/api/`, zero Node dependencies, importable from the browser), the fetch carrier pair (`src/fetch/`: `toFetchHandler` on the host side, `AbstractApiClient` plus platform subclasses on the client side), and the host-side implementation (`src/api-proxy.ts`: `createApiProxy` plus the default-exported `ApiProxyService` gateway plugin — config `{provider, model, workspaceRoot?}`, provides `ctx.apiProxy`). Transport-agnostic by design: this package registers no routes; carriers (HTTP today, IPC later) wrap `ctx.apiProxy` themselves. The shipped core composition lives in [`apps/cli/cordis.yml`](../../../apps/cli/cordis.yml). ## Contract layer (`/api`) @@ -10,6 +10,8 @@ The layering/protocol decisions are recorded in the [GUI layering and RPC protoc The mux stream projects the latest log-backed title as a validated `session/title` control frame after each attached-session subscription baseline and immediately after the corresponding live raw title event. This projection does not add titles to `session.list`; cold sessions remain metadata-only there until opening or resuming attaches their logs. +Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed` plus `host/session-added` carry committed increments in either arrival order. Session drafts are client-only and have no wire method. + ## Carrier layer (`/client` + root) `AbstractApiClient` holds every protocol invariant — rpcId minting, envelope wrap/unwrap, zod parsing, SSE frame decoding, unary timeout, microtask-batched envelope observation (`subscribeEnvelopes`) — while platform subclasses supply only the `doFetch` transport aspect. `InProcessApiClient` over `toFetchHandler(api)` is the isomorphic point: the full wire serialization/validation path with no network, used by `dsh -p` headless. diff --git a/packages/host/apiproxy/package.json b/packages/host/apiproxy/package.json index 471cccc96d..959f84c46b 100644 --- a/packages/host/apiproxy/package.json +++ b/packages/host/apiproxy/package.json @@ -49,6 +49,7 @@ "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/dsh-user-approval": "workspace:^", "@deepseek-ai/dsh-user-interaction": "workspace:^", + "@deepseek-ai/dsh-workspace": "workspace:^", "schemastery": "^3.18.0", "zod": "^4.4.3" }, @@ -57,6 +58,8 @@ "@deepseek-ai/dsh-invariants": "^0.0.1" }, "devDependencies": { + "@deepseek-ai/dsh-storage": "workspace:^", + "@deepseek-ai/dsh-storage-domain": "workspace:^", "cordis": "^4.0.0-rc.7", "@deepseek-ai/dsh-invariants": "workspace:^" } diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index e5759d828d..201bc555a9 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -5,16 +5,22 @@ import { randomUUID } from 'node:crypto' import { mkdir, stat } from 'node:fs/promises' +import { join } from 'node:path' import type { Context } from 'cordis' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' import type { JsonValue, Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' +import type { Workspace, WorkspaceRecord } from '@deepseek-ai/dsh-workspace' +import { + workspaceDomainState, workspaceRecord, WorkspaceId as brandWorkspaceId, WorkspaceNameConflictError, +} from '@deepseek-ai/dsh-workspace' // Type-only: brings the `ctx.tools` Context merge into this program (viewFor reads presenters). import type {} from '@deepseek-ai/dsh-tools' import type { ApiProxy, HistoryEntry, HostFrame, MuxFrame, QuestionResponsePayload, SessionSummary, ToolEventView, + WorkspaceId, WorkspaceView, } from './api/index.ts' import { questionResponsePayloadSchema } from './api/questions.schema.ts' import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from './api/rpc.ts' @@ -172,12 +178,14 @@ async function summarizeCold(persistence: SessionPersistence, meta: SessionHeade } } -/** Host-level default agent routing: provider/model from the gateway config, cwd from the host process. */ +/** Resolved Host routing and project-directory defaults consumed by the API implementation. */ export interface ApiProxyDefaults { provider: string model: string /** Default project directory for new sessions whose create request carries no cwd. */ cwd: string + /** Parent directory for name-created workspaces. */ + workspaceRoot: string } /** The tool/call payload fields the presenter path reads. */ @@ -273,17 +281,62 @@ function backscanArgs(events: readonly SessionEvent[], callId: string): { name: */ class SessionNotFound extends Error {} +/** Requested identity already belongs to a session with another project cwd. */ +class SessionCwdConflict extends Error { + constructor( + readonly sessionId: SessionId, + readonly requestedCwd: string, + readonly existingCwd: string | undefined, + ) { + super( + `session "${sessionId}" already exists with cwd ${JSON.stringify(existingCwd)}; ` + + `requested ${JSON.stringify(requestedCwd)}`, + ) + } +} + +/** Host failed before the registry could adopt a name-created directory. */ +class WorkspaceDirectoryCreationError extends Error {} + +/** Wire projection of one workspace entity (the workspace.* value row). */ +function workspaceView(workspace: Workspace): WorkspaceView { + return { + workspaceId: workspace.id, + path: workspace.path, + title: workspace.title, + sessionIds: [...workspace.sessionIds], + createdAt: workspace.createdAt, + updatedAt: workspace.updatedAt, + } +} + +/** Wire projection of the durable record carried by `domain/changed`. */ +function changedWorkspaceView(workspaceId: string, value: unknown): WorkspaceView { + const record: WorkspaceRecord = workspaceRecord.parse(value) + return { + workspaceId: workspaceId as WorkspaceId, + path: record.path, + title: record.title, + sessionIds: [...record.sessionIds], + createdAt: record.createdAt, + updatedAt: record.updatedAt, + } +} + /** * Implement ApiProxy over a composed host context. - * @param ctx - a context with the host spine mounted (sessions/agents/tools/userInteraction services). - * @param defaults - host-level default provider/model: injected as - * agentOptions on create/resume, reported by describe from the same source. + * @param ctx - a context with the Host spine and Workspace registry mounted. + * @param defaults - host routing and project-directory defaults. * @returns the ApiProxy implementation. */ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiProxy { const agentOptions = { provider: defaults.provider, model: defaults.model } /** Implicit resume of cold sessions, deduplicating concurrent calls (follows the jsonrpc sessionCreations precedent). */ const resumes = new Map>() + /** Client-chosen identity creation/resume, deduplicated across concurrent retries. */ + const sessionCreations = new Map>() + /** Serializes path ownership checks with record creation across spellings. */ + let workspaceCreationChain = Promise.resolve() const pendingQuestions = new Map() const muxQueues = new Set>>() @@ -384,6 +437,78 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro } } + /** Resolve one requested identity to a live agent, creating or resuming it once. */ + async function ensureSession(sessionId: SessionId, cwd: string, checkPersistedIdentity: boolean): Promise { + let creation = sessionCreations.get(sessionId) + if (creation === undefined) { + creation = (async () => { + const live = ctx.agents.get(sessionId) + if (live !== undefined) return live + + const persistence = checkPersistedIdentity ? ctx.get('sessionPersistence') : undefined + const stored = persistence === undefined + ? undefined + : (await persistence.list()).find(header => header.id === sessionId) + if (stored !== undefined) { + if (stored.cwd !== cwd) { + throw new SessionCwdConflict(sessionId, cwd, stored.cwd) + } + return (await ctx.agents.resume({ resumeSessionId: sessionId, agentOptions })).agent + } + + try { + await mkdir(cwd, { recursive: true }) + } catch (error: unknown) { + throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error }) + } + return (await ctx.agents.create({ sessionId, agentOptions, meta: { cwd } })).agent + })().catch((error: unknown) => { + // Another Host entry path may have published the same identity while + // this operation crossed an asynchronous persistence/filesystem step. + const live = ctx.agents.get(sessionId) + if (live !== undefined) return live + throw error + }).finally(() => { + sessionCreations.delete(sessionId) + }) + sessionCreations.set(sessionId, creation) + } + const agent = await creation + if (agent.session.header.cwd !== cwd) { + throw new SessionCwdConflict(sessionId, cwd, agent.session.header.cwd) + } + return agent + } + + /** Resolve or create one path while holding the Host's workspace-create chain. */ + function ensureWorkspace( + path: string, + title: string | undefined, + rejectExistingName = false, + createDirectory = false, + ): Promise<{ workspace: Workspace; created: boolean }> { + const operation = workspaceCreationChain.then(async () => { + if (rejectExistingName && title !== undefined + && ctx.workspace.list().some(workspace => workspace.title === title)) { + throw new WorkspaceNameConflictError(title) + } + if (createDirectory) { + try { + await mkdir(path, { recursive: true }) + } catch (error: unknown) { + throw new WorkspaceDirectoryCreationError( + `failed to create workspace directory "${path}": ${String(error)}`, + ) + } + } + const existing = await ctx.workspace.resolveByPath(path) + if (existing !== undefined) return { workspace: existing, created: false } + return { workspace: await ctx.workspace.create(path, title), created: true } + }) + workspaceCreationChain = operation.then(() => undefined, () => undefined) + return operation + } + return { sessions: { // Attached sessions summarize from memory; persisted-but-unattached (cold) @@ -406,23 +531,51 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }, async create(request) { - const sessionId = `session-${randomUUID()}` as SessionId - // A session's cwd is its project path. When the creator does not choose - // one, the default project is the host-level default (the host process - // working directory unless boot overrides it). Ensure the directory - // exists so Create-workspace and typed paths land on a real folder. - const cwd = request.payload.cwd ?? defaults.cwd + const sessionId = request.payload.sessionId ?? `session-${randomUUID()}` as SessionId + let workspace: Workspace | undefined + if (request.payload.workspaceId !== undefined) { + workspace = ctx.workspace.get(brandWorkspaceId(request.payload.workspaceId)) + if (workspace === undefined) { + return err(request, { + code: 'workspace-not-found', + message: `workspace "${request.payload.workspaceId}" not found`, + details: { workspaceId: request.payload.workspaceId }, + }) + } + } + const cwd = workspace?.path ?? request.payload.cwd ?? defaults.cwd try { - await mkdir(cwd, { recursive: true }) + await ensureSession(sessionId, cwd, request.payload.sessionId !== undefined) } catch (error: unknown) { + if (error instanceof SessionCwdConflict) { + return err(request, { + code: 'session-conflict', + message: error.message, + details: { + sessionId: error.sessionId, + requestedCwd: error.requestedCwd, + ...error.existingCwd === undefined ? {} : { existingCwd: error.existingCwd }, + }, + }) + } return err(request, { code: 'internal', - message: `failed to ensure project directory "${cwd}": ${String(error)}`, + message: `failed to create session "${sessionId}": ${String(error)}`, details: {}, }) } - const handle = await ctx.agents.create({ sessionId, agentOptions, meta: { cwd } }) - return ok(request, { sessionId: handle.agent.id }) + if (workspace !== undefined) { + try { + await workspace.attachSession(sessionId) + } catch (error: unknown) { + return err(request, { + code: 'workspace-attach-failed', + message: `session "${sessionId}" was created but could not attach to workspace "${workspace.id}": ${String(error)}`, + details: { sessionId, workspaceId: workspace.id }, + }) + } + } + return ok(request, { sessionId }) }, async history(request) { @@ -472,12 +625,71 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }, }, + workspace: { + list(request) { + return Promise.resolve(ok(request, { items: ctx.workspace.list().map(workspaceView) })) + }, + + // Exactly one of path/name arrives (schema refine). Existing-folder + // adoption reuses its canonical path; create-by-name rejects a name + // already present in the registry. + async create(request) { + const { payload } = request + let path: string + if (payload.name !== undefined) { + const name = payload.name.trim() + if (name === '' || name === '.' || name === '..' || /[/\\]/.test(name)) { + return err(request, { + code: 'workspace-invalid-path', + message: `workspace name must be one non-empty path segment, got "${payload.name}"`, + details: { path: payload.name }, + }) + } + path = join(defaults.workspaceRoot, name) + } else { + path = payload.path as string + } + try { + const name = payload.name?.trim() + const { workspace, created } = await ensureWorkspace( + path, + name, + name !== undefined, + name !== undefined, + ) + return ok(request, { workspace: workspaceView(workspace), created }) + } catch (error: unknown) { + if (error instanceof WorkspaceNameConflictError) { + return err(request, { + code: 'workspace-name-conflict', + message: error.message, + details: { name: error.workspaceName }, + }) + } + if (error instanceof WorkspaceDirectoryCreationError) { + return err(request, { code: 'internal', message: error.message, details: {} }) + } + // The registry rejects a path that does not resolve to an existing + // directory (realpath ENOENT / not-a-directory) — the business + // error of the typed-path flow, surfaced as a validation failure. + return err(request, { + code: 'workspace-invalid-path', + message: `cannot create a workspace at "${path}": ${error instanceof Error ? error.message : String(error)}`, + details: { path }, + }) + } + }, + + }, + host: { describe(request) { // TODO(step2): version should read apps/cli's package.json; placeholder for now. return Promise.resolve(ok(request, { version: '0.0.1', - cwd: process.cwd(), + // Same source as session.create's fallback: the UI's default project + // must match where an unspecified-cwd session actually lands. + cwd: defaults.cwd, provider: defaults.provider, model: defaults.model, attachedSessions: ctx.agents.list().length, @@ -542,12 +754,17 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro host(_request, signal) { const queue = new FrameQueue>() + const committedWorkspaceIds = new Set( + ctx.workspace.list().map(workspace => String(workspace.id)), + ) const disposers = [ ctx.on('session/created', (session: Session) => { queue.push(frame({ type: 'host/session-added', sessionId: session.id, ...session.header.parentSession === undefined ? {} : { parentSessionId: session.header.parentSession }, + // cwd rides the frame so the client list needs no refresh to group the new session. + ...session.header.cwd === undefined ? {} : { cwd: session.header.cwd }, })) }), ctx.on('session/disposed', (session: Session) => { @@ -560,6 +777,29 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro ctx.on('agent/error', (agent: Agent, _turn: number, _step: number, error: Error) => { queue.push(frame({ type: 'host/agent-error', sessionId: agent.id, message: String(error) })) }), + ctx.on('domain/changed', (change) => { + if (change.domain !== 'workspace' || change.operation !== 'put') return + if (change.table === '') { + const state = workspaceDomainState.parse(change.value) + for (const workspaceId of state.workspaceIds) { + if (committedWorkspaceIds.has(workspaceId)) continue + const workspace = ctx.workspace.get(workspaceId) + if (workspace === undefined) { + throw new Error(`committed workspace registry references missing workspace "${workspaceId}"`) + } + committedWorkspaceIds.add(workspaceId) + queue.push(frame({ type: 'host/workspace-changed', workspace: workspaceView(workspace) })) + } + return + } + if (change.table !== 'workspaces' || !committedWorkspaceIds.has(change.key)) return + // Existing-entity table writes are complete attach/touch commits. + // A new entity's first put waits for the global registry write above. + queue.push(frame({ + type: 'host/workspace-changed', + workspace: changedWorkspaceView(change.key, change.value), + })) + }), ] return queue.iterate(signal, () => { for (const dispose of disposers) dispose() }) }, diff --git a/packages/host/apiproxy/src/api/events.schema.ts b/packages/host/apiproxy/src/api/events.schema.ts index 0a63305b8a..c2972fc5a3 100644 --- a/packages/host/apiproxy/src/api/events.schema.ts +++ b/packages/host/apiproxy/src/api/events.schema.ts @@ -11,6 +11,7 @@ import type { Wire } from './rpc.schema.ts' import { rpcErrorSchema, rpcIdSchema } from './rpc.schema.ts' import { approvalRequestIdSchema } from './approvals.schema.ts' import { sessionEventSchema, sessionIdSchema, toolEventViewSchema } from './sessions.schema.ts' +import { workspaceViewSchema } from './workspace.schema.ts' /** Question shape validated strictly against core dsh-user-interaction. */ export const askUserQuestionItemSchema = z.object({ @@ -39,9 +40,10 @@ export const muxFrameSchema = z.discriminatedUnion('type', [ /** HostFrame union (payload slot of a host-stream ServerRequest). */ export const hostFrameSchema = z.discriminatedUnion('type', [ - z.object({ type: z.literal('host/session-added'), sessionId: sessionIdSchema, parentSessionId: sessionIdSchema.optional() }), + z.object({ type: z.literal('host/session-added'), sessionId: sessionIdSchema, parentSessionId: sessionIdSchema.optional(), cwd: z.string().optional() }), z.object({ type: z.literal('host/session-removed'), sessionId: sessionIdSchema }), z.object({ type: z.literal('host/session-status'), sessionId: sessionIdSchema, running: z.boolean() }), z.object({ type: z.literal('host/agent-error'), sessionId: sessionIdSchema, message: z.string() }), + z.object({ type: z.literal('host/workspace-changed'), workspace: workspaceViewSchema }), z.object({ type: z.literal('stream/error'), error: rpcErrorSchema }), ]) as unknown as z.ZodType diff --git a/packages/host/apiproxy/src/api/events.ts b/packages/host/apiproxy/src/api/events.ts index c03877c31d..17d2952cb2 100644 --- a/packages/host/apiproxy/src/api/events.ts +++ b/packages/host/apiproxy/src/api/events.ts @@ -12,6 +12,7 @@ import type { CallId } from '@deepseek-ai/dsh-llm/brand' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types' import type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools/presentation' import type { RpcError, RpcId, RpcRequest } from './rpc.ts' +import type { WorkspaceView } from './workspace.ts' // Client-side consumers take the render-intent vocabulary from the contract; // dsh-tools remains its owner. @@ -62,10 +63,18 @@ export type MuxFrame = | { type: 'question/resolved'; sessionId: SessionId; questionRpcId: RpcId; outcome: 'answered' | 'cancelled' } | { type: 'stream/error'; error: RpcError } -/** Host stream frames. session-added carries the lineage anchor; agent-error is the only outlet for live failures with no turn position. */ +/** + * Host stream frames. session-added carries the lineage anchor and the + * project cwd (the list-summary fields a client cannot wait for a refresh to + * learn); agent-error is the only outlet for live failures with no turn + * position; workspace-changed pushes the full new snapshot after every + * durable workspace mutation (create/attach/order change — the client + * upserts, while `workspace.list` provides the reconnect baseline). + */ export type HostFrame = - | { type: 'host/session-added'; sessionId: SessionId; parentSessionId?: SessionId } + | { type: 'host/session-added'; sessionId: SessionId; parentSessionId?: SessionId; cwd?: string } | { type: 'host/session-removed'; sessionId: SessionId } | { type: 'host/session-status'; sessionId: SessionId; running: boolean } | { type: 'host/agent-error'; sessionId: SessionId; message: string } + | { type: 'host/workspace-changed'; workspace: WorkspaceView } | { type: 'stream/error'; error: RpcError } diff --git a/packages/host/apiproxy/src/api/index.ts b/packages/host/apiproxy/src/api/index.ts index c2fbb0d189..ce8e863658 100644 --- a/packages/host/apiproxy/src/api/index.ts +++ b/packages/host/apiproxy/src/api/index.ts @@ -6,6 +6,7 @@ import type { SessionsApi } from './sessions.ts' import type { HostApi } from './host.ts' +import type { WorkspaceApi } from './workspace.ts' import type { EventsApi } from './events.ts' import type { ClientResponse, RpcReceipt } from './rpc.ts' @@ -13,6 +14,7 @@ import type { ClientResponse, RpcReceipt } from './rpc.ts' export interface ApiProxy { sessions: SessionsApi host: HostApi + workspace: WorkspaceApi events: EventsApi /** Response entry for server-requests (client-response, echoing their rpcId); not a domain method (four-quadrant model). */ respond(message: ClientResponse): Promise @@ -21,6 +23,7 @@ export interface ApiProxy { // ---- Domain interfaces and payload entities ---- export type { HistoryEntry, SessionsApi, SessionSummary } from './sessions.ts' export type { HostApi } from './host.ts' +export type { WorkspaceApi, WorkspaceId, WorkspaceView } from './workspace.ts' export type { EventsApi, MuxFrame, HostFrame, ToolCallView, ToolEventView, ToolResultView } from './events.ts' export type { ApprovalResponsePayload } from './approvals.ts' export type { QuestionResponsePayload } from './questions.ts' diff --git a/packages/host/apiproxy/src/api/rpc-map.ts b/packages/host/apiproxy/src/api/rpc-map.ts index b37cc062ff..1f0f9acef4 100644 --- a/packages/host/apiproxy/src/api/rpc-map.ts +++ b/packages/host/apiproxy/src/api/rpc-map.ts @@ -6,6 +6,7 @@ import type { SessionsApi } from './sessions.ts' import type { HostApi } from './host.ts' +import type { WorkspaceApi } from './workspace.ts' import type { RpcResponse } from './rpc.ts' /** Method name → method signature. Signatures are the single source of truth; payload/value types are always derived from here. */ @@ -16,6 +17,8 @@ export interface RpcMethodMap { 'session.prompt': SessionsApi['prompt'] 'session.cancel': SessionsApi['cancel'] 'host.describe': HostApi['describe'] + 'workspace.list': WorkspaceApi['list'] + 'workspace.create': WorkspaceApi['create'] } /** Business request payload of method K (reaches through the RpcRequest narrow form to payload). */ diff --git a/packages/host/apiproxy/src/api/rpc.schema.ts b/packages/host/apiproxy/src/api/rpc.schema.ts index 20ef251cd6..3b290e18c3 100644 --- a/packages/host/apiproxy/src/api/rpc.schema.ts +++ b/packages/host/apiproxy/src/api/rpc.schema.ts @@ -35,6 +35,11 @@ export const rpcErrorSchema: z.ZodType = z.discriminatedUnion('code', z.object({ code: z.literal('bad-request'), message: z.string(), details: z.object({ issues: z.array(z.custom()) }) }), z.object({ code: z.literal('cancelled'), message: z.string(), details: z.object({}) }), z.object({ code: z.literal('session-not-found'), message: z.string(), details: z.object({ sessionId: z.string() }) }), + z.object({ code: z.literal('session-conflict'), message: z.string(), details: z.object({ sessionId: z.string(), requestedCwd: z.string(), existingCwd: z.string().optional() }) }), + z.object({ code: z.literal('workspace-attach-failed'), message: z.string(), details: z.object({ sessionId: z.string(), workspaceId: z.string() }) }), + z.object({ code: z.literal('workspace-not-found'), message: z.string(), details: z.object({ workspaceId: z.string() }) }), + z.object({ code: z.literal('workspace-invalid-path'), message: z.string(), details: z.object({ path: z.string() }) }), + z.object({ code: z.literal('workspace-name-conflict'), message: z.string(), details: z.object({ name: z.string() }) }), z.object({ code: z.literal('agent-busy'), message: z.string(), details: z.object({ reason: z.string() }) }), z.object({ code: z.literal('internal'), message: z.string(), details: z.object({}) }), ]) as unknown as z.ZodType diff --git a/packages/host/apiproxy/src/api/rpc.ts b/packages/host/apiproxy/src/api/rpc.ts index 53b2fc43e8..dbcc975d04 100644 --- a/packages/host/apiproxy/src/api/rpc.ts +++ b/packages/host/apiproxy/src/api/rpc.ts @@ -32,6 +32,11 @@ export interface RpcErrorDetailsMap { 'bad-request': { issues: ZodIssue[] } 'cancelled': {} 'session-not-found': { sessionId: SessionId } + 'session-conflict': { sessionId: SessionId; requestedCwd: string; existingCwd?: string } + 'workspace-attach-failed': { sessionId: SessionId; workspaceId: string } + 'workspace-not-found': { workspaceId: string } + 'workspace-invalid-path': { path: string } + 'workspace-name-conflict': { name: string } 'agent-busy': { reason: string } 'internal': {} } diff --git a/packages/host/apiproxy/src/api/sessions.schema.ts b/packages/host/apiproxy/src/api/sessions.schema.ts index 3edf0e6014..441d02e4df 100644 --- a/packages/host/apiproxy/src/api/sessions.schema.ts +++ b/packages/host/apiproxy/src/api/sessions.schema.ts @@ -11,10 +11,19 @@ import type { RequestPayload, ResponseValue } from './rpc-map.ts' import type { Wire } from './rpc.schema.ts' import type { HistoryEntry, SessionSummary } from './sessions.ts' import type { ToolEventView } from './events.ts' +import type { WorkspaceId } from './workspace.ts' /** SessionId: one brand cast after shape validation (the only cast point in this domain). */ export const sessionIdSchema = z.string().min(1) as unknown as z.ZodType +/** + * WorkspaceId: the workspace domain's one brand cast. Hosted here rather + * than in workspace.schema because session.create references it while + * workspace.schema references sessionIdSchema — schema modules must stay a + * DAG (both casts used at module top level; a cycle is a load-time TDZ). + */ +export const workspaceIdSchema = z.string().min(1) as unknown as z.ZodType + /** SessionEvent passthrough: strict envelope, wide data (the client fold handles unknown types via its documented default). */ export const sessionEventSchema = z.object({ type: z.string(), @@ -44,10 +53,15 @@ export const sessionListValueSchema = z.object({ items: z.array(sessionSummarySchema), }) satisfies z.ZodType>> -/** session.create request payload. */ +/** session.create request payload (at most one of workspaceId / cwd). */ export const sessionCreateRequestSchema = z.object({ + workspaceId: workspaceIdSchema.optional(), cwd: z.string().optional(), -}) satisfies z.ZodType>> + sessionId: sessionIdSchema.optional(), +}).refine( + payload => payload.workspaceId === undefined || payload.cwd === undefined, + { message: 'session.create accepts workspaceId or cwd, not both' }, +) satisfies z.ZodType>> /** session.create response value. */ export const sessionCreateValueSchema = z.object({ diff --git a/packages/host/apiproxy/src/api/sessions.ts b/packages/host/apiproxy/src/api/sessions.ts index 393303f817..5f3e3d8740 100644 --- a/packages/host/apiproxy/src/api/sessions.ts +++ b/packages/host/apiproxy/src/api/sessions.ts @@ -8,6 +8,7 @@ import type { ContentBlock } from '@deepseek-ai/dsh-llm/types' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types' import type { RpcId, RpcRequest, RpcResponse } from './rpc.ts' import type { ToolEventView } from './events.ts' +import type { WorkspaceId } from './workspace.ts' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { @@ -49,8 +50,16 @@ export interface SessionsApi { /** Lists persisted sessions (updatedAt descending). v1 returns everything; cursor is a reserved seat, unimplemented. */ list(request: RpcRequest<{ cursor?: string }>): Promise> - /** Creates a new session (and its agent, idle and standing by). */ - create(request: RpcRequest<{ cwd?: string }>): Promise> + /** + * Creates a real session and its idle agent. At most one of `workspaceId` / + * `cwd` is accepted; an omitted project uses the Host cwd. A caller may + * preallocate `sessionId`: retries with the same id and cwd return the same + * session, while a different cwd fails with `session-conflict`. + * Workspace creation attaches the session after publication; an attach + * failure returns `workspace-attach-failed` with the published session id. + */ + create(request: RpcRequest<{ workspaceId?: WorkspaceId; cwd?: string; sessionId?: SessionId }>): + Promise> /** * Reads a window of history events; page boundaries align to message boundaries: one page = diff --git a/packages/host/apiproxy/src/api/workspace.schema.ts b/packages/host/apiproxy/src/api/workspace.schema.ts new file mode 100644 index 0000000000..a193fb0c57 --- /dev/null +++ b/packages/host/apiproxy/src/api/workspace.schema.ts @@ -0,0 +1,46 @@ +/** + * workspace domain zod schemas (names derived from map keys). The + * WorkspaceId brand cast lives in sessions.schema (see the note there) and + * is re-exported here as the domain-local name. + */ + +import { z } from 'zod' +import type { RequestPayload, ResponseValue } from './rpc-map.ts' +import type { Wire } from './rpc.schema.ts' +import type { WorkspaceView } from './workspace.ts' +import { sessionIdSchema, workspaceIdSchema } from './sessions.schema.ts' + +export { workspaceIdSchema } from './sessions.schema.ts' + +/** WorkspaceView row of every workspace.* response. */ +export const workspaceViewSchema = z.object({ + workspaceId: workspaceIdSchema, + path: z.string(), + title: z.string(), + sessionIds: z.array(sessionIdSchema), + createdAt: z.string(), + updatedAt: z.string(), +}) satisfies z.ZodType> + +/** workspace.list request payload (empty object literal). */ +export const workspaceListRequestSchema = z.object({}) satisfies z.ZodType>> + +/** workspace.list response value. */ +export const workspaceListValueSchema = z.object({ + items: z.array(workspaceViewSchema), +}) satisfies z.ZodType>> + +/** workspace.create request payload: exactly one of path/name (the contract's create spellings). */ +export const workspaceCreateRequestSchema = z.object({ + path: z.string().optional(), + name: z.string().optional(), +}).refine( + payload => (payload.path === undefined) !== (payload.name === undefined), + { message: 'workspace.create requires exactly one of path / name' }, +) satisfies z.ZodType>> + +/** workspace.create response value. */ +export const workspaceCreateValueSchema = z.object({ + workspace: workspaceViewSchema, + created: z.boolean(), +}) satisfies z.ZodType>> diff --git a/packages/host/apiproxy/src/api/workspace.ts b/packages/host/apiproxy/src/api/workspace.ts new file mode 100644 index 0000000000..86c20e2ff5 --- /dev/null +++ b/packages/host/apiproxy/src/api/workspace.ts @@ -0,0 +1,55 @@ +/** + * workspace domain contract. Wire projection of the host-side workspace + * entity (@deepseek-ai/dsh-workspace): a stable id over a directory path, + * a display title, and the ordered session account. Method signatures are the + * source of truth, same as the sessions domain. + */ + +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { RpcRequest, RpcResponse } from './rpc.ts' + +/** + * Wire-side workspace id brand. Deliberately re-declared here rather than + * imported from dsh-workspace: api/ must stay browser-importable with zero + * host-package dependencies, and the brand string matches, so both sides + * agree structurally. + */ +export type WorkspaceId = Branded<'WorkspaceId'> + +/** One workspace row: the record projection every workspace.* value carries. */ +export interface WorkspaceView { + workspaceId: WorkspaceId + /** Canonical directory path (host-side realpath canon). */ + path: string + /** Unique display title (defaults to the path basename at create). */ + title: string + /** Sessions accounted under this workspace, newest-first for display. */ + sessionIds: SessionId[] + /** ISO-8601 creation instant. */ + createdAt: string + /** ISO-8601 last-mutation instant. */ + updatedAt: string +} + +/** Workspace-domain unary methods (the map keys workspace.* of RpcMethodMap). */ +export interface WorkspaceApi { + /** Lists all workspaces in the registry's durable display order. */ + list(request: RpcRequest<{}>): Promise> + + /** + * Creates (or idempotently resolves) a workspace. Exactly one of `path` / + * `name` (schema-enforced): `path` registers an EXISTING directory (no + * mkdir — a missing or non-directory path fails with `workspace-invalid-path`); + * `name` is a single path segment the host mkdirs under its default project + * root before registering. Either spelling resolving to a directory already + * owned by a workspace returns that workspace (`created: false`) for the + * existing-folder spelling. Create-by-name rejects an existing title with + * `workspace-name-conflict`; a new path whose basename duplicates another + * Workspace title is rejected by the registry with the same code. + * A new name-created workspace uses `name` as both directory name and title; + * a path-created workspace uses the registry's basename title default. + */ + create(request: RpcRequest<{ path?: string; name?: string }>): + Promise> +} diff --git a/packages/host/apiproxy/src/fetch/client.ts b/packages/host/apiproxy/src/fetch/client.ts index 901cf7bd2a..81749fc219 100644 --- a/packages/host/apiproxy/src/fetch/client.ts +++ b/packages/host/apiproxy/src/fetch/client.ts @@ -21,6 +21,10 @@ import { sessionListValueSchema, sessionPromptValueSchema, } from '../api/sessions.schema.ts' +import { + workspaceCreateValueSchema, + workspaceListValueSchema, +} from '../api/workspace.schema.ts' /** * Client consumption face of the contract (shape a): same domain tree as ApiProxy, but unary @@ -48,6 +52,10 @@ export interface IApiClient { host: { describe(payload: RequestPayload<'host.describe'>, signal?: AbortSignal): Promise>> } + workspace: { + list(payload: RequestPayload<'workspace.list'>, signal?: AbortSignal): Promise>> + create(payload: RequestPayload<'workspace.create'>, signal?: AbortSignal): Promise>> + } events: { mux(payload: Parameters[0]['payload'], signal: AbortSignal, onOpen?: () => void): AsyncIterable> host(payload: Parameters[0]['payload'], signal: AbortSignal, onOpen?: () => void): AsyncIterable> @@ -67,6 +75,8 @@ const UNARY_VALUE_SCHEMAS: { [K in keyof RpcMethodMap]: z.ZodType this.callUnary('host.describe', payload, signal), } + readonly workspace: IApiClient['workspace'] = { + list: (payload, signal) => this.callUnary('workspace.list', payload, signal), + create: (payload, signal) => this.callUnary('workspace.create', payload, signal), + } + readonly events: IApiClient['events'] = { mux: (payload, signal, onOpen) => this.openMux(payload, signal, onOpen), host: (payload, signal, onOpen) => this.openHost(payload, signal, onOpen), diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index 03b9f6500f..e876d664b2 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -22,6 +22,10 @@ import { sessionPromptRequestSchema, } from '../api/sessions.schema.ts' import { hostDescribeRequestSchema } from '../api/host.schema.ts' +import { + workspaceCreateRequestSchema, + workspaceListRequestSchema, +} from '../api/workspace.schema.ts' /** * Unary dispatch table, keyed by (and compiler-locked to) RpcMethodMap: a map row without a @@ -44,6 +48,8 @@ const UNARY_ROUTES: UnaryRoutes = { 'session.prompt': { schema: sessionPromptRequestSchema, invoke: (api, r) => api.sessions.prompt(r) }, 'session.cancel': { schema: sessionCancelRequestSchema, invoke: (api, r) => api.sessions.cancel(r) }, 'host.describe': { schema: hostDescribeRequestSchema, invoke: (api, r) => api.host.describe(r) }, + 'workspace.list': { schema: workspaceListRequestSchema, invoke: (api, r) => api.workspace.list(r) }, + 'workspace.create': { schema: workspaceCreateRequestSchema, invoke: (api, r) => api.workspace.create(r) }, } /** Route lookup that narrows an arbitrary path segment to a map key (single cast point for the string→key refinement). */ diff --git a/packages/host/apiproxy/src/index.ts b/packages/host/apiproxy/src/index.ts index aba792bd9c..06e2f01748 100644 --- a/packages/host/apiproxy/src/index.ts +++ b/packages/host/apiproxy/src/index.ts @@ -8,6 +8,7 @@ * routes — carriers (HTTP today, IPC later) wrap `ctx.apiProxy` themselves. */ +import { resolve } from 'node:path' import { Context, Service } from 'cordis' import z from 'schemastery' import type { ApiProxy } from './api/index.ts' @@ -28,37 +29,47 @@ declare module 'cordis' { } } -/** Gateway plugin config: the host-level default agent routing. */ +/** Gateway plugin config: host-level agent routing and Workspace creation root. */ export interface Config { /** Default provider route for created/resumed agents. */ provider: string /** Default model id. */ model: string + /** Parent directory for name-created Workspaces; defaults to the Host cwd. */ + workspaceRoot?: string } /** * The API gateway service: implements the ApiProxy contract over the composed - * host context and provides it as `ctx.apiProxy`. The default project - * directory for new sessions is the host process working directory (not a - * config field this round). + * host context and provides it as `ctx.apiProxy`. The Host cwd is the default + * project directory and the fallback parent for name-created Workspaces. */ export class ApiProxyService extends Service implements ApiProxy { - static inject = ['agents', 'sessions', 'tools', 'userInteraction'] + static inject = ['agents', 'sessions', 'tools', 'userInteraction', 'workspace'] static Config: z = z.object({ provider: z.string().required(), model: z.string().required(), + workspaceRoot: z.string(), }) readonly sessions: ApiProxy['sessions'] + readonly workspace: ApiProxy['workspace'] readonly host: ApiProxy['host'] readonly events: ApiProxy['events'] readonly respond: ApiProxy['respond'] constructor(ctx: Context, config: Config) { super(ctx, 'apiProxy') - const api = createApiProxy(ctx, { provider: config.provider, model: config.model, cwd: process.cwd() }) + const cwd = process.cwd() + const api = createApiProxy(ctx, { + provider: config.provider, + model: config.model, + cwd, + workspaceRoot: resolve(config.workspaceRoot ?? cwd), + }) this.sessions = api.sessions + this.workspace = api.workspace this.host = api.host this.events = api.events // createApiProxy returns closures (no `this` capture); bind only satisfies diff --git a/packages/host/apiproxy/tests/api-proxy-cold.spec.ts b/packages/host/apiproxy/tests/api-proxy-cold.spec.ts index a3e2bf4e7a..4790e4254d 100644 --- a/packages/host/apiproxy/tests/api-proxy-cold.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-cold.spec.ts @@ -55,7 +55,7 @@ describe('sessions.list cold merge', () => { return undefined }, }) - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const response = await api.sessions.list(request({})) expect(response.result.ok).toBe(true) @@ -79,7 +79,7 @@ describe('degenerate composition (no persistence, no factory)', () => { await ctx.plugin(SessionStore) await ctx.plugin(AgentRegistry) await ctx.plugin(UserInteractionService) - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const listed = await api.sessions.list(request({})) expect(listed.result.ok).toBe(true) diff --git a/packages/host/apiproxy/tests/api-proxy-view.spec.ts b/packages/host/apiproxy/tests/api-proxy-view.spec.ts index 596bf25ac8..86ffa56eb4 100644 --- a/packages/host/apiproxy/tests/api-proxy-view.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-view.spec.ts @@ -76,7 +76,7 @@ async function collect(iterable: AsyncIterable>, count: num describe('mux live view computation', () => { it('attaches the three standard card views, omits view without a presenter, soft-falls on throw', async () => { const { ctx } = await harness() - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const abort = new AbortController() const stream = api.events.mux({ rpcId: RpcId('t-mux'), payload: {} }, abort.signal) const collected = collect(stream, 9, abort) @@ -122,7 +122,7 @@ describe('mux live view computation', () => { it('serves history entries with call/result views, backscan pairing, and soft-falls', async () => { const { ctx } = await harness() - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const session = ctx.sessions.create() // history resolves the agent first; a live structural stub is enough (only // .session is read on this path). @@ -156,7 +156,7 @@ describe('mux live view computation', () => { it('drops a disposed session from the live open-call table (result after dispose gets no view)', async () => { const { ctx } = await harness() - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const abort = new AbortController() const stream = api.events.mux({ rpcId: RpcId('t-mux3'), payload: {} }, abort.signal) @@ -177,7 +177,7 @@ describe('mux live view computation', () => { it('pairs a result after turn/end via the in-memory backscan fallback', async () => { const { ctx } = await harness() - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) const abort = new AbortController() const stream = api.events.mux({ rpcId: RpcId('t-mux2'), payload: {} }, abort.signal) const collected = collect(stream, 4, abort) diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts new file mode 100644 index 0000000000..a3dd98c5a9 --- /dev/null +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -0,0 +1,246 @@ +import { existsSync, mkdirSync, mkdtempSync, realpathSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import { Context } from 'cordis' +import AgentRegistry, { AgentMessageId } from '@deepseek-ai/dsh-agent' +import type { Agent, AgentFactory } from '@deepseek-ai/dsh-agent' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' +import Storage from '@deepseek-ai/dsh-storage' +import { DomainFacility } from '@deepseek-ai/dsh-storage-domain' +import UserInteractionService from '@deepseek-ai/dsh-user-interaction' +import WorkspaceRegistry from '@deepseek-ai/dsh-workspace' +import type { HostFrame, WorkspaceId } from '@deepseek-ai/dsh-host-apiproxy/api' +import type { RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' +import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' +import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy' +import { MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts' + +let nextRpc = 1 + +function request

(payload: P): RpcRequest

{ + return { rpcId: RpcId(`workspace-${String(nextRpc++)}`), payload } +} + +function expectOk(response: RpcResponse): T { + expect(response.result.ok).toBe(true) + if (!response.result.ok) throw new Error('unreachable') + return response.result.value +} + +async function nextHostFrame( + stream: AsyncIterator>, +): Promise> { + const next = await stream.next() + if (next.done === true) throw new Error('Host stream ended before the expected increment') + return next.value +} + +function stubAgent(session: Session): Agent { + return { + id: session.id, + options: {}, + session, + status: 'idle', + ctx: new Context(), + followup: () => AgentMessageId('stub'), + queue: () => AgentMessageId('stub'), + steer: () => AgentMessageId('stub'), + inject: () => AgentMessageId('stub'), + send: () => AgentMessageId('stub'), + cancel() {}, + whenIdle: () => Promise.resolve(), + } +} + +/** Compose the API over real Session, Agent, Storage, Domain, and Workspace services. */ +async function harness( + workspaceRoot = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-apiproxy-workspace-'))), +) { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(AgentRegistry) + await ctx.plugin(UserInteractionService) + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', new MemoryStorageBackend()) + const storageDomain = new DomainFacility(ctx, { backend: 'memory', routes: {} }) + ctx.storage.mount('domain', storageDomain) + ctx.provide('storageDomain', storageDomain) + ctx.provide('sessionPersistence', { list: () => Promise.resolve([]) } as never) + await ctx.plugin(WorkspaceRegistry) + + const factory: AgentFactory = { + async createAgent(_ownerCtx, options) { + const session = ctx.sessions.create( + options.sessionId, + options.meta === undefined ? {} : { meta: options.meta }, + ) + const agent = stubAgent(session) + const unregister = ctx.agents.register(agent) + return { + agent, + dispose: () => { + unregister() + return Promise.resolve() + }, + } + }, + async resume() { + throw new Error('test harness has no persisted sessions') + }, + } + ctx.agents.setFactory(factory) + const api = createApiProxy(ctx, { + provider: 'test', + model: 'test-model', + cwd: workspaceRoot, + workspaceRoot, + }) + return { api, ctx, storageDomain, workspaceRoot } +} + +describe('workspace.create', () => { + it('serializes concurrent names and rejects the duplicate', async () => { + const { api, workspaceRoot } = await harness() + const responses = await Promise.all([ + api.workspace.create(request({ name: 'alpha' })), + api.workspace.create(request({ name: 'alpha' })), + ]) + const created = responses.find(response => response.result.ok) + const duplicate = responses.find(response => !response.result.ok) + + expect(created).toBeDefined() + expect(expectOk(created!)).toMatchObject({ + created: true, + workspace: { path: join(workspaceRoot, 'alpha'), title: 'alpha' }, + }) + expect(duplicate?.result).toMatchObject({ + ok: false, + error: { code: 'workspace-name-conflict', details: { name: 'alpha' } }, + }) + expect(existsSync(join(workspaceRoot, 'alpha'))).toBe(true) + }) + + it('adopts only existing directories and rejects unsafe names', async () => { + const { api, workspaceRoot } = await harness() + const existing = join(workspaceRoot, 'existing') + mkdirSync(existing) + const first = expectOk(await api.workspace.create(request({ path: existing }))) + const repeated = expectOk(await api.workspace.create(request({ path: existing }))) + expect(first).toMatchObject({ created: true, workspace: { path: existing, title: 'existing' } }) + expect(repeated).toMatchObject({ created: false, workspace: { workspaceId: first.workspace.workspaceId } }) + + const missing = join(workspaceRoot, 'missing') + const missingResult = await api.workspace.create(request({ path: missing })) + expect(missingResult.result).toMatchObject({ ok: false, error: { code: 'workspace-invalid-path' } }) + expect(existsSync(missing)).toBe(false) + + for (const name of ['', '.', '..', 'a/b', 'a\\b']) { + const invalid = await api.workspace.create(request({ name })) + expect(invalid.result).toMatchObject({ ok: false, error: { code: 'workspace-invalid-path' } }) + } + }) +}) + +describe('session creation and Workspace membership', () => { + it('attaches a preallocated idempotent session while cwd-only sessions stay ungrouped', async () => { + const { api, ctx } = await harness() + const workspace = expectOk(await api.workspace.create(request({ name: 'project' }))).workspace + const sessionId = SessionId('session-workspace-preallocated') + + expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId }))) + expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId }))) + expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId]) + expect(ctx.agents.list().filter(agent => agent.id === sessionId)).toHaveLength(1) + + const ungrouped = SessionId('session-cwd-only') + expectOk(await api.sessions.create(request({ cwd: workspace.path, sessionId: ungrouped }))) + expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId]) + expect(expectOk(await api.sessions.list(request({}))).items.map(item => item.sessionId)).toContain(ungrouped) + + const conflict = await api.sessions.create(request({ cwd: join(workspace.path, 'other'), sessionId })) + expect(conflict.result).toMatchObject({ + ok: false, + error: { code: 'session-conflict', details: { sessionId, existingCwd: workspace.path } }, + }) + const missing = await api.sessions.create(request({ + workspaceId: 'missing-workspace' as WorkspaceId, + sessionId: SessionId('session-missing-workspace'), + })) + expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } }) + }) + + it('retains a published session when attachment fails and repairs it on retry', async () => { + const { api, ctx } = await harness() + const created = expectOk(await api.workspace.create(request({ name: 'project' }))).workspace + const workspace = ctx.workspace.list()[0] + if (workspace === undefined) throw new Error('workspace missing from registry') + vi.spyOn(workspace, 'attachSession').mockRejectedValueOnce(new Error('simulated write failure')) + const sessionId = SessionId('session-attach-retry') + + const failed = await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId })) + expect(failed.result).toMatchObject({ + ok: false, + error: { code: 'workspace-attach-failed', details: { sessionId, workspaceId: created.workspaceId } }, + }) + expect(ctx.agents.get(sessionId)).toBeDefined() + + expectOk(await api.sessions.create(request({ workspaceId: created.workspaceId, sessionId }))) + expect(expectOk(await api.workspace.list(request({}))).items[0]?.sessionIds).toEqual([sessionId]) + }) +}) + +describe('Host Workspace increments', () => { + it('streams committed Workspace and Session increments after empty baselines', async () => { + const { api } = await harness() + expect(expectOk(await api.workspace.list(request({}))).items).toEqual([]) + expect(expectOk(await api.sessions.list(request({}))).items).toEqual([]) + + const abort = new AbortController() + const stream: AsyncIterator> = + api.events.host(request({}), abort.signal)[Symbol.asyncIterator]() + const workspaceIncrement = nextHostFrame(stream) + const workspace = expectOk(await api.workspace.create(request({ name: 'project' }))).workspace + expect(await workspaceIncrement).toMatchObject({ + payload: { type: 'host/workspace-changed', workspace: { workspaceId: workspace.workspaceId } }, + }) + + const sessionId = SessionId('session-streamed-workspace') + const pending = nextHostFrame(stream) + expectOk(await api.sessions.create(request({ workspaceId: workspace.workspaceId, sessionId }))) + const increments: HostFrame[] = [] + increments.push((await pending).payload) + while (increments.length < 2) { + const next = await stream.next() + if (next.done === true) throw new Error('Host stream ended before both increments') + increments.push(next.value.payload) + } + expect(increments.find(increment => increment.type === 'host/session-added')).toMatchObject({ + type: 'host/session-added', sessionId, cwd: workspace.path, + }) + const workspaceChanged = increments.find( + (increment): increment is Extract => + increment.type === 'host/workspace-changed', + ) + expect(workspaceChanged?.workspace.sessionIds).toEqual([sessionId]) + abort.abort() + }) + + it('does not publish a Workspace whose registry-order commit fails', async () => { + const { api, storageDomain } = await harness() + const domain = storageDomain.get('workspace') + if (domain === undefined) throw new Error('workspace domain is not open') + vi.spyOn(domain.global, 'set').mockRejectedValueOnce(new Error('simulated registry order failure')) + const abort = new AbortController() + const stream: AsyncIterator> = + api.events.host(request({}), abort.signal)[Symbol.asyncIterator]() + const next = stream.next() + + const failed = await api.workspace.create(request({ name: 'ghost' })) + expect(failed.result.ok).toBe(false) + expect(expectOk(await api.workspace.list(request({}))).items).toEqual([]) + abort.abort() + expect(await next).toMatchObject({ done: true }) + }) +}) diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index 25af7e2f75..7dec5980eb 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -34,6 +34,10 @@ function scriptedApi(overrides: { ...overrides.sessions, }, host: { describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0 }), ...overrides.host }, + workspace: { + list: r => ok(r, { items: [] }), + create: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' }, created: true }), + }, events: { mux: () => empty(), host: () => empty(), ...overrides.events }, respond: overrides.respond ?? (() => Promise.resolve({ accepted: false as const, reason: 'not-pending' as const })), } @@ -190,6 +194,23 @@ describe('unary round trip', () => { }) }) +describe('workspace domain round trip', () => { + it('routes both workspace methods through their handler rows and value schemas', async () => { + const c = client(scriptedApi()) + const list = await c.workspace.list({}) + expect(list.result).toEqual({ ok: true, value: { items: [] } }) + const created = await c.workspace.create({ path: '/t' }) + expect(created.result.ok).toBe(true) + if (created.result.ok) expect(created.result.value.created).toBe(true) + }) + + it('rejects a create payload violating the exactly-one refine at the handler', async () => { + const response = await client(scriptedApi()).workspace.create({}) + expect(response.result.ok).toBe(false) + if (!response.result.ok) expect(response.result.error.code).toBe('bad-request') + }) +}) + describe('SSE stream path', () => { it('yields frames in order and skips the comment preamble', async () => { const frames: MuxFrame[] = [ diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index d097daecef..ede6acb9ac 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -42,6 +42,17 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0 } } } }, }, + workspace: { + async list(request) { + return { rpcId: request.rpcId, result: { ok: true, value: { items: [] } } } + }, + async create(request) { + return { + rpcId: request.rpcId, + result: { ok: true, value: { workspace: { workspaceId: 'w1' as never, path: '/w', title: 'w', sessionIds: [], createdAt: 't', updatedAt: 't' }, created: true } }, + } + }, + }, events: { mux: (_request, signal) => stream(muxFrames, signal), host: (_request, signal) => stream(hostFrames, signal), diff --git a/packages/host/apiproxy/tests/rpc-schemas.spec.ts b/packages/host/apiproxy/tests/rpc-schemas.spec.ts index 0c3eb2b320..d0f2ddd128 100644 --- a/packages/host/apiproxy/tests/rpc-schemas.spec.ts +++ b/packages/host/apiproxy/tests/rpc-schemas.spec.ts @@ -12,6 +12,10 @@ import { sessionPromptValueSchema, sessionSummarySchema, } from '../src/api/sessions.schema.ts' import { hostDescribeRequestSchema, hostDescribeValueSchema } from '../src/api/host.schema.ts' +import { + workspaceCreateRequestSchema, workspaceCreateValueSchema, workspaceIdSchema, workspaceListRequestSchema, + workspaceListValueSchema, workspaceViewSchema, +} from '../src/api/workspace.schema.ts' import { hostFrameSchema, muxFrameSchema, askUserQuestionItemSchema } from '../src/api/events.schema.ts' import { approvalRequestIdSchema, approvalResponsePayloadSchema } from '../src/api/approvals.schema.ts' import { askUserQuestionAnswerSchema, questionResponsePayloadSchema } from '../src/api/questions.schema.ts' @@ -31,6 +35,11 @@ describe('rpcErrorSchema', () => { expect(rpcErrorSchema.parse({ code: 'bad-request', message: 'm', details: { issues: [] } }).code).toBe('bad-request') expect(rpcErrorSchema.parse({ code: 'cancelled', message: 'm', details: {} }).code).toBe('cancelled') expect(rpcErrorSchema.parse({ code: 'session-not-found', message: 'm', details: { sessionId: 's' } }).code).toBe('session-not-found') + expect(rpcErrorSchema.parse({ code: 'session-conflict', message: 'm', details: { sessionId: 's', requestedCwd: '/a', existingCwd: '/b' } }).code).toBe('session-conflict') + expect(rpcErrorSchema.parse({ code: 'workspace-attach-failed', message: 'm', details: { sessionId: 's', workspaceId: 'w' } }).code).toBe('workspace-attach-failed') + expect(rpcErrorSchema.parse({ code: 'workspace-not-found', message: 'm', details: { workspaceId: 'w' } }).code).toBe('workspace-not-found') + expect(rpcErrorSchema.parse({ code: 'workspace-invalid-path', message: 'm', details: { path: '/x' } }).code).toBe('workspace-invalid-path') + expect(rpcErrorSchema.parse({ code: 'workspace-name-conflict', message: 'm', details: { name: 'x' } }).code).toBe('workspace-name-conflict') expect(rpcErrorSchema.parse({ code: 'agent-busy', message: 'm', details: { reason: 'r' } }).code).toBe('agent-busy') expect(rpcErrorSchema.parse({ code: 'internal', message: 'm', details: {} }).code).toBe('internal') }) @@ -96,6 +105,9 @@ describe('sessions domain schemas', () => { expect(sessionListRequestSchema.parse({ cursor: 'c' }).cursor).toBe('c') expect(sessionListValueSchema.parse({ items: [] }).items).toEqual([]) expect(sessionCreateRequestSchema.parse({ cwd: '/w' }).cwd).toBe('/w') + // The refine's both-sides branch: workspaceId alone passes, workspaceId+cwd rejects. + expect(sessionCreateRequestSchema.parse({ workspaceId: 'w1', sessionId: 's1' }).sessionId).toBe('s1') + expect(() => sessionCreateRequestSchema.parse({ workspaceId: 'w1', cwd: '/w' })).toThrow(/not both/) expect(sessionCreateValueSchema.parse({ sessionId: 's1' }).sessionId).toBe('s1') expect(sessionHistoryRequestSchema.parse({ sessionId: 's1', beforeSeq: 3, maxMessages: 5 }).beforeSeq).toBe(3) expect(() => sessionHistoryRequestSchema.parse({ sessionId: 's1', maxMessages: 0 })).toThrow() @@ -119,6 +131,31 @@ describe('host domain schemas', () => { }) }) +describe('workspace domain schemas', () => { + const view = { + workspaceId: 'w1', path: '/p', title: 'p', sessionIds: ['s1'], + createdAt: '2026-07-25T00:00:00.000Z', updatedAt: '2026-07-25T00:00:00.000Z', + } + + it('validates ids, the view row, and list request/value', () => { + expect(workspaceIdSchema.parse('w1')).toBe('w1') + expect(() => workspaceIdSchema.parse('')).toThrow() + expect(workspaceViewSchema.parse(view).sessionIds).toEqual(['s1']) + expect(() => workspaceViewSchema.parse({ ...view, sessionIds: 's1' })).toThrow() + expect(workspaceListRequestSchema.parse({})).toEqual({}) + expect(workspaceListValueSchema.parse({ items: [view] }).items).toHaveLength(1) + }) + + it('create requires exactly one of path/name (both refine arms)', () => { + expect(workspaceCreateRequestSchema.parse({ path: '/p' }).path).toBe('/p') + expect(workspaceCreateRequestSchema.parse({ name: 'n' }).name).toBe('n') + expect(() => workspaceCreateRequestSchema.parse({})).toThrow(/exactly one/) + expect(() => workspaceCreateRequestSchema.parse({ path: '/p', name: 'n' })).toThrow(/exactly one/) + expect(workspaceCreateValueSchema.parse({ workspace: view, created: false }).created).toBe(false) + }) + +}) + describe('events frame schemas', () => { it('accepts every mux frame branch', () => { const frames = [ diff --git a/packages/host/apiproxy/tsconfig.json b/packages/host/apiproxy/tsconfig.json index 4e22627590..9b0ae88d04 100644 --- a/packages/host/apiproxy/tsconfig.json +++ b/packages/host/apiproxy/tsconfig.json @@ -41,6 +41,9 @@ { "path": "../../ui/user-interaction" }, + { + "path": "../../workspace/workspace" + }, { "path": "../../support/invariants" } diff --git a/packages/storage/README.md b/packages/storage/README.md index f112cdb5a0..fc541e7ea5 100644 --- a/packages/storage/README.md +++ b/packages/storage/README.md @@ -7,6 +7,6 @@ The storage family persists everything that is not a session event log: a hub wh | `storage/` | The hub: named backend registry + merge-extensible data-form mounts, backend facet vocabulary, shared conformance suite | `ctx.storage` | | `storage-json/` | JSON backend: one human-readable file per unit, atomic whole-file rewrite | registers backend `json` | | `storage-sqlite/` | SQLite backend: one database hosting all routed units, document-per-row | registers backend `sqlite` | -| `domain/` | Domain data form: zod-validated records, per-domain write chain, `domain/changed` events, backend routing by configuration | mounts `ctx.storage.domain` | +| `domain/` | Domain data form: zod-validated records, per-domain write chain, `domain/changed` events, backend routing by configuration | `ctx.storageDomain` + `ctx.storage.domain` | -Backends own one medium each and expose data-shape **facets** (`kv` today; an append-log facet is reserved for the future session-backend migration). Consumers never touch backends directly — they open declared domains through the domain form. +Backends own one medium each and expose data-shape **facets** (`kv` today; an append-log facet is reserved for the future session-backend migration). Each backend plugin publishes an internal lifecycle service after registration; the domain plugin injects every configured backend key before exposing its own service, so config-tree row order carries no startup semantics. Consumers never touch backends directly — they inject `storageDomain` and open declared domains through it. diff --git a/packages/storage/storage-domain/README.md b/packages/storage/storage-domain/README.md index e89c2f1d5b..3a707f0b16 100644 --- a/packages/storage/storage-domain/README.md +++ b/packages/storage/storage-domain/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-storage-domain -Domain data form for the DeepSeek Harness storage hub: mounts `ctx.storage.domain`, opening schema-validated KV domains over configured storage backends. A domain is declared once with `defineDomain` (zod record schemas, `z.infer`-derived types), opened through `DomainFacility.open`, and served from authoritative in-memory state — reads are synchronous, writes serialize on one per-domain chain, reach durability on the routed backend first, then update memory and emit `domain/changed`. The opening consumer owns the handle's lifecycle and releases it with `Domain.close()` (idempotent; typically its own `ctx.effect` disposer); domains still open when the plugin unmounts are closed by the facility. +Domain data form for the DeepSeek Harness storage hub: exposes the injectable `ctx.storageDomain` service and the matching `ctx.storage.domain` projection after every configured backend is registered. A domain is declared once with `defineDomain` (zod record schemas, `z.infer`-derived types), opened through `DomainFacility.open`, and served from authoritative in-memory state — reads are synchronous, writes serialize on one per-domain chain, reach durability on the routed backend first, then update memory and emit `domain/changed`. The opening consumer owns the handle's lifecycle and releases it with `Domain.close()` (idempotent; typically its own `ctx.effect` disposer); domains still open when the plugin unmounts are closed by the facility. Design rationale, open semantics, and the storage/domain layer split live in the [Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). @@ -17,7 +17,7 @@ Design rationale, open semantics, and the storage/domain layer split live in the #### What the model sees -Nothing. The package registers no tools, injects no prompts, and appends no session events; it stores non-session data (workspace records, future session sidecars) behind `ctx.storage.domain` and emits only the in-process `domain/changed` event, which reaches a model only if a consumer package renders it through its own documented surface. +Nothing. The package registers no tools, injects no prompts, and appends no session events; it stores non-session data (workspace records, future session sidecars) behind `ctx.storageDomain` and emits only the in-process `domain/changed` event, which reaches a model only if a consumer package renders it through its own documented surface. #### Token effect diff --git a/packages/storage/storage-domain/src/index.ts b/packages/storage/storage-domain/src/index.ts index 974fcadc16..cb6c5f0f77 100644 --- a/packages/storage/storage-domain/src/index.ts +++ b/packages/storage/storage-domain/src/index.ts @@ -9,6 +9,7 @@ import type { Context } from 'cordis' import z from 'schemastery' +import { storageBackendServiceKey } from '@deepseek-ai/dsh-storage' import { DomainError } from './error.ts' import { descriptorOf } from './spec.ts' import type { DomainSpec } from './spec.ts' @@ -31,6 +32,12 @@ declare module '@deepseek-ai/dsh-storage' { } } +declare module 'cordis' { + interface Context { + storageDomain: DomainFacility + } +} + /** Cordis plugin name. */ export const name = 'storage-domain' /** The storage hub must be present before the form can mount. */ @@ -188,16 +195,26 @@ function parseRecord(domain: string, table: string, key: string, parse: () => * Mount the domain data form on the storage hub. * @param ctx - Plugin context. * @param config - Validated plugin config. + * @returns resolution after an already-available backend set activates the form. */ -export function apply(ctx: Context, config: Config) { - const facility = new DomainFacility(ctx, config) - ctx.effect(() => { - const unmount = ctx.storage.mount('domain', facility) - return async () => { - // Close leftovers before unmounting: draining writes still emit - // domain/changed, whose invariant resolves the facility through the hub. - await facility.closeAll() - unmount() - } +export function apply(ctx: Context, config: Config): Promise { + const backendServices = [...new Set([ + config.backend, + ...Object.values(config.routes ?? {}), + ])].map(storageBackendServiceKey) + + const fiber = ctx.inject(backendServices, (domainCtx) => { + const facility = new DomainFacility(domainCtx, config) + domainCtx.effect(() => { + const unmount = domainCtx.storage.mount('domain', facility) + return async () => { + // Close leftovers before unmounting: draining writes still emit + // domain/changed, whose invariant resolves the facility through the hub. + await facility.closeAll() + unmount() + } + }) + domainCtx.provide('storageDomain', facility) }) + return Promise.resolve(fiber).then(() => {}) } diff --git a/packages/storage/storage-domain/tests/domain.spec.ts b/packages/storage/storage-domain/tests/domain.spec.ts index 8d02cd50e5..761c1d7c1d 100644 --- a/packages/storage/storage-domain/tests/domain.spec.ts +++ b/packages/storage/storage-domain/tests/domain.spec.ts @@ -1,7 +1,7 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import { z } from 'zod' -import Storage from '@deepseek-ai/dsh-storage' +import Storage, { storageBackendServiceKey } from '@deepseek-ai/dsh-storage' import { DomainFacility, defineDomain, domainTable } from '../src/index.ts' import type { Config } from '../src/index.ts' import type { DomainChanged } from '../src/events.ts' @@ -151,15 +151,26 @@ describe('DomainFacility.open', () => { }) describe('plugin apply', () => { - it('mounts the facility as ctx.storage.domain through the plugin effect', async () => { + it('waits for routed backends, then mounts one lifecycle-bound service and form', async () => { const ctx = new Context() await ctx.plugin(Storage) - ctx.storage.backend.register('memory', new MemoryStorageBackend()) const DomainPlugin = await import('../src/index.ts') const fiber = await ctx.plugin(DomainPlugin, { backend: 'memory' }) - expect(ctx.storage.domain).toBeInstanceOf(DomainFacility) - await fiber.dispose() + expect(ctx.get('storageDomain')).toBeUndefined() expect(() => ctx.storage.form('domain')).toThrow(/not mounted/) + + const backend = new MemoryStorageBackend() + ctx.storage.backend.register('memory', backend) + const disposeBackend = ctx.provide(storageBackendServiceKey('memory'), backend) + await vi.waitFor(() => { expect(ctx.storageDomain).toBeInstanceOf(DomainFacility) }) + expect(ctx.storage.domain).toBe(ctx.storageDomain) + + disposeBackend() + await vi.waitFor(() => { + expect(ctx.get('storageDomain')).toBeUndefined() + expect(() => ctx.storage.form('domain')).toThrow(/not mounted/) + }) + await fiber.dispose() }) }) @@ -295,10 +306,12 @@ describe('close and lifecycle', () => { it('facility unmount closes domains the consumer never closed', async () => { const ctx = new Context() await ctx.plugin(Storage) - ctx.storage.backend.register('memory', new MemoryStorageBackend()) + const backend = new MemoryStorageBackend() + ctx.storage.backend.register('memory', backend) + ctx.provide(storageBackendServiceKey('memory'), backend) const DomainPlugin = await import('../src/index.ts') const fiber = await ctx.plugin(DomainPlugin, { backend: 'memory' }) - const domain = await ctx.storage.domain.open(bareSpec) + const domain = await ctx.storageDomain.open(bareSpec) const table = domain.table('rows') await table.put('a', { label: 'x', count: 1 }) await fiber.dispose() diff --git a/packages/storage/storage-json/src/index.ts b/packages/storage/storage-json/src/index.ts index b80185ecf7..c2c0ac0dd8 100644 --- a/packages/storage/storage-json/src/index.ts +++ b/packages/storage/storage-json/src/index.ts @@ -9,7 +9,7 @@ import { mkdir } from 'node:fs/promises' import { join } from 'node:path' import type { Context } from 'cordis' import z from 'schemastery' -import { StorageError, UNIT_NAME_RE } from '@deepseek-ai/dsh-storage' +import { StorageError, UNIT_NAME_RE, storageBackendServiceKey } from '@deepseek-ai/dsh-storage' import type { KvFacet, KvUnit, KvUnitDescriptor, StorageBackend } from '@deepseek-ai/dsh-storage' import { openJsonUnit } from './unit.ts' @@ -110,4 +110,5 @@ export function apply(ctx: Context, config: Config) { await backend.close() } }) + ctx.provide(storageBackendServiceKey('json'), backend) } diff --git a/packages/storage/storage-json/tests/json-backend.spec.ts b/packages/storage/storage-json/tests/json-backend.spec.ts index 870498f0ea..2f2fff90fc 100644 --- a/packages/storage/storage-json/tests/json-backend.spec.ts +++ b/packages/storage/storage-json/tests/json-backend.spec.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, describe, expect, it } from 'vitest' import { Context } from 'cordis' -import Storage from '@deepseek-ai/dsh-storage' +import Storage, { storageBackendServiceKey } from '@deepseek-ai/dsh-storage' import InvariantService from '@deepseek-ai/dsh-invariants' import { runKvBackendContract } from '../../storage/tests/contract.ts' import { Config, JsonStorageBackend, apply } from '../src/index.ts' @@ -185,10 +185,12 @@ describe('json backend specifics', () => { await ctx.plugin(Storage) const fiber = await ctx.plugin({ apply, Config, inject: ['storage'] }, { root }) const backend = ctx.storage.backend.get('json') + expect(ctx.get(storageBackendServiceKey('json'))).toBe(backend) const unit = await backend.kv!.open(descriptor) await unit.putRecord('t', 'k', { v: 1 }) await fiber.dispose() expect(() => ctx.storage.backend.get('json')).toThrow() + expect(ctx.get(storageBackendServiceKey('json'))).toBeUndefined() await expect(unit.putRecord('t', 'x', {})).rejects.toMatchObject({ code: 'closed' }) }) diff --git a/packages/storage/storage-sqlite/src/index.ts b/packages/storage/storage-sqlite/src/index.ts index 72fff382bc..eff5bb80fb 100644 --- a/packages/storage/storage-sqlite/src/index.ts +++ b/packages/storage/storage-sqlite/src/index.ts @@ -8,7 +8,7 @@ import type { Context } from 'cordis' import z from 'schemastery' import type { DatabaseSync } from 'node:sqlite' -import { StorageError, UNIT_NAME_RE } from '@deepseek-ai/dsh-storage' +import { StorageError, UNIT_NAME_RE, storageBackendServiceKey } from '@deepseek-ai/dsh-storage' import type { KvFacet, KvUnit, KvUnitDescriptor, StorageBackend } from '@deepseek-ai/dsh-storage' import { openDatabase, recordTableName, type JournalMode } from './schema.ts' import { SqliteKvUnit } from './unit.ts' @@ -164,4 +164,5 @@ export function apply(ctx: Context, config: Config) { await backend.close() } }, 'storage-sqlite.registerBackend') + ctx.provide(storageBackendServiceKey('sqlite'), backend) } diff --git a/packages/storage/storage-sqlite/tests/sqlite-backend.spec.ts b/packages/storage/storage-sqlite/tests/sqlite-backend.spec.ts index b5ddd46fb1..8e64fb40f2 100644 --- a/packages/storage/storage-sqlite/tests/sqlite-backend.spec.ts +++ b/packages/storage/storage-sqlite/tests/sqlite-backend.spec.ts @@ -4,7 +4,7 @@ import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { DatabaseSync } from 'node:sqlite' -import Storage from '@deepseek-ai/dsh-storage' +import Storage, { storageBackendServiceKey } from '@deepseek-ai/dsh-storage' import type { KvUnitDescriptor } from '@deepseek-ai/dsh-storage' import { runKvBackendContract } from '../../storage/tests/contract.ts' import * as StorageSqlite from '../src/index.ts' @@ -233,11 +233,13 @@ describe('sqlite backend specifics', () => { await ctx.plugin(Storage) const fiber = await ctx.plugin(StorageSqlite, { path: ':memory:' }) const backend = ctx.storage.backend.get('sqlite') + expect(ctx.get(storageBackendServiceKey('sqlite'))).toBe(backend) const unit = await backend.kv!.open(DESCRIPTOR) await unit.putRecord('records', 'k', { n: 1 }) await fiber.dispose() expect(ctx.storage.backend.names()).toEqual([]) + expect(ctx.get(storageBackendServiceKey('sqlite'))).toBeUndefined() await expect(backend.kv!.open(DESCRIPTOR)).rejects.toMatchObject({ code: 'closed' }) }) diff --git a/packages/storage/storage/src/index.ts b/packages/storage/storage/src/index.ts index 15fb70d778..4a24d88cc5 100644 --- a/packages/storage/storage/src/index.ts +++ b/packages/storage/storage/src/index.ts @@ -15,6 +15,18 @@ export type { StorageErrorCode } from './error.ts' export { UNIT_NAME_RE } from './backend.ts' export type { StorageBackend, KvFacet, KvUnit, KvUnitDescriptor } from './backend.ts' +/** + * Derive the Cordis lifecycle service that one named backend plugin provides. + * Domain-form providers inject these keys so activation cannot race backend + * registration even though callers continue resolving backends through the + * storage registry. + * @param name - Backend registry name. + * @returns the corresponding lifecycle-only service key. + */ +export function storageBackendServiceKey(name: string): string { + return `storage.backend.${name}` +} + declare module 'cordis' { interface Context { storage: Storage diff --git a/packages/storage/storage/tests/registry.spec.ts b/packages/storage/storage/tests/registry.spec.ts index 413bbe914c..232efc3640 100644 --- a/packages/storage/storage/tests/registry.spec.ts +++ b/packages/storage/storage/tests/registry.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { Context } from 'cordis' -import Storage, { BackendRegistry } from '../src/index.ts' +import Storage, { BackendRegistry, storageBackendServiceKey } from '../src/index.ts' import type { StorageBackend } from '../src/index.ts' const fakeBackend = (): StorageBackend => ({ close: async () => {} }) @@ -25,6 +25,11 @@ describe('BackendRegistry', () => { }) describe('Storage service', () => { + it('derives stable lifecycle service keys for named backends', () => { + expect(storageBackendServiceKey('json')).toBe('storage.backend.json') + expect(storageBackendServiceKey('tenant-a')).toBe('storage.backend.tenant-a') + }) + it('mounts on the context and exposes registry plus form mounting', async () => { const ctx = new Context() await ctx.plugin(Storage) diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index a32528517f..a687910319 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -1,18 +1,19 @@ # @deepseek-ai/dsh-workspace -Workspace entity registry (`ctx.workspace`) for the DeepSeek Harness: durable workspace records — a stable `WorkspaceId`, a canonical directory path, a display title, and the ordered account of owned sessions — stored through the domain data form (`workspaceDomainSpec`, table `workspaces`). Consumers see the `Workspace` interface only; the entity implementation stays package-private. +Workspace entity registry (`ctx.workspace`) for the DeepSeek Harness: durable workspace records, stable workspace order, and a newest-first candidate session index stored through the domain data form. Consumers see the `Workspace` interface; the entity implementation stays package-private. -Design rationale, the path/uniqueness canon, and the consistency rules live in the [Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.zh.md). +The entity/storage rationale lives in the [domain Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); header-only bootstrap and GUI ordering live in the [Workspace GUI Agent Note](../../../.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.md). ## Shape -- `ctx.workspace.create(path, title?)` — canonicalizes `path` via `fs.realpath` (trailing slashes, `..`, symlinks), rejects a nonexistent path (the original `ENOENT`), a path resolving to anything but a directory, and a canonical path another workspace already owns. Title defaults to `basename(path)`. -- `ctx.workspace.get(id)` / `list()` / `resolveByPath(path)` — cache-served lookups; `resolveByPath` is async because it runs the same `realpath` canon first. -- `Workspace.attachSession(id)` — idempotent; validates that the session's stored header `cwd`, canonicalized the same way, equals the workspace path. A missing persistence service, unknown session, absent or unresolvable `cwd`, or mismatch rejects without writing (what cannot be validated is not recorded). `detachSession` removes from the account only, never touching the session's own log. -- `Workspace.sessionIds` — the ordered ownership account (array order is display order). Accounted ids whose session no longer exists are filtered from the projection and pruned durably on the next mutation. A medium accounting one session under two workspaces, or claiming one canonical path from two records, rejects at startup (external edit — the write side makes both unreachable). Attach/detach idempotence is decided on the domain write chain, so unawaited concurrent calls settle in call order. +- `ctx.workspace.create(path, title?)` — canonicalizes `path` via `fs.realpath`, rejects a nonexistent or non-directory path, creates at most one record per canonical path, and prepends a new record to durable workspace order. Repeated calls for that path return the existing workspace without changing its title; a different path cannot create a duplicate title. +- `ctx.workspace.get(id)` / `list()` / `resolveByPath(path)` — cache-served lookups. `list()` is synchronous and follows durable registry order; `resolveByPath` is async because it applies the same `realpath` canon and rejects a missing path rather than creating it. +- `Workspace.attachSession(id)` — validates a live or persisted session header cwd against the workspace path and prepends a new id. Unknown sessions, absent/unresolvable/non-directory cwd values, and mismatches reject without writing. `detachSession` removes only the candidate index entry. +- `ctx.workspace.touchSession(id)` — moves only that validated, accounted session to the front. Ungrouped or filtered sessions are no-ops, and workspace order never changes. +- `Workspace.sessionIds` — synchronous id-plus-canonical-cwd membership projection in durable candidate order. Missing headers, invalid cwd values, and mismatches are filtered; the next workspace mutation prunes them. A medium indexing one session under two workspaces, claiming one path from two records, or diverging from durable workspace order rejects at startup. - `Workspace.status()` — uncached directory check, `'ok' | 'missing-dir'`; a missing directory never mutates the record. -Session persistence is an optional peer resolved with `ctx.get`: absent, attach rejects and projections serve the account unfiltered. +`storageDomain` and `sessionPersistence` are required startup dependencies. An unavailable peer leaves the plugin pending and cannot commit an empty initialized marker. On the first successful start, the registry calls `SessionPersistence.list()` and uses only header `id`, `cwd`, and `createdAt` to group valid historical directories and persist initial order; it never reads event bodies. The initialized marker is written last, so partial bootstrap writes are reused safely after restart. Later cwd-only sessions remain Ungrouped. ## Model Experience @@ -33,5 +34,4 @@ Independent of live requests: the package never touches a request prefix, so it ## Known Limitations and Deferred Work - No delete entry point in this phase — workspace deletion ships as one complete semantic together with the session-delete primitive and cascade orchestration (future-work section of the Agent Note); a half "drop the record, keep the sessions" operation is deliberately not exposed. -- No RPC surface or GUI wiring yet; the record schema is the direct source of the next phase's wire projection. -- The known-session view refreshes at startup and on attach validation; a session deleted by an external process during this one is filtered only after the next refresh. +- The header index refreshes at startup and when attach must resolve an uncached persisted id; deletion or cwd damage performed by another process is observed after the next refresh or restart. diff --git a/packages/workspace/workspace/package.json b/packages/workspace/workspace/package.json index 6bfab64773..8ef0c34382 100644 --- a/packages/workspace/workspace/package.json +++ b/packages/workspace/workspace/package.json @@ -15,12 +15,17 @@ "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, "./src/*": "./src/*", "./package.json": "./package.json" }, "files": [ "lib/index.js", "lib/invariant.js", + "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts index 6ce2c01a00..7f213db0b8 100644 --- a/packages/workspace/workspace/src/entity.ts +++ b/packages/workspace/workspace/src/entity.ts @@ -2,7 +2,7 @@ * Package-private workspace entity: the single {@link Workspace} * implementation. Holds a record snapshot that is swapped in place after each * durable mutation; every write funnels through the private `mutate` so - * `updatedAt` stamping and dead-account pruning happen exactly once. + * `updatedAt` stamping and invalid-account pruning happen exactly once. * Not re-exported from the package entrypoint — consumers see only the * `Workspace` interface. * @module @deepseek-ai/dsh-workspace/src/entity @@ -17,8 +17,8 @@ import { realpathNormalize } from './paths.ts' /** * The registry-owned machinery an entity mutates through. Entities never see - * the registry itself — only the open table, the known-session view backing - * the `sessionIds` projection, and header reads for attach validation. + * the registry itself — only the open table, the canonical session-path + * index backing the `sessionIds` projection, and attach-time header reads. */ export interface WorkspaceEntityHost { /** @@ -28,13 +28,12 @@ export interface WorkspaceEntityHost { table(): KvTable /** - * Synchronous view of the session ids known to exist in session - * persistence. - * @returns the id set, or `undefined` when persistence has been absent so - * far (membership cannot be verified, so projections serve the account - * unfiltered). + * Read a session's canonical directory from the registry's header index. + * @param id - Session whose indexed path is requested. + * @returns the canonical directory, or `undefined` when the header is + * missing or its cwd cannot identify an existing directory. */ - knownSessionIds(): ReadonlySet | undefined + sessionPath(id: SessionId): string | undefined /** * Read one stored session header for attach validation. @@ -43,6 +42,13 @@ export interface WorkspaceEntityHost { * no session with this id. */ readSessionHeader(id: SessionId): Promise + + /** + * Publish a successfully validated canonical cwd to the projection index. + * @param id - Validated session id. + * @param path - Canonical existing directory from the immutable header cwd. + */ + rememberSessionPath(id: SessionId, path: string): void } /** Chain-slot abort sentinel thrown by the update fn when the record needs no change; only `mutate` observes it. */ @@ -53,7 +59,7 @@ export class WorkspaceEntity implements Workspace { private record: WorkspaceRecord /** - * @param host - Registry-owned table, known-session view, and header reads. + * @param host - Registry-owned table, session-path index, and header reads. * @param id - The record's stable id. * @param record - The validated record snapshot loaded or just written. */ @@ -73,10 +79,16 @@ export class WorkspaceEntity implements Workspace { return this.record.title } + get createdAt(): string { + return this.record.createdAt + } + + get updatedAt(): string { + return this.record.updatedAt + } + get sessionIds(): readonly SessionId[] { - const known = this.host.knownSessionIds() - if (known === undefined) return this.record.sessionIds - return this.record.sessionIds.filter(id => known.has(id)) + return this.record.sessionIds.filter(id => this.host.sessionPath(id) === this.record.path) } async setTitle(title: string): Promise { @@ -106,16 +118,49 @@ export class WorkspaceEntity implements Workspace { { cause: error }, ) } + if (!(await stat(cwd)).isDirectory()) { + throw new Error( + `cannot attach session '${sessionId}' to workspace '${this.record.path}': ` + + `its cwd '${header.cwd}' is not a directory`, + ) + } if (cwd !== this.record.path) { throw new Error( `cannot attach session '${sessionId}' to workspace '${this.record.path}': ` + `its cwd resolves to '${cwd}'`, ) } + this.host.rememberSessionPath(sessionId, cwd) } await this.mutate(record => record.sessionIds.includes(sessionId) ? record - : { ...record, sessionIds: [...record.sessionIds, sessionId] }) + : { ...record, sessionIds: [sessionId, ...record.sessionIds] }) + } + + /** + * Test the durable candidate account without applying header projection. + * @param sessionId - Candidate session id. + * @returns whether this workspace's stored account contains the id. + */ + hasSession(sessionId: SessionId): boolean { + return this.record.sessionIds.includes(sessionId) + } + + /** + * Move one validated accounted session to the front without touching peers. + * @param sessionId - Accounted session whose activity was observed. + */ + async touchSession(sessionId: SessionId): Promise { + if ( + this.host.sessionPath(sessionId) !== this.record.path + || this.record.sessionIds[0] === sessionId + ) return + await this.mutate(record => !record.sessionIds.includes(sessionId) || record.sessionIds[0] === sessionId + ? record + : { + ...record, + sessionIds: [sessionId, ...record.sessionIds.filter(id => id !== sessionId)], + }) } async detachSession(sessionId: SessionId): Promise { @@ -136,9 +181,9 @@ export class WorkspaceEntity implements Workspace { /** * The single write path: run `fn` on the domain write chain via - * `table.update`, stamping `updatedAt` and pruning accounted ids whose - * session no longer exists (consistency rule: dead ids are dropped on the - * next mutation, whatever that mutation is), then swap the snapshot. + * `table.update`, stamping `updatedAt` and pruning candidates that no + * longer pass the id-plus-canonical-cwd membership check, then swap the + * snapshot. * * `fn` sees the value current at its chain slot, so membership decisions * (attach/detach idempotence) are race-free against queued writes; a fn @@ -147,14 +192,13 @@ export class WorkspaceEntity implements Workspace { * rewrites the medium nor emits a change event. */ private async mutate(fn: (record: WorkspaceRecord) => WorkspaceRecord): Promise { - const known = this.host.knownSessionIds() let next: WorkspaceRecord try { next = await this.host.table().update(this.id, (current) => { const changed = fn(current) - const sessionIds = known === undefined - ? changed.sessionIds - : changed.sessionIds.filter(id => known.has(id)) + const sessionIds = changed.sessionIds.filter( + id => this.host.sessionPath(id) === changed.path, + ) if (changed === current && sessionIds.length === current.sessionIds.length) { throw unchangedSentinel } diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index 3754a9917a..c20c2143c6 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -1,8 +1,7 @@ /** - * Workspace entity registry (`ctx.workspace`): durable workspace records over - * the domain data form, with session attachment validated against stored - * session headers. This package owns the `WorkspaceId` brand and the - * `workspace` domain; consumers see the {@link Workspace} interface only. + * Workspace entity registry (`ctx.workspace`): durable workspace records, + * stable registry order, and header-validated session membership over the + * domain data form. * @module @deepseek-ai/dsh-workspace */ @@ -11,20 +10,18 @@ import { stat } from 'node:fs/promises' import { basename } from 'node:path' import { Context, Service } from 'cordis' import type { SessionHeader, SessionId } from '@deepseek-ai/dsh-session' -// Type-only: merges `sessionPersistence` into the Context service map for the -// optional `ctx.get` lookups below. import type {} from '@deepseek-ai/dsh-session-persistence' -import type { KvTable } from '@deepseek-ai/dsh-storage-domain' -import { workspaceDomainSpec } from './spec.ts' -import type { WorkspaceRecord } from './spec.ts' +import type { DomainGlobal, KvTable } from '@deepseek-ai/dsh-storage-domain' import { WorkspaceEntity } from './entity.ts' import type { WorkspaceEntityHost } from './entity.ts' import { realpathNormalize } from './paths.ts' +import { workspaceDomainSpec } from './spec.ts' +import type { WorkspaceDomainState, WorkspaceRecord } from './spec.ts' import type { Workspace, WorkspaceId as WorkspaceIdBrand } from './types.ts' export type { Workspace } from './types.ts' -export { workspaceRecord, workspaceDomainSpec } from './spec.ts' -export type { WorkspaceRecord } from './spec.ts' +export { workspaceDomainState, workspaceRecord, workspaceDomainSpec } from './spec.ts' +export type { WorkspaceDomainState, WorkspaceRecord } from './spec.ts' export { realpathNormalize } from './paths.ts' /** Identifies one workspace record (see `src/types.ts` for the brand rationale). */ @@ -32,74 +29,345 @@ export type WorkspaceId = WorkspaceIdBrand /** * Brand a string as a {@link WorkspaceId}. - * @param id - the raw workspace id string. - * @returns the same string, branded (a compile-time cast — no runtime cost). + * @param id - Raw workspace id string. + * @returns the same string, branded at compile time. */ export function WorkspaceId(id: string): WorkspaceId { return id as WorkspaceId } +/** A create request would give two Workspaces the same display name. */ +export class WorkspaceNameConflictError extends Error { + /** + * @param workspaceName - Conflicting display name. + */ + constructor(readonly workspaceName: string) { + super(`workspace name '${workspaceName}' is already in use`) + this.name = 'WorkspaceNameConflictError' + } +} + declare module 'cordis' { interface Context { workspace: WorkspaceRegistry } } +interface BootstrapGroup { + readonly path: string + readonly headers: SessionHeader[] + readonly newestAt: number +} + +const sameIds = (left: readonly WorkspaceId[], right: readonly WorkspaceId[]): boolean => + left.length === right.length && left.every((id, index) => id === right[index]) + +const compareHeaders = (left: SessionHeader, right: SessionHeader): number => + right.createdAt - left.createdAt || String(left.id).localeCompare(String(right.id)) + /** - * The workspace registry service. Opens the `workspace` domain at startup, - * rebuilds one entity per stored record, and serves entities from an - * in-memory cache keyed by id. Session persistence is an OPTIONAL peer - * (resolved via `ctx.get`, never injected): while it is absent, session - * attachment rejects (what cannot be validated is not recorded) and - * `sessionIds` projections serve the account unfiltered. - * - * There is deliberately no delete entry point in this phase: workspace - * deletion ships as one complete semantic together with the session-cascade - * primitives (future work in the owning Agent Note). + * Durable workspace registry. Startup waits for `sessionPersistence`, builds + * one canonical-cwd header index, and completes the one-time history + * bootstrap before the service becomes active. The persistence dependency is + * mandatory so an unavailable peer can never be mistaken for an empty + * history and commit the initialized marker. */ export class WorkspaceRegistry extends Service { - static inject = ['storage'] + static inject = ['storageDomain', 'sessionPersistence'] private table?: KvTable + private global?: DomainGlobal + private state?: WorkspaceDomainState private readonly entities = new Map() - /** - * Session ids known to exist in session persistence; `undefined` until the - * first successful listing. Refreshed at startup and on every attach - * validation — within one process sessions are only ever added (this phase - * has no delete primitive), so the set can only lag by missing very recent - * sessions, never by holding dead ones from this process's lifetime. - */ - private known?: Set + private readonly headers = new Map() + private readonly sessionPaths = new Map() + private readonly invalidSessionPaths = new Map() + private readonly pendingTouches = new Map>() + private operationTail: Promise = Promise.resolve() private readonly host: WorkspaceEntityHost = { table: () => this.requireTable(), - knownSessionIds: () => this.known, + sessionPath: id => this.sessionPaths.get(id), readSessionHeader: id => this.readSessionHeader(id), + rememberSessionPath: (id, path) => { + this.sessionPaths.set(id, path) + this.invalidSessionPaths.delete(id) + }, } constructor(ctx: Context) { super(ctx, 'workspace') } - /** Open the domain and rebuild the entity cache before the service is published as active. */ + /** Open the domain, finish bootstrap when required, and rebuild the ordered cache. */ protected async [Service.init](): Promise { - const domain = await this.ctx.storage.domain.open(workspaceDomainSpec) - // This registry owns the domain handle it opened: closing on fiber - // disposal frees the domain name, so a re-plugged registry can reopen it. + const domain = await this.ctx.storageDomain.open(workspaceDomainSpec) this.ctx.effect(() => () => domain.close(), 'workspace.domainClose') this.table = domain.table('workspaces') - const persistence = this.ctx.get('sessionPersistence') - if (persistence !== undefined) { - this.known = new Set((await persistence.list()).map(header => header.id)) + this.global = domain.global + this.state = domain.global.get() + + this.validateStoredState(this.state) + if (!this.state.initialized) { + const headers = await this.ctx.sessionPersistence.list() + await this.replaceHeaderIndex(headers) + await this.bootstrap(headers) + } else if (this.table.size > 0) { + await this.replaceHeaderIndex(await this.ctx.sessionPersistence.list()) } - // Rebuild entities, rejecting states the write side makes structurally - // impossible (an external medium edit is the only way in, and hiding it - // would silently pick a winner): one session accounted under two - // workspaces, or two records claiming one canonical path (plain string - // equality — stored paths are already canonical, so no realpath here). - const accounted = new Map() + + await this.indexLiveSessions() + this.validateStoredState(this.requireState()) + this.rebuildEntities() + this.reportFilteredCandidates() + // Session activity is authoritative even when no RPC/SSE consumer is + // connected. This service-owned listener is disposed with the registry. + this.ctx.on('session/event', (session) => { + void this.touchSession(session.id).catch((error: unknown) => { + this.ctx.logger.warn(`workspace activity touch failed for session '${session.id}': ${String(error)}`) + }) + }) + } + + /** + * Create or reuse a workspace for an existing directory. The path is + * canonicalized through `fs.realpath`; a nonexistent path rejects with the + * original error and a non-directory rejects. Repeated calls for the same + * canonical path return the existing entity without changing its title. + * A newly created workspace is prepended to the durable registry order. + * A different canonical path cannot create a duplicate display title. + * @param path - Existing directory to own, in any path spelling. + * @param title - Display title used only when a new record is created. + * @returns the existing or newly durable workspace. + */ + async create(path: string, title?: string): Promise { + const canonical = await realpathNormalize(path) + if (!(await stat(canonical)).isDirectory()) { + throw new Error(`cannot create a workspace at '${canonical}': path is not a directory`) + } + return await this.enqueueOperation(() => this.createCanonical(canonical, title)) + } + + /** + * Look up a workspace by id. + * @param id - Workspace id. + * @returns the workspace, or `undefined` when unknown. + */ + get(id: WorkspaceId): Workspace | undefined { + return this.entities.get(id) + } + + /** + * Synchronous workspace projection in durable registry order. Every + * entity's `sessionIds` getter is already filtered by the startup/live + * canonical-cwd header index; this method performs no persistence reads. + * @returns a fresh ordered array of workspace entities. + */ + list(): Workspace[] { + return this.requireState().workspaceIds.map((id) => { + const entity = this.entities.get(id) + if (entity === undefined) { + throw new Error(`workspace registry order references missing workspace '${id}'`) + } + return entity + }) + } + + /** + * Move one accounted, cwd-validated session to the front of its workspace. + * Ungrouped sessions and candidates filtered by the header check are + * no-ops. The owning workspace's relative position never changes. + * @param sessionId - Session whose activity was observed. + * @returns resolution after the possible record write. + */ + async touchSession(sessionId: SessionId): Promise { + const pending = this.pendingTouches.get(sessionId) + if (pending !== undefined) { + await pending + return + } + for (const entity of this.entities.values()) { + if (!entity.hasSession(sessionId)) continue + const touch = entity.touchSession(sessionId) + this.pendingTouches.set(sessionId, touch) + try { + await touch + } finally { + this.pendingTouches.delete(sessionId) + } + return + } + } + + /** + * Resolve by canonical directory path without creating or mutating a + * workspace. A missing path rejects during `realpath`; an existing unowned + * directory returns `undefined`. + * @param path - Existing directory path in any spelling. + * @returns the workspace owning the canonical path, when one exists. + */ + async resolveByPath(path: string): Promise { + const canonical = await realpathNormalize(path) + for (const entity of this.entities.values()) { + if (entity.path === canonical) return entity + } + return undefined + } + + private async createCanonical(canonical: string, title?: string): Promise { + for (const entity of this.entities.values()) { + if (entity.path === canonical) return entity + } + + const workspaceName = title ?? basename(canonical) + if ([...this.entities.values()].some(entity => entity.title === workspaceName)) { + throw new WorkspaceNameConflictError(workspaceName) + } + + const table = this.requireTable() + const state = this.requireState() + const id = WorkspaceId(randomUUID()) + const now = new Date().toISOString() + const record: WorkspaceRecord = { + path: canonical, + title: workspaceName, + sessionIds: [], + createdAt: now, + updatedAt: now, + } + const entity = new WorkspaceEntity(this.host, id, record) + this.entities.set(id, entity) + try { + await table.put(id, record) + } catch (error) { + this.entities.delete(id) + throw error + } + + try { + await this.setState({ initialized: true, workspaceIds: [id, ...state.workspaceIds] }) + } catch (error) { + this.entities.delete(id) + try { + await table.delete(id) + } catch (rollbackError) { + this.entities.set(id, entity) + throw new AggregateError( + [error, rollbackError], + `workspace '${id}' was stored but its registry order and rollback both failed`, + ) + } + throw error + } + return entity + } + + private async bootstrap(headers: readonly SessionHeader[]): Promise { + const table = this.requireTable() + const state = this.requireState() + const groupsByPath = new Map() + for (const header of headers) { + const path = this.sessionPaths.get(header.id) + if (path === undefined) continue + const group = groupsByPath.get(path) + if (group === undefined) groupsByPath.set(path, [header]) + else group.push(header) + } + const groups: BootstrapGroup[] = [...groupsByPath].map(([path, groupHeaders]) => { + groupHeaders.sort(compareHeaders) + const newest = groupHeaders[0] as SessionHeader + return { path, headers: groupHeaders, newestAt: newest.createdAt } + }).sort((left, right) => + right.newestAt - left.newestAt || left.path.localeCompare(right.path)) + + const byPath = new Map() + const accounted = new Map() + for (const [id, record] of table.entries()) { + byPath.set(record.path, id) + for (const sessionId of record.sessionIds) accounted.set(sessionId, id) + } + + for (const group of groups) { + let id = byPath.get(group.path) + if (id === undefined) { + const sessionIds = group.headers + .map(header => header.id) + .filter(sessionId => !accounted.has(sessionId)) + if (sessionIds.length === 0) continue + id = WorkspaceId(randomUUID()) + const createdAt = new Date(group.newestAt).toISOString() + const record: WorkspaceRecord = { + path: group.path, + title: basename(group.path), + sessionIds, + createdAt, + updatedAt: createdAt, + } + await table.put(id, record) + byPath.set(group.path, id) + for (const sessionId of sessionIds) accounted.set(sessionId, id) + continue + } + + const current = table.get(id) as WorkspaceRecord + const historical = group.headers + .map(header => header.id) + .filter(sessionId => accounted.get(sessionId) === undefined || accounted.get(sessionId) === id) + const historicalSet = new Set(historical) + const sessionIds = [ + ...historical, + ...current.sessionIds.filter(sessionId => !historicalSet.has(sessionId)), + ] + if (sameSessionIds(current.sessionIds, sessionIds)) continue + await table.update(id, record => ({ + ...record, + sessionIds, + updatedAt: new Date().toISOString(), + })) + for (const sessionId of historical) accounted.set(sessionId, id) + } + + const groupRank = new Map(groups.map(group => [group.path, group.newestAt])) + const priorRank = new Map(state.workspaceIds.map((id, index) => [id, index])) + const workspaceIds = [...table.entries()] + .sort(([leftId, left], [rightId, right]) => { + const leftTime = groupRank.get(left.path) ?? Date.parse(left.createdAt) + const rightTime = groupRank.get(right.path) ?? Date.parse(right.createdAt) + return rightTime - leftTime + || (priorRank.get(leftId) ?? Number.MAX_SAFE_INTEGER) + - (priorRank.get(rightId) ?? Number.MAX_SAFE_INTEGER) + || String(leftId).localeCompare(String(rightId)) + }) + .map(([id]) => id) + + if (!sameIds(state.workspaceIds, workspaceIds)) { + await this.setState({ initialized: false, workspaceIds }) + } + await this.setState({ initialized: true, workspaceIds }) + } + + private validateStoredState(state: WorkspaceDomainState): void { + const table = this.requireTable() + const order = new Set() + for (const id of state.workspaceIds) { + if (order.has(id)) { + throw new Error(`workspace domain is inconsistent: registry order repeats workspace '${id}'`) + } + if (table.get(id) === undefined) { + throw new Error(`workspace domain is inconsistent: registry order references missing workspace '${id}'`) + } + order.add(id) + } + if (state.initialized && order.size !== table.size) { + const orphan = [...table.keys()].find(id => !order.has(id)) + throw new Error( + `workspace domain is inconsistent: workspace '${orphan as WorkspaceId}' is absent from registry order`, + ) + } + const paths = new Map() - for (const [id, record] of this.table.entries()) { + const accounted = new Map() + for (const [id, record] of table.entries()) { const pathHolder = paths.get(record.path) if (pathHolder !== undefined) { throw new Error( @@ -118,114 +386,112 @@ export class WorkspaceRegistry extends Service { } accounted.set(sessionId, id) } + } + } + + private rebuildEntities(): void { + this.entities.clear() + for (const id of this.requireState().workspaceIds) { + const record = this.requireTable().get(id) as WorkspaceRecord this.entities.set(id, new WorkspaceEntity(this.host, id, record)) } } - /** - * Create a workspace over an existing directory. The path is canonicalized - * through `fs.realpath` first — a nonexistent path rejects with the - * original `ENOENT`, a path resolving to anything but a directory rejects, - * and a canonical path already owned by another workspace (including a - * symlink resolving to it) rejects. - * @param path - Directory the workspace points at; canonicalized before storing. - * @param title - Display title; defaults to `basename` of the canonical path. - * @returns the created workspace after durability. - */ - async create(path: string, title?: string): Promise { - const table = this.requireTable() - const canonical = await realpathNormalize(path) - if (!(await stat(canonical)).isDirectory()) { - throw new Error(`cannot create a workspace at '${canonical}': path is not a directory`) + private async replaceHeaderIndex(headers: readonly SessionHeader[]): Promise { + this.headers.clear() + this.sessionPaths.clear() + this.invalidSessionPaths.clear() + await this.indexHeaders(headers) + } + + private async indexHeaders(headers: readonly SessionHeader[]): Promise { + for (const header of headers) await this.indexHeader(header) + } + + private async indexHeader(header: SessionHeader): Promise { + this.headers.set(header.id, header) + this.sessionPaths.delete(header.id) + if (header.cwd === undefined) { + this.invalidSessionPaths.set(header.id, 'header has no cwd') + return } + try { + const path = await realpathNormalize(header.cwd) + if (!(await stat(path)).isDirectory()) { + this.invalidSessionPaths.set(header.id, `cwd '${header.cwd}' is not a directory`) + return + } + this.sessionPaths.set(header.id, path) + this.invalidSessionPaths.delete(header.id) + } catch { + this.invalidSessionPaths.set(header.id, `cwd '${header.cwd}' does not resolve`) + } + } + + private async indexLiveSessions(): Promise { + const sessions = this.ctx.get('sessions') + if (sessions === undefined) return + await this.indexHeaders(sessions.list().map(session => session.header)) + } + + private reportFilteredCandidates(): void { for (const entity of this.entities.values()) { - if (entity.path === canonical) { - throw new Error(`a workspace for '${canonical}' already exists ('${entity.id}')`) + const record = this.requireTable().get(entity.id) as WorkspaceRecord + for (const sessionId of record.sessionIds) { + const path = this.sessionPaths.get(sessionId) + if (path === record.path) continue + const reason = this.invalidSessionPaths.get(sessionId) + ?? (this.headers.has(sessionId) + ? `canonical cwd '${path}' differs from workspace path '${record.path}'` + : 'session header is missing') + this.ctx.logger.warn( + `workspace '${entity.id}' filtered session '${sessionId}' from membership: ${reason}`, + ) } } - const id = WorkspaceId(randomUUID()) - const now = new Date().toISOString() - const record: WorkspaceRecord = { - path: canonical, - title: title ?? basename(canonical), - sessionIds: [], - createdAt: now, - updatedAt: now, - } - const entity = new WorkspaceEntity(this.host, id, record) - // Cache before the durable put: a concurrent same-path create fails the - // scan above, and the entity already exists when `domain/changed` fires. - this.entities.set(id, entity) - try { - await table.put(id, record) - } catch (error) { - this.entities.delete(id) - throw error - } - return entity } - /** - * Look up a workspace by id. - * @param id - The workspace id. - * @returns the workspace, or `undefined` when unknown. - */ - get(id: WorkspaceId): Workspace | undefined { - return this.entities.get(id) - } - - /** - * Snapshot of all workspaces, in load-then-creation order. - * @returns a fresh array of the cached entities. - */ - list(): Workspace[] { - return [...this.entities.values()] - } - - /** - * Resolve a workspace by directory path, through the same `fs.realpath` - * canon as {@link create} (hence async). A path that does not exist rejects - * with the original error — a missing directory has no canonical form to - * compare (a workspace whose recorded directory vanished is only reachable - * by id; see `Workspace.status`). - * @param path - Directory path in any spelling (symlinks, `..`, trailing slash). - * @returns the owning workspace, or `undefined` when none matches. - */ - async resolveByPath(path: string): Promise { - const canonical = await realpathNormalize(path) - for (const entity of this.entities.values()) { - if (entity.path === canonical) return entity - } - return undefined - } - - private requireTable(): KvTable { - if (this.table === undefined) { - throw new Error('workspace registry is not started yet') - } - return this.table - } - - /** - * Read one stored session header for attach validation, refreshing the - * known-session view from the same listing. Rejects when session - * persistence is absent or holds no session with this id. - */ private async readSessionHeader(id: SessionId): Promise { - const persistence = this.ctx.get('sessionPersistence') - if (persistence === undefined) { - throw new Error( - `cannot validate session '${id}': no session persistence service is available`, - ) + const live = this.ctx.get('sessions')?.get(id) + if (live !== undefined) { + this.headers.set(id, live.header) + return live.header } - const headers = await persistence.list() - this.known = new Set(headers.map(header => header.id)) - const header = headers.find(candidate => candidate.id === id) + const cached = this.headers.get(id) + if (cached !== undefined) return cached + + const headers = await this.ctx.sessionPersistence.list() + await this.indexHeaders(headers) + const header = this.headers.get(id) if (header === undefined) { throw new Error(`cannot validate session '${id}': session persistence holds no such session`) } return header } + + private requireTable(): KvTable { + if (this.table === undefined) throw new Error('workspace registry is not started yet') + return this.table + } + + private requireState(): WorkspaceDomainState { + if (this.state === undefined) throw new Error('workspace registry is not started yet') + return this.state + } + + private async setState(state: WorkspaceDomainState): Promise { + await (this.global as DomainGlobal).set(state) + this.state = state + } + + private enqueueOperation(operation: () => Promise): Promise { + const result = this.operationTail.then(operation) + this.operationTail = result.then(() => {}, () => {}) + return result + } } +const sameSessionIds = (left: readonly SessionId[], right: readonly SessionId[]): boolean => + left.length === right.length && left.every((id, index) => id === right[index]) + export default WorkspaceRegistry diff --git a/packages/workspace/workspace/src/invariant.ts b/packages/workspace/workspace/src/invariant.ts index 70c9ea4b48..1764ce2fe3 100644 --- a/packages/workspace/workspace/src/invariant.ts +++ b/packages/workspace/workspace/src/invariant.ts @@ -19,19 +19,22 @@ export const inject = ['invariants'] * Owned relationship: the registry's entity cache mirrors the workspace * domain's durable table. Every `domain/changed` for the `workspaces` table * must name a record the cache already holds an entity for (the registry - * caches before the durable put and mutates only through cached entities), - * and no `deleted` operation may appear at all — this phase ships no delete - * entry point, so a deletion proves a write path outside the registry. + * caches before the durable put and mutates only through cached entities). + * A delete is valid only for create rollback, after the provisional cache + * entry has been removed; deleting a published entity proves a bypass. */ const install: InvariantInstaller = Object.assign( (ctx: Context, fail: (message: string) => never) => { ctx.on('domain/changed', (change: DomainChanged) => { if (change.domain !== 'workspace' || change.table !== 'workspaces') return if (change.operation === 'deleted') { - fail( - `workspace record '${change.key}' emitted a deleted change, but the registry ` - + 'exposes no delete entry point — some write path bypassed ctx.workspace', - ) + if (ctx.workspace.get(WorkspaceId(change.key)) !== undefined) { + fail( + `workspace record '${change.key}' was deleted while the registry cache still ` + + 'publishes it — some write path bypassed ctx.workspace', + ) + } + return } if (ctx.workspace.get(WorkspaceId(change.key)) === undefined) { fail( diff --git a/packages/workspace/workspace/src/spec.ts b/packages/workspace/workspace/src/spec.ts index 7ef1487bd7..8df908949a 100644 --- a/packages/workspace/workspace/src/spec.ts +++ b/packages/workspace/workspace/src/spec.ts @@ -10,6 +10,9 @@ import { SessionId } from '@deepseek-ai/dsh-session' import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain' import type { WorkspaceId } from './types.ts' +/** Workspace id schema at the durable boundary; branding has no runtime representation. */ +const workspaceId = z.string().transform(value => value as WorkspaceId) + /** * Durable shape of one workspace record. `path` is the `fs.realpath` canon * stamped at create; `sessionIds` is the ordered ownership account (array @@ -26,14 +29,31 @@ export const workspaceRecord = z.object({ /** One stored workspace record, inferred from {@link workspaceRecord}. */ export type WorkspaceRecord = z.infer +/** + * Durable registry state. `initialized` distinguishes a valid empty registry + * from one that still needs the header-only history bootstrap; + * `workspaceIds` is the authoritative display order. + */ +export const workspaceDomainState = z.object({ + initialized: z.boolean(), + workspaceIds: z.array(workspaceId), +}) + +/** Durable registry state inferred from {@link workspaceDomainState}. */ +export type WorkspaceDomainState = z.infer + /** * The workspace domain spec: one `workspaces` table keyed by - * {@link WorkspaceId}, no global singleton. The registry opens this through - * `ctx.storage.domain`; the spec object is the single source of the domain's - * identity, version, and record schema. + * {@link WorkspaceId} plus the bootstrap/order singleton. The registry opens + * this through `ctx.storage.domain`; the spec object is the single source of + * the domain's identity, version, and schemas. */ export const workspaceDomainSpec = defineDomain({ name: 'workspace', - version: 1, + version: 2, + global: { + schema: workspaceDomainState, + initial: { initialized: false, workspaceIds: [] }, + }, tables: { workspaces: domainTable(workspaceRecord) }, }) diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts index cc5d75653d..ca254ca2cb 100644 --- a/packages/workspace/workspace/src/types.ts +++ b/packages/workspace/workspace/src/types.ts @@ -16,9 +16,9 @@ export type WorkspaceId = Branded<'WorkspaceId'> /** * One workspace: a stable id over an existing directory, a display title, and - * the ordered account of sessions that belong to it. The account is the sole - * source of ownership — sessions are never inferred from cwd. Consumers only - * see this interface; the entity implementation stays package-private. + * an ordered candidate account of sessions. Membership requires both an id in + * that account and a session header whose canonical cwd equals the workspace + * path. Consumers only see this interface; the implementation stays private. */ export interface Workspace { /** Stable record id (generated uuid). */ @@ -34,13 +34,17 @@ export interface Workspace { /** Display title. Defaults to `basename(path)` at create; duplicates are allowed. */ readonly title: string + /** ISO-8601 creation instant, stamped at create and never rewritten. */ + readonly createdAt: string + + /** ISO-8601 instant of the last durable mutation (create counts as one). */ + readonly updatedAt: string + /** - * Sessions recorded under this workspace, in attach order (the array order - * is the display order). A projection: accounted ids whose session no - * longer exists in session persistence are filtered out here (and dropped - * from the durable account on the next mutation); when session persistence - * is absent the account is served unfiltered because membership cannot be - * verified. + * Header-validated sessions in newest-first display order. The durable + * candidate account is filtered synchronously: missing headers, invalid + * cwd values, and canonical cwd mismatches are never returned. A subsequent + * workspace mutation prunes those filtered candidates durably. */ readonly sessionIds: readonly SessionId[] @@ -52,16 +56,12 @@ export interface Workspace { setTitle(title: string): Promise /** - * Record a session under this workspace. Idempotent: a session already on - * the account resolves without writing (membership is decided on the - * domain write chain, so unawaited concurrent attach/detach calls settle - * in call order). For a session not yet on the account, its stored header - * is read from session persistence and its `cwd`, normalized through the - * same `fs.realpath` canon as workspace paths, must equal this workspace's - * {@link path} — a missing persistence service, an unknown session id, a - * header without `cwd`, a `cwd` that no longer resolves, or a mismatched - * `cwd` all reject without touching the account (what cannot be validated - * is not recorded). + * Prepend a session to this workspace's candidate account. An already + * accounted id resolves without writing; activity-driven reordering uses + * `WorkspaceRegistry.touchSession` instead. A new id's live or persisted + * header cwd must resolve to an existing directory equal to {@link path}; + * unknown ids, missing or invalid cwd values, and mismatches reject without + * writing. * @param sessionId - The session to record. * @returns resolution after durability. */ diff --git a/packages/workspace/workspace/tests/invariant.spec.ts b/packages/workspace/workspace/tests/invariant.spec.ts index 583c516937..ea1fbaa64c 100644 --- a/packages/workspace/workspace/tests/invariant.spec.ts +++ b/packages/workspace/workspace/tests/invariant.spec.ts @@ -43,10 +43,15 @@ describe('workspace cache/table invariant', () => { expect(() => { ctx.emit('domain/changed', put({ table: 'other', key: 'missing' })) }).not.toThrow() }) - it('fails a deleted operation — this phase exposes no delete entry point', async () => { + it('fails deletion while the registry still publishes the entity', async () => { const ctx = await setup(['w1']) expect(() => { ctx.emit('domain/changed', deleted()) }) - .toThrow(/no delete entry point/) + .toThrow(/cache still publishes/) + }) + + it('allows deletion only after a provisional create cache entry was removed for rollback', async () => { + const ctx = await setup([]) + expect(() => { ctx.emit('domain/changed', deleted()) }).not.toThrow() }) it('fails a put whose record the registry cache does not hold', async () => { diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index 9d2c71c5cc..cde0b35098 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { basename, join } from 'node:path' @@ -7,103 +7,158 @@ import Storage from '@deepseek-ai/dsh-storage' import type { StorageBackend } from '@deepseek-ai/dsh-storage' import { DomainFacility } from '@deepseek-ai/dsh-storage-domain' import type { DomainChanged } from '@deepseek-ai/dsh-storage-domain' -import { SessionId } from '@deepseek-ai/dsh-session' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionHeader } from '@deepseek-ai/dsh-session' import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts' -import WorkspaceRegistry, { WorkspaceId } from '../src/index.ts' -import type { WorkspaceRecord } from '../src/index.ts' +import { WorkspaceEntity } from '../src/entity.ts' +import WorkspaceRegistry, { WorkspaceId, WorkspaceNameConflictError } from '../src/index.ts' +import type { WorkspaceDomainState, WorkspaceRecord } from '../src/index.ts' -const header = (id: string, cwd?: string): SessionHeader => - ({ version: 0, id: SessionId(id), createdAt: 0, ...(cwd === undefined ? {} : { cwd }) }) +const DOMAIN_VERSION = 2 -/** - * Boot storage hub + memory backend + domain form + the workspace registry. - * `sessions: 'absent'` boots without a sessionPersistence service; otherwise - * a stub serving exactly the given headers from `list()` is provided, and - * `setSessions` swaps what it serves next. - */ -async function harness(options?: { +const header = (id: string, cwd?: string, createdAt = 0): SessionHeader => ({ + version: 0, + id: SessionId(id), + createdAt, + ...(cwd === undefined ? {} : { cwd }), +}) + +interface HarnessOptions { pool?: MemoryMediaPool - sessions?: SessionHeader[] | 'absent' + sessions?: SessionHeader[] + liveSessions?: SessionHeader[] + sessionStore?: boolean backend?: StorageBackend -}) { +} + +/** Boot the real storage/domain/registry composition over controllable header-only peers. */ +async function harness(options: HarnessOptions = {}) { + const pool = options.pool ?? new MemoryMediaPool() const ctx = new Context() await ctx.plugin(Storage) - ctx.storage.backend.register('memory', options?.backend ?? new MemoryStorageBackend(options?.pool)) - ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) - let listed = options?.sessions === 'absent' ? undefined : options?.sessions ?? [] - if (listed !== undefined) { - ctx.provide('sessionPersistence', { list: async () => listed ?? [] }) + ctx.storage.backend.register('memory', options.backend ?? new MemoryStorageBackend(pool)) + const facility = new DomainFacility(ctx, { backend: 'memory', routes: {} }) + ctx.storage.mount('domain', facility) + ctx.provide('storageDomain', facility) + + let listed = options.sessions ?? [] + const list = vi.fn(async () => listed) + const load = vi.fn(() => { throw new Error('event bodies must not be loaded') }) + const inspect = vi.fn(() => { throw new Error('event bodies must not be inspected') }) + ctx.provide('sessionPersistence', { list, load, inspect } as never) + + if (options.sessionStore === true) { + await ctx.plugin(SessionStore) + } else if (options.liveSessions !== undefined) { + const live = new Map(options.liveSessions.map(meta => [meta.id, { header: meta }])) + ctx.provide('sessions', { + get: (id: SessionId) => live.get(id), + list: () => [...live.values()], + } as never) } + const changes: DomainChanged[] = [] ctx.on('domain/changed', (change) => { changes.push(change) }) - await ctx.plugin(WorkspaceRegistry) + const fiber = await ctx.plugin(WorkspaceRegistry) + const initChanges = [...changes] + changes.length = 0 return { ctx, + fiber, + pool, registry: ctx.workspace, changes, + initChanges, + list, + load, + inspect, setSessions: (headers: SessionHeader[]) => { listed = headers }, } } -/** A memory backend whose next `putRecord` throws once when armed, for write-failure paths. */ -function failingBackend(): { backend: StorageBackend; arm: () => void } { - const inner = new MemoryStorageBackend() - let failNext = false +/** Boot only the storage side, for dependency-pending and startup-failure cases. */ +async function storageContext(pool: MemoryMediaPool, backend: StorageBackend = new MemoryStorageBackend(pool)) { + const ctx = new Context() + await ctx.plugin(Storage) + ctx.storage.backend.register('memory', backend) + const facility = new DomainFacility(ctx, { backend: 'memory', routes: {} }) + ctx.storage.mount('domain', facility) + ctx.provide('storageDomain', facility) + return ctx +} + +/** Backend wrapper that injects one selected bootstrap write failure. */ +function selectiveFailureBackend( + pool: MemoryMediaPool, + failure: { putAt?: number; deleteAt?: number; globalAt?: number }, +): StorageBackend { + const inner = new MemoryStorageBackend(pool) + let puts = 0 + let deletes = 0 + let globals = 0 return { - arm: () => { failNext = true }, - backend: { - kv: { - open: async (descriptor) => { - const unit = await inner.kv.open(descriptor) - return { - loadAll: () => unit.loadAll(), - putRecord: async (table, key, value) => { - if (failNext) { - failNext = false - throw new Error('medium write failed (injected)') - } - return unit.putRecord(table, key, value) - }, - deleteRecord: (table, key) => unit.deleteRecord(table, key), - setGlobal: value => unit.setGlobal(value), - close: () => unit.close(), - } - }, + kv: { + open: async (descriptor) => { + const unit = await inner.kv.open(descriptor) + return { + loadAll: () => unit.loadAll(), + putRecord: async (table, key, value) => { + puts += 1 + if (puts === failure.putAt) throw new Error('selected bootstrap put failure') + await unit.putRecord(table, key, value) + }, + deleteRecord: async (table, key) => { + deletes += 1 + if (deletes === failure.deleteAt) throw new Error('selected rollback delete failure') + await unit.deleteRecord(table, key) + }, + setGlobal: async (value) => { + globals += 1 + if (globals === failure.globalAt) throw new Error('selected bootstrap marker failure') + await unit.setGlobal(value) + }, + close: () => unit.close(), + } }, - close: () => inner.close(), }, + close: () => inner.close(), } } -/** A pool pre-stamped with one stored workspace record, simulating a prior run. */ -function pooledRecord(id: string, record: WorkspaceRecord): MemoryMediaPool { +function record(path: string, sessionIds: string[], createdAt = '2026-07-24T00:00:00.000Z'): WorkspaceRecord { + return { + path, + title: basename(path), + sessionIds: sessionIds.map(SessionId), + createdAt, + updatedAt: createdAt, + } +} + +function storedPool( + entries: Array<[string, WorkspaceRecord]>, + state: WorkspaceDomainState, +): MemoryMediaPool { const pool = new MemoryMediaPool() - pool.versions.set('workspace', 1) + pool.versions.set('workspace', DOMAIN_VERSION) pool.media.set('workspace', { - tables: new Map([['workspaces', new Map([[id, record]])]]), - global: null, + tables: new Map([['workspaces', new Map(entries)]]), + global: state, }) return pool } -const record = (path: string, sessionIds: string[]): WorkspaceRecord => ({ - path, - title: basename(path), - sessionIds: sessionIds.map(SessionId), - createdAt: '2026-07-24T00:00:00.000Z', - updatedAt: '2026-07-24T00:00:00.000Z', -}) - -/** Stored record as the memory medium currently holds it. */ function storedRecord(pool: MemoryMediaPool, id: string): WorkspaceRecord { return pool.media.get('workspace')!.tables.get('workspaces')!.get(id) as WorkspaceRecord } +function storedState(pool: MemoryMediaPool): WorkspaceDomainState { + return pool.media.get('workspace')!.global as WorkspaceDomainState +} + let base: string const tempDirs: string[] = [] -/** A fresh real directory under a canonicalized temp base. */ async function makeDir(name: string): Promise { base ??= await realpath(await mkdtemp(join(tmpdir(), 'dsh-workspace-'))) if (tempDirs.length === 0) tempDirs.push(base) @@ -117,265 +172,540 @@ afterEach(async () => { base = undefined as never }) -describe('WorkspaceRegistry.create', () => { - it('stores the canonical path, defaults the title to basename, and lists the entity', async () => { - const dir = await makeDir('proj') - const { registry } = await harness() - const workspace = await registry.create(dir + '/') - expect(workspace.path).toBe(dir) - expect(workspace.title).toBe('proj') - expect(workspace.sessionIds).toEqual([]) - expect(registry.list()).toEqual([workspace]) - expect(registry.get(workspace.id)).toBe(workspace) - const titled = await registry.create(await makeDir('other'), 'Custom') - expect(titled.title).toBe('Custom') +describe('WorkspaceRegistry lifecycle and bootstrap', () => { + it('stays pending without sessionPersistence and never opens or marks the domain', async () => { + const pool = new MemoryMediaPool() + const ctx = await storageContext(pool) + const fiber = await ctx.plugin(WorkspaceRegistry) + expect(ctx.get('workspace')).toBeUndefined() + expect(pool.media.has('workspace')).toBe(false) + + const list = vi.fn(async () => [] as SessionHeader[]) + ctx.provide('sessionPersistence', { list } as never) + await fiber.await() + expect(ctx.workspace.list()).toEqual([]) + expect(list).toHaveBeenCalledTimes(1) + expect(storedState(pool)).toEqual({ initialized: true, workspaceIds: [] }) }) - it('rejects a nonexistent directory with the original ENOENT', async () => { - const dir = await makeDir('exists') - const { registry } = await harness() - await expect(registry.create(join(dir, 'nope'))).rejects.toMatchObject({ code: 'ENOENT' }) - expect(registry.list()).toEqual([]) + it('bootstraps once from list headers only, in workspace/session createdAt order', async () => { + const older = await makeDir('older') + const newer = await makeDir('newer') + const alias = join(base, 'older-link') + const plain = join(base, 'plain.txt') + await symlink(older, alias) + await writeFile(plain, 'not a directory') + const missing = join(base, 'missing') + const result = await harness({ + sessions: [ + header('older-first', older, 100), + header('newer-only', newer, 500), + header('older-latest', alias, 300), + header('no-cwd', undefined, 900), + header('missing-dir', missing, 800), + header('plain-file', plain, 700), + ], + }) + + expect(result.list).toHaveBeenCalledTimes(1) + expect(result.load).not.toHaveBeenCalled() + expect(result.inspect).not.toHaveBeenCalled() + expect(result.registry.list().map(workspace => workspace.path)).toEqual([newer, older]) + expect(result.registry.list().map(workspace => workspace.sessionIds)).toEqual([ + ['newer-only'], + ['older-latest', 'older-first'], + ]) + expect(storedState(result.pool)).toEqual({ + initialized: true, + workspaceIds: result.registry.list().map(workspace => workspace.id), + }) }) - it('rejects a path resolving to a plain file', async () => { - const dir = await makeDir('has-file') - const file = join(dir, 'plain.txt') - await writeFile(file, 'not a directory') - const { registry } = await harness() - await expect(registry.create(file)).rejects.toThrow(/not a directory/) - expect(registry.list()).toEqual([]) + it('breaks equal bootstrap timestamps by session id and canonical path', async () => { + const first = await makeDir('tie-first') + const second = await makeDir('tie-second') + const result = await harness({ + sessions: [ + header('z-session', first, 100), + header('a-session', first, 100), + header('second-session', second, 100), + ], + }) + expect(new Set(result.registry.list().map(workspace => workspace.path))).toEqual(new Set([first, second])) + expect(result.registry.list().find(workspace => workspace.path === first)!.sessionIds) + .toEqual(['a-session', 'z-session']) }) - it('rejects a duplicate path, including a symlink resolving to an existing workspace', async () => { - const dir = await makeDir('real') - const link = join(base, 'link') - await symlink(dir, link) - const { registry } = await harness() - await registry.create(dir) - await expect(registry.create(link)).rejects.toThrow(/already exists/) - expect(registry.list()).toHaveLength(1) + it('does not rerun bootstrap for a genuinely initialized empty registry', async () => { + const late = await makeDir('late-cwd-only') + const pool = new MemoryMediaPool() + const first = await harness({ pool, sessions: [] }) + expect(first.list).toHaveBeenCalledTimes(1) + await first.fiber.dispose() + + const second = await harness({ pool, sessions: [header('late', late, 100)] }) + expect(second.list).not.toHaveBeenCalled() + expect(second.registry.list()).toEqual([]) + expect(storedState(pool)).toEqual({ initialized: true, workspaceIds: [] }) }) - it('resolves by path through the same canon', async () => { - const dir = await makeDir('canon') - const link = join(base, 'canon-link') - await symlink(dir, link) - const { registry } = await harness() - const workspace = await registry.create(dir) - expect(await registry.resolveByPath(link)).toBe(workspace) - expect(await registry.resolveByPath(await makeDir('unowned'))).toBeUndefined() + it('reuses partial records after a bootstrap record write fails', async () => { + const firstDir = await makeDir('partial-first') + const secondDir = await makeDir('partial-second') + const sessions = [header('first', firstDir, 200), header('second', secondDir, 100)] + const pool = new MemoryMediaPool() + await expect(harness({ + pool, + sessions, + backend: selectiveFailureBackend(pool, { putAt: 2 }), + })).rejects.toThrow(/selected bootstrap put failure/) + expect(pool.media.get('workspace')!.tables.get('workspaces')!.size).toBe(1) + expect(pool.media.get('workspace')!.global).toBeNull() + + const retried = await harness({ pool, sessions }) + expect(retried.registry.list()).toHaveLength(2) + expect(pool.media.get('workspace')!.tables.get('workspaces')!.size).toBe(2) + expect(storedState(pool).initialized).toBe(true) }) - it('rolls the entity cache back when the durable write fails, leaving the path free to retry', async () => { - const dir = await makeDir('rollback') - const { backend, arm } = failingBackend() - const { registry } = await harness({ backend }) - arm() - await expect(registry.create(dir)).rejects.toThrow(/injected/) - expect(registry.list()).toEqual([]) - const retried = await registry.create(dir) - expect(retried.path).toBe(dir) + it('reuses durable order when the final initialized marker write fails', async () => { + const dir = await makeDir('marker-retry') + const sessions = [header('session', dir, 100)] + const pool = new MemoryMediaPool() + await expect(harness({ + pool, + sessions, + backend: selectiveFailureBackend(pool, { globalAt: 2 }), + })).rejects.toThrow(/selected bootstrap marker failure/) + expect(storedState(pool)).toMatchObject({ initialized: false }) + expect(storedState(pool).workspaceIds).toHaveLength(1) + + const retried = await harness({ pool, sessions }) + expect(retried.registry.list()).toHaveLength(1) + expect(pool.media.get('workspace')!.tables.get('workspaces')!.size).toBe(1) + expect(storedState(pool).initialized).toBe(true) }) - it('rejects any table access before the registry has started', async () => { - const dir = await makeDir('unstarted') - const ctx = new Context() - // Constructed directly, Service.init never ran: no domain, no table. - const registry = new WorkspaceRegistry(ctx) - await expect(registry.create(dir)).rejects.toThrow(/not started/) + it('merges partial records and leaves an already-accounted cwd drift ungrouped', async () => { + const owned = await makeDir('partial-owned') + const prior = await makeDir('partial-prior') + const drifted = await makeDir('partial-drifted') + const ownedId = WorkspaceId('00000000-0000-4000-8000-000000000010') + const priorId = WorkspaceId('00000000-0000-4000-8000-000000000011') + const pool = storedPool( + [ + [ownedId, record(owned, ['old'], '2026-07-24T00:00:00.000Z')], + [priorId, record(prior, ['drift'], '2026-07-23T00:00:00.000Z')], + ], + { initialized: false, workspaceIds: [] }, + ) + const result = await harness({ + pool, + sessions: [header('new', owned, 200), header('old', owned, 100), header('drift', drifted, 300)], + }) + expect(result.registry.list().map(workspace => workspace.id)).toContain(ownedId) + expect(result.registry.get(ownedId)!.sessionIds).toEqual(['new', 'old']) + expect(result.registry.list().some(workspace => workspace.path === drifted)).toBe(false) }) - it('closes its domain on fiber disposal so a re-plugged registry reopens it', async () => { + it('orders headerless partial records by prior order, then stable id', async () => { + const first = await makeDir('fallback-first') + const second = await makeDir('fallback-second') + const firstId = WorkspaceId('00000000-0000-4000-8000-000000000020') + const secondId = WorkspaceId('00000000-0000-4000-8000-000000000021') + const entries: Array<[string, WorkspaceRecord]> = [ + [secondId, record(second, [], '2026-07-24T00:00:00.000Z')], + [firstId, record(first, [], '2026-07-24T00:00:00.000Z')], + ] + const prior = await harness({ + pool: storedPool(entries, { initialized: false, workspaceIds: [secondId, firstId] }), + }) + expect(prior.registry.list().map(workspace => workspace.id)).toEqual([secondId, firstId]) + + const byId = await harness({ + pool: storedPool(entries, { initialized: false, workspaceIds: [] }), + }) + expect(byId.registry.list().map(workspace => workspace.id)).toEqual([firstId, secondId]) + }) + + it('closes its domain on disposal and reloads the persisted stable order', async () => { const dir = await makeDir('replug') - const ctx = new Context() - await ctx.plugin(Storage) - ctx.storage.backend.register('memory', new MemoryStorageBackend()) - ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) - const fiber = ctx.plugin(WorkspaceRegistry) - await fiber - const first = await ctx.workspace.create(dir) - await fiber.dispose() - // The registry's effect closed the domain, freeing the name: a second - // plugin of the same registry must reopen it (not already-open) and see - // the durable record. - await ctx.plugin(WorkspaceRegistry) - const reloaded = await ctx.workspace.resolveByPath(dir) - expect(reloaded?.id).toBe(first.id) + const result = await harness() + const first = await result.registry.create(dir) + await result.fiber.dispose() + const nextFiber = await result.ctx.plugin(WorkspaceRegistry) + expect(result.ctx.workspace.list().map(workspace => workspace.id)).toEqual([first.id]) + await nextFiber.dispose() }) }) -describe('Workspace.attachSession', () => { - it('attaches when the session cwd resolves to the workspace path, keeping attach order', async () => { - const dir = await makeDir('attach') - const link = join(base, 'attach-link') - await symlink(dir, link) - // s2's cwd is spelled through the symlink: same canon, must attach. - const { registry } = await harness({ - sessions: [header('s1', dir), header('s2', link), header('s3', dir)], - }) - const workspace = await registry.create(dir) - await workspace.attachSession(SessionId('s1')) - await workspace.attachSession(SessionId('s2')) - await workspace.attachSession(SessionId('s3')) - expect(workspace.sessionIds).toEqual(['s1', 's2', 's3']) - await workspace.detachSession(SessionId('s2')) - expect(workspace.sessionIds).toEqual(['s1', 's3']) +describe('WorkspaceRegistry create and lookup', () => { + it('creates newest-first and idempotently reuses a canonical path without retitling', async () => { + const firstDir = await makeDir('first') + const secondDir = await makeDir('second') + const alias = join(base, 'first-link') + await symlink(firstDir, alias) + const { registry, pool } = await harness() + const first = await registry.create(firstDir, 'Original') + const second = await registry.create(secondDir) + const reused = await registry.create(alias, 'Ignored') + expect(reused).toBe(first) + expect(first.title).toBe('Original') + expect(registry.list()).toEqual([second, first]) + expect(storedState(pool).workspaceIds).toEqual([second.id, first.id]) + expect(await registry.resolveByPath(alias)).toBe(first) + expect(await registry.resolveByPath(await makeDir('unowned'))).toBeUndefined() }) - it('rejects a cwd resolving elsewhere, a missing cwd, and an unknown session', async () => { + it('serializes concurrent same-path creates into one entity', async () => { + const dir = await makeDir('concurrent') + const { registry, pool } = await harness() + const [left, right] = await Promise.all([ + registry.create(dir, 'Winner'), + registry.create(dir, 'Loser'), + ]) + expect(left).toBe(right) + expect(registry.list()).toEqual([left]) + expect(pool.media.get('workspace')!.tables.get('workspaces')!.size).toBe(1) + }) + + it('rejects a duplicate display name on a different canonical path', async () => { + const firstDir = await makeDir('named-first') + const secondDir = await makeDir('named-second') + const { registry } = await harness() + await registry.create(firstDir, 'Shared') + await expect(registry.create(secondDir, 'Shared')).rejects.toEqual( + expect.objectContaining>({ + workspaceName: 'Shared', + }), + ) + expect(registry.list()).toHaveLength(1) + }) + + it('rejects nonexistent and non-directory paths without changing order', async () => { + const parent = await makeDir('invalid') + const file = join(parent, 'plain.txt') + await writeFile(file, 'file') + const { registry } = await harness() + await expect(registry.create(join(parent, 'missing'))).rejects.toMatchObject({ code: 'ENOENT' }) + await expect(registry.create(file)).rejects.toThrow(/not a directory/) + await expect(registry.resolveByPath(join(parent, 'missing'))).rejects.toMatchObject({ code: 'ENOENT' }) + expect(registry.list()).toEqual([]) + }) + + it('rolls back the provisional cache when the record write fails', async () => { + const dir = await makeDir('write-failure') + const result = await harness() + result.pool.failNextWrites = 1 + await expect(result.registry.create(dir)).rejects.toThrow(/injected/) + expect(result.registry.list()).toEqual([]) + expect(await result.registry.create(dir)).toBeDefined() + }) + + it('rolls back a record when registry-order persistence fails', async () => { + const dir = await makeDir('order-write-failure') + const pool = new MemoryMediaPool() + const result = await harness({ + pool, + backend: selectiveFailureBackend(pool, { globalAt: 2 }), + }) + await expect(result.registry.create(dir)).rejects.toThrow(/marker failure/) + expect(result.registry.list()).toEqual([]) + expect(pool.media.get('workspace')!.tables.get('workspaces')!.size).toBe(0) + }) + + it('reports both order and rollback failures while retaining the recoverable record', async () => { + const dir = await makeDir('rollback-write-failure') + const pool = new MemoryMediaPool() + const result = await harness({ + pool, + backend: selectiveFailureBackend(pool, { globalAt: 2, deleteAt: 1 }), + }) + await expect(result.registry.create(dir)).rejects.toBeInstanceOf(AggregateError) + expect(pool.media.get('workspace')!.tables.get('workspaces')!.size).toBe(1) + }) + + it('rejects table access before the registry has started', async () => { + const dir = await makeDir('unstarted') + const registry = new WorkspaceRegistry(new Context()) + await expect(registry.create(dir)).rejects.toThrow(/not started/) + expect(() => registry.list()).toThrow(/not started/) + }) +}) + +describe('Workspace session ordering', () => { + it('prepends new attaches, keeps repeat attach idempotent, and touches one id only', async () => { + const dir = await makeDir('attach-order') + const result = await harness() + result.setSessions([ + header('s1', dir, 1), + header('s2', dir, 2), + header('ungrouped', dir, 3), + ]) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('s1')) + await workspace.attachSession(SessionId('s2')) + expect(workspace.sessionIds).toEqual(['s2', 's1']) + await workspace.attachSession(SessionId('s1')) + expect(workspace.sessionIds).toEqual(['s2', 's1']) + + const beforeTouch = result.changes.length + await Promise.all([ + result.registry.touchSession(SessionId('s1')), + result.registry.touchSession(SessionId('s1')), + ]) + expect(workspace.sessionIds).toEqual(['s1', 's2']) + expect(result.changes).toHaveLength(beforeTouch + 1) + await result.registry.touchSession(SessionId('s1')) + expect(result.changes).toHaveLength(beforeTouch + 1) + await result.registry.touchSession(SessionId('ungrouped')) + expect(result.changes).toHaveLength(beforeTouch + 1) + expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s1', 's2']) + }) + + it('does not resurrect a session detached before its queued touch', async () => { + const dir = await makeDir('detach-touch-race') + const result = await harness({ sessions: [header('s1', dir), header('s2', dir)] }) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('s1')) + await workspace.attachSession(SessionId('s2')) + await Promise.all([ + workspace.detachSession(SessionId('s1')), + result.registry.touchSession(SessionId('s1')), + ]) + const written = result.changes.length + await workspace.detachSession(SessionId('absent')) + expect(result.changes).toHaveLength(written) + expect(workspace.sessionIds).toEqual(['s2']) + }) + + it('does not reinsert a candidate absent at the durable touch slot', async () => { + const dir = await makeDir('stale-touch') + const id = WorkspaceId('00000000-0000-4000-8000-000000000030') + let durable = record(dir, ['s2', 's1']) + const table = { + update: async ( + _id: WorkspaceId, + update: (current: WorkspaceRecord) => WorkspaceRecord, + ): Promise => { + durable = { ...durable, sessionIds: [SessionId('s2')] } + durable = update(durable) + return durable + }, + } + const entity = new WorkspaceEntity({ + table: () => table as never, + sessionPath: () => dir, + readSessionHeader: async () => header('s1', dir), + rememberSessionPath: () => {}, + }, id, record(dir, ['s2', 's1'])) + await entity.touchSession(SessionId('s1')) + expect(durable.sessionIds).toEqual(['s2']) + }) + + it('validates a lazy live session without requiring it in persistence.list()', async () => { + const dir = await makeDir('live') + const result = await harness({ sessions: [], liveSessions: [header('live', dir, 1)] }) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('live')) + expect(workspace.sessionIds).toEqual(['live']) + expect(result.list).toHaveBeenCalledTimes(1) + }) + + it('rejects mismatched, missing, unresolved, non-directory, and unknown cwd facts', async () => { const dir = await makeDir('strict') const elsewhere = await makeDir('elsewhere') - const { registry } = await harness({ - sessions: [header('other-dir', elsewhere), header('no-cwd', undefined)], - }) - const workspace = await registry.create(dir) - await expect(workspace.attachSession(SessionId('other-dir'))).rejects.toThrow(/resolves to/) + const gone = await makeDir('gone') + const file = join(base, 'cwd-file') + await writeFile(file, 'file') + const result = await harness() + result.setSessions([ + header('mismatch', elsewhere), + header('no-cwd'), + header('gone', gone), + header('file', file), + ]) + await rm(gone, { recursive: true }) + const workspace = await result.registry.create(dir) + await expect(workspace.attachSession(SessionId('mismatch'))).rejects.toThrow(/resolves to/) await expect(workspace.attachSession(SessionId('no-cwd'))).rejects.toThrow(/no cwd/) + await expect(workspace.attachSession(SessionId('gone'))).rejects.toThrow(/does not resolve/) + await expect(workspace.attachSession(SessionId('file'))).rejects.toThrow(/not a directory/) await expect(workspace.attachSession(SessionId('unknown'))).rejects.toThrow(/no such session/) expect(workspace.sessionIds).toEqual([]) }) - it('rejects a cwd that no longer resolves', async () => { - const dir = await makeDir('target') - const gone = await makeDir('gone') - const { registry } = await harness({ sessions: [header('s1', gone)] }) - const workspace = await registry.create(dir) - await rm(gone, { recursive: true }) - await expect(workspace.attachSession(SessionId('s1'))).rejects.toThrow(/does not resolve/) - }) - - it('rejects every attach while session persistence is absent', async () => { - const dir = await makeDir('no-persistence') - const { registry } = await harness({ sessions: 'absent' }) - const workspace = await registry.create(dir) - await expect(workspace.attachSession(SessionId('s1'))).rejects.toThrow(/no session persistence/) - }) - - it('is idempotent on both attach and detach — a no-op never writes', async () => { - const dir = await makeDir('idem') - const { registry, changes, setSessions } = await harness({ sessions: [header('s1', dir)] }) - const workspace = await registry.create(dir) - await workspace.attachSession(SessionId('s1')) - const written = changes.length - // Re-attaching skips validation entirely: even with the session gone from - // the listing, the id already being on the account resolves without IO. - setSessions([]) - await workspace.attachSession(SessionId('s1')) - await workspace.detachSession(SessionId('absent')) - expect(changes.length).toBe(written) - }) - - it('decides membership at the write-chain slot: unawaited detach then attach re-attaches', async () => { + it('decides detach/attach membership at domain write-chain slots', async () => { const dir = await makeDir('race') - const { registry } = await harness({ sessions: [header('s1', dir)] }) - const workspace = await registry.create(dir) + const result = await harness({ sessions: [header('s1', dir)] }) + const workspace = await result.registry.create(dir) await workspace.attachSession(SessionId('s1')) - // Both fire before either lands. Snapshot-based idempotence would see - // 's1' still on the account and turn the attach into a no-op, losing it; - // chain-slot decisions replay detach → attach in order. (The attach skips - // re-validation off the same stale snapshot — the cwd fact is immutable — - // and enqueues immediately, keeping the chain order deterministic here.) const detached = workspace.detachSession(SessionId('s1')) const attached = workspace.attachSession(SessionId('s1')) await Promise.all([detached, attached]) expect(workspace.sessionIds).toEqual(['s1']) }) + + it('keeps workspace order stable while touch order survives reload', async () => { + const older = await makeDir('stable-older') + const newer = await makeDir('stable-newer') + const sessions = [ + header('old-1', older, 100), + header('old-2', older, 200), + header('new-1', newer, 300), + ] + const pool = new MemoryMediaPool() + const first = await harness({ pool, sessions }) + const originalWorkspaceIds = first.registry.list().map(workspace => workspace.id) + const oldWorkspace = first.registry.list().find(workspace => workspace.path === older)! + expect(oldWorkspace.sessionIds).toEqual(['old-2', 'old-1']) + await first.registry.touchSession(SessionId('old-1')) + expect(oldWorkspace.sessionIds).toEqual(['old-1', 'old-2']) + expect(first.registry.list().map(workspace => workspace.id)).toEqual(originalWorkspaceIds) + await first.fiber.dispose() + + const reloaded = await harness({ pool, sessions }) + expect(reloaded.registry.list().map(workspace => workspace.id)).toEqual(originalWorkspaceIds) + expect(reloaded.registry.list().find(workspace => workspace.path === older)!.sessionIds) + .toEqual(['old-1', 'old-2']) + }) + + it('persists activity order from session/event without any stream consumer', async () => { + const dir = await makeDir('event-touch') + const result = await harness({ sessionStore: true }) + const workspace = await result.registry.create(dir) + const first = result.ctx.sessions.create(SessionId('event-first'), { meta: { cwd: dir } }) + result.ctx.sessions.create(SessionId('event-second'), { meta: { cwd: dir } }) + await workspace.attachSession(SessionId('event-first')) + await workspace.attachSession(SessionId('event-second')) + expect(workspace.sessionIds).toEqual(['event-second', 'event-first']) + + first.append('turn/start', { + turn: 1, + trigger: { kind: 'message', source: { kind: 'user' } }, + }) + await vi.waitFor(() => { expect(workspace.sessionIds).toEqual(['event-first', 'event-second']) }) + expect(storedRecord(result.pool, workspace.id).sessionIds) + .toEqual(['event-first', 'event-second']) + }) + + it('contains a background activity write failure at the service listener', async () => { + const dir = await makeDir('event-touch-failure') + const result = await harness({ sessionStore: true }) + const workspace = await result.registry.create(dir) + const first = result.ctx.sessions.create(SessionId('failed-first'), { meta: { cwd: dir } }) + result.ctx.sessions.create(SessionId('failed-second'), { meta: { cwd: dir } }) + await workspace.attachSession(SessionId('failed-first')) + await workspace.attachSession(SessionId('failed-second')) + const warn = vi.spyOn(result.ctx.logger, 'warn') + result.pool.failNextWrites = 1 + first.append('turn/start', { + turn: 1, + trigger: { kind: 'message', source: { kind: 'user' } }, + }) + await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith(expect.stringContaining('touch failed')) }) + expect(workspace.sessionIds).toEqual(['failed-second', 'failed-first']) + }) }) -describe('consistency projections', () => { - it('filters accounted ids with no stored session and prunes them on the next mutation', async () => { - const dir = await makeDir('stale') +describe('header-validated membership projection', () => { + it('requires both candidate id and matching canonical cwd without re-reading on list()', async () => { + const owned = await makeDir('owned') + const elsewhere = await makeDir('projection-elsewhere') const id = WorkspaceId('00000000-0000-4000-8000-000000000001') - const pool = pooledRecord(id, record(dir, ['live', 'ghost'])) - const { registry } = await harness({ pool, sessions: [header('live', dir)] }) - const workspace = registry.get(id)! - // Rule 1: the projection hides the dead id; the durable account still holds it. - expect(workspace.sessionIds).toEqual(['live']) - expect(storedRecord(pool, id).sessionIds).toEqual(['live', 'ghost']) - // Any mutation prunes it durably. - await workspace.setTitle('renamed') - expect(storedRecord(pool, id).sessionIds).toEqual(['live']) - expect(workspace.title).toBe('renamed') + const pool = storedPool( + [[id, record(owned, ['good', 'mismatch', 'missing'])]], + { initialized: true, workspaceIds: [id] }, + ) + const result = await harness({ + pool, + sessions: [ + header('good', owned), + header('mismatch', elsewhere), + header('cwd-only', owned), + ], + }) + const workspace = result.registry.list()[0]! + expect(workspace.sessionIds).toEqual(['good']) + expect(result.registry.list()[0]!.sessionIds).toEqual(['good']) + expect(result.list).toHaveBeenCalledTimes(1) + expect(storedRecord(pool, id).sessionIds).toEqual(['good', 'mismatch', 'missing']) + + await workspace.setTitle('pruned') + expect(storedRecord(pool, id).sessionIds).toEqual(['good']) + expect(workspace.sessionIds).not.toContain('cwd-only') }) - it('serves the account unfiltered while session persistence is absent', async () => { - const dir = await makeDir('unverifiable') - const id = WorkspaceId('00000000-0000-4000-8000-000000000002') - const pool = pooledRecord(id, record(dir, ['maybe'])) - const { registry } = await harness({ pool, sessions: 'absent' }) - const workspace = registry.get(id)! - expect(workspace.sessionIds).toEqual(['maybe']) - // Mutations must not prune either: unverifiable membership is kept as-is. - await workspace.setTitle('still-unverified') - expect(storedRecord(pool, id).sessionIds).toEqual(['maybe']) + it('rejects duplicate candidate ownership, duplicate paths, and initialized order drift', async () => { + const first = await makeDir('corrupt-first') + const second = await makeDir('corrupt-second') + const firstId = '00000000-0000-4000-8000-000000000002' + const secondId = '00000000-0000-4000-8000-000000000003' + const duplicateSession = storedPool( + [[firstId, record(first, ['dup'])], [secondId, record(second, ['dup'])]], + { initialized: true, workspaceIds: [WorkspaceId(firstId), WorkspaceId(secondId)] }, + ) + await expect(harness({ pool: duplicateSession })).rejects.toThrow(/accounted/) + + const duplicatePath = storedPool( + [[firstId, record(first, [])], [secondId, record(first, [])]], + { initialized: true, workspaceIds: [WorkspaceId(firstId), WorkspaceId(secondId)] }, + ) + await expect(harness({ pool: duplicatePath })).rejects.toThrow(/claimed/) + + const orphan = storedPool( + [[firstId, record(first, [])], [secondId, record(second, [])]], + { initialized: true, workspaceIds: [WorkspaceId(firstId)] }, + ) + await expect(harness({ pool: orphan })).rejects.toThrow(/absent from registry order/) + + const repeated = storedPool( + [[firstId, record(first, [])]], + { initialized: true, workspaceIds: [WorkspaceId(firstId), WorkspaceId(firstId)] }, + ) + await expect(harness({ pool: repeated })).rejects.toThrow(/repeats workspace/) + + const missing = storedPool( + [], + { initialized: true, workspaceIds: [WorkspaceId(firstId)] }, + ) + await expect(harness({ pool: missing })).rejects.toThrow(/references missing workspace/) }) - it('prunes dead ids even when the triggering mutation is itself a no-op', async () => { - const dir = await makeDir('prune-on-noop') - const id = WorkspaceId('00000000-0000-4000-8000-000000000007') - const pool = pooledRecord(id, record(dir, ['ghost'])) - const { registry, changes } = await harness({ pool, sessions: [] }) - const workspace = registry.get(id)! - // Detaching an id that was never on the account changes nothing by - // itself, but the mutation slot still prunes the dead 'ghost' durably. - await workspace.detachSession(SessionId('never-there')) - expect(storedRecord(pool, id).sessionIds).toEqual([]) - expect(changes).toHaveLength(1) - }) - - it('rejects startup over a medium accounting one session twice', async () => { - const dirA = await makeDir('double-a') - const dirB = await makeDir('double-b') - const pool = pooledRecord('00000000-0000-4000-8000-000000000003', record(dirA, ['dup'])) - pool.media.get('workspace')!.tables.get('workspaces')! - .set('00000000-0000-4000-8000-000000000004', record(dirB, ['dup'])) - const ctx = new Context() - await ctx.plugin(Storage) - ctx.storage.backend.register('memory', new MemoryStorageBackend(pool)) - ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) - await expect(Promise.resolve(ctx.plugin(WorkspaceRegistry))).rejects.toThrow(/accounted/) - }) - - it('rejects startup over a medium where two records claim one path', async () => { - const dirA = await makeDir('claimed') - const pool = pooledRecord('00000000-0000-4000-8000-000000000005', record(dirA, [])) - pool.media.get('workspace')!.tables.get('workspaces')! - .set('00000000-0000-4000-8000-000000000006', record(dirA, [])) - const ctx = new Context() - await ctx.plugin(Storage) - ctx.storage.backend.register('memory', new MemoryStorageBackend(pool)) - ctx.storage.mount('domain', new DomainFacility(ctx, { backend: 'memory', routes: {} })) - await expect(Promise.resolve(ctx.plugin(WorkspaceRegistry))).rejects.toThrow(/claimed/) + it('fails list if the durable order and entity cache are externally diverged', async () => { + const dir = await makeDir('cache-diverged') + const result = await harness() + const workspace = await result.registry.create(dir) + const internals = result.registry as unknown as { entities: Map } + internals.entities.delete(workspace.id) + expect(() => result.registry.list()).toThrow(/references missing workspace/) }) }) -describe('Workspace mutation failures', () => { - it('propagates a medium write failure from a mutation and keeps the old snapshot', async () => { - const dir = await makeDir('write-fail') - const { backend, arm } = failingBackend() - const { registry } = await harness({ backend }) - const workspace = await registry.create(dir) - arm() - await expect(workspace.setTitle('lost')).rejects.toThrow(/injected/) - expect(workspace.title).toBe('write-fail') +describe('workspace mutation and status', () => { + it('keeps createdAt stable, advances updatedAt, and preserves snapshot on write failure', async () => { + const dir = await makeDir('timestamps') + const result = await harness() + const workspace = await result.registry.create(dir) + const createdAt = workspace.createdAt + expect(workspace.updatedAt).toBe(createdAt) await workspace.setTitle('kept') + expect(workspace.createdAt).toBe(createdAt) + expect(Date.parse(workspace.updatedAt)).toBeGreaterThanOrEqual(Date.parse(createdAt)) + result.pool.failNextWrites = 1 + await expect(workspace.setTitle('lost')).rejects.toThrow(/injected/) expect(workspace.title).toBe('kept') }) -}) -describe('Workspace.status', () => { - it('reports ok while the directory exists and missing-dir once it is gone, without mutating the record', async () => { + it('reports directory disappearance without mutating the workspace', async () => { const dir = await makeDir('vanishing') const { registry } = await harness() const workspace = await registry.create(dir) expect(await workspace.status()).toBe('ok') await rm(dir, { recursive: true }) expect(await workspace.status()).toBe('missing-dir') - expect(workspace.path).toBe(dir) - expect(registry.get(workspace.id)).toBe(workspace) - // The path re-materializing as a non-directory is still missing-dir. await writeFile(dir, 'now a file') expect(await workspace.status()).toBe('missing-dir') + expect(registry.get(workspace.id)).toBe(workspace) }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6b3b39ab93..7f19dcce27 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -152,6 +152,9 @@ importers: '@deepseek-ai/dsh-client-ui-trajectory': specifier: workspace:^ version: link:../../packages/client/ui-trajectory + '@deepseek-ai/dsh-client-ui-workspace': + specifier: workspace:^ + version: link:../../packages/client/ui-workspace '@deepseek-ai/dsh-compact-basic': specifier: workspace:^ version: link:../../packages/compact/compact-basic @@ -203,6 +206,15 @@ importers: '@deepseek-ai/dsh-spill-policy': specifier: workspace:^ version: link:../../packages/spill/spill-policy + '@deepseek-ai/dsh-storage': + specifier: workspace:^ + version: link:../../packages/storage/storage + '@deepseek-ai/dsh-storage-domain': + specifier: workspace:^ + version: link:../../packages/storage/storage-domain + '@deepseek-ai/dsh-storage-json': + specifier: workspace:^ + version: link:../../packages/storage/storage-json '@deepseek-ai/dsh-subagent': specifier: workspace:^ version: link:../../packages/subagent/subagent @@ -260,6 +272,9 @@ importers: '@deepseek-ai/dsh-workflow-workerthread': specifier: workspace:^ version: link:../../packages/workflow/workflow-workerthread + '@deepseek-ai/dsh-workspace': + specifier: workspace:^ + version: link:../../packages/workspace/workspace '@deepseek-ai/dsh-workspace-context': specifier: workspace:^ version: link:../../packages/context/workspace-context @@ -850,6 +865,9 @@ importers: react: specifier: ^18.2.0 version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) react-markdown: specifier: ^10.1.0 version: 10.1.0(@types/react@18.3.31)(react@18.3.1) @@ -863,6 +881,9 @@ importers: '@types/react': specifier: ~18.3.1 version: 18.3.31 + '@types/react-dom': + specifier: ~18.3.0 + version: 18.3.7(@types/react@18.3.31) cordis: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) @@ -992,6 +1013,36 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-workspace: + devDependencies: + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-ui-conversation': + specifier: workspace:^ + version: link:../ui-conversation + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-sidebar': + specifier: workspace:^ + version: link:../ui-sidebar + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 + packages/client/web: dependencies: '@deepseek-ai/dsh-client-modules': @@ -2228,6 +2279,9 @@ importers: '@deepseek-ai/dsh-user-interaction': specifier: workspace:^ version: link:../../ui/user-interaction + '@deepseek-ai/dsh-workspace': + specifier: workspace:^ + version: link:../../workspace/workspace schemastery: specifier: ^3.18.0 version: 3.18.0 @@ -2238,6 +2292,12 @@ importers: '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@deepseek-ai/dsh-storage': + specifier: workspace:^ + version: link:../../storage/storage + '@deepseek-ai/dsh-storage-domain': + specifier: workspace:^ + version: link:../../storage/storage-domain cordis: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 7774f2d34d..b1c6318b3b 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -207,8 +207,10 @@ const TYPE_LINK_EXEMPTIONS: Readonly> = { BashEnvVariableInfo: 'service-local metadata type is owned by packages/bash/tool-bash/src/index.ts', CompactAgentContext: 'compaction service input is owned by packages/compact/compact/src/index.ts', CreateAgentOptions: 'agent creation contract is owned by packages/core/agent/README.md', + Domain: 'domain interface is owned by packages/storage/storage-domain/README.md', DomainChanged: 'event-local snapshot is owned by packages/storage/storage-domain/src/events.ts', DomainFacility: 'domain form facility is owned by packages/storage/storage-domain/README.md', + DomainImpl: 'domain implementation contract is owned by packages/storage/storage-domain/README.md', DomainSpec: 'domain declaration contract is owned by packages/storage/storage-domain/README.md', StorageBackend: 'backend contract is owned by packages/storage/storage/src/backend.ts', StorageForms: 'merge-extensible form map is owned by packages/storage/storage/src/index.ts', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 2ef0e385e3..9996fb9f6f 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -141,16 +141,24 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Non-session storage hub', mode: 'seam', implementations: ['storage-json', 'storage-sqlite'], - consumers: ['storage-domain', 'workspace'], + consumers: ['storage-domain'], note: 'Backends register side by side under names; data forms (domain first) mount on the hub and translate typed operations into opaque KV-unit primitives.', }, + { + key: 'storageDomain', + pkg: 'storage-domain', + title: 'Domain data facility', + mode: 'core', + consumers: ['workspace'], + note: 'Waits for every configured backend, then publishes the domain form as one lifecycle-bound service for typed durable state.', + }, { key: 'workspace', pkg: 'workspace', title: 'Workspace entity registry', mode: 'core', - consumers: [], - note: 'Owns WorkspaceId-branded records over the domain form; sessionIds is the single source of ownership truth. RPC and GUI consumers arrive next phase.', + consumers: ['apiproxy'], + note: 'Owns WorkspaceId-branded records over the domain facility; stable sessionIds accounts drive Host RPC and GUI projections.', }, { key: 'sessionQuery', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 5687e51bac..20d4195737 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -57,6 +57,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-conversation': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-question': { kind: 'indirect', reason: 'The package mounts dsh-tool-ask-user; that tool owns the model-visible schema and answer rendering.' }, 'packages/client/ui-trajectory': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, + 'packages/client/ui-workspace': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-theme': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/i18n': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/web': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 533b23e724..a449a34c4e 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -113,6 +113,7 @@ "@deepseek-ai/dsh-client-ui-conversation": ["./packages/client/ui-conversation/src"], "@deepseek-ai/dsh-client-ui-question": ["./packages/client/ui-question/src"], "@deepseek-ai/dsh-client-ui-trajectory": ["./packages/client/ui-trajectory/src"], + "@deepseek-ai/dsh-client-ui-workspace": ["./packages/client/ui-workspace/src"], "@deepseek-ai/dsh-client-ui-theme": ["./packages/client/ui-theme/src"], "@deepseek-ai/dsh-client-i18n": ["./packages/client/i18n/src"], "@deepseek-ai/dsh-client-web": ["./packages/client/web/src"], diff --git a/tsconfig.client.json b/tsconfig.client.json index 7915df50ff..17f34b601f 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -34,6 +34,7 @@ { "path": "./packages/client/ui-layout" }, { "path": "./packages/client/ui-sidebar" }, { "path": "./packages/client/ui-conversation" }, + { "path": "./packages/client/ui-workspace" }, { "path": "./packages/client/ui-question" }, { "path": "./packages/client/ui-trajectory" }, { "path": "./packages/client/ui-theme" }, diff --git a/vitest.web.config.ts b/vitest.web.config.ts index de220c9f12..c3de18c94a 100644 --- a/vitest.web.config.ts +++ b/vitest.web.config.ts @@ -1,10 +1,10 @@ import tsconfigPaths from 'vite-tsconfig-paths' import { defineConfig } from 'vitest/config' -// Web smoke lane (GUI, gate-exempt — not part of the CI sequence yet): built -// page + real chromium, so it lives outside the unit/e2e includes. The -// real-host test self-skips without DEEPSEEK_API_KEY; the fixture test is -// keyless and deterministic. +// Web smoke lane (GUI, gate-exempt — not part of the CI sequence yet): real +// host entry points plus built-client interaction snapshots, outside the +// unit/e2e includes. Real-model cases self-skip without DEEPSEEK_API_KEY; +// fixture branches stay keyless and deterministic. try { // Node >= 21.7 native; throws when the file does not exist. process.loadEnvFile(new URL('.env', import.meta.url).pathname) @@ -18,7 +18,10 @@ export default defineConfig({ // workspace imports to source like every other lane. plugins: [tsconfigPaths({ projects: ['./tsconfig.base.json'] })], test: { - include: ['apps/web/tests/**/*.e2e.ts'], + include: [ + 'apps/web/tests/**/*.e2e.ts', + 'apps/web/tests/**/*.snapshot.ts', + ], // Browser boot + real-model turns are slow; files share one browser, run serial. testTimeout: 180_000, hookTimeout: 120_000, From 08ce02da2b742de256a2a40fcdac60bcbcb8855d Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 16:15:29 +0800 Subject: [PATCH 065/113] docs(web): finalize workspace UI product flow --- ...07-25-workspace-ui-product-flow.i18n.yaml} | 4 +- .../2026-07-25-workspace-ui-product-flow.md | 117 +++++++++++++++++ ...2026-07-25-workspace-ui-product-flow.zh.md | 117 +++++++++++++++++ ...-07-25-workspace-gui-and-session-drafts.md | 121 ------------------ ...-25-workspace-gui-and-session-drafts.zh.md | 121 ------------------ packages/client/runtime/README.md | 2 +- .../runtime/src/client/sessions/manager.ts | 10 +- .../runtime/src/client/sessions/service.ts | 11 +- .../runtime/src/client/sessions/session.ts | 5 +- ...drafts.spec.ts => session-intents.spec.ts} | 0 packages/client/ui-conversation/README.md | 2 +- .../ui-conversation/src/client/service.ts | 5 +- packages/host/apiproxy/README.md | 2 +- packages/workspace/workspace/README.md | 2 +- 14 files changed, 265 insertions(+), 254 deletions(-) rename .agents/notes/{proposed/feature/2026-07-25-workspace-gui-and-session-drafts.i18n.yaml => implemented/feature/2026-07-25-workspace-ui-product-flow.i18n.yaml} (61%) create mode 100644 .agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.md create mode 100644 .agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.zh.md delete mode 100644 .agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.md delete mode 100644 .agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.zh.md rename packages/client/runtime/tests/{session-drafts.spec.ts => session-intents.spec.ts} (100%) diff --git a/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.i18n.yaml b/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.i18n.yaml similarity index 61% rename from .agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.i18n.yaml rename to .agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.i18n.yaml index 7ea5b2afb3..3295a845f3 100644 --- a/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.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 -2026-07-25-workspace-gui-and-session-drafts.md: 9e44e092ca584a285d5e49c109063aecbbac239d -2026-07-25-workspace-gui-and-session-drafts.zh.md: 7e13e7de281711227bf446e406e0e4a18394cb4f +2026-07-25-workspace-ui-product-flow.md: a02087235a36f2c257de407facf2dc02ed072f3b +2026-07-25-workspace-ui-product-flow.zh.md: 8ccbf5b98401bef9c3fd40e948d35ec5f0818202 diff --git a/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.md b/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.md new file mode 100644 index 0000000000..a02087235a --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.md @@ -0,0 +1,117 @@ +# Agent Note: Workspace UI Complete Product Flow + +Status: implemented + +English | [中文](2026-07-25-workspace-ui-product-flow.zh.md) + +## Problem + +[Domain KV Storage and the Workspace Entity](../../proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md) defines the persistent Workspace entity, path conventions, and ordered Session ledger, but not the Host wiring, historical-data initialization, or GUI flow. The GUI presents both Workspaces and Sessions; users must be able to type immediately after entering New Session, even when no Host Session or Host Workspace exists yet. + +Pending Workspaces, pending Sessions, retained input, and Host entity publication need clear owners and must preserve the same page identity when RPC completions and Host frames arrive in either order. Eagerly creating a Host Session for the zero state would bring a page with no input into the Host lifecycle. Historical Sessions also expose only the lightweight `SessionHeader.cwd` for grouping; initialization cannot read event bodies. + +## Decision + +### Host and persistent data + +The Host provides the following GUI wiring on the Workspace entity: + +| RPC | Behavior | +| --- | --- | +| `workspace.list` | Returns persistent Workspaces in order and filters out Session ids that fail header validation | +| `workspace.create({ name })` | Creates a directory and Workspace at `workspaceRoot/name`; fails on a display-name conflict | +| `workspace.create({ path })` | Adopts an existing directory and does not create an arbitrary path | +| `session.create({ workspaceId, sessionId? })` | Resolves cwd from the Workspace, idempotently creates a Session with an optional preallocated id, and attaches it | +| `session.create({ cwd })` | Remains available to non-Workspace callers and creates an Ungrouped Session | + +`workspaceRoot` is an independent Host setting that falls back to the Host cwd when unset; it is unrelated to `storageRoot`, which stores Workspace domain data. The Host stream pushes Workspace and Session deltas, and the Client refreshes the `workspace.list` and `session.list` baselines separately after reconnecting. + +A Workspace's `sessionIds` is an ordered candidate index. A membership projection requires both that an id appear in the index and that the corresponding canonicalized `SessionHeader.cwd` equal the Workspace path; SessionHeader does not gain a `workspaceId`. A Session whose cwd matches but whose id is absent from the index remains Ungrouped, while an indexed id is filtered out if its header is missing, its cwd is invalid, or its cwd does not match. Two Workspace indexes claiming the same Session is corrupt state and fails loudly. + +The Workspace domain uses a durable marker to distinguish “never initialized” from “initialized but empty.” When the marker is absent, the Registry calls only `SessionPersistence.list()` to read header metadata; it calls neither `load` nor `inspect`, reads no history, and parses no event bodies. Valid cwd values are grouped by canonical path, and both Sessions within each group and the Workspace groups themselves are initialized in descending header `createdAt` order. Bootstrap is reentrant and writes the marker last; after the marker is written, new Sessions created without `workspaceId` are no longer adopted automatically. + +### Client object model + +`Session` and `Workspace` are frontend objects from the page Intent stage onward. + +- A frontend Session preallocates a SessionId when created and owns its Intent target and `pendingPrompt`; it remains the same Session object after Host `session.create` succeeds. +- Before materialization, a frontend Workspace has no WorkspaceId and owns its create input, phase, and error; after Host `workspace.create` succeeds, the same Workspace object adopts the returned view. +- `SessionManager` and `WorkspaceManager` own object indexes and merge Host baselines and deltas; the objects are the sole source of state for both Intents and Host views. +- `SessionsService` provides Session objects, real selection, scope, and list projections; `WorkspacesService` depends on `SessionsService` and owns the default Workspace, cross-object New Session flow, and Workspace materialization. + +A page has at most one frontend Session Intent and one accompanying Workspace Intent that exists only in the zero-Workspace state. Intents exist only on the current page and disappear on refresh; real Session selection can be restored persistently. Selecting a real Session or starting another Session Intent revokes the old Intent's eligibility for automatic sending, but does not roll back a Session already published by the Host or any accepted message. + +The Session owns the first input and drives one internal pipeline: when necessary, it attaches to a Workspace with its preallocated id, then sends `pendingPrompt`. Both attach and send failures return to the same Session. Workspace creation phase and error belong only to the Workspace object; the Session does not simulate the Workspace lifecycle. + +### User flow + +On initial entry, the application waits until both the Workspace and Session baselines are ready. It restores a real Session selection that remains valid; otherwise, it enters New Session and selects the most recent Workspace exactly once. The most recent Workspace is determined by the maximum `updatedAt` of its member Sessions, falling back to `createdAt` for an empty Workspace. This derived value chooses only the default target: it does not alter the Host Workspace order or trigger another selection after later hydration. + +When no Workspace exists, the page creates a frontend Workspace object named `workspace` and a frontend Session that targets it. Neither writes to the Host, and the composer always accepts input; the first send materializes the Workspace, attaches the Session, and sends the message in that order. + +Top-level New Session, the plus button on a Workspace row, and the Workspace picker all invoke the same New Session action. An explicit Workspace id becomes the target directly; when none is specified, the action uses the most recent Workspace, or the Workspace Intent if no real Workspace exists. The Workspace picker's Use an existing folder and Create a new workspace actions immediately create a real Workspace when the user confirms, then retarget the frontend Session to it; an explicitly created empty Workspace remains even if the user sends no message. + +Create a new workspace temporarily uses the same input as both the directory name and display name. The UI prevents duplicate confirmation based on current Workspace titles, while the Host continues to reject same-name requests that bypass the UI or race concurrently. Rename, Delete, moving across Workspaces, drag-and-drop ordering, manual adoption from Ungrouped, and separate display-name and directory-name inputs are outside this iteration's scope. + +### First send and recovery + +A frontend Session's `pendingPrompt` retains its original text until the Host accepts the message. The first send advances through Workspace materialization, Session attachment, and prompt sending in order: + +1. If Workspace creation fails, the Workspace Intent retains its input and error, and the Session continues to target that object. +2. If Session creation fails before publication, the Session Intent returns to an editable state and retries with the same preallocated SessionId. +3. `workspace-attach-failed` proves that the Session has been published; the same Session object enters the real list and retains the prompt, and subsequent retries attach it. +4. If the prompt fails, the Session retains it and retries only send without recreating the Workspace or Session. +5. If the page switches to another Intent while a Session is being created, the old Session does not send automatically even if it is subsequently published; it retains its original prompt and visible error. + +Lost RPC responses, Host frames arriving before completions, and completions arriving before Host frames all converge through the preallocated SessionId and object identity. The Manager performs ordered upserts of Host views and prioritizes preserving the original object identity during local materialization, rather than creating a temporary second row with the same id. + +### Sidebar and ordering + +Workspace groups strictly follow the persistent order returned by the Host. Bootstrap determines the historical order once, explicitly created Workspaces are placed first, and Session activity does not move Workspace groups. + +Within each group, order strictly follows `Workspace.sessionIds`. A newly attached Session is placed first; when a Session later becomes active, the Host moves only that id to the front and persists the change. The Client does not reorder the entire group by time after the Session list arrives, so it never displays one Workspace order and then jumps to another during hydration. + +A frontend Session Intent appears as a “New session” row and temporarily counts toward the group's Session total only when it targets a real Workspace. When it targets a Workspace Intent, neither the Workspace nor the Session appears in the sidebar. After the Intent is published, the real row with the same preallocated id takes its place; after refresh, both the Intent row and temporary count disappear. Search mode neither retains nor filters Intent rows. + +Real Sessions that cannot be assigned to any Workspace appear under Ungrouped. Host `session-added` and `workspace-changed` events may arrive in either order; list merging does not depend on frame order. + +### React and slot boundaries + +React components only consume `useSessions`, `useWorkspaces`, and session-scoped hooks; they do not own entity lifecycles. The Zustand store retains only layout, the current view, composer text for ordinary real Sessions, and other purely presentational state. Session and Workspace Intents, materialization phases, errors, and retained prompts reside in the React-free runtime object layer. + +The Sidebar and conversation empty hero receive standardized actions through slots: `startSession`, `updateSessionPrompt`, `sendSession`, `open`, and `toggleSidebar`. The Workspace picker reuses the same component and the `createWorkspace` seam; its owner supplies only popover state, an anchor, and a selection callback. The presentation layer does not send `host/workspace-changed` directly; Host events originate only from Host mutations and the stream adapter. + +## Alternatives considered + +**Store separate page records for pending Workspaces and Sessions.** This approach must replace identities after materialization and hand off input, errors, focus, and sidebar rows; Intent state owned by the objects preserves identity continuity. + +**Let the presentation layer or root Zustand store orchestrate object lifecycles.** This approach duplicates Manager and Service responsibilities and brings domain state back into React. Runtime services provide standardized actions, while slots inject only the narrow interfaces required by presentation. + +**Immediately create a Host Session or Host persistence intent in the zero state.** A page with no input would enter the Host lifecycle and change refresh semantics; before the first send, the frontend Session retains only a page-local Intent. + +**Delay an explicit Create Workspace until the first send.** After confirmation, the sidebar would still show no real empty Workspace, conflating “create a Workspace” with “prepare a Session”; only the zero-Workspace Intent generated automatically by the system delays materialization. + +**Continuously derive Workspaces dynamically from cwd.** This cannot represent empty Workspaces, stable display names, or explicit ordering, and would automatically adopt non-Workspace callers; cwd is used only for one historical bootstrap and bidirectional membership validation. + +**Have the Client batch-reorder by time after the Session list arrives.** The initial screen would first show the Host order and then jump as a whole, and reconnecting could change positions again; the Host's persistent ledger owns ordering, while the Client merges only individual updates. + +**Add workspaceId to SessionHeader.** This would create two persistent ownership fields alongside the Workspace index and require double writes; the header retains the Session's own cwd fact, while the Workspace index owns explicit membership. + +## Verification + +- The zero state with no Workspace writes nothing to the Host and accepts input; explicit Create Workspace immediately creates and displays an empty Workspace. +- Frontend Sessions and Workspaces preserve object identity across materialization; input, errors, focus, and sidebar projections always originate from the object layer. +- The first send advances through Workspace, Session, and prompt in order; successful stages are not rolled back, input is not lost before the prompt is accepted, and creation retries use the same SessionId. +- Workspace list performs one reentrant bootstrap using only headers; an initialized empty registry does not initialize again after restart, and membership reads validate both the index and canonical cwd. +- The initial default target is determined exactly once after both baselines are ready; Workspace groups are not reordered as a whole by hydration or Session activity, and an active Session moves only itself to the front. +- A frontend Session under a real Workspace temporarily counts toward the sidebar total, while a Workspace Intent remains hidden; neither publication nor refresh leaves duplicate rows or counts. +- Both the UI and Host reject duplicate Workspace names; cwd-only Sessions, Sessions with invalid historical cwd values, and unattached Sessions remain Ungrouped. +- Keyless runnable snapshots cover the zero state, explicit creation, and the first send; package-level tests cover bootstrap, membership validation, ordering, idempotency, failure recovery, and arbitrary frame order. + +## Consequences + +- SessionHeader does not record last-active time, so historical bootstrap can initialize order only by `createdAt`; real Session activity events move individual entries afterward. +- Historical Sessions with a missing cwd, an invalid directory, or a failed realpath remain Ungrouped; this iteration has no manual-adoption entry point. +- Refreshing the page discards unmaterialized Workspace and Session Intents and input not yet accepted by the Host; this is the page-local contract. +- Explicit Create Workspace writes to disk immediately, so leaving without sending still leaves an empty Workspace. +- Before its first event, a Host Session retains the existing lazy-persistence semantics; frontend Intents do not change empty-Session behavior after a Host restart. diff --git a/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.zh.md b/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.zh.md new file mode 100644 index 0000000000..8ccbf5b984 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.zh.md @@ -0,0 +1,117 @@ +# Agent Note: Workspace UI 完整产品动线 + +[English](2026-07-25-workspace-ui-product-flow.md) | 中文 + +Status: implemented + +## Problem + +[Domain KV storage 与 Workspace entity](../../proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md)定义了 Workspace 的持久实体、路径规范和有序 Session 账本,但没有定义 Host 接线、历史数据初始化或 GUI 动线。GUI 同时呈现 Workspace 和 Session;用户进入 New Session 后必须立即输入,即使此时还没有 Host Session,甚至没有 Host Workspace。 + +待创建 Workspace、待创建 Session、输入保留与 Host 实体发布必须具有明确所有者,并在 RPC completion 与 Host frame 以任意顺序到达时保持同一页面身份。若零态提前创建 Host Session,则无输入的页面状态会进入 Host 生命周期。历史 Session 又只有轻量 `SessionHeader.cwd` 可用于归组,初始化不能读取事件正文。 + +## Decision + +### Host 与持久数据 + +Host 在 Workspace entity 上提供以下 GUI 接线: + +| RPC | 行为 | +| --- | --- | +| `workspace.list` | 返回持久有序的 Workspace,并过滤未通过 header 校验的 Session id | +| `workspace.create({ name })` | 在 `workspaceRoot/name` 创建目录和 Workspace;显示名冲突时失败 | +| `workspace.create({ path })` | 收编已经存在的目录,不为任意路径创建目录 | +| `session.create({ workspaceId, sessionId? })` | 从 Workspace 解析 cwd,以可选预分配 id 幂等创建 Session 并 attach | +| `session.create({ cwd })` | 保留给非 Workspace 调用方,创建 Ungrouped Session | + +`workspaceRoot` 是独立 Host 配置,未配置时回退到 Host cwd;它与保存 Workspace domain 数据的 `storageRoot` 无关。Host stream 推送 Workspace 与 Session 增量,Client 重连后分别刷新 `workspace.list` 与 `session.list` 基线。 + +Workspace 的 `sessionIds` 是有序候选索引。成员投影同时要求 id 位于索引且对应 `SessionHeader.cwd` canonical 后等于 Workspace path;SessionHeader 不增加 `workspaceId`。cwd 匹配但未入索引的 Session 保持 Ungrouped,索引命中但 header 缺失、cwd 无效或 cwd 不匹配的 id 被过滤。同一 Session 被两个 Workspace 索引占用属于损坏状态并 fail loud。 + +Workspace domain 以 durable marker 区分“从未初始化”和“已初始化但为空”。marker 未设置时,Registry 只调用 `SessionPersistence.list()` 读取 header 元数据,不调用 `load`、`inspect`、history 或解析事件正文;有效 cwd 按 canonical path 分组,组内 Session 与 Workspace 组均按 header `createdAt` 降序初始化。Bootstrap 可重入,最后才写 marker;marker 写入后,绕过 `workspaceId` 的新 Session 不再被自动收编。 + +### Client 对象模型 + +`Session` 与 `Workspace` 从页面 Intent 阶段开始就是前端对象。 + +- 前端 Session 创建时预分配 SessionId,并在对象内持有 Intent target 与 `pendingPrompt`;Host `session.create` 成功后仍是同一个 Session 对象。 +- 前端 Workspace 在 materialize 前没有 WorkspaceId,并在对象内持有 create input、phase 与 error;Host `workspace.create` 成功后同一个 Workspace 对象 adopt 返回的 view。 +- `SessionManager` 与 `WorkspaceManager` 负责对象索引、Host 基线和增量合并;对象是 Intent 与 Host view 的唯一状态源。 +- `SessionsService` 提供 Session 对象、真实 selection、scope 与列表投影;`WorkspacesService` 依赖 `SessionsService`,负责默认 Workspace、跨对象 New Session 动线和 Workspace materialize。 + +页面至多有一个前端 Session Intent 和一个仅在零 Workspace 状态下配套的 Workspace Intent。Intent 只存在于当前页面,刷新后消失;真实 Session selection 可以持久恢复。选择真实 Session 或启动另一个 Session Intent 会放弃旧 Intent 的自动发送资格,但已经由 Host 发布的 Session 和已经接受的消息不会回滚。 + +Session 自己持有首条输入并驱动一条内部流水线:必要时以预分配 id attach 到 Workspace,然后发送 `pendingPrompt`。attach 与 send 的失败都落回同一 Session。Workspace 创建 phase/error 只属于 Workspace 对象,Session 不模拟 Workspace 生命周期。 + +### 用户动线 + +应用首次进入时等待 Workspace 与 Session 两份基线 ready。仍有效的真实 Session selection 被恢复;否则进入 New Session,并固定选择一次最近 Workspace。最近 Workspace 取其成员 Session 的最大 `updatedAt`,空 Workspace 回退到 `createdAt`;该派生只决定默认目标,不改变 Host Workspace 顺序,也不会在后续 hydration 时二次改选。 + +完全没有 Workspace 时,页面创建默认名为 `workspace` 的前端 Workspace 对象和指向它的前端 Session。两者不写 Host,composer 始终可输入;首次发送才依次 materialize Workspace、attach Session、发送消息。 + +顶部 New Session、Workspace 行内加号和 Workspace picker 最终都调用同一 New Session 动作:显式 Workspace id 直接成为目标,未指定时使用最近 Workspace,没有真实 Workspace 时使用 Workspace Intent。Workspace picker 的 Use an existing folder 与 Create a new workspace 会在用户确认时立即创建真实 Workspace,再把前端 Session 定位到该 Workspace;即使用户不发送消息,显式创建的空 Workspace 也保留。 + +Create a new workspace 暂时用同一个输入作为目录名和显示名。UI 根据当前 Workspace title 禁止重复确认,Host 继续拒绝绕过 UI 或并发产生的同名请求。Rename、Delete、跨 Workspace 移动、拖拽排序、Ungrouped 手动收编和显示名/目录名双输入不在本期范围。 + +### 首次发送与恢复 + +前端 Session 的 `pendingPrompt` 在 Host 接受消息前始终保留原文。首次发送按 Workspace materialize、Session attach、prompt send 顺序推进: + +1. Workspace 创建失败时,Workspace Intent 保留输入与错误,Session 仍指向该对象。 +2. Session 创建在发布前失败时,Session Intent 回到可编辑状态,以同一预分配 SessionId 重试。 +3. `workspace-attach-failed` 证明 Session 已发布;同一 Session 对象进入真实列表并保留 prompt,后续重试 attach。 +4. prompt 失败时,Session 保留 prompt 并只重试 send,不重复创建 Workspace 或 Session。 +5. Session 创建期间若页面切换到另一个 Intent,旧 Session 即使随后发布也不自动发送;它保留原 prompt 和可见错误。 + +RPC lost response、Host frame 先于 completion 和 completion 先于 Host frame 都通过预分配 SessionId 与对象身份收敛。Manager 对 Host view 做有序 upsert,本地 materialize 时优先保留原对象身份,不生成同 id 的临时第二行。 + +### Sidebar 与排序 + +Workspace 组严格使用 Host 返回的持久顺序。Bootstrap 一次性确定历史顺序,显式创建的新 Workspace 放在首位;Session 活跃不会移动 Workspace 组。 + +组内严格使用 `Workspace.sessionIds`。新 attach 的 Session 放在首位,后续某个 Session 活跃时 Host 只前移该 id 并持久化。Client 不在 Session list 到达后按时间整体重排,因此不会先显示一套 Workspace 顺序再因 hydration 瞬间跳动。 + +前端 Session Intent 只有在目标是真实 Workspace 时才作为 “New session” 行显示,并临时计入该组 Session 数量;目标是 Workspace Intent 时,Workspace 与 Session 都不进入 sidebar。Intent 发布后由同一预分配 id 对应的真实行接替,刷新后 Intent 行和临时计数一起消失。搜索模式不保存或筛选 Intent 行。 + +无法归入任何 Workspace 的真实 Session 进入 Ungrouped。Host `session-added` 与 `workspace-changed` 可以任意顺序到达,列表合并不依赖 frame 顺序。 + +### React 与 slot 边界 + +React 组件只消费 `useSessions`、`useWorkspaces` 与 session-scoped hooks,不拥有实体生命周期。Zustand store 只保留布局、当前 view、普通真实 Session 的 composer 文本和其他纯呈现状态;Session/Workspace Intent、materialize phase、错误和 retained prompt 位于 React-free runtime 对象层。 + +Sidebar 与 conversation empty hero 通过 slot 获得标准化动作:`startSession`、`updateSessionPrompt`、`sendSession`、`open` 与 `toggleSidebar`。Workspace picker 复用同一组件与 `createWorkspace` seam;owner 只提供 popover 开关、锚点和选中回调。呈现层不直接发送 `host/workspace-changed`,Host event 只由 Host mutation 与 stream adapter 产生。 + +## Alternatives considered + +**为待创建 Workspace 与 Session 保存独立页面记录。** 该方案在 materialize 后需要替换身份并转交输入、错误、焦点和 sidebar 行;对象自身的 Intent 状态可以保持身份连续。 + +**由呈现层或 root Zustand store 编排对象生命周期。** 该方案会重复 Manager/Service 的职责,并把领域状态带回 React。标准化动作由 runtime service 提供,slot 只注入呈现所需的窄接口。 + +**零态立即创建 Host Session 或 Host persistence intent。** 未输入页面会进入 Host 生命周期,并改变刷新语义;前端 Session 在首次发送前只保留 page-local Intent。 + +**显式 Create Workspace 延迟到首次发送。** 用户确认后 sidebar 仍看不到真实空 Workspace,“创建 Workspace”与“准备 Session”语义混合;只有系统自动产生的零 Workspace Intent 延迟 materialize。 + +**持续按 cwd 动态派生 Workspace。** 该方案无法表达空 Workspace、稳定显示名和显式顺序,也会自动收编非 Workspace 调用方;cwd 只用于一次历史 bootstrap 与成员双向校验。 + +**Client 在 Session list 到达后按时间批量重排。** 首屏会先展示 Host 顺序再整体跳动,重连也可能改变位置;排序由 Host 持久账本拥有,Client 只合并单项更新。 + +**在 SessionHeader 增加 workspaceId。** 它会与 Workspace 索引形成两个持久归属字段并要求双写;header 保留 Session 自身 cwd 事实,Workspace 索引负责显式归属。 + +## Verification + +- 完全无 Workspace 的零态不写 Host 且允许输入;显式 Create Workspace 立即创建并显示空 Workspace。 +- 前端 Session 与 Workspace 在 materialize 前后保持对象身份,输入、错误、焦点和 sidebar 投影始终来自对象层。 +- 首发按 Workspace、Session、prompt 顺序推进,各成功阶段不回滚,输入在 prompt 接受前不丢失,创建重试使用同一 SessionId。 +- Workspace list 只读取 header 完成一次可重入 bootstrap;initialized 的空 registry 重启不重复初始化,成员读取同时校验索引与 canonical cwd。 +- 初始默认目标只在两份基线 ready 后确定一次;Workspace 组不因 hydration 或 Session 活跃整体重排,单个活跃 Session 只前移自身。 +- 真实 Workspace 下的前端 Session 临时计入 sidebar 数量,Workspace Intent 保持隐藏,发布与刷新都不会留下重复行或重复计数。 +- UI 与 Host 两层拒绝同名 Workspace;cwd-only Session、无效历史 cwd 和未 attach Session 保持 Ungrouped。 +- keyless runnable snapshot 覆盖零态、显式创建和首次发送;包级测试覆盖 bootstrap、成员校验、排序、幂等、失败恢复及任意 frame 顺序。 + +## Consequences + +- SessionHeader 不记录最后活跃时间,历史 bootstrap 只能按 `createdAt` 初始化;此后由真实 Session 活跃事件逐项前移。 +- 历史 cwd 缺失、目录无效或 realpath 失败的 Session 留在 Ungrouped;本期没有手动收编入口。 +- 页面刷新会丢弃未 materialize 的 Workspace/Session Intent 和尚未被 Host 接受的输入,这是 page-local 契约。 +- 显式 Create Workspace 立即落盘,用户不发送就离开也会留下空 Workspace。 +- Host Session 在首个事件前仍遵循现有懒持久化语义;前端 Intent 不改变 Host 重启后的空 Session 行为。 diff --git a/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.md b/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.md deleted file mode 100644 index 9e44e092ca..0000000000 --- a/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.md +++ /dev/null @@ -1,121 +0,0 @@ -# Agent Note: Workspace GUI and session drafts - -Status: proposed - -English | [中文](2026-07-25-workspace-gui-and-session-drafts.zh.md) - -## Problem - -[Domain KV storage and the Workspace entity](../architecture/2026-07-24-domain-kv-storage-and-workspace.md) define the persistent Workspace entity, path conventions, and ordered session ledger, but do not define Host wiring, historical-data initialization, or GUI flows. The GUI displays Workspaces and Sessions together, and users must be able to type immediately after entering the New Session page, even when no real Session or even real Workspace exists yet. - -Using one intent to represent both a pending Workspace and a pending Session would make explicit Create Workspace actions, the automatic empty state, sidebar draft rows, and first-send failures share an ambiguous state. Creating a Host Session in advance to support the empty state would instead produce an empty Session with no user input, no persisted data before its first event, and no survival across restarts. Existing historical Sessions also expose only `SessionHeader.cwd`, so the system needs to build an initial Workspace view without reading event bodies. - -## Proposal - -### State and ownership - -Workspace and Session are two real Host objects; WorkspaceDraft and SessionDraft are two page-local Client states: - -- A `Workspace` can be empty, persists durably, and always appears in the sidebar; -- A `Session` is a real object already created by the Host; -- A `WorkspaceDraft` exists only for the automatic empty state when the system has no Workspace at all and does not appear in the sidebar; -- A `SessionDraft` represents a pending Session and holds its target Workspace or WorkspaceDraft, preallocated SessionId, composer content, and send phase. - -At most one SessionDraft exists on a page. A draft under a real Workspace appears in the sidebar as “New session”; neither a WorkspaceDraft nor its SessionDraft appears there. A new draft replaces the old one; selecting a real Session or refreshing the page discards any unmaterialized draft and uncommitted input. Real Workspaces, real Sessions, and messages already accepted by the Host are unaffected. - -The Client represents the current page with the discriminated union `ConversationStage = Session | SessionDraft` instead of simulating a draft by clearing current and storing an intent elsewhere. Workspace, Session, and ConversationStage are separate object layers; only a real Session selection can be persisted. - -### End-to-end Host and wire flow - -The Host exposes the following GUI wiring over the existing Workspace entity: - -| RPC | Behavior | -| --- | --- | -| `workspace.list` | Returns real Workspaces in a stable order and filters out session ids that fail header validation | -| `workspace.create({ name })` | Creates a directory at `workspaceRoot/name` and a Workspace when the name is available; duplicate-name requests fail | -| `workspace.create({ path })` | Adopts an existing directory without creating directories for arbitrary input paths | -| `session.create({ workspaceId, sessionId? })` | Resolves cwd from the Workspace, idempotently creates a real Session with an optional preallocated id, and attaches it | -| `session.create({ cwd })` | Remains available to non-GUI callers and creates an Ungrouped Session | - -`workspaceRoot` is an independent Host configuration that falls back to the Host cwd when unset; it is unrelated to the `storageRoot` that stores Workspace domain data. The Host stream pushes incremental Workspace and Session updates, while reconnection uses `workspace.list` and `session.list` as its two baselines. - -The GUI preallocates a SessionId in SessionDraft but creates no Host intent before the first send. On the first send, the Client passes that id to `session.create`; the Host uses the same id to create both the real Session and its persistence create-intent. Retrying the same id with the same cwd is idempotent; an existing id with a different cwd fails loudly. This lets a lost response or partial attach failure reconcile to the same Session instead of creating a duplicate. - -A Workspace's `sessionIds` is an ordered candidate index. A Session is a member only when its id is present in the index and its canonicalized `SessionHeader.cwd` equals the Workspace path; SessionHeader does not gain a `workspaceId`. A Session whose cwd matches but whose id is absent from the index remains Ungrouped, while an indexed id with a missing header or mismatched cwd does not enter the projection. A Session appearing in two Workspace indexes is corrupt state and fails loudly. - -### One-time historical initialization - -The Workspace domain uses a durable marker to distinguish “never initialized” from “initialized but empty.” When the marker is absent, WorkspaceRegistry performs a reentrant bootstrap once: - -1. Call `SessionPersistence.list()` exactly once; JSONL reads only the first header line, SQLite reads only session metadata rows, and the bootstrap must not call `load`, `inspect`, history APIs, or parse event bodies. -2. Ignore headers with no cwd, a nonexistent path, a path that is not a directory, or a failed realpath lookup; these Sessions remain Ungrouped. -3. Group by canonical cwd, sort each group by header `createdAt` in descending order before writing `sessionIds`, and order Workspace groups stably by each group's maximum `createdAt`, also descending. -4. After a crash, reentry reuses Workspaces already written for the same canonical path and merges missing ids; write the marker last, after all records are durable. - -After the marker is written, the system no longer creates Workspaces or backfills their ledgers automatically from cwd. Subsequent call paths that omit `workspaceId` remain Ungrouped; this is a compatibility path, not a second source that continuously derives Workspaces. - -### User flows - -On initial entry, the Client waits until both Workspace and Session baselines are ready; it restores a still-existing real Session selection when possible and otherwise enters the New Session flow. When the user explicitly enters New Session, the Client does not restore the old selection: it selects the most recent Workspace and creates a SessionDraft. The most recent Workspace is determined by the maximum `updatedAt` among its validated member Sessions, with an empty Workspace falling back to `createdAt`. This value only chooses the default target for New Session; it neither changes the sidebar Workspace order nor triggers a second selection after the Session list arrives. - -When no Workspace exists at all, the page creates a WorkspaceDraft named `workspace` and its SessionDraft. Neither is written to the Host, but the composer always remains editable. The top-level New Session action reenters this empty-state selection flow without calling `session.create` immediately. - -The plus button in the Sidebar Workspace section header and the Workspace creation entry in the composer reuse the same picker and modal: - -- Select an existing Workspace: create only a SessionDraft targeting that Workspace; -- Use an existing folder: call `workspace.create({ path })`, then create a SessionDraft under it after success; -- Create new: use one input as both the directory name and title; the UI disables confirmation when an existing Workspace has that title, and the Host rejects duplicate-name requests caused by bypassing the UI or concurrent creation; after success, create a SessionDraft under it. - -Explicit Create Workspace creates a real Workspace as soon as the user confirms and immediately displays it in the sidebar; the empty Workspace remains even if the user never sends a message. The inline plus button on a Workspace row creates only a SessionDraft under that group: it neither creates another Workspace nor immediately creates a Host Session. - -Sending the first message performs these steps in order: create the Workspace when necessary, create the Session with the preallocated id, hand the stage and composer buffer off to the real Session, and call `session.prompt`. The Client clears the input only after the Host accepts the prompt. A Workspace remains if failure occurs after it is created; a real Session remains selected if failure occurs after it is published; a prompt failure retains the original input and retries the same Session. - -### Sidebar and ordering - -Workspace groups use the persistent stable order returned by the Host. Bootstrap establishes the historical order once, and explicitly created Workspaces go first; Session activity never moves Workspace groups. - -Within a group, Sessions render strictly in `Workspace.sessionIds` order. Historical Sessions are initialized from the header `createdAt`, and new Sessions go first; whenever a Session's `updatedAt` advances afterward, the Host moves only that id to the front of its Workspace and persists the change. The Client does not batch-sort by `updatedAt` after Session list hydration, so the page never displays the bootstrap order and then jumps as a whole. - -SessionDraft is a presentation-layer row appended without writing to `sessionIds`. When a real Workspace has a SessionDraft, the sidebar's page-derived session count temporarily increases by one; once the real Session with the same id appears, it must not be counted twice, and refreshing removes both the draft and its temporary count. `host/session-added` and `host/workspace-changed` may arrive in either order; the Client merges them by the preallocated SessionId and removes the draft once the real row can be located, without ever briefly showing two rows with the same id. - -### Client and UI boundaries - -A dedicated WorkspacesService manages the Workspace list phase, incremental upserts, reconnect refresh, creation, and recent-Workspace derivation. SessionsService manages only the real Session list, Session scope, history, running state, and real selection. A page-local conversation coordinator manages ConversationStage, SessionDraft, materialization phase, errors, and composer-buffer handoff. - -The existing sidebar layout, row styles, EmptyHero, composer styles, Menu/Modal/Tooltip, portal and slot infrastructure, and `ui-workspace` component skeleton can remain. The Workspace/Session state boundary, empty state, creation actions, first-send state machine, historical initialization, and component props need to be rewritten. The Sidebar and conversation-empty entry points must use the same Workspace data and creation actions; only their anchor direction, open state, and selection callback may differ. - -This phase uses English UI text and does not provide Workspace rename/delete, Session delete, cross-Workspace moves, drag ordering, manual adoption from Ungrouped, multiple SessionDrafts, draft restoration after refresh, or separate display-name and directory-name inputs. - -## Alternatives considered - -**Continue deriving Workspaces dynamically from cwd.** This cannot represent empty Workspaces, stable display names, or explicit order, and it would automatically adopt non-GUI Sessions. Derivation is allowed only for the one-time historical bootstrap; ownership must subsequently be written explicitly to the index. - -**Use one WorkspaceIntent to represent both WorkspaceDraft and SessionDraft.** Their visibility, persistence, and materialization timing differ. Combining them prevents explicit Create Workspace from taking effect immediately and prevents the sidebar from distinguishing a hidden WorkspaceDraft from a draft row under a real Workspace. - -**Create a Host Session or Host persistence intent immediately for the empty state.** A Session with no input would enter the Host lifecycle, while refresh semantics would conflict with a page-local draft. Only a Client SessionDraft exists before the first send. - -**Delay explicit Create Workspace until the first send.** The sidebar would still have no real empty Workspace after user confirmation, conflating “Create Workspace” with “prepare Session.” Only the automatic no-Workspace empty state allows delayed creation. - -**Batch-reorder on the Client by updatedAt after the Session list arrives.** The page would first show the bootstrap `createdAt` order and then jump as a whole, while reconnection could not restore the same order. The Host moves only the corresponding id when an individual Session becomes active. - -**Add workspaceId to SessionHeader.** This would create two persistent ownership fields alongside the Workspace index and require dual writes. The header retains the Session's own cwd fact, the Workspace index owns explicit membership, and reads validate both directions. - -## Acceptance criteria - -- Explicit Create Workspace immediately creates and displays an empty Workspace; the automatic empty state with no Workspace writes nothing to the Host and remains editable. -- New Session, selecting an existing Workspace, both Workspace creation methods, and the inline plus button on a Workspace row each produce the single SessionDraft and follow the sidebar visibility rules. -- The first send materializes Workspace, Session, and prompt in that order; successful stages are not rolled back, input is retained until the prompt is accepted, and retries use the same SessionId. -- The Workspace list performs one reentrant bootstrap using headers only; tests prove it never reads event bodies and that an initialized empty registry does not repeat the bootstrap after restart. -- Membership reads validate both the index and header cwd; cwd-only Sessions, invalid historical cwd values, and failed attaches become Ungrouped. -- Initial rendering waits for both baselines to be ready; Session activity does not move Workspace groups, arrival of the Session list does not trigger a full reorder, and activity in one Session moves only that Session to the front and preserves the order across reconnection. -- Workspace and Session updates arriving in either order never create duplicate Session rows; every first-send failure stage can recover to the same preallocated id. -- Create new rejects duplicate Workspace names at both the UI and Host layers; a SessionDraft under a real Workspace temporarily counts toward the sidebar total, and neither materialization nor refresh leaves a duplicate count. -- Real runnable keyless snapshots cover the empty state, explicit creation, successful first send, failed first send, refresh, and Ungrouped; package-level tests cover bootstrap, bidirectional membership validation, ordering, and idempotency. - -## Risks - -- Header-only bootstrap has no historical activity time and can initialize order only from `createdAt`; it does not batch-correct from the Session list afterward, and only new activity in individual Sessions progressively changes in-group order. -- Historical Sessions with a missing cwd or a path that cannot be resolved by realpath remain Ungrouped; this phase has no manual adoption entry point. -- Refreshing the page discards WorkspaceDraft, SessionDraft, and input not yet accepted by the Host; this is the page-local contract. -- Before its first event, a Host Session still has only a live object and a persistence create-intent; restarting the Host loses that empty Session. This design does not change the existing lazy-persistence semantics by persisting page drafts. -- Explicit Create Workspace persists immediately, so leaving without sending a message still leaves an empty Workspace; this is the cost of making the operation take effect immediately. diff --git a/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.zh.md b/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.zh.md deleted file mode 100644 index 7e13e7de28..0000000000 --- a/.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.zh.md +++ /dev/null @@ -1,121 +0,0 @@ -# Agent Note: Workspace GUI and session drafts - -[English](2026-07-25-workspace-gui-and-session-drafts.md) | 中文 - -Status: proposed - -## Problem - -[Domain KV storage 与 Workspace entity](../architecture/2026-07-24-domain-kv-storage-and-workspace.md)定义了 Workspace 的持久实体、路径规范和有序 session 账本,但没有定义 Host 接线、历史数据初始化或 GUI 动线。GUI 同时显示 Workspace 和 Session,并且用户进入 New Session 页面后必须立即输入,即使此时还没有真实 Session,甚至没有真实 Workspace。 - -若用一个 intent 同时表示待创建 Workspace 和待创建 Session,显式 Create Workspace、自动零态、sidebar draft 行和首发失败会共享一组含混状态。若为了解决零态而提前创建 Host Session,又会产生没有用户输入、首个事件前不落盘且重启即消失的空 Session。现有历史 Session 还只有 `SessionHeader.cwd`,需要在不读取事件正文的前提下建立一次初始 Workspace 视图。 - -## Proposal - -### 状态与所有权 - -Workspace 与 Session 是两个真实 Host 对象;WorkspaceDraft 与 SessionDraft 是两个 page-local Client 状态: - -- `Workspace` 可以为空,持久存在并始终显示在 sidebar; -- `Session` 是已经由 Host 创建的真实对象; -- `WorkspaceDraft` 只用于“系统完全没有 Workspace”的自动零态,不显示在 sidebar; -- `SessionDraft` 表示一个待创建 Session,持有目标 Workspace 或 WorkspaceDraft、预分配 SessionId、composer 内容和发送 phase。 - -页面至多存在一个 SessionDraft。真实 Workspace 下的 draft 在 sidebar 显示为 “New session”;WorkspaceDraft 及其 SessionDraft 都不显示。新 draft 替换旧 draft;选择真实 Session 或刷新页面会丢弃未物化 draft 和未提交输入。真实 Workspace、真实 Session 和已经接受的消息不受影响。 - -Client 用判别联合 `ConversationStage = Session | SessionDraft` 表达当前页面,不再用“清空 current 再另存 intent”模拟草稿。Workspace、Session 和 ConversationStage 各有独立对象层;只有真实 Session selection 可以持久化。 - -### Host 与 wire 全链路 - -Host 在现有 Workspace entity 上提供以下 GUI 接线: - -| RPC | 行为 | -| --- | --- | -| `workspace.list` | 返回稳定有序的真实 Workspace,并过滤未通过 header 校验的 session id | -| `workspace.create({ name })` | 名称未被占用时在 `workspaceRoot/name` 建目录并创建 Workspace;重名请求失败 | -| `workspace.create({ path })` | 收编已经存在的目录,不为任意输入路径建目录 | -| `session.create({ workspaceId, sessionId? })` | 从 Workspace 解析 cwd,以可选预分配 id 幂等创建真实 Session 并 attach | -| `session.create({ cwd })` | 保留给非 GUI 调用方,创建 Ungrouped Session | - -`workspaceRoot` 是独立 Host 配置,未配置时回退到 Host cwd;它与保存 Workspace domain 数据的 `storageRoot` 无关。Host stream 推送 Workspace 和 Session 增量,重连以 `workspace.list` 与 `session.list` 两份基线为准。 - -GUI 在 SessionDraft 中预分配 SessionId,但首次发送前不创建任何 Host intent。首次发送时,Client 才把该 id 传给 `session.create`;Host 用同一 id 创建真实 Session 和 persistence create-intent。相同 id、相同 cwd 的重试幂等;id 已存在但 cwd 不同则 fail loud。这样响应丢失和 attach 部分失败都能对账到同一个 Session,而不是重复创建。 - -Workspace 的 `sessionIds` 是有序候选索引。读取成员必须同时满足 id 在索引中且 `SessionHeader.cwd` canonical 后等于 Workspace path;SessionHeader 不增加 `workspaceId`。cwd 匹配但未入索引的 Session 仍是 Ungrouped,索引命中但 header 缺失或 cwd 不匹配的 id 不进入投影。同一 Session 出现在两个 Workspace 索引中属于损坏状态并 fail loud。 - -### 一次性历史初始化 - -Workspace domain 用 durable marker 区分“从未初始化”和“已初始化但为空”。marker 未设置时,WorkspaceRegistry 执行一次可重入 bootstrap: - -1. 只调用一次 `SessionPersistence.list()`;JSONL 只读 header 首行,SQLite 只读 session 元数据行,禁止调用 `load`、`inspect`、history 或解析事件正文。 -2. 忽略无 cwd、目录不存在、非目录或 realpath 失败的 header;这些 Session 留在 Ungrouped。 -3. 按 canonical cwd 分组,组内按 header `createdAt` 降序写入 `sessionIds`,Workspace 组按各组最大 `createdAt` 降序写入稳定顺序。 -4. 崩溃重入时按 canonical path 复用已经写入的 Workspace 并合并缺失 id;全部记录 durable 后最后写 marker。 - -marker 写入后不再按 cwd 自动建 Workspace 或补账。后续绕过 `workspaceId` 的调用链保持 Ungrouped;这是一条兼容路径,不是持续派生 Workspace 的第二写源。 - -### 用户动线 - -应用首次进入时,Client 等待 Workspace 与 Session 两份基线都 ready;仍存在的真实 Session selection 可以恢复,否则进入 New Session 流程。用户显式进入 New Session 时不恢复旧 selection,而是选择最近 Workspace 并创建 SessionDraft。最近 Workspace 取其已验证成员 Session 的最大 `updatedAt`;空 Workspace 回退到 `createdAt`。该值只决定 New Session 的默认目标,不改变 sidebar 的 Workspace 顺序,也不会在 Session list 到达后触发二次选择。 - -完全没有 Workspace 时,页面创建名为 `workspace` 的 WorkspaceDraft 和其 SessionDraft。它们不写 Host,但 composer 始终可输入。顶部 New Session 重新进入该零态选择流程,不立即调用 `session.create`。 - -Sidebar Workspace 区头加号和 composer 的 Workspace 创建入口复用同一个 picker 与 modal: - -- 选择已有 Workspace:只创建指向该 Workspace 的 SessionDraft; -- Use an existing folder:调用 `workspace.create({ path })`,成功后创建其下的 SessionDraft; -- Create new:用一个输入同时作为目录名和 title;UI 对已有 Workspace title 禁止确认,Host 拒绝绕过 UI 或并发产生的重名请求;成功后创建其下的 SessionDraft。 - -显式 Create Workspace 在用户确认时立即产生真实 Workspace,并立即显示在 sidebar;即使用户不发送消息,也会留下空 Workspace。Workspace 行内加号只创建该组下的 SessionDraft,不创建另一个 Workspace,也不立即创建 Host Session。 - -发送首条消息时依次执行:必要时创建 Workspace、以预分配 id 创建 Session、把 stage 和 composer buffer 转交给真实 Session、调用 `session.prompt`。只有 Host 接受 prompt 后才清空输入。Workspace 已创建后失败则保留 Workspace;Session 已发布后失败则保留并聚焦真实 Session;prompt 失败则保留原输入并重试同一 Session。 - -### Sidebar 与排序 - -Workspace 组使用 Host 返回的持久稳定顺序。Bootstrap 一次性确定历史顺序,显式创建的新 Workspace 放到首位;Session 活跃不会移动 Workspace 组。 - -组内严格按 `Workspace.sessionIds` 渲染。历史 Session 以 header `createdAt` 初始化,新 Session 放到首位;此后某个 Session 的 `updatedAt` 前进时,Host 只把该 id 移到所属 Workspace 的首位并持久化。Client 不在 Session list hydration 后按 `updatedAt` 批量排序,因此页面不会先显示 bootstrap 顺序再整体跳动。 - -SessionDraft 是渲染层附加行,不写入 `sessionIds`。真实 Workspace 下存在 SessionDraft 时,sidebar 的页面派生 session 数量临时加一;同 id 的真实 Session 出现后不能重复计数,刷新后 draft 与临时计数一起消失。`host/session-added` 与 `host/workspace-changed` 可能以任意顺序到达;Client 按预分配 SessionId 合并,并在真实行可定位后移除 draft,不能短暂显示两个同 id 行。 - -### Client 与 UI 边界 - -独立 WorkspacesService 管理 Workspace list phase、增量 upsert、重连 refresh、create 和最近 Workspace 派生;SessionsService 只管理真实 Session list、Session scope、history、running 状态与真实 selection;page-local conversation coordinator 管理 ConversationStage、SessionDraft、物化 phase、错误和 composer buffer 转交。 - -现有 sidebar 布局、行样式、EmptyHero、composer 样式、Menu/Modal/Tooltip、portal、slot 基建和 `ui-workspace` 组件骨架可以保留。需要重写的是 Workspace/Session 状态边界、零态、创建动作、首发状态机、历史初始化和组件 props。Sidebar 与 conversation empty 两个入口必须使用同一 Workspace 数据和创建动作,只允许锚点方向、开关状态与选中回调不同。 - -本期 UI 使用英文,不提供 Workspace rename/delete、Session delete、跨 Workspace 移动、拖拽排序、Ungrouped 手动收编、多 SessionDraft、draft 刷新恢复或显示名与目录名的双输入。 - -## Alternatives considered - -**继续按 cwd 动态派生 Workspace。** 该方案无法表示空 Workspace、稳定显示名或显式顺序,也会把非 GUI Session 自动收编;只允许一次历史 bootstrap,之后归属必须显式写入索引。 - -**用一个 WorkspaceIntent 同时表示 WorkspaceDraft 与 SessionDraft。** 两者的显示、持久化和物化时点不同;合并后显式 Create Workspace 无法立即生效,sidebar 也无法区分隐藏 WorkspaceDraft 与真实 Workspace 下的 draft 行。 - -**零态立即创建 Host Session 或 Host persistence intent。** 未输入的 Session 会进入 Host 生命周期,刷新语义与 page-local 草稿冲突;首次发送前只保留 Client SessionDraft。 - -**显式 Create Workspace 延迟到首次发送。** 用户确认后 sidebar 仍没有真实空 Workspace,“Create Workspace”与“准备 Session”语义混合;只有自动无 Workspace 零态允许延迟。 - -**Client 在 Session list 到达后按 updatedAt 批量重排。** 页面会先展示 bootstrap 的 `createdAt` 顺序再整体跳动,重连也无法恢复同一顺序;Host 只在单个 Session 活跃时前移对应 id。 - -**在 SessionHeader 中增加 workspaceId。** 它会与 Workspace 索引形成两个持久归属字段并要求双写;header 保留 session 自身的 cwd 事实,Workspace 索引负责显式归属,读取时双向校验。 - -## Acceptance criteria - -- 显式 Create Workspace 立即创建并显示空 Workspace;完全无 Workspace 的自动零态不写 Host 且允许输入。 -- New Session、选择已有 Workspace、两种 Workspace 创建方式和 Workspace 行内加号都产生唯一的 SessionDraft,并遵守 sidebar 可见性规则。 -- 首发按 Workspace、Session、prompt 顺序物化;各已成功阶段不回滚,输入在 prompt 接受前不丢失,重复创建使用同一 SessionId。 -- Workspace list 只用 header 完成一次可重入 bootstrap;测试证明不读取事件正文,initialized 的空 registry 重启也不重复执行。 -- 归属读取同时校验索引与 header cwd;cwd-only Session、无效历史 cwd 和 attach 失败进入 Ungrouped。 -- 首次渲染等待两份基线 ready;Workspace 组不因 Session 活跃移动,Session list 到达不触发整体重排,单个活跃 Session 只前移自身并在重连后保持顺序。 -- Workspace 与 Session 增量以任意顺序到达都不会产生重复 Session 行;首发各失败阶段都能恢复到同一个预分配 id。 -- Create new 在 UI 与 Host 两层拒绝重名 Workspace;真实 Workspace 下的 SessionDraft 临时计入 sidebar 数量,物化与刷新都不会留下重复计数。 -- 真实 runnable keyless snapshot 覆盖零态、显式创建、首发成功、首发失败、刷新和 Ungrouped;包级测试覆盖 bootstrap、双向归属、排序与幂等。 - -## Risks - -- Header-only bootstrap 没有历史活跃时间,只能用 `createdAt` 初始化顺序;初始化后不按 Session list 批量修正,只有新的单项活跃逐步改变组内顺序。 -- 历史 cwd 缺失或无法 realpath 的 Session 会留在 Ungrouped;本期没有手动收编入口。 -- 页面刷新会丢弃 WorkspaceDraft、SessionDraft 和尚未接受的输入;这是 page-local 契约。 -- Host Session 在首个事件前仍只有 live 对象和 persistence create-intent,Host 重启会丢失该空 Session;本设计不通过持久化页面 draft 改变现有懒持久化语义。 -- 显式 Create Workspace 立即落盘,因此用户不发送就离开也会留下空 Workspace;这是该操作真实生效的代价。 diff --git a/packages/client/runtime/README.md b/packages/client/runtime/README.md index f1e13f007a..6b697cbed9 100644 --- a/packages/client/runtime/README.md +++ b/packages/client/runtime/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-client-runtime -Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects, list/scope/history state, and page-local Session Intent state; WorkspacesService owns Workspace objects, list/actions, page-local Workspace Intent state, and default-target derivation. The runtime fans the shared Host stream into both managers. Contract: api-contracts v3 §4. +Client cordis boot and React-free object services: SlotsService wraps SlotCore and supplies renderer data sources; SessionsService owns Session objects, list/scope/history state, and page-local Session Intent state; WorkspacesService depends on SessionsService and owns Workspace objects, list/actions, page-local Workspace Intent state, default-target derivation, and the cross-object New Session flow. The runtime fans the shared Host stream into both managers. Contract: api-contracts v3 §4. ## Workspace and Session lists diff --git a/packages/client/runtime/src/client/sessions/manager.ts b/packages/client/runtime/src/client/sessions/manager.ts index 8d9dd4d958..907fc961f6 100644 --- a/packages/client/runtime/src/client/sessions/manager.ts +++ b/packages/client/runtime/src/client/sessions/manager.ts @@ -149,12 +149,18 @@ export class SessionManager { return session } - /** @returns the active frontend Session, if one remains selected. */ + /** + * Resolve the active frontend Session Intent. + * @returns the active frontend Session, if one remains selected. + */ getIntent(): Session | undefined { return this.intentSessionId === undefined ? undefined : this.sessions.get(this.intentSessionId) } - /** @param text - exact controlled-input value for the active frontend Session. */ + /** + * Update the retained prompt of the active frontend Session. + * @param text - exact controlled-input value for the active frontend Session. + */ updateIntent(text: string): void { this.getIntent()?.updatePendingPrompt(text) } diff --git a/packages/client/runtime/src/client/sessions/service.ts b/packages/client/runtime/src/client/sessions/service.ts index f77717d7f0..845292a481 100644 --- a/packages/client/runtime/src/client/sessions/service.ts +++ b/packages/client/runtime/src/client/sessions/service.ts @@ -209,17 +209,24 @@ export class SessionsService { * Start or retarget the sole client-local Session intent. * @param target - resolved real or frontend-only Workspace target. * @param prompt - optional prompt retained across retargeting. + * @returns the frontend Session object that owns the Intent. */ startIntent(target: SessionIntentTarget, prompt = ''): Session { return this.manager.startIntent(target, prompt) } - /** @returns the active frontend Session object, if one exists. */ + /** + * Resolve the active frontend Session Intent. + * @returns the active frontend Session object, if one exists. + */ intent(): Session | undefined { return this.manager.getIntent() } - /** @param text - exact controlled-input value for the current Session Intent. */ + /** + * Update the retained prompt of the active frontend Session. + * @param text - exact controlled-input value for the current Session Intent. + */ updateIntent(text: string): void { this.manager.updateIntent(text) } diff --git a/packages/client/runtime/src/client/sessions/session.ts b/packages/client/runtime/src/client/sessions/session.ts index 4173318fc2..396d0aa798 100644 --- a/packages/client/runtime/src/client/sessions/session.ts +++ b/packages/client/runtime/src/client/sessions/session.ts @@ -141,7 +141,10 @@ export class Session implements ObservableSnapshot { return result } - /** @param text - exact controlled value of this Session's retained prompt. */ + /** + * Update this Session's retained prompt while it remains editable. + * @param text - exact controlled value of this Session's retained prompt. + */ updatePendingPrompt(text: string): void { const pending = this.pendingPrompt if (pending === null || pending.phase === 'sending') return diff --git a/packages/client/runtime/tests/session-drafts.spec.ts b/packages/client/runtime/tests/session-intents.spec.ts similarity index 100% rename from packages/client/runtime/tests/session-drafts.spec.ts rename to packages/client/runtime/tests/session-intents.spec.ts diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 0b7e4ef247..0711adcccb 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -2,7 +2,7 @@ Conversation domain: skeleton (header/tabs/composer/empty state), chat view (grouped step-summary flow, streaming tail isolation, stats line, per-tool row slot with a bash sample registrant), minimal details panel, scope-addressed ConversationService. Contract: api-contracts v3 §7 plus the slot terminal design (store seat / props shares). -The no-session hero renders the frontend Session Intent from the Session list projection, including its frontend Workspace Intent when no real Workspace exists. It declares `conversation.empty.workspace`, where ui-workspace registers the same picker used by the sidebar. WorkspacesService starts and publishes the two intents. The Session object keeps its identity across publication and retains any prompt that still needs connection or delivery; ConversationRoot reads that `pendingPrompt` from `useSession` and edits or retries it through the scoped ConversationService. +The no-session hero renders the frontend Session Intent from the Session list projection, including its frontend Workspace Intent when no real Workspace exists. It declares `conversation.empty.workspace`, where ui-workspace registers the same picker used by the sidebar. WorkspacesService starts the cross-object flow; each Workspace or Session object owns its own materialization. The Session keeps its identity across publication and retains any prompt that still needs connection or delivery; ConversationRoot reads that `pendingPrompt` from `useSession` and edits or retries it through the scoped ConversationService. The view ring IS a slot: the conversation registration declares the `'conversation.view'` list slot (session scope) in its `children` table, ConversationRoot renders the active entry through its renderSlot share (`only: `), and view tabs project from the ring ledger's registration options (`id`/`order`/`label`). The chat view is this package's own ring entry; other plugins (ui-trajectory) contribute tabs through plain `ctx.slots.register` — the former package-local view registry (`registerView`/`ViewEntry`/`ConversationViewMap` and the chrome attachment table) is retired, with per-view chrome dissolved into the view components themselves. diff --git a/packages/client/ui-conversation/src/client/service.ts b/packages/client/ui-conversation/src/client/service.ts index 6e1ca2b70e..5ea5ea96ee 100644 --- a/packages/client/ui-conversation/src/client/service.ts +++ b/packages/client/ui-conversation/src/client/service.ts @@ -49,7 +49,10 @@ export class ConversationService extends Service { await this.scopedSession('loadOlder').loadOlder() } - /** Update the scoped Session's retained pending prompt. */ + /** + * Update the scoped Session's retained pending prompt. + * @param text - exact controlled-input value to retain. + */ updatePendingPrompt(text: string): void { this.scopedSession('updatePendingPrompt').updatePendingPrompt(text) } diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index cc8b5a7237..58cab1f2cc 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -10,7 +10,7 @@ The layering/protocol decisions are recorded in the [GUI layering and RPC protoc The mux stream projects the latest log-backed title as a validated `session/title` control frame after each attached-session subscription baseline and immediately after the corresponding live raw title event. This projection does not add titles to `session.list`; cold sessions remain metadata-only there until opening or resuming attaches their logs. -Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed` plus `host/session-added` carry committed increments in either arrival order. Session drafts are client-only and have no wire method. +Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed` plus `host/session-added` carry committed increments in either arrival order. Frontend Workspace and Session Intents are client-only and have no wire method. ## Carrier layer (`/client` + root) diff --git a/packages/workspace/workspace/README.md b/packages/workspace/workspace/README.md index a687910319..b333d90ad0 100644 --- a/packages/workspace/workspace/README.md +++ b/packages/workspace/workspace/README.md @@ -2,7 +2,7 @@ Workspace entity registry (`ctx.workspace`) for the DeepSeek Harness: durable workspace records, stable workspace order, and a newest-first candidate session index stored through the domain data form. Consumers see the `Workspace` interface; the entity implementation stays package-private. -The entity/storage rationale lives in the [domain Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); header-only bootstrap and GUI ordering live in the [Workspace GUI Agent Note](../../../.agents/notes/proposed/feature/2026-07-25-workspace-gui-and-session-drafts.md). +The entity/storage rationale lives in the [domain Agent Note](../../../.agents/notes/proposed/architecture/2026-07-24-domain-kv-storage-and-workspace.md); header-only bootstrap and GUI ordering live in the [Workspace UI product-flow Agent Note](../../../.agents/notes/implemented/feature/2026-07-25-workspace-ui-product-flow.md). ## Shape From 468c64a078472b7758962f0f38d428b4ae763f39 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 16:19:36 +0800 Subject: [PATCH 066/113] fix(web): keep composer add action attachment-only --- .../client/ui-conversation/src/client/skeleton/EmptyHero.tsx | 4 ---- .../client/ui-conversation/src/client/skeleton/EmptyState.tsx | 1 - packages/client/ui-conversation/tests/skeleton.spec.tsx | 2 ++ 3 files changed, 2 insertions(+), 5 deletions(-) diff --git a/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx b/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx index b8badba406..941729f9a0 100644 --- a/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx @@ -73,7 +73,6 @@ export interface EmptyHeroProps { status?: string onDraftChange: (text: string) => void onSend: (mode: 'queue' | 'steer') => void - onAdd?: () => void /** Overlay content after the stack (EmptyState's modals). */ children?: ReactNode } @@ -92,7 +91,6 @@ export function EmptyHero({ status, onDraftChange, onSend, - onAdd, children, }: EmptyHeroProps) { // Stable filter id so multiple hero mounts do not collide in the DOM. @@ -140,8 +138,6 @@ export function EmptyHero({ placeholder={placeholder ?? 'Describe what you want to build'} onDraftChange={onDraftChange} onSend={onSend} - {...(onAdd === undefined ? {} : { onAdd })} - addLabel="Create workspace" /* v8 ignore next -- structural noop: hero never passes running=true, so stop is unreachable. */ onStop={() => {}} /> diff --git a/packages/client/ui-conversation/src/client/skeleton/EmptyState.tsx b/packages/client/ui-conversation/src/client/skeleton/EmptyState.tsx index dd8865efb8..c363d094a6 100644 --- a/packages/client/ui-conversation/src/client/skeleton/EmptyState.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/EmptyState.tsx @@ -72,7 +72,6 @@ export function EmptyState({ error={error} onDraftChange={updateSessionPrompt} onSend={() => { sendSession() }} - onAdd={() => { setPickerOpen(true) }} /> ) } diff --git a/packages/client/ui-conversation/tests/skeleton.spec.tsx b/packages/client/ui-conversation/tests/skeleton.spec.tsx index fc596ec821..e4a8aa2696 100644 --- a/packages/client/ui-conversation/tests/skeleton.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.spec.tsx @@ -72,6 +72,8 @@ describe('EmptyState', () => { prompt: 'draft', phase: 'ready', }) expect(b.view.getByRole('button', { name: 'Choose workspace' }).textContent).toContain('workspace') + fireEvent.click(b.view.getByRole('button', { name: 'Add attachment' })) + expect((b.pickerOwner() as { open: boolean }).open).toBe(false) fireEvent.change(b.view.getByPlaceholderText('Describe what you want to build'), { target: { value: 'build it' } }) expect(b.updateSessionPrompt).toHaveBeenCalledWith('build it') fireEvent.click(b.view.getByRole('button', { name: 'Send message' })) From c06cb2deec6dafb19bd6c1c8bd9121cf84011e10 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 16:30:23 +0800 Subject: [PATCH 067/113] test(web): stabilize workspace snapshots --- apps/web/tests/session-title.snapshot.ts | 5 +++-- apps/web/tests/workspace-flow.snapshot.ts | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/apps/web/tests/session-title.snapshot.ts b/apps/web/tests/session-title.snapshot.ts index 5fbb23814b..c1616bb724 100644 --- a/apps/web/tests/session-title.snapshot.ts +++ b/apps/web/tests/session-title.snapshot.ts @@ -93,8 +93,9 @@ it('projects initial and revised durable titles through the built nine-plugin fi unmount = () => { entry.dispose() } }) - const projectLabel = await screen.findByText('fixture', {}, { timeout: 10_000 }) - const projectRow = projectLabel.closest('[role="treeitem"]') + const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 }) + const projectCount = await within(tree).findByText('4 sessions') + const projectRow = projectCount.closest('[role="treeitem"]') if (projectRow === null) throw new Error('fixture project row missing') fireEvent.click(projectRow) diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index 6ebc3bb7c0..78ac843a64 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -108,7 +108,7 @@ function visibleText(element: Element): string { return (element.textContent ?? '').replace(/\s+/g, ' ').trim() } -/** The labelled chip and its adjacent plus button intentionally share a label. */ +/** Identify the interactive Workspace chip by its menu contract. */ function workspaceChip(): HTMLElement { const chip = screen.getAllByRole('button', { name: 'Choose workspace' }) .find(element => element.getAttribute('aria-haspopup') === 'menu') @@ -116,12 +116,18 @@ function workspaceChip(): HTMLElement { return chip } +/** Wait for the runtime-owned controlled input to echo a browser edit. */ +async function setComposerText(composer: HTMLElement, value: string): Promise { + fireEvent.change(composer, { target: { value } }) + await waitFor(() => { expect((composer as HTMLTextAreaElement).value).toBe(value) }) +} + it('starts a writable page-local draft without inventing a sidebar Workspace', async () => { boot('?fixture=empty') const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 }) const tree = screen.getByRole('tree', { name: 'Sessions' }) - fireEvent.change(composer, { target: { value: 'keep this local' } }) + await setComposerText(composer, 'keep this local') expect({ headline: visibleText(screen.getByText("Let's start building")), @@ -182,7 +188,7 @@ it('drops the page-local draft on refresh while retaining real Workspaces and Se const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 }) const tree = screen.getByRole('tree', { name: 'Sessions' }) - fireEvent.change(composer, { target: { value: 'discard this page-local draft' } }) + await setComposerText(composer, 'discard this page-local draft') const beforeGroup = within(tree).getByText('4 sessions').closest('[role="treeitem"]') if (beforeGroup === null) throw new Error('fixture Workspace projection missing before refresh') @@ -226,7 +232,7 @@ it('keeps a published Session with only cwd membership evidence in Ungrouped', a boot('?fixture&fixtureAttach=fail') const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 }) - fireEvent.change(composer, { target: { value: 'keep this cwd-only session' } }) + await setComposerText(composer, 'keep this cwd-only session') fireEvent.click(screen.getByRole('button', { name: 'Send message' })) const tree = screen.getByRole('tree', { name: 'Sessions' }) @@ -261,7 +267,7 @@ it('materializes the automatic Workspace and Session on the first successful sen boot('?fixture=empty') const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 }) - fireEvent.change(composer, { target: { value: 'build a lighthouse' } }) + await setComposerText(composer, 'build a lighthouse') fireEvent.click(screen.getByRole('button', { name: 'Send message' })) const tree = screen.getByRole('tree', { name: 'Sessions' }) @@ -290,7 +296,7 @@ it('keeps the published Workspace, Session, and unsent prompt after rejection', boot('?fixture=empty&fixturePrompt=reject') const composer = await screen.findByPlaceholderText('Describe what you want to build', {}, { timeout: 10_000 }) - fireEvent.change(composer, { target: { value: 'do not lose this' } }) + await setComposerText(composer, 'do not lose this') fireEvent.click(screen.getByRole('button', { name: 'Send message' })) const alert = await screen.findByRole('alert', {}, { timeout: 10_000 }) From 1a9c1596b8dd1ddaa0e0b199b77bc6f4c7c3bf88 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 16:38:32 +0800 Subject: [PATCH 068/113] test(web): cover workspace UI branches --- .../client/connection/tests/fixture.spec.ts | 36 ++++ .../client/ui-sidebar/tests/rows.spec.tsx | 76 ++++++++ .../ui-sidebar/tests/sidebar-root.spec.tsx | 183 +++++++++++++++++- packages/client/ui-sidebar/tests/tree.spec.ts | 86 +++++++- .../tests/workspace-picker.spec.tsx | 46 ++++- .../storage-domain/tests/domain.spec.ts | 21 +- 6 files changed, 440 insertions(+), 8 deletions(-) create mode 100644 packages/client/ui-sidebar/tests/rows.spec.tsx diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index d860c69234..16fa4b4ed6 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -377,6 +377,42 @@ describe('createFixtureApi', () => { }) }) + it('attaches an existing ungrouped Session to a matching Workspace', async () => { + const api = createFixtureApi() + const sessionId = sid('fx-existing-ungrouped') + await expect(api.sessions.create(req({ sessionId, cwd: '/tmp/fixture' }))).resolves.toMatchObject({ + result: { ok: true, value: { sessionId } }, + }) + + await expect(api.sessions.create(req({ + sessionId, + workspaceId: 'fx-ws-fixture' as WorkspaceId, + }))).resolves.toMatchObject({ result: { ok: true, value: { sessionId } } }) + + const workspaces = await api.workspace.list(req({})) + if (!workspaces.result.ok) throw new Error('workspace list failed') + expect(workspaces.result.value.items[0]?.sessionIds).toContain(sessionId) + }) + + it('reports a conflict without an existing cwd detail for an unrecorded cwd', async () => { + const api = createFixtureApi() + const listed = await api.sessions.list(req({})) + if (!listed.result.ok) throw new Error('session list failed') + const existing = listed.result.value.items.find(item => item.sessionId === sid('fx-alpha')) + if (existing === undefined) throw new Error('fixture Session missing') + delete existing.cwd + + const conflict = await api.sessions.create(req({ sessionId: existing.sessionId })) + expect(conflict.result).toEqual({ + ok: false, + error: { + code: 'session-conflict', + message: `session ${existing.sessionId} already uses no cwd`, + details: { sessionId: existing.sessionId, requestedCwd: '/tmp/fixture' }, + }, + }) + }) + it('publishes an ungrouped Session when Workspace attachment fails', async () => { const api = createFixtureApi({ failWorkspaceAttach: true }) const sessionId = sid('fx-partial') diff --git a/packages/client/ui-sidebar/tests/rows.spec.tsx b/packages/client/ui-sidebar/tests/rows.spec.tsx new file mode 100644 index 0000000000..468ce550d9 --- /dev/null +++ b/packages/client/ui-sidebar/tests/rows.spec.tsx @@ -0,0 +1,76 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' +import { IntentRowItem, ProjectRowItem, SessionNodeItem } from '../src/client/Rows.tsx' +import type { GroupNode, SessionNode } from '../src/client/tree.ts' + +afterEach(cleanup) + +const sid = (id: string) => id as SessionId +const wid = (id: string) => id as WorkspaceId + +describe('sidebar rows', () => { + it('renders an active Workspace and keeps its create action separate from toggling', () => { + const onToggle = vi.fn() + const onCreate = vi.fn() + const group: GroupNode = { + key: 'project', workspaceId: wid('project'), cwd: '/projects/project', label: 'Project', + sessionCount: 1, expanded: true, containsCurrent: true, intentHere: false, sessions: [], + } + render() + + expect(screen.getByText('1 session')).toBeTruthy() + expect(screen.getByRole('treeitem').getAttribute('aria-expanded')).toBe('true') + fireEvent.click(screen.getByRole('button', { name: 'New session in Project' })) + expect(onCreate).toHaveBeenCalledOnce() + expect(onToggle).not.toHaveBeenCalled() + fireEvent.click(screen.getByText('Project')) + expect(onToggle).toHaveBeenCalledOnce() + }) + + it('renders the frontend Intent placeholder as selected', () => { + render() + expect(screen.getByRole('treeitem').getAttribute('aria-selected')).toBe('true') + }) + + it('renders and operates selected, running, recursive Session nodes', () => { + const child: SessionNode = { + id: sid('child'), title: 'Child', children: [], hasChildren: false, + expanded: false, running: false, updatedAt: 0, + } + const parent: SessionNode = { + id: sid('parent'), title: 'Parent', children: [child], hasChildren: true, + expanded: true, running: true, updatedAt: 0, + } + const onOpen = vi.fn() + const onToggle = vi.fn() + const view = render( + , + ) + + const parentRow = screen.getByText('Parent').closest('[role="treeitem"]')! + const childRow = screen.getByText('Child').closest('[role="treeitem"]')! + expect(parentRow.getAttribute('aria-selected')).toBe('true') + expect(parentRow.getAttribute('aria-expanded')).toBe('true') + expect(childRow.getAttribute('aria-selected')).toBe('false') + expect(childRow.hasAttribute('aria-expanded')).toBe(false) + + fireEvent.click(screen.getByRole('button', { name: 'Collapse' })) + expect(onToggle).toHaveBeenCalledWith(parent.id) + expect(onOpen).not.toHaveBeenCalled() + fireEvent.click(parentRow) + fireEvent.click(childRow) + expect(onOpen.mock.calls).toEqual([[parent.id], [child.id]]) + + view.rerender( + , + ) + expect(screen.getByRole('button', { name: 'Expand' })).toBeTruthy() + expect(screen.getByRole('treeitem').getAttribute('aria-selected')).toBe('false') + expect(screen.getByRole('treeitem').style.paddingLeft).toBe('24px') + }) +}) diff --git a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx index bae2ed69ee..26adafd793 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx @@ -1,13 +1,16 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import type { SessionId, SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' import type { SidebarRootComponentProps } from '../src/client/contract/slots.ts' import { SidebarRoot } from '../src/client/SidebarRoot.tsx' -afterEach(cleanup) +afterEach(() => { + cleanup() + vi.useRealTimers() +}) const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId const hook = (snapshot: T) => (selector: (state: T) => S): S => selector(snapshot) @@ -41,6 +44,43 @@ function mount(sessionState: SessionListState = sessions) { return { view, startSession, open, pickerOwner: () => pickerOwner } } +function mountSidebar({ + sessionState = sessions, + workspaceState = workspaces, + collapsed = false, + width = 300, +}: { + sessionState?: SessionListState + workspaceState?: WorkspaceListState + collapsed?: boolean + width?: number +} = {}) { + const startSession = vi.fn() + const open = vi.fn() + const toggleSidebar = vi.fn() + let pickerOwner: unknown + let current = { sessionState, workspaceState, collapsed, width } + const root = () => ( + { pickerOwner = owner; return null }) as SidebarRootComponentProps['renderSlot']} + /> + ) + const view = render(root()) + return { + startSession, + open, + toggleSidebar, + pickerOwner: () => pickerOwner, + rerender(next: Partial) { + current = { ...current, ...next } + view.rerender(root()) + }, + } +} + describe('SidebarRoot', () => { it('renders real Workspaces from useWorkspaces and routes New Session', () => { const b = mount() @@ -79,4 +119,143 @@ describe('SidebarRoot', () => { fireEvent.click(screen.getByText('First session')) expect(b.open).toHaveBeenCalledWith(sid('s1')) }) + + it('opens, selects, dismisses, and toggles the group-by menu', () => { + mount() + const button = screen.getByRole('button', { name: 'Group by' }) + + fireEvent.click(button) + fireEvent.click(screen.getByRole('menuitem', { name: 'Workspace' })) + expect(screen.queryByRole('menu')).toBeNull() + + fireEvent.click(button) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + + fireEvent.click(button) + fireEvent.click(button) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('routes every Workspace picker close path', () => { + const b = mount() + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + const owner = b.pickerOwner() as { open: boolean; onClose(): void } + expect(owner.open).toBe(true) + act(() => { owner.onClose() }) + expect((b.pickerOwner() as { open: boolean }).open).toBe(false) + }) + + it('focuses, filters, and clears search while distinguishing both empty states', () => { + mount() + const input = screen.getByPlaceholderText('Search name, keywords...') + fireEvent.click(input.parentElement!) + expect(document.activeElement).toBe(input) + fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) + + fireEvent.change(input, { target: { value: 'missing' } }) + expect(screen.getByText('No matches')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Clear search' })) + expect(screen.queryByText('No matches')).toBeNull() + + cleanup() + const emptySessions = listState() + const emptyWorkspaces: WorkspaceListState = { ...workspaces, items: [], recentWorkspaceId: undefined } + mountSidebar({ sessionState: emptySessions, workspaceState: emptyWorkspaces }) + expect(screen.getByText('No sessions yet')).toBeTruthy() + }) + + it('toggles Workspace and nested Session expansion in both directions', () => { + const parent = sid('parent') + const child = sid('child') + const nestedSessions: SessionListState = { + ...sessions, + ids: [parent, child], + byId: { + [parent]: { id: parent, displayTitle: 'Parent', running: false, updatedAt: 2 }, + [child]: { id: child, displayTitle: 'Child', running: false, updatedAt: 1, parentId: parent }, + }, + } + const nestedWorkspace: WorkspaceListState = { + ...workspaces, + items: [{ ...workspace, sessionIds: [parent, child] }], + } + mountSidebar({ sessionState: nestedSessions, workspaceState: nestedWorkspace }) + + fireEvent.click(screen.getByText('Project')) + fireEvent.click(screen.getByRole('button', { name: 'Expand' })) + expect(screen.getByText('Child')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Collapse' })) + expect(screen.queryByText('Child')).toBeNull() + fireEvent.click(screen.getByText('Project')) + expect(screen.queryByText('Parent')).toBeNull() + }) + + it('does not start a Session from an Ungrouped row create action', () => { + const loose = sid('loose') + const looseSessions: SessionListState = { + ...listState(), + ids: [loose], + byId: { [loose]: { id: loose, displayTitle: 'Loose', running: false, updatedAt: 1 } }, + current: loose, + } + const b = mountSidebar({ + sessionState: looseSessions, + workspaceState: { ...workspaces, items: [], recentWorkspaceId: undefined }, + }) + fireEvent.click(screen.getByRole('button', { name: 'New session in Ungrouped' })) + expect(b.startSession).not.toHaveBeenCalled() + }) + + it('keeps an already expanded selected Workspace open and resolves later Workspace matches', () => { + const b = mountSidebar() + fireEvent.click(screen.getByText('Project')) + const other = { ...workspace, workspaceId: wid('other'), title: 'Other', sessionIds: [] } + b.rerender({ + sessionState: { ...sessions, current: sid('s1') }, + workspaceState: { ...workspaces, items: [other, workspace] }, + }) + expect(screen.getByText('First session')).toBeTruthy() + + b.rerender({ + sessionState: { + ...sessions, + current: sid('draft'), + intent: { sessionId: sid('draft'), target: { kind: 'workspace-intent' }, prompt: '', phase: 'ready' }, + }, + }) + expect(screen.getByText('Project')).toBeTruthy() + }) + + it('renders the static collapsed rail and expands rail search into focused input', () => { + vi.useFakeTimers() + const b = mountSidebar({ collapsed: true }) + expect(screen.getByRole('button', { name: 'Open sidebar' })).toBeTruthy() + expect(screen.queryByPlaceholderText('Search name, keywords...')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' })) + expect(b.toggleSidebar).toHaveBeenCalledOnce() + + fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) + expect(b.toggleSidebar).toHaveBeenCalledTimes(2) + b.rerender({ collapsed: false }) + const input = screen.getByPlaceholderText('Search name, keywords...') + act(() => { vi.advanceTimersByTime(300) }) + expect(document.activeElement).toBe(input) + }) + + it('keeps wide content during live collapse, then settles to the rail', () => { + vi.useFakeTimers() + const b = mountSidebar({ width: 320 }) + fireEvent.click(screen.getByRole('button', { name: 'Collapse sidebar' })) + expect(b.toggleSidebar).toHaveBeenCalledOnce() + b.rerender({ collapsed: true, width: 56 }) + expect(screen.getByPlaceholderText('Search name, keywords...')).toBeTruthy() + act(() => { vi.advanceTimersByTime(150) }) + expect(screen.queryByPlaceholderText('Search name, keywords...')).toBeNull() + expect(screen.getByRole('button', { name: 'Open sidebar' })).toBeTruthy() + }) }) + +function listState(): SessionListState { + return { ids: [], byId: {}, current: undefined, phase: 'ready', intent: undefined } +} diff --git a/packages/client/ui-sidebar/tests/tree.spec.ts b/packages/client/ui-sidebar/tests/tree.spec.ts index 76d68db4ee..d114d43dea 100644 --- a/packages/client/ui-sidebar/tests/tree.spec.ts +++ b/packages/client/ui-sidebar/tests/tree.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest' import type { SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' -import { deriveGroups, formatRelativeTime, UNGROUPED_KEY } from '../src/client/tree.ts' +import { deriveGroups, formatRelativeTime, projectLabel, UNGROUPED_KEY, UNGROUPED_LABEL } from '../src/client/tree.ts' const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId @@ -59,6 +59,90 @@ describe('deriveGroups', () => { expect(groups[0]!.intentHere).toBe(false) expect(groups[0]!.sessionCount).toBe(2) }) + + it('builds, sorts, expands, and cycle-guards an ungrouped session tree', () => { + const parent = summary('parent', 1) + const oldChild = { ...summary('old-child', 10), parentId: parent.id } + const newChild = { ...summary('new-child', 20), parentId: parent.id } + const tieB = { ...summary('tie-b', 20), parentId: parent.id } + const tieA = { ...summary('tie-a', 20), parentId: parent.id } + const self = { ...summary('self', 2), parentId: sid('self') } + const orphan = { ...summary('orphan', 3), parentId: sid('missing') } + const cycleA = { ...summary('cycle-a', 4), parentId: sid('cycle-b') } + const cycleB = { ...summary('cycle-b', 5), parentId: sid('cycle-a') } + const groups = deriveGroups( + list(parent, oldChild, newChild, tieB, tieA, self, orphan, cycleA, cycleB), + [], + { expandedProjects: [UNGROUPED_KEY], expandedSessions: [parent.id, cycleA.id, cycleB.id], query: '' }, + ) + + expect(groups).toHaveLength(1) + expect(groups[0]!.sessions.map(node => node.id)).toEqual([ + sid('orphan'), sid('self'), parent.id, sid('cycle-a'), + ]) + expect(groups[0]!.sessions[2]!.children.map(node => node.id)).toEqual([ + newChild.id, tieA.id, tieB.id, oldChild.id, + ]) + + // Equal timestamps use ids as a deterministic tiebreak in either input order. + expect(deriveGroups(list(summary('tie-a', 1), summary('tie-b', 1)), [], view([UNGROUPED_KEY]))[0]! + .sessions.map(node => node.id)).toEqual([sid('tie-a'), sid('tie-b')]) + }) + + it('tolerates Workspace membership arriving before its Session summary', () => { + const partial: SessionListState = { + ...list(), + ids: [sid('present')], + byId: { [sid('present')]: summary('present', 1) }, + } + const groups = deriveGroups(partial, [workspace('project', ['missing', 'present'])], view(['project'])) + expect(groups[0]!.sessions.map(node => node.id)).toEqual([sid('present')]) + }) + + it('searches descendants with ancestors and handles cycles, self parents, and label-only hits', () => { + const root = { ...summary('root', 1), displayTitle: 'Ancestor' } + const match = { ...summary('match', 2), displayTitle: 'Needle child', parentId: root.id } + const sibling = { ...summary('sibling', 3), displayTitle: 'Other child', parentId: root.id } + const self = { ...summary('self', 4), displayTitle: 'Needle self', parentId: sid('self') } + const orphan = { ...summary('orphan', 5), displayTitle: 'Needle orphan', parentId: sid('absent') } + const cycleA = { ...summary('cycle-a', 6), displayTitle: 'Needle cycle A', parentId: sid('cycle-b') } + const cycleB = { ...summary('cycle-b', 7), displayTitle: 'Needle cycle B', parentId: sid('cycle-a') } + const sessions = list(root, match, sibling, self, orphan, cycleA, cycleB) + const groups = deriveGroups(sessions, [workspace('project', sessions.ids)], view([], 'needle')) + + expect(groups[0]!.sessions.flatMap(node => [node.id, ...node.children.map(child => child.id)])).toEqual([ + root.id, match.id, self.id, orphan.id, cycleA.id, cycleB.id, + ]) + + const labelOnly = deriveGroups( + list(summary('hidden', 1)), + [workspace('label-hit', ['hidden']), workspace('other', [])], + view([], 'label'), + ) + expect(labelOnly).toEqual([ + expect.objectContaining({ key: 'label-hit', expanded: false, sessions: [], sessionCount: 1 }), + ]) + }) + + it('marks selected Workspace and Ungrouped sessions without relying on an Intent', () => { + const owned = summary('owned', 1) + const loose = summary('loose', 2) + const ws = workspace('project', ['owned']) + const ownedGroups = deriveGroups({ ...list(owned, loose), current: owned.id }, [ws], view()) + expect(ownedGroups.find(group => group.key === 'project')!.containsCurrent).toBe(true) + const looseGroups = deriveGroups({ ...list(owned, loose), current: loose.id }, [ws], view()) + expect(looseGroups.find(group => group.key === UNGROUPED_KEY)!.containsCurrent).toBe(true) + }) +}) + +describe('projectLabel', () => { + it('uses the Ungrouped fallback and extracts POSIX and Windows basenames', () => { + expect(projectLabel(undefined)).toBe(UNGROUPED_LABEL) + expect(projectLabel('')).toBe(UNGROUPED_LABEL) + expect(projectLabel('/projects/demo/')).toBe('demo') + expect(projectLabel('C:\\projects\\demo\\')).toBe('demo') + expect(projectLabel('/')).toBe('/') + }) }) describe('formatRelativeTime', () => { diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index 32d5be145b..523e869961 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -79,12 +79,23 @@ describe('WorkspacePicker', () => { const createWorkspace = vi.fn(async () => created) const b = mount([], createWorkspace) chooseCreateItem('Use an existing folder') - fireEvent.change(screen.getByLabelText('Existing folder path'), { target: { value: ' /tmp/project ' } }) - fireEvent.click(screen.getByRole('button', { name: 'Use folder' })) + const input = screen.getByLabelText('Existing folder path') + fireEvent.keyDown(input, { key: 'ArrowRight' }) + fireEvent.keyDown(input, { key: 'Enter' }) + expect(createWorkspace).not.toHaveBeenCalled() + fireEvent.change(input, { target: { value: ' /tmp/project ' } }) + fireEvent.keyDown(input, { key: 'Enter' }) expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) await waitFor(() => { expect(b.onPick).toHaveBeenCalledWith(created.workspaceId) }) }) + it('closes a creation modal when the user cancels', () => { + mount([]) + chooseCreateItem('Create a new workspace') + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(screen.queryByRole('dialog')).toBeNull() + }) + it('blocks a create-new name already present in the Workspace list', () => { const b = mount([workspace('alpha', 'Alpha')]) chooseCreateItem('Create a new workspace') @@ -98,16 +109,43 @@ describe('WorkspacePicker', () => { it('exposes creation phase and error text while retaining the modal for retry', async () => { let reject!: (reason: unknown) => void const pending = new Promise((_resolve, rejectPromise) => { reject = rejectPromise }) - const b = mount([], vi.fn(() => pending)) + const createWorkspace = vi.fn(() => pending) + const b = mount([], createWorkspace) chooseCreateItem('Create a new workspace') - fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: 'broken' } }) + const input = screen.getByLabelText('New workspace name') + fireEvent.keyDown(input, { key: 'ArrowRight' }) + fireEvent.change(input, { target: { value: 'broken' } }) fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) expect(screen.getByRole('status').textContent).toBe('Creating workspace…') + fireEvent.keyDown(input, { key: 'Enter' }) + expect(createWorkspace).toHaveBeenCalledTimes(1) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.getByRole('dialog')).toBeTruthy() await act(async () => { reject(new Error('disk unavailable')); await pending.catch(() => {}) }) expect(screen.getByRole('alert').textContent).toBe('Workspace creation failed: disk unavailable') expect(b.view.getByRole('dialog')).toBeTruthy() }) + it('reports non-Error creation failures', async () => { + const b = mount([], vi.fn(async () => { throw 'permission denied' })) + chooseCreateItem('Create a new workspace') + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + await waitFor(() => { + expect(screen.getByRole('alert').textContent).toBe('Workspace creation failed: permission denied') + }) + expect(b.onPick).not.toHaveBeenCalled() + }) + + it('waits to show its menu until an optional anchor is available', () => { + render( + , + ) + expect(screen.queryByRole('menu')).toBeNull() + }) + it('shows list loading through a stable status surface', () => { const state: WorkspaceListState = { ...workspaceState([]), phase: 'pending', state: 'loading', baselinesReady: false, diff --git a/packages/storage/storage-domain/tests/domain.spec.ts b/packages/storage/storage-domain/tests/domain.spec.ts index 761c1d7c1d..4a083b3f78 100644 --- a/packages/storage/storage-domain/tests/domain.spec.ts +++ b/packages/storage/storage-domain/tests/domain.spec.ts @@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import { z } from 'zod' import Storage, { storageBackendServiceKey } from '@deepseek-ai/dsh-storage' -import { DomainFacility, defineDomain, domainTable } from '../src/index.ts' +import { apply, DomainFacility, defineDomain, domainTable } from '../src/index.ts' import type { Config } from '../src/index.ts' import type { DomainChanged } from '../src/events.ts' import { MemoryMediaPool, MemoryStorageBackend } from './helpers/memory-backend.ts' @@ -151,6 +151,25 @@ describe('DomainFacility.open', () => { }) describe('plugin apply', () => { + it('uses only the default backend when routes are omitted', async () => { + const ctx = new Context() + await ctx.plugin(Storage) + const backend = new MemoryStorageBackend() + ctx.storage.backend.register('memory', backend) + const disposeBackend = ctx.provide(storageBackendServiceKey('memory'), backend) + + const fiber = await ctx.plugin({ + name: 'storage-domain-routeless-test', + inject: ['storage'], + apply: (domainCtx: Context) => apply(domainCtx, { backend: 'memory' }), + }) + await vi.waitFor(() => { expect(ctx.storageDomain).toBeInstanceOf(DomainFacility) }) + + disposeBackend() + await vi.waitFor(() => { expect(ctx.get('storageDomain')).toBeUndefined() }) + await fiber.dispose() + }) + it('waits for routed backends, then mounts one lifecycle-bound service and form', async () => { const ctx = new Context() await ctx.plugin(Storage) From 1f0d555f60af9149010f1ff1204010911fb036f6 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 16:45:50 +0800 Subject: [PATCH 069/113] docs(missions): record workspace GUI closeout lessons --- missions/readme.md | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 missions/readme.md diff --git a/missions/readme.md b/missions/readme.md new file mode 100644 index 0000000000..66167719ad --- /dev/null +++ b/missions/readme.md @@ -0,0 +1,36 @@ +# Workspace GUI 收尾备忘 + +## 产品改动 + +- 用户要求“去掉功能”时,先拆开视觉入口、可访问性语义和响应行为分别确认。本次 composer 加号保留原样和 `Add attachment` 标签,只在组合层停止传入 Workspace 回调;不要删除按钮、改样式或把它禁用。 +- 临时交互不应上浮到 React 呈现层。Session/Workspace Intent、首次消息保留和 materialize 重试归 runtime 对象与 service;组件只接收标准 action、hooks 和纯呈现状态。 +- RFC、测试名称和 PR 描述只写最终产品语义,不保留 `reconcilePublishedDraft`、`pendingCwd` 等已经撤销的中间方案。 + +## Snapshot 与测试定位 + +- `apps/web/tests/**/*.snapshot.ts` 验证 built application,需用 `DSH_EXAMPLE_MODE=lib`,并确认相关 `lib/` 已由当前源码构建;普通 source-mode Vitest 通过不能替代它。 +- 对 runtime 管理的受控输入执行 `fireEvent.change` 后,必须 `waitFor` 输入值回显再点击发送,否则发送可能读取旧的空 prompt。 +- 页面中 Workspace 与 Session 可以同名,禁止用无作用域的 `findByText` 定位。先用 `within` 锁定 Sessions tree、计数或对应 group,再找目标行。 +- 新 push 后先看 assembled snapshot 是否真正跑过;本地 focused snapshot 通过后仍以 `gh pr checks` 的 artifact job 为准。 + +## Coverage 收口 + +- 测试筛选和 coverage 筛选是两件事。用 owning tests 配合逐个 `--coverage.include=''`,先拿到真实未覆盖行和分支,不要直接反复跑全仓 coverage。 +- 多个 coverage 进程并发时必须给不同的 `--coverage.reportsDirectory`,否则报告目录互相覆盖。各 worker 完成后再跑一次合并后的精确 coverage,确认共享 worktree 的改动组合起来仍为 100%。 +- 全仓 coverage 若先被无关测试超时打断,不能把它当作目标文件的结论;先用精确 include 修本分支缺口,再让 CI exhaustive coverage 验证整体。 +- Coverage 测试仍要描述行为,不写“为了覆盖某分支”的注释。不可达分支才使用已有规范允许的 `v8 ignore`,可达分支补真实行为测试。 + +## 并发与提交 + +- Coverage 适合按不相交写区并发:例如 Sidebar tests、Workspace picker tests、connection/storage tests。派工时明确“只改 tests、不改 src、不 commit、不得回滚他人改动”。 +- 不直接信任各 worker 的单独结果;主会话审查 diff、运行合并后的 focused coverage、清理生成报告,再统一 commit。 +- 推送前按 `dsh-pre-push-checks` 选择最小充分验证,不重复已经通过的检查;正常 push 让 pre-push typecheck 运行,并核对本地 HEAD 与远端 ref 一致。 +- 生成的 `.coverage/` 只属于本地诊断。环境拒绝 `rm -rf` 时,依次使用 `find .coverage -type f -delete` 和 `find .coverage -depth -type d -empty -delete`;不要让报告进入 commit。 + +## GitHub 与 CI + +- GitHub 操作统一走 `gh`,并从 git 配置注入代理:`proxy="$(git config --get http.https://github.com.proxy)"; https_proxy="$proxy" http_proxy="$proxy" GH_PAGER=cat ~/.local/bin/gh ...`。不要改用网页。 +- 每次 push 都会产生一轮新 checks;旧轮次的失败不能代表当前 HEAD。先确认 run 对应当前提交,再拉失败日志。 +- `gh run watch` 只监视一个 workflow。最终必须用 `gh pr checks` 汇总 CI、e2e、sandbox 和 Windows 等独立 workflow;偶发平台失败先等当前 HEAD 重跑结果,不预先修改无关代码。 +- PR base 和 description 在最终 push 后再次用 `gh pr edit --base ... --body-file ...` 同步。PR 描述应包含最终产品动线、架构边界和实际运行过的验证,不写仍待执行的承诺。 +- Review thread 用 GraphQL/`gh api` 检查 `isResolved` 和已有回复,避免对已经解决的旧实现评论重复修复。 From fd8d93da12903b8c9d8455cab0972ff272f36bc0 Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 25 Jul 2026 18:02:36 +0800 Subject: [PATCH 070/113] docs: prohibit creating PR labels --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 6ec6383d6a..eae3007c86 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,7 +111,7 @@ Real-API tests and demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, - **A tool's UI render intent is part of its design**, decided up front (`generic`/`terminal`/`diff`, `locations`); presentation methods are pure functions of `args` ([cookbook](docs/cookbook/adding-a-tool.md)). - **Plan unit, e2e, and snapshot coverage** for new seams, lifecycle shapes, and transcript surfaces; missing snapshot-harness support is part of the implementation, not deferred follow-up. - **Keep PRs coherent and merge with merge commits.** Split an independently meaningful feature or design decision into a separate or stacked PR when combining it obscures ownership, intent, or verification. Never squash/rebase or rewrite pushed branches; put a review fix on its introducing PR, then merge down the stack ([guide](docs/cookbook/responding-to-pr-review-on-a-stack.md)). -- Use matching existing PR labels (`documentation`, `web`, `tui`, `core`); never create one implicitly. +- Pick matching existing GitHub labels such as `documentation`, `web`, `tui`, or `core`; never create new labels. - TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)). - Files end with exactly one trailing newline; `git diff --cached --check` (pre-commit) gates it. From b78daaad8c97484754d5fb0fe706d4cac41c3dfa Mon Sep 17 00:00:00 2001 From: Hypatia May Date: Sat, 25 Jul 2026 18:14:36 +0800 Subject: [PATCH 071/113] fix(session-query): keep model tools opt-in --- ...model-facing-session-query-tools.i18n.yaml | 4 +- ...-07-24-model-facing-session-query-tools.md | 4 +- ...-24-model-facing-session-query-tools.zh.md | 4 +- docs/tool-catalog.md | 4 +- examples/acp-agent/README.md | 2 +- examples/acp-agent/composition.md | 12 - examples/acp-agent/cordis.yml | 20 - examples/acp-agent/fs.cordis.snapshot.yml | 23 +- examples/acp-agent/fs.cordis.yml | 23 +- .../session-query.cordis.snapshot.yml | 12 + examples/acp-agent/session-query.cordis.yml | 12 + examples/acp-agent/tests/acp.snapshot.ts | 5 +- .../system-prompt.expected.md | 78 -- .../tool-schemas.expected.json | 204 ------ .../both-mode-turn/system-prompt.expected.md | 78 -- .../both-mode-turn/tool-schemas.expected.json | 204 ------ .../code-mode-turn/system-prompt.expected.md | 78 -- .../system-prompt.expected.md | 78 -- .../system-prompt.expected.md | 2 - .../tool-schemas.expected.json | 204 ------ .../lsp-definition/system-prompt.expected.md | 2 - .../lsp-definition/tool-schemas.expected.json | 204 ------ .../pty-tools/system-prompt.expected.md | 2 - .../pty-tools/tool-schemas.expected.json | 204 ------ .../session-query-spill/session.jsonl | 2 +- .../system-prompt.expected.md | 27 + .../tool-schemas.expected.json | 677 ++++++++++++++++++ .../skill-load/system-prompt.expected.md | 2 - .../skill-load/tool-schemas.expected.json | 204 ------ .../text-turn/system-prompt.expected.md | 2 - .../text-turn/tool-schemas.expected.json | 204 ------ .../system-prompt.expected.md | 2 - .../tool-schemas.expected.json | 204 ------ examples/tui-agent/composition.md | 3 - examples/tui-agent/cordis.yml | 5 - packages/examples/acp-demo/README.md | 2 +- .../examples/acp-demo/tests/load-path.e2e.ts | 5 +- packages/examples/tui-demo/README.md | 2 +- packages/host/runtime/README.md | 44 +- packages/host/runtime/package.json | 1 - packages/host/runtime/src/boot.ts | 2 - .../host/runtime/tests/host-runtime.spec.ts | 5 +- packages/host/runtime/tsconfig.json | 3 - .../tool-session-query/README.md | 2 +- pnpm-lock.yaml | 3 - scripts/gen-tool-catalog.ts | 2 +- 46 files changed, 779 insertions(+), 2087 deletions(-) create mode 100644 examples/acp-agent/session-query.cordis.snapshot.yml create mode 100644 examples/acp-agent/session-query.cordis.yml create mode 100644 examples/acp-agent/tests/snapshots/session-query-spill/system-prompt.expected.md create mode 100644 examples/acp-agent/tests/snapshots/session-query-spill/tool-schemas.expected.json diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml index 86b4e1deed..bf64ecf4d3 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.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 -2026-07-24-model-facing-session-query-tools.md: bc9143150d1e17eda9eab7f4864ed3a2f4983157 -2026-07-24-model-facing-session-query-tools.zh.md: c8a0c70789f21e4bbca523b6acc81925fb17b604 +2026-07-24-model-facing-session-query-tools.md: f05f9792619155070ec1c5c721702d7ed94442ce +2026-07-24-model-facing-session-query-tools.zh.md: 2570dda4b3ff22ff26e12e2f9d1418d76f079f5c diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md index bc9143150d..f05f979261 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.md @@ -36,7 +36,7 @@ Session-level results include the latest folded title when available. Each tool ## Host composition -The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.sessionQuery`. TUI and Web use their existing timeout and spill policies. ACP mounts the same timeout policy and private local spill backend with the shared 50,000-byte inline threshold, so the five tools have one model-facing contract across hosts. Web also mounts the SQLite query backend at its persistence root; generic tool presentation requires no session-query-specific client plugin. +The consumer is an opt-in plugin. The shipped ACP, TUI, and Web compositions mount `ctx.sessionQuery` for their non-model consumers but do not mount `@deepseek-ai/dsh-tool-session-query`, so their default model requests gain no query prompt or schemas. A composition that opts in also chooses whether to mount the generic timeout and spill policies; the dedicated ACP snapshot fixture mounts both and uses private local spill storage. Generic tool presentation requires no session-query-specific client plugin. ## Alternatives considered @@ -48,7 +48,7 @@ The shipped ACP, TUI, and Web compositions all mount the consumer beside `ctx.se ## Verification -Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, parent-filter preauthorization and oracle resistance, changed-observation rejection, service-diagnostic redaction for ordinary and adversarial unknown values, best-effort cyclic-cause logging, logger-failure containment, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, exclusive search and parallel exact-read classification, count caps, exact-signal forwarding, abort-reason preservation, persistence cleanup quiescence, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Loader and assembled-host coverage proves that ACP, TUI, and Web register the tools with timeout and spill support, while keyless assembled ACP snapshots pin the prompt guidance and schemas plus path-independent exact event-read spill and retention behavior. +Package tests pin argument validation, filter translation, timestamp normalization, exact-workspace authorization, parent-filter preauthorization and oracle resistance, changed-observation rejection, service-diagnostic redaction for ordinary and adversarial unknown values, best-effort cyclic-cause logging, logger-failure containment, missing-identity behavior, hidden-boundary pruning, current-step exclusion, internal provider paging, exclusive search and parallel exact-read classification, count caps, exact-signal forwarding, abort-reason preservation, persistence cleanup quiescence, one-scan bounded batch title enrichment, projection-before-dequeue ordering, queued-work suppression, started-worker quiescence, per-header validation, title fallbacks, representative search/trace/read rendering, generic presentation, and disposable registration. Integration coverage uses the real SQLite FTS provider over live and persisted sessions. Default-host tests and assembled request-header snapshots prove that the model-facing consumer remains absent while `ctx.sessionQuery` stays available. A package-owned Loader smoke and dedicated keyless ACP snapshot explicitly mount the consumer with timeout and spill support, pinning its prompt guidance, schemas, and path-independent exact event-read retention behavior. ## Consequences diff --git a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md index c8a0c70789..2570dda4b3 100644 --- a/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md +++ b/.agents/notes/implemented/feature/2026-07-24-model-facing-session-query-tools.zh.md @@ -36,7 +36,7 @@ Status: implemented ## 宿主组合 -发布的 ACP、TUI 与 Web 组合都在 `ctx.sessionQuery` 旁挂载该消费者。TUI 与 Web 使用已有的超时与 spill 策略。ACP 挂载同一超时策略与私有本地 spill 后端,并采用共享的 50,000 字节行内阈值,因此五个工具在各宿主中具有同一面向模型的契约。Web 还在其持久化根目录挂载 SQLite 查询后端;通用工具表现无需会话查询专用客户端插件。 +该消费方是一个需显式启用的插件。发布的 ACP、TUI 与 Web 组合为其非模型消费方挂载 `ctx.sessionQuery`,但不挂载 `@deepseek-ai/dsh-tool-session-query`,因此其默认模型请求中不包含查询提示词或 schema。选择启用该插件的组合还要决定是否挂载通用的超时与 spill 策略;专用的 ACP 快照 fixture(测试前置数据)同时挂载这两项策略,并使用私有的本地 spill 存储。通用工具表现无需会话查询专用客户端插件。 ## 考虑过的替代方案 @@ -48,7 +48,7 @@ Status: implemented ## 验证 -包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、父级过滤预授权与抵御预言机探测、变更观测拒绝、普通值与对抗性未知值的服务诊断脱敏、尽力记录循环 cause、日志失败隔离、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、搜索独占与精确读取并行分类、数量上限、精确信号传递、中止原因保留、持久化清理静止、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。Loader 与组装宿主覆盖证明 ACP、TUI 和 Web 会注册带超时及 spill 支持的工具;无密钥组装 ACP 快照则固定提示词指导与 schema,以及与路径无关的精确事件读取 spill 与保留行为。 +包级测试固定参数校验、过滤条件转换、时间戳规范化、精确工作区授权、父级过滤预授权与抵御预言机探测、变更观测拒绝、普通值与对抗性未知值的服务诊断脱敏、尽力记录循环 cause、日志失败隔离、身份缺失行为、隐藏边界裁剪、当前步骤排除、内部提供方翻页、搜索独占与精确读取并行分类、数量上限、精确信号传递、中止原因保留、持久化清理静止、单次扫描且并发有界的批量标题扩充、先投影再取出下一个任务的顺序、抑制排队工作、等待已启动 worker 静止、逐会话头校验、标题回退、代表性搜索/追踪/读取渲染、通用表现与可释放注册。集成覆盖使用真实 SQLite FTS 提供方查询实时与持久化会话。默认宿主测试与组装后的请求头快照证明:面向模型的消费方仍未挂载,而 `ctx.sessionQuery` 保持可用。包自身的 Loader 冒烟测试与专用无密钥 ACP 快照显式挂载该消费方,并配套启用超时与 spill 支持,固定其提示词指引、schema 以及与路径无关的精确事件读取保留行为。 ## 后果 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 06a0ec989c..3cdc822a7a 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -27,7 +27,7 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.tools`, `ctx.lsp`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The lsp tool keeps provider selection and language-server subprocesses behind ctx.lsp, so its model-visible schema stays stable across providers. Requires a registered provider (e.g. `@deepseek-ai/dsh-lsp-local`) at runtime; without one, a query returns the structured `LSP_UNAVAILABLE` error rather than changing the schema. | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`, `ctx.workflows`, `ctx.subagents`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents every fresh round)` | `tool/call`, `tool/result`, `workflow and child session events during execution` | - | A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap. | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.tools`, `ctx.skills` | `tool/call`, `tool/result` | - | - | -| `@deepseek-ai/dsh-tool-session-query` | `session_event_read`, `session_event_search`, `session_event_trace`, `session_search`, `session_trace` | `ctx.tools`, `ctx.systemPrompt`, `ctx.sessionQuery`, `a calling Agent for workspace authority` | `tool/call`, `tool/result` | - | The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. Default ACP, TUI, and Web compositions enforce the declared search timeout and apply the generic tool-result spill policy. | +| `@deepseek-ai/dsh-tool-session-query` | `session_event_read`, `session_event_search`, `session_event_trace`, `session_search`, `session_trace` | `ctx.tools`, `ctx.systemPrompt`, `ctx.sessionQuery`, `a calling Agent for workspace authority` | `tool/call`, `tool/result` | - | The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies. | | `@deepseek-ai/dsh-tool-subagent` | `subagent` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The registered tool name is the load-time `toolName` config (default `subagent`); the schema above is that default. The shipped example agents load this package once per subagent backend, so the model additionally sees `subagent_fork` (bound to the fork backend) with an identical schema — see `examples/tui-agent/cordis.yml` and `examples/acp-agent/cordis.yml`. | | `@deepseek-ai/dsh-tool-tasks` | `task_kill`, `task_list`, `task_output` | `ctx.tools`, `ctx.tasks`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-task control surface: background bash commands, PTY sends, and subagents are read, listed, and killed through the same three tools. Loading the plugin attaches the control surface that arms producers' `ctx.tasks.start()`. | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`, `owning Agent session` | `tool/call`, `todo/write`, `tool/result` | - | todo_write is session-owned state; UIs render the latest todo/write event as a checklist. | @@ -1010,7 +1010,7 @@ Read the authorized session lineage around one session, including complete visib Source: [`packages/session-query/tool-session-query/src/index.ts`](../packages/session-query/tool-session-query/src/index.ts) -The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. Default ACP, TUI, and Web compositions enforce the declared search timeout and apply the generic tool-result spill policy. +The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies. ## `@deepseek-ai/dsh-tool-subagent` diff --git a/examples/acp-agent/README.md b/examples/acp-agent/README.md index 52cc51db15..892a32cdc7 100644 --- a/examples/acp-agent/README.md +++ b/examples/acp-agent/README.md @@ -7,7 +7,7 @@ pnpm run demo:acp # needs DEEPSEEK_API_KEY (repo-root .env or env) pnpm run demo:code-mode acp # same protocol with the Code Mode tool transport ``` -The leaf loads the ACP app, DeepSeek adapter, sandboxed bash and filesystem stacks, one-shot approval policy, compaction, subagents, workflows, hooks, a derived session-query index, workspace-authorized session-query tools, generic timeout and local spill policies, and repeat guard. The app creates one fresh agent per `session/new`, persists sessions to JSONL, and keeps stdout protocol-pure. [`fs.cordis.yml`](fs.cordis.yml) redirects spill storage and lowers the inline threshold for dedicated filesystem scenarios; [`code-mode.cordis.yml`](code-mode.cordis.yml) adds `run_code` and its generated TypeScript SDK. +The leaf loads the ACP app, DeepSeek adapter, sandboxed bash and filesystem stacks, one-shot approval policy, compaction, subagents, workflows, hooks, a derived session-query index, and repeat guard. The app creates one fresh agent per `session/new`, persists sessions to JSONL, and keeps stdout protocol-pure. [`session-query.cordis.yml`](session-query.cordis.yml) explicitly opts into the workspace-authorized query tools and generic timeout/spill policies for their dedicated snapshot; [`fs.cordis.yml`](fs.cordis.yml) adds spill storage for filesystem scenarios, while [`code-mode.cordis.yml`](code-mode.cordis.yml) adds `run_code` and its generated TypeScript SDK. ## Protocol channel diff --git a/examples/acp-agent/composition.md b/examples/acp-agent/composition.md index ba9ece13b5..8d112f2910 100644 --- a/examples/acp-agent/composition.md +++ b/examples/acp-agent/composition.md @@ -27,14 +27,6 @@ flowchart LR bundle_agent_core --> spine_sessions["ctx.sessions"] bundle_agent_core --> spine_tools["ctx.tools + tool-bash"] bundle_agent_core --> spine_loop["ctx.agents + ctx.agentLoop"] - plugin_acp_tool_session_query["tool-session-query
@deepseek-ai/dsh-tool-session-query"] - cfg --> plugin_acp_tool_session_query - plugin_acp_timeout_policy["timeout-policy
@deepseek-ai/dsh-timeout-policy"] - cfg --> plugin_acp_timeout_policy - plugin_acp_spill_local["spill-local
@deepseek-ai/dsh-spill-local"] - cfg --> plugin_acp_spill_local - plugin_acp_spill_policy["spill-policy
@deepseek-ai/dsh-spill-policy"] - cfg --> plugin_acp_spill_policy plugin_acp_token_meter["token-meter
@deepseek-ai/dsh-token-meter"] cfg --> plugin_acp_token_meter plugin_acp_compact_basic["compact-basic
@deepseek-ai/dsh-compact-basic"] @@ -79,10 +71,6 @@ flowchart LR | `bash` | `@deepseek-ai/dsh-bash-sandbox` | | `approval` | `@deepseek-ai/dsh-user-approval` | | `acp-agent` | `@deepseek-ai/dsh-acp-demo` | -| `tool-session-query` | `@deepseek-ai/dsh-tool-session-query` | -| `timeout-policy` | `@deepseek-ai/dsh-timeout-policy` | -| `spill-local` | `@deepseek-ai/dsh-spill-local` | -| `spill-policy` | `@deepseek-ai/dsh-spill-policy` | | `token-meter` | `@deepseek-ai/dsh-token-meter` | | `compact-basic` | `@deepseek-ai/dsh-compact-basic` | | `subagent` | `@deepseek-ai/dsh-subagent` | diff --git a/examples/acp-agent/cordis.yml b/examples/acp-agent/cordis.yml index 484809db04..fa7f6ad4ef 100644 --- a/examples/acp-agent/cordis.yml +++ b/examples/acp-agent/cordis.yml @@ -63,26 +63,6 @@ Verify your work by running the code or tests. Keep answers brief and factual. -# The automation app opens ctx.sessionQuery before its ACP transport; this leaf -# owns the workspace-authorized model-facing consumer. -- id: tool-session-query - name: '@deepseek-ai/dsh-tool-session-query' - -# Enforce declared search deadlines and spill oversized plain-text tool output -# without introducing a session-query-specific truncation path. -- id: timeout-policy - name: '@deepseek-ai/dsh-timeout-policy' - -- id: spill-local - name: '@deepseek-ai/dsh-spill-local' - config: - root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT - -- id: spill-policy - name: '@deepseek-ai/dsh-spill-policy' - config: - maxInlineBytes: 50000 - # Replay-aware request pressure; the routed adapter supplies model capacity. - id: token-meter name: '@deepseek-ai/dsh-token-meter' diff --git a/examples/acp-agent/fs.cordis.snapshot.yml b/examples/acp-agent/fs.cordis.snapshot.yml index 29cef3fe82..0417074edd 100644 --- a/examples/acp-agent/fs.cordis.snapshot.yml +++ b/examples/acp-agent/fs.cordis.snapshot.yml @@ -1,6 +1,7 @@ -# Keyless filesystem snapshots patch the base spill stack and apply the replay -# overlay directly. The sandboxed filesystem stack already lives in the base -# cordis.yml. This file also re-pins the acp-agent model to `deepseek-v4-flash`: `cordis.yml` ships +# Keyless filesystem snapshots apply the spill and replay overlays directly +# because include patches cannot target entries behind a nested include. The +# sandboxed filesystem stack already lives in the base cordis.yml. This file also +# re-pins the acp-agent model to `deepseek-v4-flash`: `cordis.yml` ships # `deepseek-v4-pro`, but the recorded corpus was captured on flash, and a config # patch replaces the whole app config, so the base fields are restated verbatim. - id: base @@ -24,15 +25,15 @@ You are a coding assistant powered by the {{model}} model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. Verify your work by running the code or tests. Keep answers brief and factual. - - id: spill-local - name: '@deepseek-ai/dsh-spill-local' - config: - root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' - - id: spill-policy - name: '@deepseek-ai/dsh-spill-policy' - config: - maxInlineBytes: 800 - insert: + - id: spill-local + name: '@deepseek-ai/dsh-spill-local' + config: + root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' + - id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: 800 - id: llm-replay name: '@deepseek-ai/dsh-llm-replay' config: diff --git a/examples/acp-agent/fs.cordis.yml b/examples/acp-agent/fs.cordis.yml index 4528ccf7c0..0d667255c8 100644 --- a/examples/acp-agent/fs.cordis.yml +++ b/examples/acp-agent/fs.cordis.yml @@ -1,16 +1,17 @@ -# Filesystem-scenario overlay: the sandboxed filesystem and generic spill stacks -# already live in the base cordis.yml, so this overlay only redirects spill -# storage and lowers the inline threshold for dedicated scenarios. +# Filesystem-scenario overlay: the sandboxed filesystem stack already lives in +# the base cordis.yml, so this overlay adds only the local tool-result spill +# storage those scenarios exercise. - id: base name: '@cordisjs/plugin-include' config: path: ./cordis.yml patches: - - id: spill-local - name: '@deepseek-ai/dsh-spill-local' - config: - root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' - - id: spill-policy - name: '@deepseek-ai/dsh-spill-policy' - config: - maxInlineBytes: !!js process.env.DSH_SNAPSHOT && 800 || 50000 + - insert: + - id: spill-local + name: '@deepseek-ai/dsh-spill-local' + config: + root: !!js process.env.DSH_SNAPSHOT_SPILL_ROOT ?? './.spill' + - id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: !!js process.env.DSH_SNAPSHOT && 800 || 50000 diff --git a/examples/acp-agent/session-query.cordis.snapshot.yml b/examples/acp-agent/session-query.cordis.snapshot.yml new file mode 100644 index 0000000000..1edadf8374 --- /dev/null +++ b/examples/acp-agent/session-query.cordis.snapshot.yml @@ -0,0 +1,12 @@ +# Keyless counterpart to session-query.cordis.yml: the nested snapshot overlay +# supplies replay plus deterministic private spill storage and its byte limit. +- id: base + name: '@cordisjs/plugin-include' + config: + path: ./fs.cordis.snapshot.yml + patches: + - insert: + - id: tool-session-query + name: '@deepseek-ai/dsh-tool-session-query' + - id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' diff --git a/examples/acp-agent/session-query.cordis.yml b/examples/acp-agent/session-query.cordis.yml new file mode 100644 index 0000000000..e5e45025df --- /dev/null +++ b/examples/acp-agent/session-query.cordis.yml @@ -0,0 +1,12 @@ +# Explicit session-query tool opt-in for the dedicated spill scenario. The +# nested filesystem overlay supplies private spill storage and its byte limit. +- id: base + name: '@cordisjs/plugin-include' + config: + path: ./fs.cordis.yml + patches: + - insert: + - id: tool-session-query + name: '@deepseek-ai/dsh-tool-session-query' + - id: timeout-policy + name: '@deepseek-ai/dsh-timeout-policy' diff --git a/examples/acp-agent/tests/acp.snapshot.ts b/examples/acp-agent/tests/acp.snapshot.ts index f7fa1a2a47..8e74711a57 100644 --- a/examples/acp-agent/tests/acp.snapshot.ts +++ b/examples/acp-agent/tests/acp.snapshot.ts @@ -34,6 +34,7 @@ const BOTH_MODE_CONFIG = fileURLToPath(new URL('../both-mode.cordis.yml', import const WORKSPACE_CONTEXT_CONFIG = fileURLToPath(new URL('../workspace-context.cordis.yml', import.meta.url)) const ADVANCED_CONFIG = fileURLToPath(new URL('../advanced.cordis.yml', import.meta.url)) const FS_CONFIG = fileURLToPath(new URL('../fs.cordis.yml', import.meta.url)) +const SESSION_QUERY_CONFIG = fileURLToPath(new URL('../session-query.cordis.yml', import.meta.url)) const PTY_CONFIG = fileURLToPath(new URL('../pty.cordis.yml', import.meta.url)) const DEPTH_TWO_CONFIG = fileURLToPath(new URL('../depth-two.cordis.yml', import.meta.url)) const PACKED_CHUNKS_CONFIG = fileURLToPath(new URL('../packed-chunks.cordis.yml', import.meta.url)) @@ -92,7 +93,9 @@ const SCENARIOS: Scenario[] = [ name: 'session-query-spill', hasModelTurn: true, recorded: false, - configPath: FS_CONFIG, + pinsHeader: true, + headerClass: 'session-query', + configPath: SESSION_QUERY_CONFIG, posixOnly: true, }, { diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md index d45a386c99..fde52770d5 100644 --- a/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -115,77 +113,6 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; - /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ - session_event_read: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - /** Number of preceding raw events to summarize. Omit for none. */ - before?: number; - /** Number of following raw events to summarize. Omit for none. */ - after?: number; - } & Record; - /** Search prior events in one authorized session; the current session excludes the step performing this call. */ - session_event_search: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Literal full-text query over the target session. */ - query: string; - /** Inclusive event sequence lower bound. */ - seq_from?: number; - /** Inclusive event sequence upper bound. */ - seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read every direct replacement and provenance relationship for one event in an authorized session. */ - session_event_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - } & Record; - /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ - session_search: { - /** Literal full-text query over prior session history. */ - query: string; - /** Optional session ids to include. */ - session_ids?: string[]; - /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ - created_at_from?: string; - /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ - created_at_to?: string; - /** Optional direct parent session ids. */ - parent_session_ids?: string[]; - /** Include sessions with no parent in the parent filter. */ - include_root_sessions?: boolean; - /** Require at least one selected source availability. */ - availability?: ("live" | "persisted")[]; - /** Inclusive event sequence lower bound. */ - event_seq_from?: number; - /** Inclusive event sequence upper bound. */ - event_seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - event_time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - event_time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - event_surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ - session_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -385,11 +312,6 @@ interface ToolOutputMap { }[]; totalLines: number; }; - session_event_read: string; - session_event_search: string; - session_event_trace: string; - session_search: string; - session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json index bb239d8c2d..73b9176478 100644 --- a/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/advanced-toolchain/tool-schemas.expected.json @@ -232,210 +232,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md index b66bb0de0c..3817b0bc8a 100644 --- a/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -98,77 +96,6 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; - /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ - session_event_read: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - /** Number of preceding raw events to summarize. Omit for none. */ - before?: number; - /** Number of following raw events to summarize. Omit for none. */ - after?: number; - } & Record; - /** Search prior events in one authorized session; the current session excludes the step performing this call. */ - session_event_search: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Literal full-text query over the target session. */ - query: string; - /** Inclusive event sequence lower bound. */ - seq_from?: number; - /** Inclusive event sequence upper bound. */ - seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read every direct replacement and provenance relationship for one event in an authorized session. */ - session_event_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - } & Record; - /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ - session_search: { - /** Literal full-text query over prior session history. */ - query: string; - /** Optional session ids to include. */ - session_ids?: string[]; - /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ - created_at_from?: string; - /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ - created_at_to?: string; - /** Optional direct parent session ids. */ - parent_session_ids?: string[]; - /** Include sessions with no parent in the parent filter. */ - include_root_sessions?: boolean; - /** Require at least one selected source availability. */ - availability?: ("live" | "persisted")[]; - /** Inclusive event sequence lower bound. */ - event_seq_from?: number; - /** Inclusive event sequence upper bound. */ - event_seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - event_time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - event_time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - event_surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ - session_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -356,11 +283,6 @@ interface ToolOutputMap { }[]; totalLines: number; }; - session_event_read: string; - session_event_search: string; - session_event_trace: string; - session_search: string; - session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json index ac3323d626..0fc8107917 100644 --- a/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/both-mode-turn/tool-schemas.expected.json @@ -175,210 +175,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md index b66bb0de0c..3817b0bc8a 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -98,77 +96,6 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; - /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ - session_event_read: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - /** Number of preceding raw events to summarize. Omit for none. */ - before?: number; - /** Number of following raw events to summarize. Omit for none. */ - after?: number; - } & Record; - /** Search prior events in one authorized session; the current session excludes the step performing this call. */ - session_event_search: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Literal full-text query over the target session. */ - query: string; - /** Inclusive event sequence lower bound. */ - seq_from?: number; - /** Inclusive event sequence upper bound. */ - seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read every direct replacement and provenance relationship for one event in an authorized session. */ - session_event_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - } & Record; - /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ - session_search: { - /** Literal full-text query over prior session history. */ - query: string; - /** Optional session ids to include. */ - session_ids?: string[]; - /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ - created_at_from?: string; - /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ - created_at_to?: string; - /** Optional direct parent session ids. */ - parent_session_ids?: string[]; - /** Include sessions with no parent in the parent filter. */ - include_root_sessions?: boolean; - /** Require at least one selected source availability. */ - availability?: ("live" | "persisted")[]; - /** Inclusive event sequence lower bound. */ - event_seq_from?: number; - /** Inclusive event sequence upper bound. */ - event_seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - event_time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - event_time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - event_surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ - session_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -356,11 +283,6 @@ interface ToolOutputMap { }[]; totalLines: number; }; - session_event_read: string; - session_event_search: string; - session_event_trace: string; - session_search: string; - session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md index b66bb0de0c..3817b0bc8a 100644 --- a/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/code-mode-workspace-context/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). @@ -98,77 +96,6 @@ interface ToolArgsMap { /** Maximum number of lines to return. Defaults to 2000. */ limit?: number; } & Record; - /** Read one full unabridged event and optional neighboring raw-event summaries from an authorized session. */ - session_event_read: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - /** Number of preceding raw events to summarize. Omit for none. */ - before?: number; - /** Number of following raw events to summarize. Omit for none. */ - after?: number; - } & Record; - /** Search prior events in one authorized session; the current session excludes the step performing this call. */ - session_event_search: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Literal full-text query over the target session. */ - query: string; - /** Inclusive event sequence lower bound. */ - seq_from?: number; - /** Inclusive event sequence upper bound. */ - seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read every direct replacement and provenance relationship for one event in an authorized session. */ - session_event_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - /** Target event sequence number. */ - seq: number; - } & Record; - /** Search prior sessions in the caller workspace and return the strongest matching event from each session. */ - session_search: { - /** Literal full-text query over prior session history. */ - query: string; - /** Optional session ids to include. */ - session_ids?: string[]; - /** Inclusive timezone-qualified ISO 8601 creation-time lower bound. */ - created_at_from?: string; - /** Inclusive timezone-qualified ISO 8601 creation-time upper bound. */ - created_at_to?: string; - /** Optional direct parent session ids. */ - parent_session_ids?: string[]; - /** Include sessions with no parent in the parent filter. */ - include_root_sessions?: boolean; - /** Require at least one selected source availability. */ - availability?: ("live" | "persisted")[]; - /** Inclusive event sequence lower bound. */ - event_seq_from?: number; - /** Inclusive event sequence upper bound. */ - event_seq_to?: number; - /** Inclusive timezone-qualified ISO 8601 event-time lower bound. */ - event_time_from?: string; - /** Inclusive timezone-qualified ISO 8601 event-time upper bound. */ - event_time_to?: string; - /** Event types to include. */ - event_types?: string[]; - /** Event surfaces to include. */ - event_surfaces?: ("current" | "shadowed" | "log-only")[]; - } & Record; - /** Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships. */ - session_trace: { - /** Target session id. Omit for the current session. */ - session_id?: string; - } & Record; /** Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill. */ skill: { /** The exact skill name from the available skills list. */ @@ -356,11 +283,6 @@ interface ToolOutputMap { }[]; totalLines: number; }; - session_event_read: string; - session_event_search: string; - session_event_trace: string; - session_search: string; - session_trace: string; skill: { name: string; provider: string; diff --git a/examples/acp-agent/tests/snapshots/escalation-approved/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/escalation-approved/system-prompt.expected.md index 362d0a6355..e3437ad61a 100644 --- a/examples/acp-agent/tests/snapshots/escalation-approved/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/escalation-approved/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. diff --git a/examples/acp-agent/tests/snapshots/escalation-approved/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/escalation-approved/tool-schemas.expected.json index dde0ba0d7a..d4973bfea4 100644 --- a/examples/acp-agent/tests/snapshots/escalation-approved/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/escalation-approved/tool-schemas.expected.json @@ -159,210 +159,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md index cb50752e91..7bde8fe289 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/lsp-definition/system-prompt.expected.md @@ -17,8 +17,6 @@ Track every background task id you start. You are notified in-session when a tas Use search/read for ordinary navigation. Use lsp when textual matches are ambiguous or before a change requires precise definitions, implementations, or references. Positions are one-based line and character (UTF-16) at the cursor; an off-symbol position may return no results. findReferences always includes the declaration. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json index 3d28b1dfb8..5d27e93da3 100644 --- a/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/lsp-definition/tool-schemas.expected.json @@ -196,210 +196,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md index ccce83d9b7..df065a83cb 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/pty-tools/system-prompt.expected.md @@ -17,8 +17,6 @@ Use a terminal session only when work needs persistent terminal state or interac Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json index d29602b97d..e9f7a2ea63 100644 --- a/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/pty-tools/tool-schemas.expected.json @@ -159,210 +159,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl b/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl index 6d8a294c1e..26fd2bf5c1 100644 --- a/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl +++ b/examples/acp-agent/tests/snapshots/session-query-spill/session.jsonl @@ -11,7 +11,7 @@ {"type":"assistant/chunk","seq":9,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}} {"type":"assistant/message","seq":10,"time":0,"data":{"turn":1,"step":1,"content":[{"type":"tool-call","id":"call_session_query_spill","name":"session_event_read","arguments":"{\"seq\":4}"}],"provenance":{"provider":"deepseek","model":"deepseek-v4-flash"},"usage":{"inputTokens":10,"outputTokens":5}},"sourceEventSeqs":[5,6,7,8,9],"surfaceOp":"append"} {"type":"tool/call","seq":11,"time":0,"data":{"turn":1,"step":1,"callId":"call_session_query_spill","name":"session_event_read","arguments":"{\"seq\":4}"}} -{"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"call_session_query_spill","content":[{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": 1784876318672,\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted 39431 bytes. Full formatted result stored at: /tmp/dsh-acp-snap-035d1d054/session-ac29d2afe494/505bce11df84-session_event_read.txt. Use read with offset/limit, or grep this path to search within it.)"}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} +{"type":"tool/result","seq":12,"time":0,"data":{"turn":1,"step":1,"callId":"call_session_query_spill","content":[{"type":"text","text":"Session {{sessionId}} — Read request event 4 with\nTarget event seq 4:\n```json\n{\n \"type\": \"request/header\",\n \"seq\": 4,\n \"time\": 1784876318672,\n \"data\": {\n \"header\": {\n \"config\": {\n \"provider\": \"deepseek\",\n \"model\": \"deepseek-v4-flash\"\n },\n rmissions: one sentence for the user explaining why this exact file operation needs the wider access.\"\n }\n },\n \"required\": [\n \"file_path\",\n \"content\"\n ]\n }\n }\n ]\n },\n \"reason\": \"initial\"\n }\n}\n```\n\n(Omitted 36006 bytes. Full formatted result stored at: /tmp/dsh-acp-snap-035d1d054/session-ac29d2afe494/505bce11df84-session_event_read.txt. Use read with offset/limit, or grep this path to search within it.)"}],"isError":false},"sourceEventSeqs":[11],"surfaceOp":"append"} {"type":"step/end","seq":13,"time":0,"data":{"turn":1,"step":1}} {"type":"step/start","seq":14,"time":0,"data":{"turn":1,"step":2}} {"type":"assistant/chunk","seq":15,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}} diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/session-query-spill/system-prompt.expected.md new file mode 100644 index 0000000000..68bdd841c7 --- /dev/null +++ b/examples/acp-agent/tests/snapshots/session-query-spill/system-prompt.expected.md @@ -0,0 +1,27 @@ +You are an AI agent powered by the DeepSeek Harness SDK. + +You are a coding assistant powered by the deepseek-v4-flash model. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox — a `[sandbox: file access denied …]` result is policy, not a command bug. + +Verify your work by running the code or tests. Keep answers brief and factual. + + +Use the read tool — not shell commands like cat — to inspect text files. Results include line numbers. Use offset and limit to continue reading large files. + +Use the write tool to create files or completely replace file contents. Existing files are overwritten, so read an existing file first (the default fs-policy requires it) and prefer edit for targeted changes. + +Use the edit tool for targeted changes to existing UTF-8 text files. It replaces literal old_string with new_string; by default old_string must appear exactly once. If old_string appears multiple times, provide a more specific old_string or set replace_all to true. Read the file first (the default fs-policy requires it), unless you just created or edited it in this session. + +Check the [exit code: N] marker on every bash result; investigate failures before moving on. + +Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. + +Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. + +Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. + +Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). + + +Use the workflow tool ONLY when the user explicitly asks for a workflow or for large multi-agent orchestration: you write a JavaScript script (the tool description documents the exact format) that fans work out across many subagents with phases and structured results. For one or two delegations, prefer plain subagent calls. + +Use the ralph tool ONLY when the direct human explicitly asks for a Ralph loop or fresh-agent iterative execution. Each Ralph round starts a fresh child with no conversation seed and uses the shared workspace as durable memory. Completion and blockers are worker reports, not independent evaluation. Use same-session goal tools for ordinary long-running objectives, and plain subagents or workflows for bounded delegation and fan-out. diff --git a/examples/acp-agent/tests/snapshots/session-query-spill/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/session-query-spill/tool-schemas.expected.json new file mode 100644 index 0000000000..dde0ba0d7a --- /dev/null +++ b/examples/acp-agent/tests/snapshots/session-query-spill/tool-schemas.expected.json @@ -0,0 +1,677 @@ +{ + "initial": [ + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell: no state (cwd, variables, functions) persists between calls — pass `workdir` instead of using `cd`. Non-zero exits are reported as `[exit code: N]`. Current harness environment facts are exposed through managed `$DSH_*` variables; inspect them when needed. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]` — a policy denial, not a bug in the command; do not retry another way. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Set `run_in_background: true` for long-running commands: the call returns a task id immediately; read its output with `task_output` and stop it with `task_kill`. Attempting a command the sandbox may deny is safe and expected: run it and read the marker rather than assuming the denial. When a command is denied and a wider mode would let it succeed, escalate immediately in the same turn — the one sanctioned exception to a denial: retry the exact same command once with `sandbox_permissions` (the narrowest wider mode that suffices) plus a one-sentence `justification`. Do not detour through chat to ask permission first — the approval prompt raised by that retry is how the user consents. If the session states approval prompts are disabled, there is no exception: a denial is final — do not set `sandbox_permissions`. Never escalate speculatively: ground the request in a real denial — normally the one this command just hit; escalating up front is fine only when this session already denied the same access. A rejected escalation is final for that command — stop and explain, never work around it — but it does not forbid attempting or escalating other commands later.", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap, and kills the command on expiry." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a task id immediately (collect with task_output, stop with task_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this command needs. Only valid as a one-shot retry of a command the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access." + } + }, + "required": [ + "command", + "description" + ] + } + }, + { + "name": "create_goal", + "description": "Create one persisted same-session completion goal when the current direct human request is a long-running objective that should continue across autonomous goal rounds. You may infer that intent without requiring the user to say \"create a goal\". Do not use this for trivial single-turn work. Execution rejects non-human and subagent authority.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace. Must match exactly." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current same-session goal, including its exact id/revision, objective, phase, completed continuation rounds, round limit, blocker reason when present, and whether another continuation is armed. Call this before updating a goal.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "ralph", + "description": "Run a foreground fresh-agent Ralph loop toward one immutable objective. Use only when the direct human explicitly asks for Ralph or fresh-agent iteration. Each round opens a new child with no parent conversation or prior child session; the shared workspace is long-term memory, and only a bounded structured report crosses rounds. The call returns when a worker reports completion or a concrete blocker, or at the round limit. Ordinary long-running same-session work belongs to goal tools.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The immutable completion objective for every fresh Ralph round." + }, + "maxRounds": { + "type": "number", + "description": "Optional positive safe-integer round cap, bounded by the deployment ceiling." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "session_event_read", + "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + }, + "before": { + "type": "integer", + "description": "Number of preceding raw events to summarize. Omit for none." + }, + "after": { + "type": "integer", + "description": "Number of following raw events to summarize. Omit for none." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_event_search", + "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "query": { + "type": "string", + "description": "Literal full-text query over the target session." + }, + "seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_event_trace", + "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + }, + "seq": { + "type": "integer", + "description": "Target event sequence number." + } + }, + "required": [ + "seq" + ] + } + }, + { + "name": "session_search", + "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", + "parameters": { + "type": "object", + "properties": { + "query": { + "type": "string", + "description": "Literal full-text query over prior session history." + }, + "session_ids": { + "type": "array", + "description": "Optional session ids to include.", + "items": { + "type": "string" + } + }, + "created_at_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." + }, + "created_at_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." + }, + "parent_session_ids": { + "type": "array", + "description": "Optional direct parent session ids.", + "items": { + "type": "string" + } + }, + "include_root_sessions": { + "type": "boolean", + "description": "Include sessions with no parent in the parent filter." + }, + "availability": { + "type": "array", + "description": "Require at least one selected source availability.", + "items": { + "type": "string", + "enum": [ + "live", + "persisted" + ] + } + }, + "event_seq_from": { + "type": "integer", + "description": "Inclusive event sequence lower bound." + }, + "event_seq_to": { + "type": "integer", + "description": "Inclusive event sequence upper bound." + }, + "event_time_from": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." + }, + "event_time_to": { + "type": "string", + "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." + }, + "event_types": { + "type": "array", + "description": "Event types to include.", + "items": { + "type": "string" + } + }, + "event_surfaces": { + "type": "array", + "description": "Event surfaces to include.", + "items": { + "type": "string", + "enum": [ + "current", + "shadowed", + "log-only" + ] + } + } + }, + "required": [ + "query" + ] + } + }, + { + "name": "session_trace", + "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", + "parameters": { + "type": "object", + "properties": { + "session_id": { + "type": "string", + "description": "Target session id. Omit for the current session." + } + } + } + }, + { + "name": "skill", + "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) and return its final result. Use this to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent runs to completion and you receive only its final answer, not its intermediate steps. Give it a complete, standalone prompt: it does not see this conversation. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn), returning only its final result. Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive only its final answer, not its intermediate steps. Set `run_in_background: true` to return a task id; collect with `task_output` and stop with `task_kill`.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background task and return its id; collect with task_output or stop with task_kill." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "task_kill", + "description": "Request cancellation of a running background task by task id. Returns immediately; the task settles as killed once its work actually stops.", + "parameters": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "Task id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the task." + } + }, + "required": [ + "task_id" + ] + } + }, + { + "name": "task_list", + "description": "List your background tasks (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "task_output", + "description": "Read a background task. Stream tasks return only output since the previous read; final-output tasks return their result after settlement. Every response ends with `[status: ...]`. Reads are non-blocking unless `wait: true`, which waits up to the configured cap.", + "parameters": { + "type": "object", + "properties": { + "task_id": { + "type": "string", + "description": "Task id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the task reaches a terminal status or the timeout expires. A timed-out wait returns [status: running] and leaves the task alive." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds (only meaningful with wait: true). Defaults to the configured wait timeout; capped by the configured maximum." + } + }, + "required": [ + "task_id" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (there are no partial updates, no per-item edits). Use it to plan multi-step work and show progress: add one todo per concrete step before you start. Keep AT MOST ONE todo `in_progress` at a time; while work remains, exactly one active task should be `in_progress`. Mark a todo `completed` the moment it is done (do not batch completions), and allow no `in_progress` item only once all work is complete. Skip the list for trivial single-step tasks. Statuses: `pending` (not started), `in_progress` (being worked on now), `completed` (finished).", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the exact current goal revision. edit, pause, and resume require a direct top-level human request. During an automatic continuation of the current goal, complete and blocked are also allowed. blocked is rejected before the configured minimum round count; the model remains responsible for judging that the same condition persisted across those rounds and must explain it in blocked_reason.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit | pause | resume | complete | blocked", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Concrete blocking condition; required only with action blocked." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nThe workflow's identity rides the `meta` parameter as JSON: required `name` (short kebab-case) and `description` strings, optional `whenToUse` string and `phases` array (`{title, detail?, provider?, model?}`). The `script` parameter is the plain JavaScript body ONLY (NOT TypeScript, and NO `export const meta` statement — meta is a parameter, not code), running with top-level await; end with `return ` — the value must be JSON-serializable and is this tool's result.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf — no pattern/format/numeric bounds) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides (either may be provided alone). Anything else (`effort`/`isolation`/`agentType`) is rejected loudly.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. An ordinary stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) throw errors that ALWAYS kill the script — they never dissolve into a per-item `null`.\n\nConstraints: concurrency and total-agent caps apply; no filesystem, network, timers, or Node.js APIs are provided — the agents do the work, the script only coordinates them. The run executes in the foreground: this call returns when the whole script finishes.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain-JS workflow script body (top-level await allowed; NO `export const meta` statement; end with `return `)." + }, + "meta": { + "type": "object", + "description": "The workflow identity block (plain JSON — never code).", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The wider sandbox mode this file operation needs. Only valid as a one-shot retry of an operation the sandbox just denied; requires justification and user approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + "changes": [] +} diff --git a/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md index 68bdd841c7..17e6773a03 100644 --- a/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/skill-load/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json index dde0ba0d7a..d4973bfea4 100644 --- a/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/skill-load/tool-schemas.expected.json @@ -159,210 +159,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md index 68bdd841c7..17e6773a03 100644 --- a/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/text-turn/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json index dde0ba0d7a..d4973bfea4 100644 --- a/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/text-turn/tool-schemas.expected.json @@ -159,210 +159,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md b/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md index 45c9e0970c..6cd8d5725f 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md +++ b/examples/acp-agent/tests/snapshots/workspace-context/system-prompt.expected.md @@ -15,8 +15,6 @@ Check the [exit code: N] marker on every bash result; investigate failures befor Track every background task id you start. You are notified in-session when a task finishes — do not busy-poll or sleep on one; keep working on independent steps and do not duplicate a running task's work. Before giving a final answer, collect every still-relevant task with task_output (set wait: true only when you are genuinely blocked on it), and task_kill tasks that stopped mattering. -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. - Use goal tools for one long-running completion objective in the current session. create_goal may infer goal intent from a direct human request in any language; do not create a goal for routine single-turn work. Call get_goal before update_goal and copy its exact goal_id and revision. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least 3 consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked. Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`). diff --git a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json index dde0ba0d7a..d4973bfea4 100644 --- a/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json +++ b/examples/acp-agent/tests/snapshots/workspace-context/tool-schemas.expected.json @@ -159,210 +159,6 @@ ] } }, - { - "name": "session_event_read", - "description": "Read one full unabridged event and optional neighboring raw-event summaries from an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - }, - "before": { - "type": "integer", - "description": "Number of preceding raw events to summarize. Omit for none." - }, - "after": { - "type": "integer", - "description": "Number of following raw events to summarize. Omit for none." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_event_search", - "description": "Search prior events in one authorized session; the current session excludes the step performing this call.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "query": { - "type": "string", - "description": "Literal full-text query over the target session." - }, - "seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_event_trace", - "description": "Read every direct replacement and provenance relationship for one event in an authorized session.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - }, - "seq": { - "type": "integer", - "description": "Target event sequence number." - } - }, - "required": [ - "seq" - ] - } - }, - { - "name": "session_search", - "description": "Search prior sessions in the caller workspace and return the strongest matching event from each session.", - "parameters": { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Literal full-text query over prior session history." - }, - "session_ids": { - "type": "array", - "description": "Optional session ids to include.", - "items": { - "type": "string" - } - }, - "created_at_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time lower bound." - }, - "created_at_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 creation-time upper bound." - }, - "parent_session_ids": { - "type": "array", - "description": "Optional direct parent session ids.", - "items": { - "type": "string" - } - }, - "include_root_sessions": { - "type": "boolean", - "description": "Include sessions with no parent in the parent filter." - }, - "availability": { - "type": "array", - "description": "Require at least one selected source availability.", - "items": { - "type": "string", - "enum": [ - "live", - "persisted" - ] - } - }, - "event_seq_from": { - "type": "integer", - "description": "Inclusive event sequence lower bound." - }, - "event_seq_to": { - "type": "integer", - "description": "Inclusive event sequence upper bound." - }, - "event_time_from": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time lower bound." - }, - "event_time_to": { - "type": "string", - "description": "Inclusive timezone-qualified ISO 8601 event-time upper bound." - }, - "event_types": { - "type": "array", - "description": "Event types to include.", - "items": { - "type": "string" - } - }, - "event_surfaces": { - "type": "array", - "description": "Event surfaces to include.", - "items": { - "type": "string", - "enum": [ - "current", - "shadowed", - "log-only" - ] - } - } - }, - "required": [ - "query" - ] - } - }, - { - "name": "session_trace", - "description": "Read the authorized session lineage around one session, including complete visible ancestor and descendant relationships.", - "parameters": { - "type": "object", - "properties": { - "session_id": { - "type": "string", - "description": "Target session id. Omit for the current session." - } - } - } - }, { "name": "skill", "description": "Load the full instructions for an available skill. Call this with the exact skill name from the session skill catalog before acting on a task that names or clearly matches that skill.", diff --git a/examples/tui-agent/composition.md b/examples/tui-agent/composition.md index 557923b733..fd6d163952 100644 --- a/examples/tui-agent/composition.md +++ b/examples/tui-agent/composition.md @@ -23,8 +23,6 @@ flowchart LR bundle_agent_core --> spine_sessions["ctx.sessions"] bundle_agent_core --> spine_tools["ctx.tools + tool-bash"] bundle_agent_core --> spine_loop["ctx.agents + ctx.agentLoop"] - plugin_tui_tool_session_query["tool-session-query
@deepseek-ai/dsh-tool-session-query"] - cfg --> plugin_tui_tool_session_query plugin_tui_session_title_llm["session-title-llm
@deepseek-ai/dsh-session-title-first-message-llm"] cfg --> plugin_tui_session_title_llm plugin_tui_token_meter["token-meter
@deepseek-ai/dsh-token-meter"] @@ -73,7 +71,6 @@ flowchart LR | `llm-deepseek` | `@deepseek-ai/dsh-llm-deepseek` | | `bash` | `@deepseek-ai/dsh-bash-local` | | `tui-agent` | `@deepseek-ai/dsh-tui-demo` | -| `tool-session-query` | `@deepseek-ai/dsh-tool-session-query` | | `session-title-llm` | `@deepseek-ai/dsh-session-title-first-message-llm` | | `token-meter` | `@deepseek-ai/dsh-token-meter` | | `tool-result-prune` | `@deepseek-ai/dsh-compact-tool-result-prune` | diff --git a/examples/tui-agent/cordis.yml b/examples/tui-agent/cordis.yml index 4fccfff1c7..3070fcdc01 100644 --- a/examples/tui-agent/cordis.yml +++ b/examples/tui-agent/cordis.yml @@ -52,11 +52,6 @@ Verify your work by running the code or tests. Keep answers brief and factual. -# The app above owns ctx.sessionQuery; expose its workspace-authorized -# prior-session search and exact trace/read operations to the model. -- id: tool-session-query - name: '@deepseek-ai/dsh-tool-session-query' - # Model-made session titles on the first-message cadence: replaces the spine's # deterministic fallback title with a short model summary. The TUI renders the # logged `session/title` as the banner subtitle and the terminal window title. diff --git a/packages/examples/acp-demo/README.md b/packages/examples/acp-demo/README.md index e215a80939..9666e4444f 100644 --- a/packages/examples/acp-demo/README.md +++ b/packages/examples/acp-demo/README.md @@ -36,7 +36,7 @@ The app does not install commands, user interaction, session navigation, configu | `goals` | owner defaults | Persisted same-session goal domain and model tools, or `false`. | | `llmRetry` | owner defaults | Bounded transient model-request retry policy. | -The shipped [`examples/acp-agent/cordis.yml`](../../../examples/acp-agent/cordis.yml) adds the DeepSeek adapter, sandboxed bash and filesystem providers, one-shot approval policy, compaction, subagents, workflows, hooks, a derived session-query index, generic timeout and spill policies, and model-facing tools. Snapshot overlays replace only nondeterministic providers or policy values. +The shipped [`examples/acp-agent/cordis.yml`](../../../examples/acp-agent/cordis.yml) adds the DeepSeek adapter, sandboxed bash and filesystem providers, one-shot approval policy, compaction, subagents, workflows, hooks, and model-facing tools. The app supplies the derived session-query index, while the model-facing query consumer remains an explicit leaf opt-in. Snapshot overlays replace only nondeterministic providers or policy values. ## Bin diff --git a/packages/examples/acp-demo/tests/load-path.e2e.ts b/packages/examples/acp-demo/tests/load-path.e2e.ts index 9f61e28314..2c507a0bad 100644 --- a/packages/examples/acp-demo/tests/load-path.e2e.ts +++ b/packages/examples/acp-demo/tests/load-path.e2e.ts @@ -28,9 +28,8 @@ const tsxLoader = fileURLToPath(import.meta.resolve('tsx')) // Repo root is four levels up from packages/examples/acp-demo/tests. const repoTsconfig = fileURLToPath(new URL('../../../../tsconfig.json', import.meta.url)) -// A minimal leaf that loads this app + the two backends and the shipped -// session-query consumer/policies — the same shape as examples/acp-agent/cordis.yml, -// inlined so the package test owns its fixture. +// A minimal opt-in leaf that loads this app + the two backends and the optional +// session-query consumer/policies, inlined so the package test owns its fixture. const CORDIS_YML = ` - id: llm-deepseek name: '@deepseek-ai/dsh-llm-deepseek' diff --git a/packages/examples/tui-demo/README.md b/packages/examples/tui-demo/README.md index 9e2a50f1b5..e3321bd97f 100644 --- a/packages/examples/tui-demo/README.md +++ b/packages/examples/tui-demo/README.md @@ -13,7 +13,7 @@ Use [`@deepseek-ai/dsh-cli-demo`](../cli-demo/README.md) for pipes, scripts, and | `@deepseek-ai/dsh-command-goal` | Direct `/goal` status and mutation over the spine's persisted-goal stack | | `@deepseek-ai/dsh-session-persistence-jsonl` | Durable session log under `persistenceRoot` | | `@deepseek-ai/dsh-session-checkpoint-policy` | Semantic durability barriers before model requests and top-level tool effects, plus completed-step checkpoints | -| `@deepseek-ai/dsh-session-query-sqlite` + `@deepseek-ai/dsh-session-reference` | Combined exact/FTS session queries and bounded `@session` snapshots consumed by the TUI; the default leaf adds the model-facing query tools | +| `@deepseek-ai/dsh-session-query-sqlite` + `@deepseek-ai/dsh-session-reference` | Combined exact/FTS session queries and bounded `@session` snapshots consumed by the TUI; model-facing query tools remain a leaf opt-in | | `@deepseek-ai/dsh-user-interaction` | Provider-neutral human question service | | `@deepseek-ai/dsh-tui` | Full-screen transcript, editor, tool cards, plan, and question overlays | | `@deepseek-ai/dsh-tool-ask-user` | Model-facing `ask_user_question` tool | diff --git a/packages/host/runtime/README.md b/packages/host/runtime/README.md index 221f0f46c0..14ce60e1c2 100644 --- a/packages/host/runtime/README.md +++ b/packages/host/runtime/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-host-runtime -Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence, a derived SQLite FTS session-query index, immediate fallback titles, optional first-message model summaries, system prompt, tool and agent registries, agent loop, five workspace-authorized model-facing session-query tools, workspace instructions, local bash, the generic tool-timeout and 50,000-byte spill policies, and the provider-neutral user-interaction service), and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }` (its `api` comes from [`dsh-host-apiproxy`](../apiproxy/README.md)'s `createApiProxy` over that composition). +Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence, a derived SQLite FTS session-query index, immediate fallback titles, optional first-message model summaries, system prompt, tool and agent registries, agent loop, workspace instructions, local bash, the generic tool-timeout and 50,000-byte spill policies, and the provider-neutral user-interaction service), and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }` (its `api` comes from [`dsh-host-apiproxy`](../apiproxy/README.md)'s `createApiProxy` over that composition). Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly two sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`) and headless session-event subscription; consuming clients must not bypass `api` through it. @@ -22,53 +22,19 @@ Unary methods take the narrow `RpcRequest

` and echo `request.rpcId`; a prompt ## Model Experience -### Prior-history system prompt +### Optional session-query consumer #### What the model sees -Every main host agent receives the fixed prior-history guidance below because `bootHost` always mounts the session-query tool plugin. - -##### Prior-history guidance - -```markdown -Use session_search to find relevant work from prior sessions, or session_event_search to search earlier events in one session. Search results are cursor-free and workspace-scoped. Follow a useful hit with session_trace, session_event_trace, or session_event_read when you need lineage, relationships, or exact data. -``` +The derived `ctx.sessionQuery` index is not model-facing. `bootHost` intentionally leaves the optional [`dsh-tool-session-query`](../../session-query/tool-session-query/README.md) consumer unmounted, so main host agents receive neither its prior-history prompt section nor its five schemas by default. #### Token effect -One fixed concise section is present on every request; `workspaceContext: false` does not remove it. +The index adds no prompt or schema tokens. A custom composition that mounts the consumer owns its added prompt, schemas, calls, and results. #### KV Cache effect -The repeated prefix is stable while the fixed host assembly and guidance text are unchanged. Provider cache availability and eviction remain outside the host contract. - -### Session-query tool schemas - -#### What the model sees - -The fixed assembly mounts the generated [`session_search`, `session_event_search`, `session_trace`, `session_event_trace`, and `session_event_read` schemas](../../../docs/tool-catalog.md#deepseek-aidsh-tool-session-query). The schemas expose no workspace path, provider cursor, output page, model-controlled result limit, or timeout argument. - -#### Token effect - -Five fixed read-only schemas are present on every main-agent request; their cost changes only if the host assembly or an agent-scoped visibility policy changes. - -#### KV Cache effect - -The schema prefix is stable while visibility, definitions, and order are unchanged. The host makes no claim that a provider will cache or retain that prefix. - -### Session-query execution and results - -#### What the model sees - -Cross-session results require exact equality with the calling session's workspace, while a caller without a workspace can target only itself. `session_search` excludes the calling session, and `session_event_search` on the current session excludes the step performing the call. Both searches are cursor-free, collect at most 100 authorized results, and carry a cooperative 30-second deadline; the three trace/read tools carry caller cancellation but declare no host deadline. Results are plain text. When a final result exceeds 50,000 UTF-8 bytes, the generic spill policy attempts to retain the complete formatted text in a private session-scoped file and replace it with a bounded preview, locator, and retrieval hint; a spill failure leaves the original result visible. - -#### Token effect - -Call arguments and data-dependent results remain in history until compaction. Search result count is bounded; after a successful spill, only the bounded preview and retrieval notice are resent, while the complete text remains outside model context. - -#### KV Cache effect - -Calls and results append after the reusable request prefix. Compaction may replace earlier history; timeout or spill outcomes change only the appended result text. +The index alone does not change the reusable model-request prefix; mounting the optional consumer would add its stable prompt and schema prefix. ### Workspace instructions diff --git a/packages/host/runtime/package.json b/packages/host/runtime/package.json index cb31e87fe9..b43cb9c468 100644 --- a/packages/host/runtime/package.json +++ b/packages/host/runtime/package.json @@ -58,7 +58,6 @@ "@deepseek-ai/dsh-tool-fs": "workspace:^", "@deepseek-ai/dsh-tool-fs-search": "workspace:^", "@deepseek-ai/dsh-tool-skill": "workspace:^", - "@deepseek-ai/dsh-tool-session-query": "workspace:^", "@deepseek-ai/dsh-tool-subagent": "workspace:^", "@deepseek-ai/dsh-tool-tasks": "workspace:^", "@deepseek-ai/dsh-tool-todo": "workspace:^", diff --git a/packages/host/runtime/src/boot.ts b/packages/host/runtime/src/boot.ts index 353f74d0b6..4e2976ccc4 100644 --- a/packages/host/runtime/src/boot.ts +++ b/packages/host/runtime/src/boot.ts @@ -20,7 +20,6 @@ import AgentLoop from '@deepseek-ai/dsh-agent-loop' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' import SessionQuerySqlite from '@deepseek-ai/dsh-session-query-sqlite' -import * as toolSessionQuery from '@deepseek-ai/dsh-tool-session-query' import LocalBashExecutor from '@deepseek-ai/dsh-bash-local' import * as toolBash from '@deepseek-ai/dsh-tool-bash' import * as toolTodo from '@deepseek-ai/dsh-tool-todo' @@ -135,7 +134,6 @@ export async function bootHost(options: BootHostOptions): Promise { await ctx.plugin(LlmDeepSeek, {}) await ctx.plugin(SessionPersistenceJsonl, { root: options.persistenceRoot }) await ctx.plugin(SessionQuerySqlite, { path: join(options.persistenceRoot, 'session-query.db') }) - await ctx.plugin(toolSessionQuery, {}) await ctx.plugin(LocalBashExecutor, {}) // Tool suite mirroring the demo:repl composition (repl-agent/cordis.yml + // the agent-spine bundle) so web sessions get the same coding-agent tool diff --git a/packages/host/runtime/tests/host-runtime.spec.ts b/packages/host/runtime/tests/host-runtime.spec.ts index 9912ec0785..22f64fb198 100644 --- a/packages/host/runtime/tests/host-runtime.spec.ts +++ b/packages/host/runtime/tests/host-runtime.spec.ts @@ -141,21 +141,20 @@ describe('bootHost / startHost', () => { await handle.dispose() }) - it('assembles workspace-authorized session query tools over the derived SQLite index', async () => { + it('assembles the derived SQLite query index without model-facing query tools', async () => { const persistenceRoot = mkdtempSync(join(tmpdir(), 'dsh-boot-session-query-')) const handle = await bootHost({ persistenceRoot, workspaceContext: false, }) expect(handle.ctx.get('sessionQuery')).toBeDefined() - expect(handle.ctx.tools.schemas().map(schema => schema.name)).toEqual(expect.arrayContaining([ + expect(handle.ctx.tools.schemas().map(schema => schema.name)).toEqual(expect.not.arrayContaining([ 'session_search', 'session_event_search', 'session_trace', 'session_event_trace', 'session_event_read', ])) - expect(handle.ctx.tools.get('session_search')?.timeoutMs).toBe(30_000) await handle.dispose() }) diff --git a/packages/host/runtime/tsconfig.json b/packages/host/runtime/tsconfig.json index b0cef9eb16..55f517f778 100644 --- a/packages/host/runtime/tsconfig.json +++ b/packages/host/runtime/tsconfig.json @@ -50,9 +50,6 @@ { "path": "../../session-query/session-query-sqlite" }, - { - "path": "../../session-query/tool-session-query" - }, { "path": "../../bash/bash-local" }, diff --git a/packages/session-query/tool-session-query/README.md b/packages/session-query/tool-session-query/README.md index 504405d698..ef957765c4 100644 --- a/packages/session-query/tool-session-query/README.md +++ b/packages/session-query/tool-session-query/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-tool-session-query -Workspace-authorized model tools over `ctx.sessionQuery`. The package depends only on the unified interface and registers `session_search`, `session_event_search`, `session_trace`, `session_event_trace`, and `session_event_read`. +Workspace-authorized model tools over `ctx.sessionQuery`. The opt-in package depends only on the unified interface and registers `session_search`, `session_event_search`, `session_trace`, `session_event_trace`, and `session_event_read`; shipped host compositions do not mount it by default. ## Configuration diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 400ae6df7e..de8e114782 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2346,9 +2346,6 @@ importers: '@deepseek-ai/dsh-tool-fs-search': specifier: workspace:^ version: link:../../fs/tool-fs-search - '@deepseek-ai/dsh-tool-session-query': - specifier: workspace:^ - version: link:../../session-query/tool-session-query '@deepseek-ai/dsh-tool-skill': specifier: workspace:^ version: link:../../skill/tool-skill diff --git a/scripts/gen-tool-catalog.ts b/scripts/gen-tool-catalog.ts index 6c81aee2c6..3bbfd5b1ea 100644 --- a/scripts/gen-tool-catalog.ts +++ b/scripts/gen-tool-catalog.ts @@ -331,7 +331,7 @@ const TOOL_PACKAGES: ToolPackage[] = [ await ctx.plugin(ToolSessionQuery) }, note: - 'The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. Default ACP, TUI, and Web compositions enforce the declared search timeout and apply the generic tool-result spill policy.', + 'The five read-only tools hide provider cursors and authorize every result from the immutable calling agent session. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies.', }, { pkg: '@deepseek-ai/dsh-tool-subagent', From be3a9f6a75ba2d1c86b2e738c1ccc95018073522 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 20:05:29 +0800 Subject: [PATCH 072/113] docs: document repository clean workflow --- .../process/2026-06-17-ts-build-config.i18n.yaml | 4 ++-- .../implemented/process/2026-06-17-ts-build-config.md | 8 ++++++++ .../implemented/process/2026-06-17-ts-build-config.zh.md | 8 ++++++++ AGENTS.md | 1 + 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml b/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml index 80f7838d45..32202d837f 100644 --- a/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.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 -2026-06-17-ts-build-config.md: 1275a635242ea887c941db9dc0554fd33acd4102 -2026-06-17-ts-build-config.zh.md: 7691118dd152874e2849f1ace686069c9ea3f61f +2026-06-17-ts-build-config.md: 527570393c42d581d28da0380efdf9ba8bade8ae +2026-06-17-ts-build-config.zh.md: 6535add99115bff0e396e87729bef225dae39e6c diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.md b/.agents/notes/implemented/process/2026-06-17-ts-build-config.md index 1275a63524..527570393c 100644 --- a/.agents/notes/implemented/process/2026-06-17-ts-build-config.md +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.md @@ -43,6 +43,8 @@ In-package relative imports use explicit `.ts` specifiers. - Referenced package/vendor projects keep the same emit behavior as build, so typecheck refreshes their `lib/types` outputs instead of using a separate no-emit graph. Project-specific strictness changes live in the owning `packages/*/*/tsconfig.json` or `vendor/*/tsconfig.json`. - The no-emit aggregates disable `rewriteRelativeImportExtensions`; they emit nothing and include tests that import helpers across project-reference boundaries. Package/vendor emit projects keep the rewrite enabled. +Composite projects keep their incremental build information inside their package-local `lib/` output. `pnpm run clean` explicitly removes package/vendor/CLI `lib/` outputs, legacy root build information, and deleted `packages/*/*` directories that contain only known generated residue. It preserves `node_modules` for every package that still has a `package.json`, and refuses to remove a manifest-less directory containing unknown files. Build does not invoke clean automatically, so ordinary builds retain incremental state. + The command orchestration shape is: ```sh @@ -55,6 +57,9 @@ tsx scripts/verify-node-next-types.ts pnpm run typecheck: tsc -b + +pnpm run clean: +tsx scripts/clean.ts ``` `pnpm run demo:*` still runs `src` directly through tsx and root paths, without a compile step. @@ -63,6 +68,8 @@ tsc -b - **Keep `tsdown`/oxc as the TypeScript transformer** — oxc's transform is not `tsc` behavior (decorator transform differs, bundled JS differs from per-file emit), and its bundled `.d.ts` conflicts with Cordis' internal relative module augmentation shape. - **One root strict program over packages, vendor, examples, tests, and scripts** — vendor source triggers type errors outside this project's ownership under the root strict flags; project references with per-project strictness are the boundary that works. +- **Clean before every build** — this would discard the incremental state owned by `tsc` and the bundler even when the workspace layout is unchanged. +- **Remove every package-level `node_modules`** — valid package dependency links do not cause the workspace-discovery failure, and deleting them would turn build cleanup into dependency reinstallation. ## Consequences @@ -76,5 +83,6 @@ Build responsibilities are clearer: - `lib/index.*` is the publish runtime output and is generated by the bundler, currently `tsdown`. - `pnpm run verify-node-next-types` scans built declarations for relative specifiers without file extensions, then typechecks a temporary external ESM consumer with `moduleResolution: "NodeNext"` against the built `types`/`exports` surface, so declaration specifier regressions fail before publish. - The `typecheck` command uses `tsconfig.json`. Examples, tests, and scripts are checked by the root no-emit project, while packages and vendor modules keep the same emit behavior as `build`. Package and vendor source stays behind project-reference boundaries. +- After changing branches or updating a checkout that deleted packages, contributors can run `pnpm run clean` to remove stale package directories before rebuilding. Unknown files in a manifest-less package directory require manual classification instead of being deleted. The Cordis vendor copy now has one more type-structure divergence from upstream. During upstream sync, that divergence must be reapplied or explicitly retired. diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md b/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md index 7691118dd1..6535add991 100644 --- a/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md @@ -43,6 +43,8 @@ Status: implemented - 被引用的包/vendor 项目保持与构建相同的输出行为,因此类型检查会刷新它们的 `lib/types` 输出,而无需使用独立的 no-emit 图。项目特定的严格度变更放在各自的 `packages/*/*/tsconfig.json` 或 `vendor/*/tsconfig.json` 中。 - 两个 no-emit 聚合禁用 `rewriteRelativeImportExtensions`;它们不输出任何文件,且包含跨 project-reference 边界导入 helper 的测试。包/vendor 的 emit 项目保持重写开启。 +复合项目将增量构建信息保存在各包本地的 `lib/` 输出中。`pnpm run clean` 会显式删除包、vendor 和 CLI(命令行界面)的 `lib/` 输出、遗留的根目录构建信息,以及已删除包留下且仅包含已知生成残留的 `packages/*/*` 目录。对于仍有 `package.json` 的每个包,该命令都会保留 `node_modules`;如果不含 `package.json` 的目录中存在未知文件,则拒绝删除。构建不会自动调用 clean,因此常规构建会保留增量状态。 + 命令编排结构如下: ```sh @@ -55,6 +57,9 @@ tsx scripts/verify-node-next-types.ts pnpm run typecheck: tsc -b + +pnpm run clean: +tsx scripts/clean.ts ``` `pnpm run demo:*` 仍通过 tsx 和根路径直接运行 `src`,无需编译步骤。 @@ -63,6 +68,8 @@ tsc -b - **继续使用 `tsdown`/oxc 作为 TypeScript 转换器**:oxc 的转换行为与 `tsc` 不同(装饰器转换有差异、打包 JS 与逐文件输出不同),且其打包 `.d.ts` 与 Cordis 内部的相对模块增强结构冲突。 - **用一个根目录严格程序覆盖包、vendor、示例、测试和脚本**:vendor 源码在根目录严格标志下会触发不属于本项目所有权范围的类型错误;带有逐项目严格度的 project references 才是可行的边界。 +- **每次构建前都执行清理**:即使工作区布局没有变化,这也会丢弃 `tsc` 和打包器拥有的增量状态。 +- **删除所有包级 `node_modules`**:有效的包依赖链接不会导致工作区发现失败,而删除这些链接会使构建清理变成重新安装依赖。 ## 后果 @@ -76,5 +83,6 @@ tsc -b - `lib/index.*` 是发布用的运行时输出,由打包器(当前为 `tsdown`)生成。 - `pnpm run verify-node-next-types` 扫描构建出的声明文件,检查是否存在缺少文件扩展名的相对说明符,然后以 `moduleResolution: "NodeNext"` 对构建出的 `types`/`exports` 接口进行临时外部 ESM 消费方的类型检查,确保声明说明符的回归在发布前被捕获。 - `typecheck` 命令使用 `tsconfig.json`。示例、测试和脚本由根 no-emit 项目检查,包和 vendor 模块保持与 `build` 相同的输出行为。包和 vendor 源码始终处于 project-reference 边界之后。 +- 切换分支或更新工作副本后,如果其中删除了包,贡献者可在重新构建前运行 `pnpm run clean`,删除残留的包目录。不含 `package.json` 的包目录如果存在未知文件,必须手动判定其类别,不能直接删除。 Cordis 的 vendor 副本现在与上游多了一处类型结构差异。在上游同步时,该差异必须被重新应用或明确废弃。 diff --git a/AGENTS.md b/AGENTS.md index 64259784fb..1ce8e5e0c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,7 @@ Package groups: [packages/README.md](packages/README.md). ```sh pnpm install # pnpm workspaces, node ^22.19 || >=24 +pnpm run clean # remove build outputs and safe residue from deleted packages pnpm run test # vitest unit tests pnpm run test:coverage # CI coverage gate: per-file 100% on packages/*/*/src pnpm run test:e2e # real-API tests; self-skip without DEEPSEEK_API_KEY From 22875a6c9d86d801cffaaa8d6af42aed76ea3463 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 20:06:01 +0800 Subject: [PATCH 073/113] fix(build): clean stale workspace residue --- package.json | 2 +- packages/examples/cli-demo/tsconfig.json | 3 +- scripts/clean.ts | 107 +++++++++++++++++++++++ 3 files changed, 109 insertions(+), 3 deletions(-) create mode 100644 scripts/clean.ts diff --git a/package.json b/package.json index a925ea3ec9..f5017bea2f 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "scripts": { "build": "tsc -b && tsdown", "build:web": "pnpm --filter @deepseek-ai/dsh-frontend run build", - "clean:build": "rm -rf .typecheck packages/*/*/lib vendor/*/lib *.tsbuildinfo", + "clean": "tsx scripts/clean.ts", "typecheck": "tsc -b", "lint": "eslint .", "lint:fix": "eslint . --fix", diff --git a/packages/examples/cli-demo/tsconfig.json b/packages/examples/cli-demo/tsconfig.json index df5758b7b8..095f7ce6a3 100644 --- a/packages/examples/cli-demo/tsconfig.json +++ b/packages/examples/cli-demo/tsconfig.json @@ -3,8 +3,7 @@ "compilerOptions": { "composite": true, "rootDir": "src", - "outDir": "lib/types", - "tsBuildInfoFile": "../../../.typecheck/cli-demo.tsbuildinfo" + "outDir": "lib/types" }, "include": ["src/**/*.ts"], "references": [ diff --git a/scripts/clean.ts b/scripts/clean.ts new file mode 100644 index 0000000000..3f0f85836f --- /dev/null +++ b/scripts/clean.ts @@ -0,0 +1,107 @@ +import { lstat, readdir, rm } from 'node:fs/promises' +import { dirname, join, relative, resolve, sep } from 'node:path' +import { fileURLToPath } from 'node:url' + +const knownOrphanEntries = new Set(['node_modules', 'lib', '.typecheck']) + +function isMissing(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT' +} + +async function exists(path: string): Promise { + try { + await lstat(path) + return true + } catch (error) { + if (isMissing(error)) return false + throw error + } +} + +async function childDirectories(path: string): Promise { + try { + const entries = await readdir(path, { withFileTypes: true }) + return entries.filter(entry => entry.isDirectory()).map(entry => join(path, entry.name)) + } catch (error) { + if (isMissing(error)) return [] + throw error + } +} + +function repositoryPath(root: string, path: string): string { + return relative(root, path).split(sep).join('/') +} + +class RepositoryCleaner { + constructor(private readonly root: string) {} + + /** + * Remove generated build state and package directories containing only known residue. + * @returns Repository-relative paths that were removed. + */ + async clean(): Promise { + const targets = await this.plan() + for (const target of targets) await rm(target, { recursive: true, force: true }) + return targets.map(target => repositoryPath(this.root, target)) + } + + private async plan(): Promise { + const targets = new Set() + const unsafeOrphans: string[] = [] + + await this.addIfPresent(targets, join(this.root, '.typecheck')) + for (const entry of await readdir(this.root, { withFileTypes: true })) { + if (entry.isFile() && entry.name.endsWith('.tsbuildinfo')) targets.add(join(this.root, entry.name)) + } + + for (const vendorDirectory of await childDirectories(join(this.root, 'vendor'))) { + await this.addIfPresent(targets, join(vendorDirectory, 'lib')) + } + await this.addIfPresent(targets, join(this.root, 'apps', 'cli', 'lib')) + + for (const groupDirectory of await childDirectories(join(this.root, 'packages'))) { + for (const packageDirectory of await childDirectories(groupDirectory)) { + if (await exists(join(packageDirectory, 'package.json'))) { + await this.addIfPresent(targets, join(packageDirectory, 'lib')) + continue + } + + const entries = await readdir(packageDirectory) + const unknown = entries.filter(entry => !knownOrphanEntries.has(entry) && !entry.endsWith('.tsbuildinfo')) + if (unknown.length > 0) { + unsafeOrphans.push(...unknown.map(entry => repositoryPath(this.root, join(packageDirectory, entry)))) + } else { + targets.add(packageDirectory) + } + } + } + + if (unsafeOrphans.length > 0) { + throw new Error([ + 'clean: refusing to remove package directories without package.json; unknown entries remain:', + ...unsafeOrphans.sort().map(path => ` ${path}`), + ].join('\n')) + } + + return [...targets].sort() + } + + private async addIfPresent(targets: Set, path: string): Promise { + if (await exists(path)) targets.add(path) + } +} + +const scriptPath = fileURLToPath(import.meta.url) +if (process.argv[1] !== undefined && resolve(process.argv[1]) === scriptPath) { + try { + const removed = await new RepositoryCleaner(resolve(dirname(scriptPath), '..')).clean() + if (removed.length === 0) { + console.log('clean: already clean') + } else { + console.log(`clean: removed ${removed.length} paths`) + } + } catch (error) { + console.error(error instanceof Error ? error.message : error) + process.exitCode = 1 + } +} From 787b4e6b9e1dbe1e88649bbc4061dee4b8912819 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 25 Jul 2026 20:30:35 +0800 Subject: [PATCH 074/113] fix(build): derive clean outputs from project graph --- .../2026-06-17-ts-build-config.i18n.yaml | 4 +- .../process/2026-06-17-ts-build-config.md | 2 +- .../process/2026-06-17-ts-build-config.zh.md | 2 +- scripts/clean.spec.ts | 62 ++++++++++++++ scripts/clean.ts | 80 +++++++++++++++++-- 5 files changed, 140 insertions(+), 10 deletions(-) create mode 100644 scripts/clean.spec.ts diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml b/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml index 32202d837f..d8530ac919 100644 --- a/.agents/notes/implemented/process/2026-06-17-ts-build-config.i18n.yaml +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.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 -2026-06-17-ts-build-config.md: 527570393c42d581d28da0380efdf9ba8bade8ae -2026-06-17-ts-build-config.zh.md: 6535add99115bff0e396e87729bef225dae39e6c +2026-06-17-ts-build-config.md: 17036438b83a77f72b49f55abf29632af3f4ffef +2026-06-17-ts-build-config.zh.md: 70e49c61deba418894a48be3016898d1d85c78a0 diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.md b/.agents/notes/implemented/process/2026-06-17-ts-build-config.md index 527570393c..17036438b8 100644 --- a/.agents/notes/implemented/process/2026-06-17-ts-build-config.md +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.md @@ -43,7 +43,7 @@ In-package relative imports use explicit `.ts` specifiers. - Referenced package/vendor projects keep the same emit behavior as build, so typecheck refreshes their `lib/types` outputs instead of using a separate no-emit graph. Project-specific strictness changes live in the owning `packages/*/*/tsconfig.json` or `vendor/*/tsconfig.json`. - The no-emit aggregates disable `rewriteRelativeImportExtensions`; they emit nothing and include tests that import helpers across project-reference boundaries. Package/vendor emit projects keep the rewrite enabled. -Composite projects keep their incremental build information inside their package-local `lib/` output. `pnpm run clean` explicitly removes package/vendor/CLI `lib/` outputs, legacy root build information, and deleted `packages/*/*` directories that contain only known generated residue. It preserves `node_modules` for every package that still has a `package.json`, and refuses to remove a manifest-less directory containing unknown files. Build does not invoke clean automatically, so ordinary builds retain incremental state. +Composite projects keep their incremental build information inside their project-local `lib/` output. `pnpm run clean` derives live output directories from the root TypeScript project-reference graph, removes legacy root build information, and removes deleted `packages/*/*` directories that contain only known generated residue. It preserves `node_modules` for every package that still has a `package.json`, and refuses to remove a manifest-less directory containing unknown files. Build does not invoke clean automatically, so ordinary builds retain incremental state. The command orchestration shape is: diff --git a/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md b/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md index 6535add991..70e49c61de 100644 --- a/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md +++ b/.agents/notes/implemented/process/2026-06-17-ts-build-config.zh.md @@ -43,7 +43,7 @@ Status: implemented - 被引用的包/vendor 项目保持与构建相同的输出行为,因此类型检查会刷新它们的 `lib/types` 输出,而无需使用独立的 no-emit 图。项目特定的严格度变更放在各自的 `packages/*/*/tsconfig.json` 或 `vendor/*/tsconfig.json` 中。 - 两个 no-emit 聚合禁用 `rewriteRelativeImportExtensions`;它们不输出任何文件,且包含跨 project-reference 边界导入 helper 的测试。包/vendor 的 emit 项目保持重写开启。 -复合项目将增量构建信息保存在各包本地的 `lib/` 输出中。`pnpm run clean` 会显式删除包、vendor 和 CLI(命令行界面)的 `lib/` 输出、遗留的根目录构建信息,以及已删除包留下且仅包含已知生成残留的 `packages/*/*` 目录。对于仍有 `package.json` 的每个包,该命令都会保留 `node_modules`;如果不含 `package.json` 的目录中存在未知文件,则拒绝删除。构建不会自动调用 clean,因此常规构建会保留增量状态。 +复合项目将增量构建信息保存在各项目本地的 `lib/` 输出中。`pnpm run clean` 会根据根 TypeScript project-reference 图确定当前有效的输出目录,删除遗留的根目录构建信息,并删除已删除包留下且仅包含已知生成残留的 `packages/*/*` 目录。对于仍有 `package.json` 的每个包,该命令都会保留 `node_modules`;如果不含 `package.json` 的目录中存在未知文件,则拒绝删除。构建不会自动调用 clean,因此常规构建会保留增量状态。 命令编排结构如下: diff --git a/scripts/clean.spec.ts b/scripts/clean.spec.ts new file mode 100644 index 0000000000..0d3aced888 --- /dev/null +++ b/scripts/clean.spec.ts @@ -0,0 +1,62 @@ +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' + +import { RepositoryCleaner } from './clean.ts' + +const roots: string[] = [] + +function fixture(): string { + const root = mkdtempSync(join(tmpdir(), 'dsh-clean-')) + roots.push(root) + return root +} + +function write(path: string, content = ''): void { + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, content) +} + +function addProject(root: string, path: string): void { + write(join(root, 'tsconfig.json'), JSON.stringify({ files: [], references: [{ path }] })) + write(join(root, path, 'tsconfig.json'), JSON.stringify({ + compilerOptions: { composite: true, outDir: 'lib/types' }, + include: ['src'], + })) + write(join(root, path, 'src/index.ts'), 'export {}\n') +} + +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) +}) + +describe('RepositoryCleaner', () => { + it('derives live build outputs from project references and removes safe stale package residue', async () => { + const root = fixture() + addProject(root, 'products/shell') + write(join(root, 'products/shell/lib/types/index.js')) + write(join(root, 'products/shell/lib/index.js')) + write(join(root, '.typecheck/legacy.tsbuildinfo')) + write(join(root, 'root.tsbuildinfo')) + write(join(root, 'packages/removed/ghost/node_modules/.bin/tool')) + + await new RepositoryCleaner(root).clean() + + expect(existsSync(join(root, 'products/shell/lib'))).toBe(false) + expect(existsSync(join(root, 'products/shell/src/index.ts'))).toBe(true) + expect(existsSync(join(root, '.typecheck'))).toBe(false) + expect(existsSync(join(root, 'root.tsbuildinfo'))).toBe(false) + expect(existsSync(join(root, 'packages/removed/ghost'))).toBe(false) + }) + + it('does not delete any target when a manifest-less package contains an unknown file', async () => { + const root = fixture() + addProject(root, 'products/shell') + write(join(root, 'products/shell/lib/types/index.js')) + write(join(root, 'packages/removed/ghost/notes.txt')) + + await expect(new RepositoryCleaner(root).clean()).rejects.toThrow('packages/removed/ghost/notes.txt') + expect(existsSync(join(root, 'products/shell/lib'))).toBe(true) + }) +}) diff --git a/scripts/clean.ts b/scripts/clean.ts index 3f0f85836f..93b9b2519c 100644 --- a/scripts/clean.ts +++ b/scripts/clean.ts @@ -1,9 +1,21 @@ import { lstat, readdir, rm } from 'node:fs/promises' -import { dirname, join, relative, resolve, sep } from 'node:path' +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { fileURLToPath } from 'node:url' +import ts from 'typescript' const knownOrphanEntries = new Set(['node_modules', 'lib', '.typecheck']) +const configHost: ts.ParseConfigFileHost = { + useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, + readDirectory: (...args) => ts.sys.readDirectory(...args), + fileExists: fileName => ts.sys.fileExists(fileName), + readFile: fileName => ts.sys.readFile(fileName), + getCurrentDirectory: () => ts.sys.getCurrentDirectory(), + onUnRecoverableConfigFileDiagnostic(diagnostic) { + throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')) + }, +} + function isMissing(error: unknown): boolean { return error instanceof Error && 'code' in error && error.code === 'ENOENT' } @@ -32,7 +44,17 @@ function repositoryPath(root: string, path: string): string { return relative(root, path).split(sep).join('/') } -class RepositoryCleaner { +function parseConfig(configPath: string): ts.ParsedCommandLine { + const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost) + if (!parsed) throw new Error(`clean: cannot parse TypeScript config ${configPath}`) + if (parsed.errors.length > 0) { + throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n')) + } + return parsed +} + +/** Plans and removes repository-owned build output without crossing the repository boundary. */ +export class RepositoryCleaner { constructor(private readonly root: string) {} /** @@ -41,6 +63,7 @@ class RepositoryCleaner { */ async clean(): Promise { const targets = await this.plan() + // Planning validates every target first, so an unsafe orphan prevents all deletion. for (const target of targets) await rm(target, { recursive: true, force: true }) return targets.map(target => repositoryPath(this.root, target)) } @@ -49,23 +72,29 @@ class RepositoryCleaner { const targets = new Set() const unsafeOrphans: string[] = [] + // These checks cover legacy root-level incremental state emitted by older configs. await this.addIfPresent(targets, join(this.root, '.typecheck')) for (const entry of await readdir(this.root, { withFileTypes: true })) { if (entry.isFile() && entry.name.endsWith('.tsbuildinfo')) targets.add(join(this.root, entry.name)) } - for (const vendorDirectory of await childDirectories(join(this.root, 'vendor'))) { - await this.addIfPresent(targets, join(vendorDirectory, 'lib')) + // The root project-reference graph is the source of truth for live build targets. + // Each emitting project declares lib/types as outDir; its parent lib also owns + // the sibling runtime bundles, so the complete build output root is removed. + for (const outputDirectory of this.buildOutputDirectories()) { + await this.addIfPresent(targets, outputDirectory) } - await this.addIfPresent(targets, join(this.root, 'apps', 'cli', 'lib')) for (const groupDirectory of await childDirectories(join(this.root, 'packages'))) { for (const packageDirectory of await childDirectories(groupDirectory)) { + // A package.json marks a live package; its output was discovered from the + // project graph above, and its package-local node_modules must be preserved. if (await exists(join(packageDirectory, 'package.json'))) { - await this.addIfPresent(targets, join(packageDirectory, 'lib')) continue } + // A manifest-less package directory is stale only when every remaining + // entry is known generated residue; unknown files make the whole clean fail. const entries = await readdir(packageDirectory) const unknown = entries.filter(entry => !knownOrphanEntries.has(entry) && !entry.endsWith('.tsbuildinfo')) if (unknown.length > 0) { @@ -86,7 +115,46 @@ class RepositoryCleaner { return [...targets].sort() } + private buildOutputDirectories(): string[] { + const outputs = new Set() + const pending = [join(this.root, 'tsconfig.json')] + const visited = new Set() + + while (pending.length > 0) { + const nextConfigPath = pending.pop() + if (nextConfigPath === undefined) break + const configPath = resolve(nextConfigPath) + if (visited.has(configPath)) continue + visited.add(configPath) + + const parsed = parseConfig(configPath) + if (parsed.options.outDir !== undefined) { + const typesDirectory = resolve(parsed.options.outDir) + if (basename(typesDirectory) !== 'types') { + throw new Error(`clean: expected TypeScript outDir to end in /types: ${repositoryPath(this.root, typesDirectory)}`) + } + const outputDirectory = dirname(typesDirectory) + this.assertRepositoryTarget(outputDirectory) + outputs.add(outputDirectory) + } + + for (const reference of parsed.projectReferences ?? []) { + pending.push(ts.resolveProjectReferencePath(reference)) + } + } + + return [...outputs] + } + + private assertRepositoryTarget(path: string): void { + const repositoryRelative = relative(this.root, path) + if (repositoryRelative === '' || repositoryRelative === '..' || repositoryRelative.startsWith(`..${sep}`) || isAbsolute(repositoryRelative)) { + throw new Error(`clean: refusing build output outside repository: ${path}`) + } + } + private async addIfPresent(targets: Set, path: string): Promise { + // Missing outputs are normal on a clean checkout; only existing paths become deletion targets. if (await exists(path)) targets.add(path) } } From badf7d1c631a06d1d565c7efc832742d69493de2 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 25 Jul 2026 22:45:58 +0800 Subject: [PATCH 075/113] fix(llm-mock-server): harden fault boundaries --- ...scriptable-llm-wire-fault-server.i18n.yaml | 4 +- ...-07-25-scriptable-llm-wire-fault-server.md | 8 ++-- ...-25-scriptable-llm-wire-fault-server.zh.md | 8 ++-- docs/module-graph.md | 3 ++ .../tests/transport-recovery.spec.ts | 20 +++++---- packages/support/llm-mock-server/README.md | 4 +- packages/support/llm-mock-server/src/cli.ts | 16 +++++-- packages/support/llm-mock-server/src/index.ts | 31 +++++++++---- .../support/llm-mock-server/tests/cli.spec.ts | 3 ++ .../llm-mock-server/tests/server.spec.ts | 43 +++++++++++++++++++ 10 files changed, 109 insertions(+), 31 deletions(-) diff --git a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.i18n.yaml b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.i18n.yaml index 4eea19c9c0..c9cebc9db9 100644 --- a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.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 -2026-07-25-scriptable-llm-wire-fault-server.md: 92f7d6aad8e7b4dc8bb08e98bb5847ff27470229 -2026-07-25-scriptable-llm-wire-fault-server.zh.md: 2f5fcc1321b0e4f501f3814e5e96d4b26cf18ec6 +2026-07-25-scriptable-llm-wire-fault-server.md: 0795f71f0eab1a107740aaa8cba6fa04b1fbd306 +2026-07-25-scriptable-llm-wire-fault-server.zh.md: a0e3c98d729adcc74e6d98933ab2beb538f71cb3 diff --git a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md index 92f7d6aad8..0795f71f0e 100644 --- a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md +++ b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.md @@ -18,11 +18,11 @@ Request behaviors cover socket reset, post-header disconnect, partial disconnect The `random` script entry performs a new weighted selection for every request. The server exposes and logs its unsigned 32-bit seed, accepts caller-supplied relative weights, and ships a success-heavy stress profile that mixes transport, protocol, provider, timeout, and semantic-empty outcomes. The profile is configurable test pressure rather than an estimate of production incident frequency; `connection_refused` remains outside the request-level pool. -The server reports wire facts only and does not classify retryability. Real-composition tests route it through `dsh-llm-deepseek`, `dsh-agent-loop`, and `dsh-llm-retry`: connection refusal, hard disconnect, partial reset, and idle timeout recover under the existing default policy; a valid content-less completion succeeds without retry; clean partial EOF remains `STREAM_CLOSED` and is not retried by default. The package does not change those policies. +The server reports wire facts only and does not classify retryability. Real-composition tests route it through `dsh-llm-deepseek`, `dsh-agent-loop`, and `dsh-llm-retry`: connection refusal, hard disconnect, partial reset, idle timeout, and a valid content-less completion recover under the existing default policy; clean partial EOF remains `STREAM_CLOSED` and is not retried by default. The package does not change those policies. ## Verification -Package tests exercise every request behavior, HTTP validation without script consumption, script exhaustion/repetition, stalled-connection teardown, CLI parsing, random seed reproducibility, weight validation, telemetry, lifecycle cleanup, and the invariant companion under the per-file coverage gate. The retry integration suite proves exact request counts, numbered retry steps, request-body identity, failed partial-chunk isolation, empty-success semantics, clean-EOF classification, timeout recovery, true refused-connection recovery after delayed listener startup, and bounded exhaustion through the real HTTP/SSE adapter. +Package tests exercise every request behavior, split UTF-8 request decoding, HTTP validation without script consumption, script exhaustion/repetition, stalled-connection teardown, CLI parsing and delay bounds, IPv6 base URLs, random seed reproducibility, weight validation, single-result telemetry, lifecycle cleanup, and the invariant companion under the per-file coverage gate. The retry integration suite proves exact request counts, numbered retry steps, request-body identity, failed partial-chunk isolation, semantic-empty recovery, clean-EOF classification, timeout recovery, true refused-connection recovery after delayed listener startup, and bounded exhaustion through the real HTTP/SSE adapter. ## Alternatives considered @@ -32,10 +32,10 @@ Package tests exercise every request behavior, HTTP validation without script co **Use only an in-process `LlmAdapter` mock** — rejected because it bypasses fetch, HTTP status/header parsing, SSE framing, socket termination, and the adapter idle watchdog: the exact boundaries this test infrastructure exists to exercise. -**Change retry defaults with the server** — rejected because the server reveals existing semantics rather than deciding policy. Adding `STREAM_CLOSED` or semantic-empty recovery requires a separate decision with its own cost, latency, and duplicate-generation trade-offs. +**Change retry defaults with the server** — rejected because the server reveals existing semantics rather than deciding policy. Extending recovery to `STREAM_CLOSED` requires a separate decision with its own cost, latency, and duplicate-generation trade-offs. ## Consequences -Developers can reproduce fault sequences by changing only provider URL/key configuration, and automated tests can keep socket-level failures deterministic through explicit scripts and seeds. The same wire fixture now exposes gaps between hard resets, clean truncation, and successful empty completions without splicing attempts or modifying model history. +Developers can reproduce fault sequences by changing only provider URL/key configuration, and automated tests can keep socket-level failures deterministic through explicit scripts and seeds. The same wire fixture now exposes gaps between hard resets, clean truncation, and recovered empty completions without splicing attempts or modifying model history. The server adds a support package, executable build entry, and behavior vocabulary that must remain compatible with both direct tests and CLI examples. Arrival-ordered scripts are intentionally shared across clients, random defaults are stress weights rather than operational truth, and exact connection refusal requires coordinating the client attempt with the pre-listen interval. diff --git a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md index 2f5fcc1321..a0e3c98d72 100644 --- a/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md +++ b/.agents/notes/implemented/testing/2026-07-25-scriptable-llm-wire-fault-server.zh.md @@ -18,11 +18,11 @@ Status: implemented 脚本项 `random` 会为每个请求重新执行一次加权选择。服务器公开并记录其无符号 32 位 seed,允许调用方提供相对权重,并内置一套偏重成功结果的压力测试配置,将传输、协议、提供方、超时和语义空结果混合在一起。该配置用于提供可调的测试压力,并非对生产事故发生频率的估算;`connection_refused` 仍不进入请求级随机池。 -服务器只报告协议层事实,不判断是否可重试。真实组合测试让请求依次经过 `dsh-llm-deepseek`、`dsh-agent-loop` 和 `dsh-llm-retry`:在现有默认策略下,连接遭拒、硬断开、部分输出后重置以及空闲超时均可恢复;合法的无内容完成无需重试即可成功;正常关闭的部分输出 EOF 仍归类为 `STREAM_CLOSED`,默认不重试。该包不会改变这些策略。 +服务器只报告协议层事实,不判断是否可重试。真实组合测试让请求依次经过 `dsh-llm-deepseek`、`dsh-agent-loop` 和 `dsh-llm-retry`:在现有默认策略下,连接遭拒、硬断开、部分输出后重置、空闲超时以及合法的无内容完成均可恢复;正常关闭的部分输出 EOF 仍归类为 `STREAM_CLOSED`,默认不重试。该包不会改变这些策略。 ## 验证 -包测试覆盖所有请求行为、不消耗脚本的 HTTP 校验、脚本耗尽与重复、停滞连接清理、CLI 解析、随机 seed 可复现性、权重校验、遥测、生命周期清理,以及逐文件覆盖率门禁下的配套不变式插件。重试集成套件通过真实 HTTP/SSE(Server-Sent Events)适配器,验证准确的请求次数、带编号的重试步骤、请求体完全一致、失败的部分分片不会泄漏、空完成成功语义、正常 EOF 分类、超时恢复、监听器延迟启动后从真实连接遭拒中恢复,以及有界重试耗尽。 +包测试覆盖所有请求行为、跨分片 UTF-8 请求解码、不消耗脚本的 HTTP 校验、脚本耗尽与重复、停滞连接清理、CLI 解析及延迟边界、IPv6 base URL、随机 seed 可复现性、权重校验、单结果遥测、生命周期清理,以及逐文件覆盖率门禁下的配套不变式插件。重试集成套件通过真实 HTTP/SSE(Server-Sent Events)适配器,验证准确的请求次数、带编号的重试步骤、请求体完全一致、失败的部分分片不会泄漏、语义空结果恢复、正常 EOF 分类、超时恢复、监听器延迟启动后从真实连接遭拒中恢复,以及有界重试耗尽。 ## 曾考虑的替代方案 @@ -32,10 +32,10 @@ Status: implemented **仅使用进程内的 `LlmAdapter` mock**:不予采纳。它会绕过 fetch、HTTP 状态与 header 解析、SSE 分帧、socket 终止以及适配器的空闲看门狗,而这正是这套测试基础设施要覆盖的边界。 -**随服务器一起修改默认重试策略**:不予采纳。服务器用于揭示既有语义,而非决定策略。是否为 `STREAM_CLOSED` 或语义空结果增加恢复能力,需要单独决策,并权衡成本、延迟和重复生成风险。 +**随服务器一起修改默认重试策略**:不予采纳。服务器用于揭示既有语义,而非决定策略。是否将恢复能力扩展到 `STREAM_CLOSED`,需要单独决策,并权衡成本、延迟和重复生成风险。 ## 后果 -开发者只需修改提供方 URL/key 配置即可复现故障序列;自动化测试则可通过显式脚本和 seed,让 socket 层故障保持确定性。同一套协议 fixture 现在可以暴露硬重置、正常截断与成功空完成之间的差异,而不会拼接多次尝试的内容或修改模型历史。 +开发者只需修改提供方 URL/key 配置即可复现故障序列;自动化测试则可通过显式脚本和 seed,让 socket 层故障保持确定性。同一套协议 fixture 现在可以暴露硬重置、正常截断与恢复后的空完成之间的差异,而不会拼接多次尝试的内容或修改模型历史。 服务器新增了一个支持包、可执行构建入口和行为词汇,三者必须同时兼容直接测试与 CLI 示例。按请求到达顺序执行的脚本有意由所有客户端共享;随机模式的默认值代表压力测试权重,而非实际运行规律;精确模拟连接遭拒时,需要让客户端尝试与监听开始前的时间区间协调一致。 diff --git a/docs/module-graph.md b/docs/module-graph.md index 9e8b3adf8a..ca1c58c101 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -117,6 +117,7 @@ flowchart TD pkg_acp_snapshot["acp-snapshot"] pkg_agent_loop_testkit["agent-loop-testkit"] pkg_invariants["invariants"] + pkg_llm_mock_server["llm-mock-server"] pkg_llm_replay["llm-replay"] pkg_loader_smoke["loader-smoke"] end @@ -224,6 +225,7 @@ flowchart TD pkg_skill --> pkg_invariants pkg_subagent_subprocess --> pkg_invariants pkg_acp_snapshot --> pkg_invariants + pkg_llm_mock_server --> pkg_invariants pkg_loader_smoke --> pkg_invariants pkg_client_i18n --> pkg_invariants pkg_client_modules --> pkg_invariants @@ -797,6 +799,7 @@ flowchart TD | [`skill`](../packages/skill/skill) | `skill` | [`invariants`](../packages/support/invariants) | | [`subagent-subprocess`](../packages/subagent/subagent-subprocess) | `subagent` | [`invariants`](../packages/support/invariants) | | [`acp-snapshot`](../packages/support/acp-snapshot) | `support` | [`invariants`](../packages/support/invariants) | +| [`llm-mock-server`](../packages/support/llm-mock-server) | `support` | [`invariants`](../packages/support/invariants) | | [`loader-smoke`](../packages/support/loader-smoke) | `support` | [`invariants`](../packages/support/invariants) | | [`client-i18n`](../packages/client/i18n) | `client` | [`invariants`](../packages/support/invariants) | | [`client-modules`](../packages/client/modules) | `client` | [`invariants`](../packages/support/invariants) | diff --git a/packages/llm/llm-retry/tests/transport-recovery.spec.ts b/packages/llm/llm-retry/tests/transport-recovery.spec.ts index 790e3e22f7..a93bbbc4b6 100644 --- a/packages/llm/llm-retry/tests/transport-recovery.spec.ts +++ b/packages/llm/llm-retry/tests/transport-recovery.spec.ts @@ -140,8 +140,11 @@ describe('bounded retry through the real DeepSeek HTTP/SSE adapter', () => { expect(finalAssistantText(agent)).toBe('recovered response') }) - it('treats a wire-valid content-less completion as success without retrying', async () => { - const server = await start(['empty', 'success'], { apiKey: 'mock-key' }) + it('retries a wire-valid content-less completion without committing an empty message', async () => { + const server = await start(['empty', 'success'], { + apiKey: 'mock-key', + successText: 'recovered from empty', + }) context = await harness(server.baseURL) const agent = context.agentLoop.create(SessionId('wire-empty'), { provider: 'deepseek', @@ -150,16 +153,17 @@ describe('bounded retry through the real DeepSeek HTTP/SSE adapter', () => { await sendAndWait(context, agent) - expect(server.requests).toHaveLength(1) - expect(agent.session.events.some(event => event.type === 'llm/retry')).toBe(false) - expect(agent.session.events.find(event => event.type === 'assistant/message')).toMatchObject({ - data: { turn: 1, step: 1, content: [] }, - }) + expect(server.requests).toHaveLength(2) + expect(server.requests[0]?.body).toEqual(server.requests[1]?.body) + expect(agent.session.events.filter(event => event.type === 'llm/retry').map(event => event.data.failure.code)) + .toEqual(['EMPTY_RESPONSE']) + expect(agent.session.events.filter(event => event.type === 'assistant/message').map(event => event.data.step)) + .toEqual([2]) expect(agent.session.events.at(-1)).toMatchObject({ type: 'turn/end', data: { reason: { kind: 'completed' } }, }) - expect(finalAssistantText(agent)).toBeUndefined() + expect(finalAssistantText(agent)).toBe('recovered from empty') }) it('exposes a clean partial EOF as non-default-retryable STREAM_CLOSED', async () => { diff --git a/packages/support/llm-mock-server/README.md b/packages/support/llm-mock-server/README.md index 20efe731d5..6fca303b47 100644 --- a/packages/support/llm-mock-server/README.md +++ b/packages/support/llm-mock-server/README.md @@ -2,7 +2,7 @@ A scriptable OpenAI-compatible HTTP/SSE server for exercising real LLM adapters, the agent loop, and recovery policy without a provider key. It accepts `POST /chat/completions` and `POST /v1/chat/completions`; each accepted request consumes one configured behavior in arrival order. Invalid methods, paths, bearer tokens, and JSON do not consume the script. -The library entry exports `startMockLlmServer(options)`, behavior and telemetry types, the default random stress weights, and a running handle with the bound `baseURL`, generated or configured `randomSeed`, captured requests, and idempotent `close()`. Closing force-terminates stalled connections. +The library entry exports `startMockLlmServer(options)`, behavior and telemetry types, the default random stress weights, the accepted Node timer bound, and a running handle with the bound `baseURL`, generated or configured `randomSeed`, captured requests, and idempotent `close()`. Closing force-terminates stalled connections. ## Standalone use @@ -67,7 +67,7 @@ When random weights include `stall`, configure the client under test with a shor ## Timing and content controls -The CLI exposes `--success-text`, `--partial-text`, `--reasoning-text`, `--chunk-size`, `--chunk-delay-ms`, `--disconnect-delay-ms`, `--retry-after-ms`, `--request-id`, `--tool-name`, and `--tool-arguments`. The library accepts the same camel-case options. An optional exact `apiKey` validates `Authorization: Bearer `; omission accepts any token. +The CLI exposes `--success-text`, `--partial-text`, `--reasoning-text`, `--chunk-size`, `--chunk-delay-ms`, `--disconnect-delay-ms`, `--retry-after-ms`, `--request-id`, `--tool-name`, and `--tool-arguments`. Millisecond delays are bounded integers within Node's timer range; `retryAfterMs` must also be positive. The library accepts the same camel-case options. An optional exact `apiKey` validates `Authorization: Bearer `; omission accepts any token. ## Model Experience diff --git a/packages/support/llm-mock-server/src/cli.ts b/packages/support/llm-mock-server/src/cli.ts index 12d10072f2..786a74c0f4 100644 --- a/packages/support/llm-mock-server/src/cli.ts +++ b/packages/support/llm-mock-server/src/cli.ts @@ -3,7 +3,7 @@ * @module @deepseek-ai/dsh-llm-mock-server/cli */ -import { MOCK_LLM_BEHAVIORS } from './index.ts' +import { MAX_MOCK_LLM_TIMER_DELAY_MS, MOCK_LLM_BEHAVIORS } from './index.ts' import type { ConcreteMockLlmBehavior, MockLlmBehavior, @@ -18,7 +18,7 @@ export const CONNECTION_REFUSED_BEHAVIOR = 'connection_refused' export interface MockLlmCliConfig { /** Server options after removing the lifecycle-only `connection_refused` entry. */ readonly server: MockLlmServerOptions - /** Delay before binding the model port; zero starts immediately. */ + /** Delay before binding the model port; an integer from zero through the Node timer maximum. */ readonly listenDelayMs: number /** Whether the original sequence requested a true pre-listen refusal phase. */ readonly startsUnavailable: boolean @@ -77,6 +77,14 @@ function numberValue(option: string, value: string): number { return parsed } +function boundedIntegerValue(option: string, value: string, min: number, max: number): number { + const parsed = numberValue(option, value) + if (!Number.isInteger(parsed) || parsed < min || parsed > max) { + throw new Error(`dsh-llm-mock-server: ${option} must be an integer between ${min} and ${max}`) + } + return parsed +} + function parseSequence(raw: string): { startsUnavailable: boolean; sequence: MockLlmBehavior[] } { const entries = raw.split(',').map(entry => entry.trim()) if (entries.some(entry => entry.length === 0)) { @@ -154,7 +162,9 @@ export function parseMockLlmCliArgs(argv: readonly string[]): MockLlmCliParseRes case '--host': host = value; break case '--port': port = numberValue(option, value); break case '--api-key': apiKey = value; break - case '--listen-delay-ms': listenDelayMs = numberValue(option, value); break + case '--listen-delay-ms': + listenDelayMs = boundedIntegerValue(option, value, 0, MAX_MOCK_LLM_TIMER_DELAY_MS) + break case '--seed': randomSeed = numberValue(option, value); break case '--random-weights': randomWeights = parseRandomWeights(value); break case '--success-text': successText = value; break diff --git a/packages/support/llm-mock-server/src/index.ts b/packages/support/llm-mock-server/src/index.ts index 45dda839e2..b07a2bb09b 100644 --- a/packages/support/llm-mock-server/src/index.ts +++ b/packages/support/llm-mock-server/src/index.ts @@ -9,7 +9,7 @@ import { createServer } from 'node:http' import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http' import { randomBytes } from 'node:crypto' -import type { AddressInfo } from 'node:net' +import { isIP, type AddressInfo } from 'node:net' import { setTimeout as delay } from 'node:timers/promises' /** Request-scoped behaviors accepted by {@link startMockLlmServer}. */ @@ -69,6 +69,9 @@ export const DEFAULT_MOCK_LLM_RANDOM_WEIGHTS: Readonly = O malformed_json: 1, }) +/** Largest millisecond delay accepted by Node timers without truncation. */ +export const MAX_MOCK_LLM_TIMER_DELAY_MS = 2_147_483_647 + /** How one accepted request ended at the mock boundary. */ export type MockLlmRequestOutcome = 'completed' | 'reset' | 'stalled' | 'client_closed' | 'server_error' @@ -186,7 +189,6 @@ interface ResolvedOptions { readonly onEvent?: (event: MockLlmServerEvent) => void } -const MAX_TIMER_DELAY_MS = 2_147_483_647 const DEFAULT_SUCCESS_TEXT = 'mock response recovered' const DEFAULT_PARTIAL_TEXT = 'discarded partial response' const DEFAULT_REASONING_TEXT = 'mock reasoning' @@ -203,14 +205,24 @@ function resolveOptions(options: MockLlmServerOptions): ResolvedOptions { const host = options.host ?? '127.0.0.1' const port = boundedInteger('port', options.port ?? 0, 0, 65_535) const chunkSize = boundedInteger('chunkSize', options.chunkSize ?? 8, 1, Number.MAX_SAFE_INTEGER) - const chunkDelayMs = boundedInteger('chunkDelayMs', options.chunkDelayMs ?? 25, 0, MAX_TIMER_DELAY_MS) + const chunkDelayMs = boundedInteger( + 'chunkDelayMs', + options.chunkDelayMs ?? 25, + 0, + MAX_MOCK_LLM_TIMER_DELAY_MS, + ) const disconnectDelayMs = boundedInteger( 'disconnectDelayMs', options.disconnectDelayMs ?? 10, 0, - MAX_TIMER_DELAY_MS, + MAX_MOCK_LLM_TIMER_DELAY_MS, + ) + const retryAfterMs = boundedInteger( + 'retryAfterMs', + options.retryAfterMs ?? 1_000, + 1, + MAX_MOCK_LLM_TIMER_DELAY_MS, ) - const retryAfterMs = boundedInteger('retryAfterMs', options.retryAfterMs ?? 1_000, 1, MAX_TIMER_DELAY_MS) const randomSeed = boundedInteger( 'randomSeed', options.randomSeed ?? randomBytes(4).readUInt32LE(0), @@ -285,8 +297,9 @@ function emit(options: ResolvedOptions, event: MockLlmServerEvent): void { } async function readJsonBody(request: IncomingMessage): Promise { - let body = '' - for await (const chunk of request) body += Buffer.from(chunk).toString('utf8') + const chunks: Buffer[] = [] + for await (const chunk of request) chunks.push(Buffer.from(chunk as Uint8Array)) + const body = Buffer.concat(chunks).toString('utf8') return body.length === 0 ? undefined : JSON.parse(body) } @@ -320,6 +333,7 @@ function finishRecord( record: MockLlmRequestRecord, outcome: MockLlmRequestOutcome, ): void { + if (record.outcome !== undefined) return record.outcome = outcome emit(options, { type: 'result', @@ -713,8 +727,9 @@ export async function startMockLlmServer(options: MockLlmServerOptions): Promise }) const address = server.address() as AddressInfo + const advertisedHost = isIP(resolved.host) === 6 ? `[${resolved.host}]` : resolved.host return { - baseURL: `http://${resolved.host}:${address.port}`, + baseURL: `http://${advertisedHost}:${address.port}`, port: address.port, randomSeed: resolved.randomSeed, requests, diff --git a/packages/support/llm-mock-server/tests/cli.spec.ts b/packages/support/llm-mock-server/tests/cli.spec.ts index 66a3868963..12c5bd6926 100644 --- a/packages/support/llm-mock-server/tests/cli.spec.ts +++ b/packages/support/llm-mock-server/tests/cli.spec.ts @@ -110,6 +110,9 @@ describe('mock LLM server CLI parser', () => { [['--sequence', 'unknown'], /unknown behavior/], [['--sequence', 'connection_refused,success', '--port', '0'], /nonzero/], [['--sequence', 'success', '--listen-delay-ms', '5'], /requires connection_refused/], + [['--sequence', 'connection_refused,success', '--listen-delay-ms', '-1'], /integer between 0 and 2147483647/], + [['--sequence', 'connection_refused,success', '--listen-delay-ms', '1.5'], /integer between 0 and 2147483647/], + [['--sequence', 'connection_refused,success', '--listen-delay-ms', '2147483648'], /integer between 0 and 2147483647/], [['--sequence', 'success', '--seed', '1'], /require random/], [['--sequence', 'random', '--random-weights', 'success'], /expects behavior=weight/], [['--sequence', 'random', '--random-weights', 'random=1'], /concrete behavior/], diff --git a/packages/support/llm-mock-server/tests/server.spec.ts b/packages/support/llm-mock-server/tests/server.spec.ts index b84931bc9f..1f15ba1a0b 100644 --- a/packages/support/llm-mock-server/tests/server.spec.ts +++ b/packages/support/llm-mock-server/tests/server.spec.ts @@ -1,3 +1,4 @@ +import { request } from 'node:http' import { afterEach, describe, expect, it } from 'vitest' import type { MockLlmBehavior, MockLlmServer, MockLlmServerEvent } from '../src/index.ts' import { startMockLlmServer } from '../src/index.ts' @@ -32,6 +33,22 @@ function chat( }) } +function rawChat(server: MockLlmServer, chunks: readonly Buffer[]): Promise { + return new Promise((resolve, reject) => { + const outgoing = request(`${server.baseURL}/v1/chat/completions`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + }, (response) => { + response.once('error', reject) + response.once('end', resolve) + response.resume() + }) + outgoing.once('error', reject) + for (const chunk of chunks) outgoing.write(chunk) + outgoing.end() + }) +} + describe('mock LLM server wire behaviors', () => { it('streams a complete text response and captures the request', async () => { const events: MockLlmServerEvent[] = [] @@ -151,10 +168,12 @@ describe('mock LLM server wire behaviors', () => { ['stream_disconnect', 100] as const, ['partial_disconnect', 100] as const, ])('records a client that closes during %s', async (behavior, delayMs) => { + const events: MockLlmServerEvent[] = [] const server = await start([behavior], { chunkDelayMs: delayMs, disconnectDelayMs: delayMs, chunkSize: 1, + onEvent: (event) => { events.push(event) }, }) const controller = new AbortController() const response = await chat(server, { signal: controller.signal }) @@ -163,6 +182,30 @@ describe('mock LLM server wire behaviors', () => { await new Promise((resolve) => { setTimeout(resolve, 5) }) expect(server.requests[0]).toMatchObject({ behavior, outcome: 'client_closed' }) + expect(events.filter(event => event.type === 'result')).toEqual([ + expect.objectContaining({ behavior, outcome: 'client_closed' }), + ]) + }) + + it('preserves UTF-8 code points split across request chunks', async () => { + const server = await start(['success']) + const encoded = Buffer.from(JSON.stringify({ messages: [{ role: 'user', content: '你好' }] })) + const characterOffset = encoded.indexOf(Buffer.from('你')) + expect(characterOffset).toBeGreaterThanOrEqual(0) + + await rawChat(server, [ + encoded.subarray(0, characterOffset + 1), + encoded.subarray(characterOffset + 1), + ]) + + expect(server.requests[0]?.body).toEqual({ messages: [{ role: 'user', content: '你好' }] }) + }) + + it('formats an IPv6 listener as a valid base URL', async () => { + const server = await start(['success'], { host: '::1' }) + + expect(server.baseURL).toMatch(/^http:\/\/\[::1\]:\d+$/) + expect((await chat(server)).status).toBe(200) }) it('emits reasoning, tool calls, max-token finishes, slow chunks, and a wrong content type', async () => { From 6e721b9fdd5524b31fc399bf7b72f0cba0f32cba Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 00:16:05 +0800 Subject: [PATCH 076/113] feat(gui): settings panel with locale and theme preferences Add the browser Settings surface as slot-composed plugins over new preference services: - Rename dsh-client-i18n to dsh-client-locale (locale is the domain name); LocaleService adds getLocale()/setLocale(id), immutable snapshots, a locale/change event, and dsh.locale persistence. - ThemeService owns the light/dark/system preference (default system), resolves system via prefers-color-scheme, publishes theme/change snapshots, persists dsh.theme, and no longer touches the DOM; ui-layout's ThemePresenter applies resolved snapshots (body[data-ds-dark-theme] + alias tokens) and cleans up on dispose. - ui-sidebar drops the phase-1 settings dropdown/modal; the foot renders the new sidebar.settings slot with the column state. - New ui-settings shell occupies sidebar.settings: foot trigger row and the centered 1080x700 panel (figma 501:29947) with 24% mask, close button / mask click / Escape all closing, and a 188px nav projected from the settings.section list slot it declares. Nav labels are registrant-localized; sections re-register on locale change, so the ledger version is the shell's only subscription. - ui-settings-general registers the General section: Permission and Tool Call skeletons, live Language (locale menu) and Appearance (Light/Dark/System cubes following the persisted preference); its slot store mirrors both service snapshots via apply-side listeners. - ui-settings-models registers the Models nav entry with an empty content column. - Portaled menus pin z-index above modal overlays (a menu anchored inside the settings dialog rendered underneath it and was unclickable). - theme/data/list-pen icons in ui-primitives; settings copy ships as zh/en dictionaries; fixture manifests gain the settings rows. --- ...6-07-25-client-settings-locale-theme.zh.md | 99 +++++++++ apps/cli/cordis.yml | 13 +- apps/cli/package.json | 5 +- apps/cli/tsconfig.json | 11 +- apps/web/tests/session-title.snapshot.ts | 5 +- apps/web/tests/smoke-real.e2e.ts | 2 +- apps/web/tests/workspace-flow.snapshot.ts | 5 +- packages/client/i18n/README.md | 16 -- packages/client/i18n/src/client/index.ts | 108 --------- packages/client/i18n/tests/i18n.spec.ts | 53 ----- packages/client/i18n/tests/invariant.spec.ts | 30 --- packages/client/i18n/tsdown.config.ts | 3 - packages/client/locale/README.md | 16 ++ packages/client/{i18n => locale}/package.json | 13 +- packages/client/locale/src/client/index.ts | 195 +++++++++++++++++ packages/client/{i18n => locale}/src/index.ts | 2 +- .../client/{i18n => locale}/src/invariant.ts | 8 +- .../client/{i18n => locale}/src/locales/en.ts | 0 .../client/{i18n => locale}/src/locales/zh.ts | 0 .../client/locale/tests/invariant.spec.ts | 30 +++ packages/client/locale/tests/locale.spec.ts | 90 ++++++++ .../client/{i18n => locale}/tsconfig.json | 3 - packages/client/locale/tsdown.config.ts | 3 + packages/client/tsdown.client.ts | 2 +- packages/client/ui-conversation/package.json | 2 +- .../tests/apply-inject.spec.tsx | 2 +- .../ui-conversation/tests/chat-apply.spec.tsx | 2 +- .../tests/chat-toolview-slot.spec.tsx | 4 +- packages/client/ui-conversation/tsconfig.json | 2 +- packages/client/ui-layout/README.md | 2 +- packages/client/ui-layout/package.json | 5 +- packages/client/ui-layout/src/client/index.ts | 19 +- .../ui-layout/src/client/theme-presenter.ts | 43 ++++ packages/client/ui-layout/tests/apply.spec.ts | 21 +- .../ui-layout/tests/theme-presenter.spec.ts | 56 +++++ packages/client/ui-layout/tsconfig.json | 3 + .../client/ui-primitives/src/Menu.module.css | 4 +- .../client/ui-primitives/src/icons/index.tsx | 87 ++++++++ .../client/ui-primitives/tests/icons.spec.tsx | 4 +- packages/client/ui-settings-general/README.md | 15 ++ .../client/ui-settings-general/package.json | 70 ++++++ .../src/client/GeneralSection.module.css | 131 +++++++++++ .../src/client/GeneralSection.tsx | 118 ++++++++++ .../src/client/contract.ts | 66 ++++++ .../ui-settings-general/src/client/index.ts | 111 ++++++++++ .../ui-settings-general/src/client/locales.ts | 42 ++++ .../ui-settings-general/src/client/store.ts | 43 ++++ .../ui-settings-general/src/css-modules.d.ts | 6 + .../client/ui-settings-general/src/index.ts | 4 + .../ui-settings-general/src/invariant.ts | 32 +++ .../client/ui-settings-general/tsconfig.json | 36 +++ .../ui-settings-general/tsdown.config.ts | 3 + packages/client/ui-settings-models/README.md | 15 ++ .../client/ui-settings-models/package.json | 63 ++++++ .../src/client/ModelsSection.tsx | 13 ++ .../ui-settings-models/src/client/index.ts | 63 ++++++ .../ui-settings-models/src/css-modules.d.ts | 6 + .../client/ui-settings-models/src/index.ts | 4 + .../ui-settings-models/src/invariant.ts | 31 +++ .../client/ui-settings-models/tsconfig.json | 30 +++ .../ui-settings-models/tsdown.config.ts | 3 + packages/client/ui-settings/README.md | 15 ++ packages/client/ui-settings/package.json | 68 ++++++ .../src/client/SettingsRoot.module.css | 192 ++++++++++++++++ .../ui-settings/src/client/SettingsRoot.tsx | 125 +++++++++++ .../ui-settings/src/client/contract/slots.ts | 62 ++++++ .../client/ui-settings/src/client/index.ts | 66 ++++++ .../client/ui-settings/src/css-modules.d.ts | 6 + packages/client/ui-settings/src/index.ts | 4 + packages/client/ui-settings/src/invariant.ts | 32 +++ packages/client/ui-settings/tsconfig.json | 33 +++ packages/client/ui-settings/tsdown.config.ts | 3 + packages/client/ui-sidebar/README.md | 4 +- .../src/client/SidebarRoot.module.css | 46 +--- .../ui-sidebar/src/client/SidebarRoot.tsx | 9 +- .../ui-sidebar/src/client/contract/slots.ts | 22 +- .../client/ui-sidebar/src/client/index.ts | 11 +- .../ui-sidebar/tests/sidebar-root.spec.tsx | 16 +- packages/client/ui-theme/README.md | 5 +- packages/client/ui-theme/package.json | 8 +- packages/client/ui-theme/src/client/index.ts | 207 ++++++++++++++---- packages/client/ui-theme/src/invariant.ts | 7 +- packages/client/ui-theme/tests/theme.spec.ts | 109 +++++---- packages/client/web/src/boot.tsx | 2 +- pnpm-lock.yaml | 120 +++++++++- .../verify-package-readme-model-experience.ts | 2 +- tsconfig.base.json | 5 +- tsconfig.client.json | 5 +- 88 files changed, 2653 insertions(+), 404 deletions(-) create mode 100644 .agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md delete mode 100644 packages/client/i18n/README.md delete mode 100644 packages/client/i18n/src/client/index.ts delete mode 100644 packages/client/i18n/tests/i18n.spec.ts delete mode 100644 packages/client/i18n/tests/invariant.spec.ts delete mode 100644 packages/client/i18n/tsdown.config.ts create mode 100644 packages/client/locale/README.md rename packages/client/{i18n => locale}/package.json (78%) create mode 100644 packages/client/locale/src/client/index.ts rename packages/client/{i18n => locale}/src/index.ts (61%) rename packages/client/{i18n => locale}/src/invariant.ts (86%) rename packages/client/{i18n => locale}/src/locales/en.ts (100%) rename packages/client/{i18n => locale}/src/locales/zh.ts (100%) create mode 100644 packages/client/locale/tests/invariant.spec.ts create mode 100644 packages/client/locale/tests/locale.spec.ts rename packages/client/{i18n => locale}/tsconfig.json (87%) create mode 100644 packages/client/locale/tsdown.config.ts create mode 100644 packages/client/ui-layout/src/client/theme-presenter.ts create mode 100644 packages/client/ui-layout/tests/theme-presenter.spec.ts create mode 100644 packages/client/ui-settings-general/README.md create mode 100644 packages/client/ui-settings-general/package.json create mode 100644 packages/client/ui-settings-general/src/client/GeneralSection.module.css create mode 100644 packages/client/ui-settings-general/src/client/GeneralSection.tsx create mode 100644 packages/client/ui-settings-general/src/client/contract.ts create mode 100644 packages/client/ui-settings-general/src/client/index.ts create mode 100644 packages/client/ui-settings-general/src/client/locales.ts create mode 100644 packages/client/ui-settings-general/src/client/store.ts create mode 100644 packages/client/ui-settings-general/src/css-modules.d.ts create mode 100644 packages/client/ui-settings-general/src/index.ts create mode 100644 packages/client/ui-settings-general/src/invariant.ts create mode 100644 packages/client/ui-settings-general/tsconfig.json create mode 100644 packages/client/ui-settings-general/tsdown.config.ts create mode 100644 packages/client/ui-settings-models/README.md create mode 100644 packages/client/ui-settings-models/package.json create mode 100644 packages/client/ui-settings-models/src/client/ModelsSection.tsx create mode 100644 packages/client/ui-settings-models/src/client/index.ts create mode 100644 packages/client/ui-settings-models/src/css-modules.d.ts create mode 100644 packages/client/ui-settings-models/src/index.ts create mode 100644 packages/client/ui-settings-models/src/invariant.ts create mode 100644 packages/client/ui-settings-models/tsconfig.json create mode 100644 packages/client/ui-settings-models/tsdown.config.ts create mode 100644 packages/client/ui-settings/README.md create mode 100644 packages/client/ui-settings/package.json create mode 100644 packages/client/ui-settings/src/client/SettingsRoot.module.css create mode 100644 packages/client/ui-settings/src/client/SettingsRoot.tsx create mode 100644 packages/client/ui-settings/src/client/contract/slots.ts create mode 100644 packages/client/ui-settings/src/client/index.ts create mode 100644 packages/client/ui-settings/src/css-modules.d.ts create mode 100644 packages/client/ui-settings/src/index.ts create mode 100644 packages/client/ui-settings/src/invariant.ts create mode 100644 packages/client/ui-settings/tsconfig.json create mode 100644 packages/client/ui-settings/tsdown.config.ts diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md new file mode 100644 index 0000000000..d3c61794b9 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md @@ -0,0 +1,99 @@ +# Agent Note: Client Settings、Locale 与 Theme 分层 + +Status: proposed + +## Problem + +浏览器端已有的 Settings 直接写在 Sidebar 内,语言和主题也由组件本地状态直接改 DOM。这使 Settings 无法由独立插件扩展,偏好状态没有稳定的跨插件服务契约,主题 registry 同时承担状态与呈现职责。 + +## Proposal + +Sidebar 声明 `sidebar.settings` 单坑位,`ui-settings` 占用它并声明 `settings.section` list 坑位。每个 section 由独立插件贡献;Settings 壳只从 slot ledger 读取 entry metadata 生成导航,通过 `only` 渲染当前 section。 + +Settings 入口是 sidebar Foot 的 Settings 行,点击直接打开 1080×700 居中浮层(黑 24% 遮罩);close 按钮、点击遮罩、ESC 均关闭。无任何中间菜单形态。 + +`@deepseek-ai/dsh-client-locale` 提供 `ctx.locale`,`ui-theme` 提供 `ctx.theme`。两个 service 都以 getter 读取、setter 写入并用 typed Cordis change event 发布 immutable snapshot;service 自己持久化偏好(只存 id,坏值回退默认)。 + +General 的 apply 层订阅 `locale/change` 和 `theme/change`,把 snapshot 投影到该 section 声明的 Zustand store。React 组件只读 `useStore`、写注入的 setter callback,不读取 ctx 或 service。 + +Theme 偏好三态:`light`、`dark`、`system`,默认 `system`(无持久化偏好或坏值时)。system 的解析属主题领域:ThemeService 持有 `prefers-color-scheme` matchMedia 监听(环境感知,非 DOM 呈现),偏好为 system 且系统配色变化时重发 snapshot;snapshot 同时携带 `preference` 与解析后的 `active` 定义。 + +Theme service 不操作 DOM。`ui-layout` 初始读取 Theme getter,随后订阅 `theme/change`,由 Layout 持有的 presenter 按 `active` 更新 `body[data-ds-dark-theme]` 和主题 token;presenter 不感知 system,只消费已解析结果。 + +### 首期 section 范围 + +| section | 插件 | 首期内容 | +|---|---|---| +| General | `ui-settings-general` | Language(Selector 下拉)与 Appearance(Light/Dark/System 三 cube)真实可切;Permission、Tool Call 仅视觉骨架,无写操作 | +| Models | `ui-settings-models` | 仅导航项,内容区为空 | +| Plugin | 不建包 | 首期不做,导航不出现该项(无目标的外链入口不上屏;后续插件注册 section 即自动出现) | + +首期只翻译 Settings 浮层内文案(General 各行 + 导航);其他页面文案不动。 + +### Slot topology + +```text +root +└─ sidebar + └─ sidebar.settings single/root + └─ ui-settings + └─ settings.section list/root + ├─ general ui-settings-general + └─ models ui-settings-models +``` + +section contribution 使用 declaration-aware deferral,不依赖 client manifest 的 apply 顺序。 + +### Service contracts + +```ts +type ThemePreference = 'light' | 'dark' | 'system' + +interface ThemeSnapshot { + preference: ThemePreference + active: ThemeDefinition // system 已解析为具体 light/dark 定义 + themes: readonly ThemeDefinition[] + revision: number +} + +interface LocaleSnapshot { + active: 'zh' | 'en' + locales: readonly LocaleDefinition[] + revision: number +} + +interface Events { + /** @param snapshot - Current locale registry snapshot. @mode emit */ + 'locale/change'(snapshot: LocaleSnapshot): void + /** @param snapshot - Current theme registry snapshot. @mode emit */ + 'theme/change'(snapshot: ThemeSnapshot): void +} +``` + +Locale 内置中文和 English;`setLocale`/`setTheme` 是唯一写入口,未知 id 失败。 + +## Alternatives considered + +**由 app shell 统一订阅偏好并重渲染 root slot tree。** 语言和主题变化只需要更新实际消费者;全树刷新放大影响面,也把业务偏好接入 shell。 + +**Theme service 直接修改 DOM。** registry service 因此依赖呈现环境,生命周期与全局样式所有权不清;Layout 已经拥有页面根呈现边界。 + +**system 由 Layout presenter 解析。** presenter 需自带 matchMedia 订阅并在 themes 列表里挑选具体定义,呈现层被迫理解偏好语义;解析放服务侧则所有消费者拿到一致的已解析 snapshot。 + +**Settings import 并枚举各 section。** 新增页面必须修改壳插件,破坏「每个功能由自己的插件占坑」的组合模型。 + +**把 Locale/Theme snapshot 直接注入 React。** inject 结果按 entry identity 缓存,易变值会陈旧;为每个 service 自造 React hook 也绕开 slot store 的统一绑定。 + +## Acceptance criteria + +- Settings 壳只依赖 slot ledger,不依赖任一 section 实现。 +- Locale 与 Theme 的写入只走 setter,持续同步只走 change event。 +- General store 初始化走 getter,后续由两个 event 更新并局部重渲染。 +- Layout 独立应用 Theme snapshot,Theme service 不访问 DOM;presenter 不出现 system 分支。 +- 中文/English 与 Light/Dark/System 能切换并刷新后恢复;偏好为 system 时系统配色变化即时生效。 +- Models 只有导航项与空内容区;Permission、Tool Call 骨架无写操作。 +- 浮层经 close 按钮、遮罩点击、ESC 均可关闭。 + +## Risks + +slot 声明与 contribution 的 apply 顺序不固定,所有新 section 必须保留 declaration-aware registration 和幂等防护。service event 可能早于 section 首次渲染,General store 的 init 与 controller attach 都必须从 getter 对齐当前 snapshot。Layout 卸载时必须清理自己设置的全局属性,ThemeService dispose 时必须移除 matchMedia 监听,避免 HMR 后残留。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index b89df77c46..8412a313b4 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -221,8 +221,8 @@ - id: ui-theme name: '@deepseek-ai/dsh-client-ui-theme' -- id: i18n - name: '@deepseek-ai/dsh-client-i18n' +- id: locale + name: '@deepseek-ai/dsh-client-locale' - id: ui-layout name: '@deepseek-ai/dsh-client-ui-layout' @@ -230,6 +230,15 @@ - id: ui-sidebar name: '@deepseek-ai/dsh-client-ui-sidebar' +- id: ui-settings + name: '@deepseek-ai/dsh-client-ui-settings' + +- id: ui-settings-general + name: '@deepseek-ai/dsh-client-ui-settings-general' + +- id: ui-settings-models + name: '@deepseek-ai/dsh-client-ui-settings-models' + - id: ui-conversation name: '@deepseek-ai/dsh-client-ui-conversation' diff --git a/apps/cli/package.json b/apps/cli/package.json index e1c07f90b5..74a6e417e1 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -23,13 +23,16 @@ "@deepseek-ai/dsh-bash-local": "workspace:^", "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-hmr": "workspace:^", - "@deepseek-ai/dsh-client-i18n": "workspace:^", + "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-modules": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-conversation": "workspace:^", "@deepseek-ai/dsh-client-ui-layout": "workspace:^", "@deepseek-ai/dsh-client-ui-question": "workspace:^", "@deepseek-ai/dsh-client-ui-sidebar": "workspace:^", + "@deepseek-ai/dsh-client-ui-settings": "workspace:^", + "@deepseek-ai/dsh-client-ui-settings-general": "workspace:^", + "@deepseek-ai/dsh-client-ui-settings-models": "workspace:^", "@deepseek-ai/dsh-client-ui-theme": "workspace:^", "@deepseek-ai/dsh-client-ui-trajectory": "workspace:^", "@deepseek-ai/dsh-client-ui-workspace": "workspace:^", diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json index 4db4861b93..7614ae2e31 100644 --- a/apps/cli/tsconfig.json +++ b/apps/cli/tsconfig.json @@ -42,7 +42,16 @@ "path": "../../packages/client/ui-theme" }, { - "path": "../../packages/client/i18n" + "path": "../../packages/client/ui-settings" + }, + { + "path": "../../packages/client/ui-settings-general" + }, + { + "path": "../../packages/client/ui-settings-models" + }, + { + "path": "../../packages/client/locale" }, { "path": "../../packages/client/ui-layout" diff --git a/apps/web/tests/session-title.snapshot.ts b/apps/web/tests/session-title.snapshot.ts index c1616bb724..b8ee3408a3 100644 --- a/apps/web/tests/session-title.snapshot.ts +++ b/apps/web/tests/session-title.snapshot.ts @@ -10,9 +10,12 @@ const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [ { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true }, { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true }, { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true }, - { id: '@deepseek-ai/dsh-client-i18n', dir: 'i18n', url: '/plugins/i18n.js', rev: 'fx', inject: [], immediately: true }, + { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true }, { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] }, { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, + { id: '@deepseek-ai/dsh-client-ui-settings', dir: 'ui-settings', url: '/plugins/ui-settings.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-sidebar', '@deepseek-ai/dsh-client-locale'] }, + { id: '@deepseek-ai/dsh-client-ui-settings-general', dir: 'ui-settings-general', url: '/plugins/ui-settings-general.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, + { id: '@deepseek-ai/dsh-client-ui-settings-models', dir: 'ui-settings-models', url: '/plugins/ui-settings-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, { id: '@deepseek-ai/dsh-client-ui-workspace', dir: 'ui-workspace', url: '/plugins/ui-workspace.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime', '@deepseek-ai/dsh-client-ui-conversation', '@deepseek-ai/dsh-client-ui-sidebar'] }, { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] }, diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index a3d511df16..70d1d81523 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -147,7 +147,7 @@ async function detailsTrack(page: Page): Promise { // Readiness gate: `dsh web` serves ALL nine manifest plugins; until every UI // plugin's client bundle exists and exports apply, the loader fail-louds and // the frame never appears. -const UI_PLUGIN_DIRS = ['connection', 'runtime', 'ui-theme', 'i18n', 'ui-layout', 'ui-sidebar', 'ui-conversation', 'ui-question', 'ui-trajectory'] +const UI_PLUGIN_DIRS = ['connection', 'runtime', 'ui-theme', 'locale', 'ui-layout', 'ui-sidebar', 'ui-conversation', 'ui-question', 'ui-trajectory'] const ROUND_DONE_MARKER = 'WEB_ROUND_DONE' const notReady = UI_PLUGIN_DIRS.filter((dir) => { const bundle = join(REPO_ROOT, 'packages/client', dir, 'lib/client.js') diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index 78ac843a64..e232d8e123 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -10,9 +10,12 @@ const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [ { id: '@deepseek-ai/dsh-client-connection', dir: 'connection', url: '/plugins/connection.js', rev: 'fx', inject: [], immediately: true }, { id: '@deepseek-ai/dsh-client-runtime', dir: 'runtime', url: '/plugins/runtime.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-connection'], immediately: true }, { id: '@deepseek-ai/dsh-client-ui-theme', dir: 'ui-theme', url: '/plugins/ui-theme.js', rev: 'fx', inject: [], immediately: true }, - { id: '@deepseek-ai/dsh-client-i18n', dir: 'i18n', url: '/plugins/i18n.js', rev: 'fx', inject: [], immediately: true }, + { id: '@deepseek-ai/dsh-client-locale', dir: 'locale', url: '/plugins/locale.js', rev: 'fx', inject: [], immediately: true }, { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] }, { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, + { id: '@deepseek-ai/dsh-client-ui-settings', dir: 'ui-settings', url: '/plugins/ui-settings.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-sidebar', '@deepseek-ai/dsh-client-locale'] }, + { id: '@deepseek-ai/dsh-client-ui-settings-general', dir: 'ui-settings-general', url: '/plugins/ui-settings-general.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, + { id: '@deepseek-ai/dsh-client-ui-settings-models', dir: 'ui-settings-models', url: '/plugins/ui-settings-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, { id: '@deepseek-ai/dsh-client-ui-workspace', diff --git a/packages/client/i18n/README.md b/packages/client/i18n/README.md deleted file mode 100644 index db6be0fe2a..0000000000 --- a/packages/client/i18n/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# @deepseek-ai/dsh-client-i18n - -i18n plugin: I18nService (ns×locale dictionaries, bind(ns)→t with a stable function identity, locale store). Contract: api-contracts v3 §8. - -## Model Experience - -None, as the i18n registry serves browser UI copy; nothing here reaches a model request. - -#### KV Cache effect - -None; this package neither assembles nor sends a provider request. - -## Known Limitations and Deferred Work - -- **zh/en ship as empty structures** — the existing UI copy is inline Chinese; extraction into dictionaries is deferred repo-wide work, so `bind(ns)` consumers today mostly receive key-echo fallbacks. -- **Locale switching re-renders the whole tree** — accepted as a low-frequency operation; no per-namespace subscription granularity. diff --git a/packages/client/i18n/src/client/index.ts b/packages/client/i18n/src/client/index.ts deleted file mode 100644 index 9dea9c4bd4..0000000000 --- a/packages/client/i18n/src/client/index.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Browser-side locale registry. Bound translation functions retain stable - * identity for injected consumers. - */ -import type { Context } from 'cordis' -// Snapshot stores are framework-neutral; React consumers bind hooks at their -// rendering boundary. -import type { SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' -import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client' -import { en } from '../locales/en.ts' -import { zh } from '../locales/zh.ts' - -/** Translate a key with optional params. */ -export type Translate = (key: string, params?: Record) => string - -/** Locale dictionary: flat key to template string ({name} placeholders). */ -export type LocaleDict = Record - -declare module 'cordis' { - interface Context { - i18n: I18nService - } -} - -/** Fallback locale consulted after the active locale misses. */ -export const FALLBACK_LOCALE = 'zh' - -/** Shared namespace for shell-level texts. */ -export const COMMON_NS = 'common' - -/** - * Dictionary registry plus locale switch. Lookup chain per key: active locale - * -> zh fallback -> the key itself (missing text stays visible, fail loud in - * the UI rather than blank). - */ -export class I18nService { - private dicts = new Map>() - private bound = new Map() - private localeStore = createSnapshotStore(FALLBACK_LOCALE) - - /** - * Register a dictionary for a namespace and locale. Duplicate (ns, locale) - * throws (single occupant; a namespace's texts have one owner). - * @param ns - namespace. - * @param locale - locale tag (zh/en to start). - * @param dict - dictionary. - * @returns disposer (idempotent). - */ - register(ns: string, locale: string, dict: LocaleDict): () => void { - let locales = this.dicts.get(ns) - if (!locales) { - locales = new Map() - this.dicts.set(ns, locales) - } - if (locales.has(locale)) throw new Error(`i18n namespace "${ns}" already has locale "${locale}"`) - locales.set(locale, dict) - return () => { - const owner = this.dicts.get(ns) - if (owner?.get(locale) === dict) owner.delete(locale) - } - } - - /** - * Bind a namespace to a translate function. The returned reference is - * stable per namespace (repeat binds return the same function), so it can - * ride inject surfaces without breaking memoization. - * @param ns - namespace. - * @returns the translate function (reads the locale store at call time). - */ - bind(ns: string): Translate { - let t = this.bound.get(ns) - if (!t) { - t = (key, params) => this.translate(ns, key, params) - this.bound.set(ns, t) - return t - } - return t - } - - /** Active locale store (switching re-renders the tree; low frequency). */ - get locale(): SnapshotStore { - return this.localeStore - } - - private translate(ns: string, key: string, params?: Record): string { - const locales = this.dicts.get(ns) - const template = locales?.get(this.localeStore.getSnapshot())?.[key] - ?? locales?.get(FALLBACK_LOCALE)?.[key] - ?? key - if (!params) return template - return template.replace(/\{(\w+)\}/g, (match, name: string) => - name in params ? String(params[name]) : match) - } -} - -/** Required services (none; the loader passes the export surface as an object plugin). */ -export const inject: string[] = [] - -/** - * Client plugin body: provide the i18n service with base dictionaries. - * @param ctx - client cordis context. - */ -export function apply(ctx: Context): void { - const i18n = new I18nService() - i18n.register(COMMON_NS, 'zh', zh) - i18n.register(COMMON_NS, 'en', en) - ctx.provide('i18n', i18n) -} diff --git a/packages/client/i18n/tests/i18n.spec.ts b/packages/client/i18n/tests/i18n.spec.ts deleted file mode 100644 index 12fef2c716..0000000000 --- a/packages/client/i18n/tests/i18n.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { I18nService } from '@deepseek-ai/dsh-client-i18n/client' - -describe('I18nService', () => { - it('translates from the active locale with zh fallback then key passthrough', () => { - const i18n = new I18nService() - i18n.register('ns', 'zh', { hello: '你好', onlyZh: '仅中文' }) - i18n.register('ns', 'en', { hello: 'Hello' }) - const t = i18n.bind('ns') - expect(i18n.locale.getSnapshot()).toBe('zh') - expect(t('hello')).toBe('你好') - i18n.locale.set('en') - expect(t('hello')).toBe('Hello') - expect(t('onlyZh')).toBe('仅中文') - expect(t('missing.key')).toBe('missing.key') - }) - - it('interpolates {name} params and leaves unknown placeholders intact', () => { - const i18n = new I18nService() - i18n.register('ns', 'zh', { greet: '你好,{name}!第 {n} 次', partial: '{known} 与 {unknown}' }) - const t = i18n.bind('ns') - expect(t('greet', { name: '世界', n: 2 })).toBe('你好,世界!第 2 次') - expect(t('partial', { known: 'A' })).toBe('A 与 {unknown}') - expect(t('greet')).toBe('你好,{name}!第 {n} 次') - }) - - it('bind returns a stable reference per namespace', () => { - const i18n = new I18nService() - expect(i18n.bind('a')).toBe(i18n.bind('a')) - expect(i18n.bind('a')).not.toBe(i18n.bind('b')) - }) - - it('duplicate (ns, locale) throws; disposer unregisters and is idempotent', () => { - const i18n = new I18nService() - const dispose = i18n.register('ns', 'zh', { k: 'v1' }) - expect(() => i18n.register('ns', 'zh', { k: 'v2' })).toThrow('already has locale') - dispose() - dispose() - const t = i18n.bind('ns') - expect(t('k')).toBe('k') - i18n.register('ns', 'zh', { k: 'v2' }) - expect(t('k')).toBe('v2') - }) - - it('locale store is subscribable (snapshot store contract)', () => { - const i18n = new I18nService() - let notified = 0 - i18n.locale.subscribe(() => { notified += 1 }) - i18n.locale.set('en') - expect(i18n.locale.getSnapshot()).toBe('en') - expect(notified).toBe(1) - }) -}) diff --git a/packages/client/i18n/tests/invariant.spec.ts b/packages/client/i18n/tests/invariant.spec.ts deleted file mode 100644 index b992e50d52..0000000000 --- a/packages/client/i18n/tests/invariant.spec.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { Context } from 'cordis' -import { apply as nodeApply } from '@deepseek-ai/dsh-client-i18n' -import { apply as clientApply, COMMON_NS, I18nService, inject } from '@deepseek-ai/dsh-client-i18n/client' -import * as I18nInvariant from '@deepseek-ai/dsh-client-i18n/invariant' -import InvariantService from '@deepseek-ai/dsh-invariants' - -describe('invariant companion', () => { - it('registers under the package name with an empty installer', async () => { - const ctx = new Context() - await ctx.plugin(InvariantService, { enabled: true }) - await expect(ctx.plugin(I18nInvariant).await()).resolves.toBeDefined() - }) - - it('node-half apply is a no-op host placeholder', () => { - nodeApply() - expect(true).toBe(true) // reaching here without throw is the contract - }) - - it('client apply provides ctx.i18n seeded with the zh/en common namespace', async () => { - expect(inject).toEqual([]) - const ctx = new Context() - await ctx.plugin({ inject, apply: clientApply }).await() - const i18n = ctx.get('i18n') - expect(i18n).toBeInstanceOf(I18nService) - // Seeded dictionaries occupy the (ns, locale) seats even while empty. - expect(() => (i18n as I18nService).register(COMMON_NS, 'zh', {})).toThrow('already has locale') - expect(() => (i18n as I18nService).register(COMMON_NS, 'en', {})).toThrow('already has locale') - }) -}) diff --git a/packages/client/i18n/tsdown.config.ts b/packages/client/i18n/tsdown.config.ts deleted file mode 100644 index 1c0802be49..0000000000 --- a/packages/client/i18n/tsdown.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { clientBundle } from '../tsdown.client.ts' - -export default clientBundle('@deepseek-ai/dsh-client-i18n', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/locale/README.md b/packages/client/locale/README.md new file mode 100644 index 0000000000..078967c2cc --- /dev/null +++ b/packages/client/locale/README.md @@ -0,0 +1,16 @@ +# @deepseek-ai/dsh-client-locale + +Locale plugin: LocaleService — the browser locale preference (`zh`/`en`, persisted under `dsh.locale`, getter/setter with `locale/change` snapshots) plus the ns×locale dictionary registry (`bind(ns)`→t with a stable function identity; lookup chain active → zh → key). + +## Model Experience + +None, as the locale registry serves browser UI copy; nothing here reaches a model request. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + +- **Only the Settings surface is translated** — other pages keep inline copy; repo-wide extraction into dictionaries is deferred. +- **Locale switching re-renders subscribed consumers only** — sections not wired to `locale/change` keep their rendered text until remount. diff --git a/packages/client/i18n/package.json b/packages/client/locale/package.json similarity index 78% rename from packages/client/i18n/package.json rename to packages/client/locale/package.json index 3e617174bf..340efe042e 100644 --- a/packages/client/i18n/package.json +++ b/packages/client/locale/package.json @@ -1,6 +1,6 @@ { - "name": "@deepseek-ai/dsh-client-i18n", - "description": "i18n plugin: I18nService (ns x locale dictionaries, bind(ns) -> t, locale store); zh/en skeleton", + "name": "@deepseek-ai/dsh-client-locale", + "description": "Locale plugin: LocaleService (zh/en preference with getter/setter/change event + persistence; ns x locale dictionaries, bind(ns) -> t)", "version": "0.0.1", "private": true, "type": "module", @@ -28,9 +28,6 @@ "immediately": true }, "license": "BSD-3-Clause", - "dependencies": { - "@deepseek-ai/dsh-client-runtime": "workspace:^" - }, "peerDependencies": { "@deepseek-ai/dsh-invariants": "^0.0.1", "cordis": "^4.0.0-rc.7" @@ -46,5 +43,9 @@ "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" - ] + ], + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + } } diff --git a/packages/client/locale/src/client/index.ts b/packages/client/locale/src/client/index.ts new file mode 100644 index 0000000000..e01d69ea25 --- /dev/null +++ b/packages/client/locale/src/client/index.ts @@ -0,0 +1,195 @@ +/** + * Browser-side locale registry. Bound translation functions retain stable + * identity for injected consumers. + */ +import type { Context } from 'cordis' +import { en } from '../locales/en.ts' +import { zh } from '../locales/zh.ts' + +/** Translate a key with optional params. */ +export type Translate = (key: string, params?: Record) => string + +/** Locale dictionary: flat key to template string ({name} placeholders). */ +export type LocaleDict = Record + +/** Locale identifier: the two shipped locales. */ +export type LocaleId = 'zh' | 'en' + +/** One selectable locale: id plus its self-described display name. */ +export interface LocaleDefinition { + /** Locale id (persisted; the setLocale argument). */ + id: LocaleId + /** Display name in its own language (中文 / English). */ + label: string +} + +/** Immutable locale state published on every change. */ +export interface LocaleSnapshot { + /** Active locale id. */ + active: LocaleId + /** Selectable locales in display order. */ + locales: readonly LocaleDefinition[] + /** Monotonic change counter (registry or active changes). */ + revision: number +} + +declare module 'cordis' { + interface Context { + locale: LocaleService + } + interface Events { + /** + * Locale state changed (active locale switched or registry updated). + * @param snapshot - Current immutable locale snapshot. + * @mode emit + */ + 'locale/change'(snapshot: LocaleSnapshot): void + } +} + +/** Fallback locale consulted after the active locale misses (also the default). */ +export const FALLBACK_LOCALE: LocaleId = 'zh' + +/** Shared namespace for shell-level texts. */ +export const COMMON_NS = 'common' + +/** localStorage key holding the persisted locale id. */ +export const STORAGE_KEY = 'dsh.locale' + +/** The two shipped locales. */ +const LOCALES: readonly LocaleDefinition[] = Object.freeze([ + { id: 'zh', label: '中文' }, + { id: 'en', label: 'English' }, +]) + +/** + * Dictionary registry plus locale preference. Lookup chain per key: active + * locale -> zh fallback -> the key itself (missing text stays visible, fail + * loud in the UI rather than blank). Reads go through {@link getLocale}; + * writes only through {@link setLocale}; continuous sync only through the + * `locale/change` event. + */ +export class LocaleService { + private dicts = new Map>() + private bound = new Map() + private snapshot: LocaleSnapshot + private readonly ctx: Context + + /** + * @param ctx - owning context (change events are emitted on it). + */ + constructor(ctx: Context) { + this.ctx = ctx + this.snapshot = Object.freeze({ active: restorePreference(), locales: LOCALES, revision: 0 }) + } + + /** + * Read the current immutable locale snapshot. + * @returns the current snapshot (stable reference until the next change). + */ + getLocale(): LocaleSnapshot { + return this.snapshot + } + + /** + * Switch the active locale — the only preference write entry. Persists the + * id and emits `locale/change`. + * @param id - a registered locale id; unknown ids throw. + */ + setLocale(id: string): void { + const match = this.snapshot.locales.find(l => l.id === id) + if (match === undefined) throw new Error(`locale "${id}" is not registered`) + if (this.snapshot.active === match.id) return + this.snapshot = Object.freeze({ + active: match.id, + locales: this.snapshot.locales, + revision: this.snapshot.revision + 1, + }) + persistPreference(match.id) + this.ctx.emit('locale/change', this.snapshot) + } + + /** + * Register a dictionary for a namespace and locale. Duplicate (ns, locale) + * throws (single occupant; a namespace's texts have one owner). + * @param ns - namespace. + * @param locale - locale tag (zh/en to start). + * @param dict - dictionary. + * @returns disposer (idempotent). + */ + register(ns: string, locale: string, dict: LocaleDict): () => void { + let locales = this.dicts.get(ns) + if (!locales) { + locales = new Map() + this.dicts.set(ns, locales) + } + if (locales.has(locale)) throw new Error(`locale namespace "${ns}" already has locale "${locale}"`) + locales.set(locale, dict) + return () => { + const owner = this.dicts.get(ns) + if (owner?.get(locale) === dict) owner.delete(locale) + } + } + + /** + * Bind a namespace to a translate function. The returned reference is + * stable per namespace (repeat binds return the same function), so it can + * ride inject surfaces without breaking memoization. + * @param ns - namespace. + * @returns the translate function (reads the active locale at call time). + */ + bind(ns: string): Translate { + let t = this.bound.get(ns) + if (!t) { + t = (key, params) => this.translate(ns, key, params) + this.bound.set(ns, t) + return t + } + return t + } + + private translate(ns: string, key: string, params?: Record): string { + const locales = this.dicts.get(ns) + const template = locales?.get(this.snapshot.active)?.[key] + ?? locales?.get(FALLBACK_LOCALE)?.[key] + ?? key + if (!params) return template + return template.replace(/\{(\w+)\}/g, (match, name: string) => + name in params ? String(params[name]) : match) + } +} + +/** Read the persisted locale id; unknown or unreadable values fall back to zh. */ +function restorePreference(): LocaleId { + try { + const stored = globalThis.localStorage?.getItem(STORAGE_KEY) + if (stored === 'zh' || stored === 'en') return stored + } catch { + // Storage access can throw (privacy mode); the default below covers it. + } + return FALLBACK_LOCALE +} + +/** Persist the locale id; storage failures are non-fatal (preference resets next boot). */ +function persistPreference(id: LocaleId): void { + try { + globalThis.localStorage?.setItem(STORAGE_KEY, id) + } catch { + // Storage access can throw (privacy mode / quota); the preference simply + // does not survive the session. + } +} + +/** Required services (none; the loader passes the export surface as an object plugin). */ +export const inject: string[] = [] + +/** + * Client plugin body: provide the locale service with base dictionaries. + * @param ctx - client cordis context. + */ +export function apply(ctx: Context): void { + const locale = new LocaleService(ctx) + locale.register(COMMON_NS, 'zh', zh) + locale.register(COMMON_NS, 'en', en) + ctx.provide('locale', locale) +} diff --git a/packages/client/i18n/src/index.ts b/packages/client/locale/src/index.ts similarity index 61% rename from packages/client/i18n/src/index.ts rename to packages/client/locale/src/index.ts index e759f1edc1..c220373932 100644 --- a/packages/client/i18n/src/index.ts +++ b/packages/client/locale/src/index.ts @@ -1,4 +1,4 @@ /** Host loader entry for the browser implementation exported from `./client`. */ -/** Host plugin body — no host-side behavior for the i18n plugin. */ +/** Host plugin body — no host-side behavior for the locale plugin. */ export function apply(): void {} diff --git a/packages/client/i18n/src/invariant.ts b/packages/client/locale/src/invariant.ts similarity index 86% rename from packages/client/i18n/src/invariant.ts rename to packages/client/locale/src/invariant.ts index b2c196e93b..96c94018f0 100644 --- a/packages/client/i18n/src/invariant.ts +++ b/packages/client/locale/src/invariant.ts @@ -1,16 +1,16 @@ /** - * Package-owned invariant companion for `@deepseek-ai/dsh-client-i18n`. - * @module @deepseek-ai/dsh-client-i18n/invariant + * Package-owned invariant companion for `@deepseek-ai/dsh-client-locale`. + * @module @deepseek-ai/dsh-client-locale/invariant */ /* jscpd:ignore-start */ import type { Context } from 'cordis' import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' -const PACKAGE_NAME = '@deepseek-ai/dsh-client-i18n' +const PACKAGE_NAME = '@deepseek-ai/dsh-client-locale' /** Cordis companion plugin name. */ -export const name = 'client-i18n-invariant' +export const name = 'client-locale-invariant' /** Service required before the companion can reserve package ownership. */ export const inject = ['invariants'] diff --git a/packages/client/i18n/src/locales/en.ts b/packages/client/locale/src/locales/en.ts similarity index 100% rename from packages/client/i18n/src/locales/en.ts rename to packages/client/locale/src/locales/en.ts diff --git a/packages/client/i18n/src/locales/zh.ts b/packages/client/locale/src/locales/zh.ts similarity index 100% rename from packages/client/i18n/src/locales/zh.ts rename to packages/client/locale/src/locales/zh.ts diff --git a/packages/client/locale/tests/invariant.spec.ts b/packages/client/locale/tests/invariant.spec.ts new file mode 100644 index 0000000000..e9f4fdee36 --- /dev/null +++ b/packages/client/locale/tests/invariant.spec.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import { apply as nodeApply } from '@deepseek-ai/dsh-client-locale' +import { apply as clientApply, COMMON_NS, LocaleService, inject } from '@deepseek-ai/dsh-client-locale/client' +import * as LocaleInvariant from '@deepseek-ai/dsh-client-locale/invariant' +import InvariantService from '@deepseek-ai/dsh-invariants' + +describe('invariant companion', () => { + it('registers under the package name with an empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + await expect(ctx.plugin(LocaleInvariant).await()).resolves.toBeDefined() + }) + + it('node-half apply is a no-op host placeholder', () => { + nodeApply() + expect(true).toBe(true) // reaching here without throw is the contract + }) + + it('client apply provides ctx.locale seeded with the zh/en common namespace', async () => { + expect(inject).toEqual([]) + const ctx = new Context() + await ctx.plugin({ inject, apply: clientApply }).await() + const locale = ctx.get('locale') + expect(locale).toBeInstanceOf(LocaleService) + // Seeded dictionaries occupy the (ns, locale) seats even while empty. + expect(() => (locale as LocaleService).register(COMMON_NS, 'zh', {})).toThrow('already has locale') + expect(() => (locale as LocaleService).register(COMMON_NS, 'en', {})).toThrow('already has locale') + }) +}) diff --git a/packages/client/locale/tests/locale.spec.ts b/packages/client/locale/tests/locale.spec.ts new file mode 100644 index 0000000000..750c2452e8 --- /dev/null +++ b/packages/client/locale/tests/locale.spec.ts @@ -0,0 +1,90 @@ +// @vitest-environment jsdom +import { beforeEach, describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import type { LocaleSnapshot } from '@deepseek-ai/dsh-client-locale/client' +import { LocaleService, STORAGE_KEY } from '@deepseek-ai/dsh-client-locale/client' + +const make = (): { ctx: Context; svc: LocaleService; events: LocaleSnapshot[] } => { + const ctx = new Context() + const events: LocaleSnapshot[] = [] + ctx.on('locale/change', (snapshot) => { events.push(snapshot) }) + return { ctx, svc: new LocaleService(ctx), events } +} + +describe('LocaleService', () => { + beforeEach(() => { + localStorage.clear() + }) + + it('translates through the active-locale -> zh -> key chain', () => { + const { svc } = make() + svc.register('ns', 'zh', { hello: '你好', onlyZh: '仅中文' }) + svc.register('ns', 'en', { hello: 'Hello' }) + const t = svc.bind('ns') + expect(svc.getLocale().active).toBe('zh') + expect(t('hello')).toBe('你好') + svc.setLocale('en') + expect(t('hello')).toBe('Hello') + expect(t('onlyZh')).toBe('仅中文') + expect(t('missing.key')).toBe('missing.key') + }) + + it('interpolates {name} params and leaves unknown placeholders intact', () => { + const { svc } = make() + svc.register('ns', 'zh', { greet: '你好,{name}!第 {n} 次', partial: '{known} 与 {unknown}' }) + const t = svc.bind('ns') + expect(t('greet', { name: '世界', n: 2 })).toBe('你好,世界!第 2 次') + expect(t('partial', { known: 'A' })).toBe('A 与 {unknown}') + }) + + it('bind returns a stable per-namespace function identity', () => { + const { svc } = make() + expect(svc.bind('a')).toBe(svc.bind('a')) + expect(svc.bind('a')).not.toBe(svc.bind('b')) + }) + + it('rejects duplicate (ns, locale) and disposer only removes its own dict', () => { + const { svc } = make() + const dispose = svc.register('ns', 'zh', { k: 'v1' }) + expect(() => svc.register('ns', 'zh', { k: 'v2' })).toThrow('already has locale') + dispose() + const t = svc.bind('ns') + expect(t('k')).toBe('k') + svc.register('ns', 'zh', { k: 'v2' }) + expect(t('k')).toBe('v2') + dispose() + expect(t('k')).toBe('v2') + }) + + it('setLocale persists, republishes an immutable snapshot, and no-ops on same value', () => { + const { svc, events } = make() + svc.setLocale('en') + expect(svc.getLocale().active).toBe('en') + expect(localStorage.getItem(STORAGE_KEY)).toBe('en') + expect(events).toHaveLength(1) + expect(events[0]).toBe(svc.getLocale()) + expect(events[0]!.revision).toBe(1) + svc.setLocale('en') + expect(events).toHaveLength(1) + }) + + it('throws on unknown locale ids', () => { + const { svc } = make() + expect(() => { svc.setLocale('fr') }).toThrow('not registered') + }) + + it('restores a persisted locale and falls back to zh on garbage', () => { + localStorage.setItem(STORAGE_KEY, 'en') + expect(make().svc.getLocale().active).toBe('en') + localStorage.setItem(STORAGE_KEY, 'fr') + expect(make().svc.getLocale().active).toBe('zh') + }) + + it('exposes the two shipped locales with self-described labels', () => { + const { svc } = make() + expect(svc.getLocale().locales).toEqual([ + { id: 'zh', label: '中文' }, + { id: 'en', label: 'English' }, + ]) + }) +}) diff --git a/packages/client/i18n/tsconfig.json b/packages/client/locale/tsconfig.json similarity index 87% rename from packages/client/i18n/tsconfig.json rename to packages/client/locale/tsconfig.json index 63eb9779ca..51f9171643 100644 --- a/packages/client/i18n/tsconfig.json +++ b/packages/client/locale/tsconfig.json @@ -11,9 +11,6 @@ { "path": "../../../vendor/cordis" }, - { - "path": "../runtime" - }, { "path": "../../support/invariants" } diff --git a/packages/client/locale/tsdown.config.ts b/packages/client/locale/tsdown.config.ts new file mode 100644 index 0000000000..2141970e5d --- /dev/null +++ b/packages/client/locale/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-locale', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 56bdd29320..9b93feae8b 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -33,7 +33,7 @@ export const INLINE_SAFE = /^@deepseek-ai\/dsh-(host-apiproxy|session|llm|tools| * Documented TEMPORARY exemption, not a platform module (hence not in * platform.ts): the snapshot-store engine (createSnapshotStore/defineStore/ * shallowEqual) lives in runtime pending its promotion-time rehoming, and - * five importers (i18n, ui-layout, ui-conversation ×3) ride this single + * five importers (locale, ui-layout, ui-conversation ×3) ride this single * exemption. At runtime the lazy CJS table answers the require natively: * runtime is an immediately-tier row, its factory is registered before any * dependent bundle materializes. TODO(webload/store-rehome): remove with the diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index d7306a6810..95fde30b5a 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -24,7 +24,7 @@ }, "dshClient": { "inject": [ - "@deepseek-ai/dsh-client-i18n", + "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-runtime", "@deepseek-ai/dsh-client-ui-layout" ], diff --git a/packages/client/ui-conversation/tests/apply-inject.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.spec.tsx index 21fe70499e..b040e847e0 100644 --- a/packages/client/ui-conversation/tests/apply-inject.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.spec.tsx @@ -99,7 +99,7 @@ async function bench() { ctx.provide('workspaces', workspacesFake) const layoutFake = { openDetails: vi.fn(), closeDetails: vi.fn() } ctx.provide('layout', layoutFake) - ctx.provide('i18n', { bind: () => (key: string) => key }) + ctx.provide('locale', { bind: () => (key: string) => key }) // The AppFrame role: the three conversation-package slots must be declared // by a live entry before apply can contribute into them (the stand-in diff --git a/packages/client/ui-conversation/tests/chat-apply.spec.tsx b/packages/client/ui-conversation/tests/chat-apply.spec.tsx index dcfe2d7de7..31b251843a 100644 --- a/packages/client/ui-conversation/tests/chat-apply.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-apply.spec.tsx @@ -48,7 +48,7 @@ async function bench() { sendSession: vi.fn(), }) ctx.provide('layout', { openDetails: vi.fn(), closeDetails: vi.fn() }) - ctx.provide('i18n', { bind: () => (key: string) => key }) + ctx.provide('locale', { bind: () => (key: string) => key }) // Declared by ui-layout's root entry in production; a stand-in root // occupant declares them here so the contributions land (it consumes diff --git a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx index bfae743cff..959ee871d8 100644 --- a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx @@ -93,7 +93,7 @@ async function bench(nodes: ToolResultNode[]) { sendSession: vi.fn(), }) ctx.provide('layout', layout) - ctx.provide('i18n', { bind: () => (key: string) => key }) + ctx.provide('locale', { bind: () => (key: string) => key }) slots.install(createSlotRenderer()) slots.register({ @@ -212,7 +212,7 @@ describe('registrant load-order seam', () => { sendSession: vi.fn(), }) ctx.provide('layout', { openDetails: vi.fn(), closeDetails: vi.fn() }) - ctx.provide('i18n', { bind: () => (key: string) => key }) + ctx.provide('locale', { bind: () => (key: string) => key }) slots.register({ name: 'root', children: { diff --git a/packages/client/ui-conversation/tsconfig.json b/packages/client/ui-conversation/tsconfig.json index 7755337093..902c1c7f9f 100644 --- a/packages/client/ui-conversation/tsconfig.json +++ b/packages/client/ui-conversation/tsconfig.json @@ -27,7 +27,7 @@ "path": "../ui-layout" }, { - "path": "../i18n" + "path": "../locale" }, { "path": "../../support/invariants" diff --git a/packages/client/ui-layout/README.md b/packages/client/ui-layout/README.md index 4a9f5e9bd5..a8c3bc0bd6 100644 --- a/packages/client/ui-layout/README.md +++ b/packages/client/ui-layout/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-client-ui-layout -Shell plugin: three-column AppFrame (drag handles and concession chain) plus the `ctx.layout` panel-geometry service; it registers into the runtime-owned `root` slot and declares `sidebar`, `conversation`, `details`, and `conversation.empty`. The sidebar is fixed-width (only details shrinks, then auto-closes); a closed sidebar retains a 56px control rail while details closes to zero width. +Shell plugin: three-column AppFrame (drag handles and concession chain) plus the `ctx.layout` panel-geometry service; it registers into the runtime-owned `root` slot and declares `sidebar`, `conversation`, `details`, and `conversation.empty`. The sidebar is fixed-width (only details shrinks, then auto-closes); a closed sidebar retains a 56px control rail while details closes to zero width. The package also seats the theme presenter: it consumes resolved `ctx.theme` snapshots and projects them onto `document.body` (`data-ds-dark-theme` from the active color scheme plus the theme's alias tokens as inline variables). AppFrame reads the runtime Session projection: `baselinesReady` selects loading, a page-local `SessionListState.intent` selects the empty composer, and a connected Session renders through `SessionProvider`. The conversation and empty-state owner shares are empty; each registrant obtains business data from standard hooks and actions from its own inject face. The sidebar owner share contains only `collapsed` and `width`; navigation actions belong to sidebar's own injected service face. diff --git a/packages/client/ui-layout/package.json b/packages/client/ui-layout/package.json index fd3e691375..17459ee5d2 100644 --- a/packages/client/ui-layout/package.json +++ b/packages/client/ui-layout/package.json @@ -24,7 +24,8 @@ }, "dshClient": { "inject": [ - "@deepseek-ai/dsh-client-runtime" + "@deepseek-ai/dsh-client-runtime", + "@deepseek-ai/dsh-client-ui-theme" ], "platform": "web" }, @@ -36,6 +37,7 @@ "peerDependencies": { "@deepseek-ai/dsh-client-runtime": "^0.0.1", "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", + "@deepseek-ai/dsh-client-ui-theme": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "cordis": "^4.0.0-rc.7", "react": "^18.2.0" @@ -43,6 +45,7 @@ "devDependencies": { "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-client-ui-theme": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@types/react": "~18.3.1", "cordis": "^4.0.0-rc.7", diff --git a/packages/client/ui-layout/src/client/index.ts b/packages/client/ui-layout/src/client/index.ts index 6ecb6f6b1d..39fee1fb52 100644 --- a/packages/client/ui-layout/src/client/index.ts +++ b/packages/client/ui-layout/src/client/index.ts @@ -4,13 +4,16 @@ * four child slots (declaration = exclusive render authority), seats the * layout store (panel geometry), and wires the panel-action service face. * ctx.layout is the cross-plugin panel-action seam; navigation state lives - * with the runtime sessions service. + * with the runtime sessions service. A second effect seats the theme + * presenter, which projects ctx.theme snapshots onto document.body. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +import type {} from '@deepseek-ai/dsh-client-ui-theme/client' import type { PanelActions } from './service.ts' import { AppFrame } from './AppFrame.tsx' import { createLayoutStore } from './stores.ts' import { LayoutService } from './service.ts' +import { ThemePresenter } from './theme-presenter.ts' // Contract surface only (export-convergence rule: cross-package consumers // keep a symbol exported; test-only/package-internal symbols live off /src). @@ -62,7 +65,7 @@ export interface DetailsOwnerProps {} export interface EmptyOwnerProps { children?: never } /** Required services (cordis fiber inject — the loader passes the whole export surface as an object plugin). */ -export const inject = ['slots'] +export const inject = ['slots', 'theme'] /** * Client plugin body: provide ctx.layout, then one register() call — AppFrame @@ -98,4 +101,16 @@ export function apply(ctx: ClientContext): void { void disposeService() } }, 'ui-layout: service + root registration') + + // Theme presentation: pure DOM writes from resolved snapshots — initial + // state through the getter once, then event-driven only; no React path. + ctx.effect(() => { + const presenter = new ThemePresenter() + presenter.apply(ctx.theme.getTheme()) + const off = ctx.on('theme/change', snapshot => { presenter.apply(snapshot) }) + return () => { + off() + presenter.dispose() + } + }, 'ui-layout: theme presenter') } diff --git a/packages/client/ui-layout/src/client/theme-presenter.ts b/packages/client/ui-layout/src/client/theme-presenter.ts new file mode 100644 index 0000000000..958f2fd93e --- /dev/null +++ b/packages/client/ui-layout/src/client/theme-presenter.ts @@ -0,0 +1,43 @@ +/** + * Global theme DOM applier: projects the resolved ThemeSnapshot onto + * document.body — the `data-ds-dark-theme` palette switch plus the active + * theme's alias-token overrides as inline CSS variables. Pure DOM writes, no + * React involvement; the presenter only ever retracts what it wrote itself, + * so foreign body attributes and inline styles survive apply/dispose. + */ +import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' + +/** Body attribute selecting the dark base palette in the token stylesheets. */ +export const DARK_ATTRIBUTE = 'data-ds-dark-theme' + +/** Applies theme snapshots to document.body; one instance per plugin fiber. */ +export class ThemePresenter { + /** Token names this presenter wrote in the last apply (its retraction set). */ + private appliedTokens: string[] = [] + + /** + * Project a snapshot onto the body: switch the palette attribute from + * `active.colorScheme` (never the id — `system` is resolved upstream) and + * replace the previously applied token variables with `active.tokens`. + * @param snapshot - resolved theme snapshot from ctx.theme. + */ + apply(snapshot: ThemeSnapshot): void { + const body = document.body + if (snapshot.active.colorScheme === 'dark') body.setAttribute(DARK_ATTRIBUTE, '') + else body.removeAttribute(DARK_ATTRIBUTE) + for (const name of this.appliedTokens) body.style.removeProperty(name) + this.appliedTokens = [] + for (const [name, value] of Object.entries(snapshot.active.tokens)) { + body.style.setProperty(name, value) + this.appliedTokens.push(name) + } + } + + /** Retract everything this presenter wrote: the palette attribute and all applied token variables. */ + dispose(): void { + const body = document.body + body.removeAttribute(DARK_ATTRIBUTE) + for (const name of this.appliedTokens) body.style.removeProperty(name) + this.appliedTokens = [] + } +} diff --git a/packages/client/ui-layout/tests/apply.spec.ts b/packages/client/ui-layout/tests/apply.spec.ts index bed0987f62..29ad4b3058 100644 --- a/packages/client/ui-layout/tests/apply.spec.ts +++ b/packages/client/ui-layout/tests/apply.spec.ts @@ -9,6 +9,7 @@ import { Context } from 'cordis' import { describe, expect, it, vi } from 'vitest' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { apply as themeApply, inject as themeInject, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' import { apply, inject, LayoutService } from '@deepseek-ai/dsh-client-ui-layout/client' import { apply as nodeApply } from '@deepseek-ai/dsh-client-ui-layout' import * as invariant from '@deepseek-ai/dsh-client-ui-layout/invariant' @@ -16,13 +17,14 @@ import * as invariant from '@deepseek-ai/dsh-client-ui-layout/invariant' async function bench() { const ctx = new Context() const slotsFiber = ctx.plugin(SlotsService) + await ctx.plugin({ inject: themeInject, apply: themeApply }).await() await slotsFiber.await() return { ctx, slots: ctx.get('slots') as SlotsService } } describe('ui-layout client apply', () => { it('declares its service dependencies', () => { - expect(inject).toEqual(['slots']) + expect(inject).toEqual(['slots', 'theme']) }) it('provides ctx.layout and registers AppFrame into root with the four child declarations', async () => { @@ -53,6 +55,23 @@ describe('ui-layout client apply', () => { expect(actions.toggleSidebar).toHaveBeenCalledOnce() }) + it('theme presenter applies the initial snapshot, follows theme/change, and unwinds on dispose', async () => { + const { ctx } = await bench() + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + // Initial getter application: jsdom has no matchMedia, system resolves light. + expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(false) + const theme = ctx.get('theme') as ThemeService + theme.setTheme('dark') + expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(true) + await fiber.dispose() + expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(false) + // Listener is off: further theme changes no longer reach the body. + theme.setTheme('light') + theme.setTheme('dark') + expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(false) + }) + it('teardown unwinds the service, the root registration, and the child declarations', async () => { const { ctx, slots } = await bench() const fiber = ctx.plugin({ inject: [...inject], apply }) diff --git a/packages/client/ui-layout/tests/theme-presenter.spec.ts b/packages/client/ui-layout/tests/theme-presenter.spec.ts new file mode 100644 index 0000000000..ced83a379e --- /dev/null +++ b/packages/client/ui-layout/tests/theme-presenter.spec.ts @@ -0,0 +1,56 @@ +// @vitest-environment jsdom +// ThemePresenter behavior account: the palette attribute follows +// active.colorScheme only, token variables replace the previous apply's set, +// and dispose retracts everything the presenter wrote. + +import { beforeEach, describe, expect, it } from 'vitest' +import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' +import { DARK_ATTRIBUTE, ThemePresenter } from '@deepseek-ai/dsh-client-ui-layout/src/client/theme-presenter.ts' + +function snapshot(colorScheme: 'light' | 'dark', tokens: Record = {}): ThemeSnapshot { + // The presenter must key off colorScheme, not the id — keep them distinct. + const active = { id: `${colorScheme}-test`, colorScheme, tokens } + return { preference: colorScheme, active, themes: [active], revision: 1 } +} + +beforeEach(() => { + document.body.removeAttribute(DARK_ATTRIBUTE) + document.body.removeAttribute('style') +}) + +describe('ThemePresenter', () => { + it('light scheme leaves the dark attribute absent', () => { + const presenter = new ThemePresenter() + presenter.apply(snapshot('light')) + expect(document.body.hasAttribute(DARK_ATTRIBUTE)).toBe(false) + }) + + it('dark scheme sets the attribute; switching back to light removes it', () => { + const presenter = new ThemePresenter() + presenter.apply(snapshot('dark')) + expect(document.body.hasAttribute(DARK_ATTRIBUTE)).toBe(true) + presenter.apply(snapshot('light')) + expect(document.body.hasAttribute(DARK_ATTRIBUTE)).toBe(false) + }) + + it('applies tokens as inline variables and clears the previous set on theme change', () => { + const presenter = new ThemePresenter() + presenter.apply(snapshot('dark', { '--dsw-alias-bg': '#111', '--dsw-alias-fg': '#eee' })) + expect(document.body.style.getPropertyValue('--dsw-alias-bg')).toBe('#111') + expect(document.body.style.getPropertyValue('--dsw-alias-fg')).toBe('#eee') + presenter.apply(snapshot('light', { '--dsw-alias-bg': '#fff' })) + expect(document.body.style.getPropertyValue('--dsw-alias-bg')).toBe('#fff') + // The old theme's extra variable is gone, not merged. + expect(document.body.style.getPropertyValue('--dsw-alias-fg')).toBe('') + }) + + it('dispose removes the attribute and every applied variable, sparing foreign inline styles', () => { + document.body.style.setProperty('--foreign', 'kept') + const presenter = new ThemePresenter() + presenter.apply(snapshot('dark', { '--dsw-alias-bg': '#111' })) + presenter.dispose() + expect(document.body.hasAttribute(DARK_ATTRIBUTE)).toBe(false) + expect(document.body.style.getPropertyValue('--dsw-alias-bg')).toBe('') + expect(document.body.style.getPropertyValue('--foreign')).toBe('kept') + }) +}) diff --git a/packages/client/ui-layout/tsconfig.json b/packages/client/ui-layout/tsconfig.json index c82482294b..4401e8e4db 100644 --- a/packages/client/ui-layout/tsconfig.json +++ b/packages/client/ui-layout/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../ui-slots" }, + { + "path": "../ui-theme" + }, { "path": "../ui-primitives" }, diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index b55abe094d..3cabe258bc 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -30,11 +30,13 @@ /* Portal mode: fixed in the viewport, coordinates supplied inline from the * anchor rect (side/align resolved in JS, the in-place offset rules above - * don't apply). */ + * don't apply). Portaled lists must layer above modal overlays (z 1000) — + * an anchor inside a dialog still expects its menu on top. */ .portal { position: fixed; top: auto; left: auto; + z-index: 1100; } /* Open above the anchor (empty-state workspace chip: figma 122:9481). */ diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index 80bb3848dd..4c2083bae1 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -583,3 +583,90 @@ export const IconTreeCorner8x10 = ({ size = 10, className }: IconProps) => ( ) + +/** ic_ds_light_outline_16 */ +export const IconLightOutline16 = ({ size = 16, className }: IconProps) => ( + + + + + + + + + + + +) + +/** ic_ds_dark_outline_16 */ +export const IconDarkOutline16 = ({ size = 16, className }: IconProps) => ( + + + +) + +/** ic_ds_followsystem_outline_16 */ +export const IconFollowsystemOutline16 = ({ size = 16, className }: IconProps) => ( + + + + +) + +/** ic_ds_data_outline_16 */ +export const IconDataOutline16 = ({ size = 16, className }: IconProps) => ( + + + + +) + +/** ic_ds_List_Pen_outline_16 */ +export const IconListPenOutline16 = ({ size = 16, className }: IconProps) => ( + + + + + + + + +) diff --git a/packages/client/ui-primitives/tests/icons.spec.tsx b/packages/client/ui-primitives/tests/icons.spec.tsx index 74bf5a9678..281124b8d5 100644 --- a/packages/client/ui-primitives/tests/icons.spec.tsx +++ b/packages/client/ui-primitives/tests/icons.spec.tsx @@ -14,8 +14,8 @@ const icons = Object.fromEntries( const iconNames = Object.keys(icons) describe('ic_ds_ icon set', () => { - it('exports the full P-I set (43 deepsuite + 7 figma extracts)', () => { - expect(iconNames.length).toBe(50) + it('exports the full P-I set (43 deepsuite + 12 figma extracts)', () => { + expect(iconNames.length).toBe(55) }) it.each(iconNames)('%s renders an svg with currentColor fills and no hardcoded palette', name => { diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md new file mode 100644 index 0000000000..435dd8c1b4 --- /dev/null +++ b/packages/client/ui-settings-general/README.md @@ -0,0 +1,15 @@ +# @deepseek-ai/dsh-client-ui-settings-general + +General settings section plugin: registers the `general` entry into `settings.section`. Language (中文/English) and Appearance (Light/Dark/System) are live preferences wired to `ctx.locale` / `ctx.theme`; Permission and Tool Call rows are visual skeletons with no write surface. + +## Model Experience + +None, as the section renders browser preference UI; nothing here reaches a model request. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + +- **Permission and Tool Call are display skeletons** — the backing host services and RPC methods do not exist yet; the controls are disabled and write nothing. diff --git a/packages/client/ui-settings-general/package.json b/packages/client/ui-settings-general/package.json new file mode 100644 index 0000000000..9b3d83e472 --- /dev/null +++ b/packages/client/ui-settings-general/package.json @@ -0,0 +1,70 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-settings-general", + "description": "General settings section plugin: Language and Appearance preferences (live), Permission and Tool Call skeleton rows", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "dshClient": { + "inject": [ + "@deepseek-ai/dsh-client-runtime", + "@deepseek-ai/dsh-client-ui-settings", + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-theme" + ], + "platform": "web" + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "BSD-3-Clause", + "dependencies": { + "clsx": "^2.0.0" + }, + "peerDependencies": { + "@deepseek-ai/dsh-client-runtime": "^0.0.1", + "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", + "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-client-locale": "workspace:^", + "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", + "@deepseek-ai/dsh-client-ui-settings": "workspace:^", + "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-client-ui-theme": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@types/react": "~18.3.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ] +} diff --git a/packages/client/ui-settings-general/src/client/GeneralSection.module.css b/packages/client/ui-settings-general/src/client/GeneralSection.module.css new file mode 100644 index 0000000000..dffafc419d --- /dev/null +++ b/packages/client/ui-settings-general/src/client/GeneralSection.module.css @@ -0,0 +1,131 @@ +/* General section rows (figma 501:29983 'Options'): four groups, 16px + * vertical padding each, hairline separator under all but the last. The + * shell's content column owns the outer horizontal padding. */ + +.section { + display: flex; + flex-direction: column; + width: 100%; +} + +/* Title + trailing control row (figma 'Setting-Cell': gap 8, pad 16/0). */ +.row { + display: flex; + align-items: center; + gap: 8px; + padding: 16px 0; + border-bottom: 1px solid var(--dsw-alias-border-l2); +} + +/* Title + full-width body group (figma 'Frame 2117131229': column, gap 8). */ +.group { + display: flex; + flex-direction: column; + gap: 8px; + padding: 16px 0; + border-bottom: 1px solid var(--dsw-alias-border-l2); +} + +.last { + border-bottom: none; +} + +/* Leading text column (figma 'Frame 2036083120': gap 4, pad-right 48). */ +.rowText { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; + padding-right: 48px; +} + +.title { + font-size: 14px; + font-weight: 400; + line-height: 22px; + color: var(--dsw-alias-label-primary); +} + +.desc { + font-size: 12px; + font-weight: 400; + line-height: 18px; + color: var(--dsw-alias-label-tertiary); +} + +/* Selector pill (figma 'Selector': h36 r18, fill #F5F6F7, pad 0/14, gap 12). */ +.selector { + display: inline-flex; + align-items: center; + gap: 12px; + height: 36px; + padding: 0 14px; + border: none; + border-radius: 18px; + background: var(--dsw-alias-bg-module-platform); + font: inherit; + font-size: 14px; + line-height: 22px; + color: var(--dsw-alias-label-primary); + cursor: pointer; +} + +.selector:disabled { + cursor: default; +} + +.chevron { + flex: none; +} + +/* Cube rows share an 8px gap; cubes stretch to equal height. */ +.cubeRow { + display: flex; + align-items: stretch; + gap: 8px; +} + +/* Tool Call mode cube (figma '.Selector Cube' 418w r16; horizontal inset = + * outer pad 4 + inner .Menu_cell pad 10, vertical = inner pad 8). */ +.modeCube { + box-sizing: border-box; + width: 418px; + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; + padding: 8px 14px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 16px; + background: transparent; + text-align: left; +} + +/* Appearance cube (figma '.Selector Cube' 276x82 r16, pad 20/32, centered + * icon-over-label column, gap 4). */ +.themeCube { + box-sizing: border-box; + width: 276px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 4px; + padding: 20px 32px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 16px; + background: transparent; + font: inherit; + font-size: 14px; + line-height: 22px; + color: var(--dsw-alias-label-primary); + cursor: pointer; +} + +/* Selected cube: #F5F6F7 fill + #ADB2B8 border (static token — the bluish-400 + * step has no alias-layer name). */ +.selected { + background: var(--dsw-alias-bg-module-platform); + border-color: var(--dsw-static-neutral-bluish-400); +} diff --git a/packages/client/ui-settings-general/src/client/GeneralSection.tsx b/packages/client/ui-settings-general/src/client/GeneralSection.tsx new file mode 100644 index 0000000000..d2947c0435 --- /dev/null +++ b/packages/client/ui-settings-general/src/client/GeneralSection.tsx @@ -0,0 +1,118 @@ +/** + * General settings section: Permission and Tool Call skeleton rows (visual + * only, no interaction), live Language and Appearance preference rows wired + * through the injected setLocale/setTheme callbacks and the snapshot-mirror + * store. Figma: Settings > Content > Options (501:29983). + */ +import { useState } from 'react' +import clsx from 'clsx' +import { + IconChevronDownOutline14, IconDarkOutline16, IconFollowsystemOutline16, IconLightOutline16, + Menu, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { GeneralSectionComponentProps, ThemePreferenceId } from './contract.ts' +import css from './GeneralSection.module.css' + +/** Appearance cube order and icons (figma 501:30015-30017: Light, Dark, System). */ +const THEME_CUBES: readonly { id: ThemePreferenceId; labelKey: string; Icon: typeof IconLightOutline16 }[] = [ + { id: 'light', labelKey: 'appearance.light', Icon: IconLightOutline16 }, + { id: 'dark', labelKey: 'appearance.dark', Icon: IconDarkOutline16 }, + { id: 'system', labelKey: 'appearance.system', Icon: IconFollowsystemOutline16 }, +] + +/** + * Render the General section content column. + * @param props - composed slot props (contract.ts). + * @returns the section element tree. + */ +export function GeneralSection(props: GeneralSectionComponentProps) { + const { t, setLocale, setTheme, useStore } = props + const localeActive = useStore(s => s.localeActive) + const localeOptions = useStore(s => s.localeOptions) + const themePreference = useStore(s => s.themePreference) + const [languageOpen, setLanguageOpen] = useState(false) + + const activeLocaleLabel = localeOptions.find(l => l.id === localeActive)?.label ?? localeActive + + return ( +

+ {/* Permission (skeleton): disabled selector pill. */} +
+
+
{t('permission.title')}
+
{t('permission.desc')}
+
+ +
+ + {/* Tool Call (skeleton): schema cube pinned selected, code cube unselected. */} +
+
{t('toolcall.title')}
+
+
+
{t('toolcall.schema.title')}
+
{t('toolcall.schema.desc')}
+
+
+
{t('toolcall.code.title')}
+
{t('toolcall.code.desc')}
+
+
+
+ + {/* Language: selector pill opens the locale menu. */} +
+
+
{t('language.title')}
+
+ { setLanguageOpen(false) }} + items={localeOptions.map(l => ({ id: l.id, label: l.label }))} + selectedId={localeActive} + onSelect={(id) => { + setLocale(id) + setLanguageOpen(false) + }} + align="end" + portal + anchor={( + + )} + /> +
+ + {/* Appearance: three preference cubes; selection follows the persisted + * preference, never the resolved active theme. */} +
+
{t('appearance.title')}
+
+ {THEME_CUBES.map(({ id, labelKey, Icon }) => ( + + ))} +
+
+
+ ) +} diff --git a/packages/client/ui-settings-general/src/client/contract.ts b/packages/client/ui-settings-general/src/client/contract.ts new file mode 100644 index 0000000000..912d925615 --- /dev/null +++ b/packages/client/ui-settings-general/src/client/contract.ts @@ -0,0 +1,66 @@ +/** + * General section component contract: the slot-store state shape, the + * injected business face, and the composed props type. The component imports + * only from here; service snapshot shapes are mirrored as plain rows so the + * presentation layer stays decoupled from the locale/theme packages. + */ +import type { PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only: pulls the shell's SlotMap merge (the 'settings.section' entry). +import type {} from '@deepseek-ai/dsh-client-ui-settings/client' +import type { createGeneralSettingsStore } from './store.ts' + +/** One selectable locale row projected into the store (id + self-described label). */ +export interface LocaleOptionRow { + /** Locale id (the setLocale argument). */ + id: string + /** Display name in its own language (中文 / English). */ + label: string +} + +/** Theme preference union mirrored from the theme service snapshot. */ +export type ThemePreferenceId = 'light' | 'dark' | 'system' + +/** + * Store state: mirrors of the locale/theme service snapshots, written only by + * the plugin's apply-world change listeners (components have no write path — + * preference writes go through the injected callbacks to the services, and + * the resulting change events flow back into this mirror). + */ +export interface GeneralSettingsState { + /** Active locale id. */ + localeActive: string + /** Selectable locales in display order. */ + localeOptions: LocaleOptionRow[] + /** Locale service revision (re-renders translated copy on dictionary/locale changes); -1 until first sync. */ + localeRevision: number + /** Persisted theme preference (selection state reads this, never the resolved active theme). */ + themePreference: ThemePreferenceId + /** Theme service revision; -1 until first sync. */ + themeRevision: number +} + +/** + * Registrant-private injected share of the General section (assembled in + * apply): the namespace-bound translate function (stable identity — re-render + * on locale change comes from the store revision, not from `t`) and the two + * preference write callbacks. + */ +export interface GeneralSectionInjected { + /** Translate a `settings.general` dictionary key to the active-locale text. */ + t: (key: string) => string + /** Switch the active locale (a registered locale id). */ + setLocale: (id: string) => void + /** Switch the theme preference. */ + setTheme: (id: ThemePreferenceId) => void +} + +/** Store handle type for the props share (type-only; the factory stays internal to apply and tests). */ +export type GeneralSettingsStoreHandle = ReturnType + +/** + * Full component props of the General section: the section owner share + * (empty marker) plus the store share and the injected face. No child slots + * are declared; menu open state is component-local viewing state. + */ +export type GeneralSectionComponentProps = + PropsRuntime<'settings.section'> & PropsStore & GeneralSectionInjected diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts new file mode 100644 index 0000000000..0e59ce2116 --- /dev/null +++ b/packages/client/ui-settings-general/src/client/index.ts @@ -0,0 +1,111 @@ +/** + * General settings section plugin, browser half. Registers the `general` + * entry into the shell-declared `settings.section` list slot; Language and + * Appearance are live preferences projected from ctx.locale / ctx.theme + * through this entry's slot store. Export discipline: packages/client/AGENTS.md. + */ +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only: pulls the shell's SlotMap merge (the 'settings.section' entry). +import type {} from '@deepseek-ai/dsh-client-ui-settings/client' +// Type-only: the locale/theme Context+Events merges and snapshot shapes. +import type { LocaleSnapshot } from '@deepseek-ai/dsh-client-locale/client' +import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' +import type { GeneralSectionInjected } from './contract.ts' +import { createGeneralSettingsStore } from './store.ts' +import { en, zh } from './locales.ts' +import { GeneralSection } from './GeneralSection.tsx' + +export type { + GeneralSectionComponentProps, GeneralSectionInjected, GeneralSettingsState, + GeneralSettingsStoreHandle, LocaleOptionRow, ThemePreferenceId, +} from './contract.ts' + +/** Dictionary namespace owned by this section (also the nav-label reference prefix). */ +const NS = 'settings.general' + +/** + * Required services (cordis fiber inject). The target slot is declared by + * ui-settings' apply, whose activation order relative to this one is NOT + * constrained; registration goes through declaration-aware deferral. + */ +export const inject = ['slots', 'locale', 'theme'] + +/** + * Register the `settings.general` dictionaries and the General section entry + * once the `settings.section` declaration is on the ledger. The slot store + * mirrors the locale/theme snapshots: change listeners attach here in apply, + * write through the bound actions captured at inject time, and the inject + * factory re-syncs from the getters so no event is lost between registration + * and first render (the store's revision guard drops stale duplicates). + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => { + const disposeZh = ctx.locale.register(NS, 'zh', zh) + const disposeEn = ctx.locale.register(NS, 'en', en) + return () => { + disposeZh() + disposeEn() + } + }, 'ui-settings-general: dictionaries') + + const store = createGeneralSettingsStore() + let bound: BoundActions | undefined + + const syncLocale = (snapshot: LocaleSnapshot): void => { + bound?.syncLocale( + snapshot.active, + snapshot.locales.map(l => ({ id: l.id, label: l.label })), + snapshot.revision, + ) + } + const syncTheme = (snapshot: ThemeSnapshot): void => { + bound?.syncTheme(snapshot.preference, snapshot.revision) + } + ctx.on('locale/change', syncLocale) + ctx.on('theme/change', syncTheme) + + const injected = (actions: BoundActions): GeneralSectionInjected => { + bound = actions + syncLocale(ctx.locale.getLocale()) + syncTheme(ctx.theme.getTheme()) + return { + t: ctx.locale.bind(NS), + setLocale: (id) => { ctx.locale.setLocale(id) }, + setTheme: (id) => { ctx.theme.setTheme(id) }, + } + } + + ctx.effect(() => { + let dispose: (() => void) | undefined + const register = (): void => { + dispose = ctx.slots.register({ + name: 'settings.section', + id: 'general', + order: 0, + label: ctx.locale.bind(NS)('nav'), + store, + inject: injected, + }, GeneralSection) + } + const tryRegister = (): void => { + if (ctx.slots.spec('settings.section') === undefined || dispose !== undefined) return + register() + } + // Nav labels are registrant-localized: re-register on locale change so + // the ledger carries fresh text (the version bump re-renders the shell). + const offLocale = ctx.on('locale/change', () => { + if (dispose === undefined) return + dispose() + register() + }) + const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) + tryRegister() + return () => { + offLocale() + unsubscribe() + dispose?.() + } + }, 'ui-settings-general: section registration') +} diff --git a/packages/client/ui-settings-general/src/client/locales.ts b/packages/client/ui-settings-general/src/client/locales.ts new file mode 100644 index 0000000000..ff10ce5c37 --- /dev/null +++ b/packages/client/ui-settings-general/src/client/locales.ts @@ -0,0 +1,42 @@ +/** + * `settings.general` namespace dictionaries. Skeleton-row technical copy + * (Read only / Schema mode / Code mode and their descriptions) is shared + * verbatim across locales per the Figma design. + */ +import type { LocaleDict } from '@deepseek-ai/dsh-client-locale/client' + +const SHARED = { + 'permission.value': 'Read only', + 'toolcall.schema.title': 'Schema mode', + 'toolcall.schema.desc': 'Traditional function calling — invoke tools one at a time', + 'toolcall.code.title': 'Code mode', + 'toolcall.code.desc': 'Chain multiple tools with code — multi-step orchestration', +} satisfies LocaleDict + +/** Simplified Chinese dictionary. */ +export const zh: LocaleDict = { + ...SHARED, + 'nav': '通用设置', + 'permission.title': '权限', + 'permission.desc': '选择默认权限模式', + 'toolcall.title': '工具调用', + 'language.title': '语言', + 'appearance.title': '外观', + 'appearance.light': '浅色', + 'appearance.dark': '深色', + 'appearance.system': '跟随系统', +} + +/** English dictionary. */ +export const en: LocaleDict = { + ...SHARED, + 'nav': 'General', + 'permission.title': 'Permission', + 'permission.desc': 'Choose default permission mode', + 'toolcall.title': 'Tool Call', + 'language.title': 'Language', + 'appearance.title': 'Appearance', + 'appearance.light': 'Light', + 'appearance.dark': 'Dark', + 'appearance.system': 'System', +} diff --git a/packages/client/ui-settings-general/src/client/store.ts b/packages/client/ui-settings-general/src/client/store.ts new file mode 100644 index 0000000000..121e3f52a9 --- /dev/null +++ b/packages/client/ui-settings-general/src/client/store.ts @@ -0,0 +1,43 @@ +/** + * General section slot store: locale/theme snapshot mirrors. The plugin + * creates the handle at apply time (identity follows the fiber) and its + * change listeners are the only writers; components read via props.useStore. + */ +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client' +import type { GeneralSettingsState, LocaleOptionRow, ThemePreferenceId } from './contract.ts' + +/** Declared action shape used to give the exported factory a stable return type. */ +type GeneralSettingsActions = { + syncLocale: (draft: GeneralSettingsState, active: string, options: LocaleOptionRow[], revision: number) => void + syncTheme: (draft: GeneralSettingsState, preference: ThemePreferenceId, revision: number) => void +} + +/** + * Declares the General section state and write surface. Revisions start at -1 + * so the apply-time initial sync (revision 0) always lands as a change. + * @returns the store handle. + */ +export function createGeneralSettingsStore(): EngineStoreHandle { + return defineStore({ + init: (): GeneralSettingsState => ({ + localeActive: '', + localeOptions: [], + localeRevision: -1, + themePreference: 'system', + themeRevision: -1, + }), + actions: { + syncLocale: (d, active: string, options: LocaleOptionRow[], revision: number) => { + if (revision <= d.localeRevision) return + d.localeActive = active + d.localeOptions = options + d.localeRevision = revision + }, + syncTheme: (d, preference: ThemePreferenceId, revision: number) => { + if (revision <= d.themeRevision) return + d.themePreference = preference + d.themeRevision = revision + }, + }, + }) +} diff --git a/packages/client/ui-settings-general/src/css-modules.d.ts b/packages/client/ui-settings-general/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-settings-general/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-settings-general/src/index.ts b/packages/client/ui-settings-general/src/index.ts new file mode 100644 index 0000000000..94b9bdf674 --- /dev/null +++ b/packages/client/ui-settings-general/src/index.ts @@ -0,0 +1,4 @@ +/** Host loader entry for the browser implementation exported from `./client`. */ + +/** Host plugin body — no host-side behavior for the general settings plugin. */ +export function apply(): void {} diff --git a/packages/client/ui-settings-general/src/invariant.ts b/packages/client/ui-settings-general/src/invariant.ts new file mode 100644 index 0000000000..a40cc3cc00 --- /dev/null +++ b/packages/client/ui-settings-general/src/invariant.ts @@ -0,0 +1,32 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-settings-general`. + * @module @deepseek-ai/dsh-client-ui-settings-general/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-settings-general' + +/** Cordis companion plugin name. */ +export const name = 'client-ui-settings-general-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: a section plugin projecting two service change events + * into its own slot store — it emits no cordis events of its own and owns no + * cross-plugin mutable relation; snapshot/store agreement is asserted by this + * package's behavior specs. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/client/ui-settings-general/tsconfig.json b/packages/client/ui-settings-general/tsconfig.json new file mode 100644 index 0000000000..9b2cc5b838 --- /dev/null +++ b/packages/client/ui-settings-general/tsconfig.json @@ -0,0 +1,36 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../runtime" + }, + { + "path": "../ui-settings" + }, + { + "path": "../locale" + }, + { + "path": "../ui-theme" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/client/ui-settings-general/tsdown.config.ts b/packages/client/ui-settings-general/tsdown.config.ts new file mode 100644 index 0000000000..bf67c4f10f --- /dev/null +++ b/packages/client/ui-settings-general/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-ui-settings-general', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md new file mode 100644 index 0000000000..c96e2843e4 --- /dev/null +++ b/packages/client/ui-settings-models/README.md @@ -0,0 +1,15 @@ +# @deepseek-ai/dsh-client-ui-settings-models + +Models settings section plugin: registers the `models` nav entry into `settings.section` with an intentionally empty content column — model management lands in a later phase. + +## Model Experience + +None, as the section renders an empty browser UI column; nothing here reaches a model request. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + +- **Content column is empty by design** — provider list, editing form, and activation flow are deferred until the model-management service exists. diff --git a/packages/client/ui-settings-models/package.json b/packages/client/ui-settings-models/package.json new file mode 100644 index 0000000000..da8fa8c18d --- /dev/null +++ b/packages/client/ui-settings-models/package.json @@ -0,0 +1,63 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-settings-models", + "description": "Models settings section plugin: nav entry with an empty content column (model management lands later)", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "dshClient": { + "inject": [ + "@deepseek-ai/dsh-client-runtime", + "@deepseek-ai/dsh-client-ui-settings", + "@deepseek-ai/dsh-client-locale" + ], + "platform": "web" + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "BSD-3-Clause", + "peerDependencies": { + "@deepseek-ai/dsh-client-runtime": "^0.0.1", + "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-client-locale": "workspace:^", + "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-client-ui-settings": "workspace:^", + "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@types/react": "~18.3.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ] +} diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.tsx b/packages/client/ui-settings-models/src/client/ModelsSection.tsx new file mode 100644 index 0000000000..ee33b916cb --- /dev/null +++ b/packages/client/ui-settings-models/src/client/ModelsSection.tsx @@ -0,0 +1,13 @@ +/** + * Models settings section: an intentionally empty content column — the nav + * entry exists so the section slot composition is visible; model management + * lands in a later phase. + */ + +/** + * Render the (empty) Models section content column. + * @returns null — no content this phase. + */ +export function ModelsSection() { + return null +} diff --git a/packages/client/ui-settings-models/src/client/index.ts b/packages/client/ui-settings-models/src/client/index.ts new file mode 100644 index 0000000000..8ad2ebb750 --- /dev/null +++ b/packages/client/ui-settings-models/src/client/index.ts @@ -0,0 +1,63 @@ +/** + * Models settings section plugin, browser half. Registers the `models` nav + * entry into the shell-declared `settings.section` list slot; the content + * column is intentionally empty until model management lands. Export + * discipline: packages/client/AGENTS.md. + */ +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +// Type-only: pulls the shell's SlotMap merge (the 'settings.section' entry). +import type {} from '@deepseek-ai/dsh-client-ui-settings/client' +// Type-only: pulls the locale plugin's Context merge (ctx.locale). +import type {} from '@deepseek-ai/dsh-client-locale/client' +import { ModelsSection } from './ModelsSection.tsx' + +/** + * Required services (cordis fiber inject). The target slot is declared by + * ui-settings' apply, whose activation order relative to this one is NOT + * constrained; registration goes through declaration-aware deferral. + */ +export const inject = ['slots', 'locale'] + +/** + * Register the Models section once the `settings.section` declaration is on + * the ledger. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => { + const disposers = [ + ctx.locale.register('settings.models', 'zh', { nav: '模型' }), + ctx.locale.register('settings.models', 'en', { nav: 'Models' }), + ] + return () => { for (const dispose of disposers) dispose() } + }, 'ui-settings-models: nav copy dictionaries') + ctx.effect(() => { + let dispose: (() => void) | undefined + const register = (): void => { + dispose = ctx.slots.register({ + name: 'settings.section', + id: 'models', + order: 10, + label: ctx.locale.bind('settings.models')('nav'), + }, ModelsSection) + } + const tryRegister = (): void => { + if (ctx.slots.spec('settings.section') === undefined || dispose !== undefined) return + register() + } + // Nav labels are registrant-localized: re-register on locale change so + // the ledger carries fresh text (the version bump re-renders the shell). + const offLocale = ctx.on('locale/change', () => { + if (dispose === undefined) return + dispose() + register() + }) + const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) + tryRegister() + return () => { + offLocale() + unsubscribe() + dispose?.() + } + }, 'ui-settings-models: section registration') +} diff --git a/packages/client/ui-settings-models/src/css-modules.d.ts b/packages/client/ui-settings-models/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-settings-models/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-settings-models/src/index.ts b/packages/client/ui-settings-models/src/index.ts new file mode 100644 index 0000000000..da3060fe59 --- /dev/null +++ b/packages/client/ui-settings-models/src/index.ts @@ -0,0 +1,4 @@ +/** Host loader entry for the browser implementation exported from `./client`. */ + +/** Host plugin body — no host-side behavior for the models settings plugin. */ +export function apply(): void {} diff --git a/packages/client/ui-settings-models/src/invariant.ts b/packages/client/ui-settings-models/src/invariant.ts new file mode 100644 index 0000000000..9ffdc668d7 --- /dev/null +++ b/packages/client/ui-settings-models/src/invariant.ts @@ -0,0 +1,31 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-settings-models`. + * @module @deepseek-ai/dsh-client-ui-settings-models/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-settings-models' + +/** Cordis companion plugin name. */ +export const name = 'client-ui-settings-models-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: a nav-entry-only section plugin rendering a fixed + * empty content column — it emits no cordis events and owns no cross-plugin + * mutable relation. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/client/ui-settings-models/tsconfig.json b/packages/client/ui-settings-models/tsconfig.json new file mode 100644 index 0000000000..dde94c20af --- /dev/null +++ b/packages/client/ui-settings-models/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../ui-slots" + }, + { + "path": "../runtime" + }, + { + "path": "../ui-settings" + }, + { + "path": "../locale" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/client/ui-settings-models/tsdown.config.ts b/packages/client/ui-settings-models/tsdown.config.ts new file mode 100644 index 0000000000..7a2688a097 --- /dev/null +++ b/packages/client/ui-settings-models/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-ui-settings-models', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md new file mode 100644 index 0000000000..64250c7917 --- /dev/null +++ b/packages/client/ui-settings/README.md @@ -0,0 +1,15 @@ +# @deepseek-ai/dsh-client-ui-settings + +Settings shell plugin: the sidebar trigger row and the modal settings panel occupying `sidebar.settings`; declares the `settings.section` list slot that section plugins contribute pages into. The shell projects the section ledger into navigation and renders only the active section (`only` filtering). + +## Model Experience + +None, as the settings shell serves browser UI composition; nothing here reaches a model request. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + +- **Panel is browser-preference scope only** — host-side settings (permission mode, tool-call mode) render as skeletons in the General section; no RPC surface exists yet. diff --git a/packages/client/ui-settings/package.json b/packages/client/ui-settings/package.json new file mode 100644 index 0000000000..8f71d90c8b --- /dev/null +++ b/packages/client/ui-settings/package.json @@ -0,0 +1,68 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-settings", + "description": "Settings shell plugin: sidebar trigger + modal panel occupying sidebar.settings; declares the settings.section list slot", + "version": "0.0.1", + "private": true, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./invariant": { + "types": "./lib/types/invariant.d.ts", + "default": "./lib/invariant.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "dshClient": { + "inject": [ + "@deepseek-ai/dsh-client-runtime", + "@deepseek-ai/dsh-client-ui-sidebar", + "@deepseek-ai/dsh-client-locale" + ], + "platform": "web" + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "BSD-3-Clause", + "dependencies": { + "clsx": "^2.0.0" + }, + "peerDependencies": { + "@deepseek-ai/dsh-client-runtime": "^0.0.1", + "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", + "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", + "@deepseek-ai/dsh-invariants": "^0.0.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "devDependencies": { + "@deepseek-ai/dsh-client-locale": "workspace:^", + "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", + "@deepseek-ai/dsh-client-ui-sidebar": "workspace:^", + "@deepseek-ai/dsh-client-ui-slots": "workspace:^", + "@deepseek-ai/dsh-invariants": "workspace:^", + "@types/react": "~18.3.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" + }, + "files": [ + "lib/index.js", + "lib/invariant.js", + "lib/client.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "src" + ] +} diff --git a/packages/client/ui-settings/src/client/SettingsRoot.module.css b/packages/client/ui-settings/src/client/SettingsRoot.module.css new file mode 100644 index 0000000000..bf557c0a04 --- /dev/null +++ b/packages/client/ui-settings/src/client/SettingsRoot.module.css @@ -0,0 +1,192 @@ +/* Settings shell (figma 501:29904 mask context / 501:29947 panel): sidebar + foot trigger row + centered 1080x700 modal panel. The trigger reproduces + the former sidebar foot geometry (49px wide row / 36px rail circle); the + panel is a two-column layout — 188px nav rail + content column with a + 54px header and the 24px-padded options area. */ + +/* Trigger row (former sidebar foot, figma 133:7668): 49px hover pill. */ +.trigger { + flex: none; + display: flex; + align-items: center; + gap: 8px; + width: 100%; + height: 49px; + margin: 8px 0 0; + padding: 0 2px 0 6px; + border: none; + border-radius: 12px; + background: transparent; + cursor: pointer; + overflow: hidden; + color: var(--dsw-alias-label-primary); + font-family: inherit; + font-size: 14px; +} + +.trigger:hover { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* Rail trigger: the same 36x36 circle box as the other rail controls. */ +.trigger.rail { + width: 36px; + height: 36px; + margin: 18px 0 10px; + justify-content: center; + gap: 0; + padding: 0; + border-radius: 50%; +} + +.triggerLabel { + overflow: hidden; + white-space: nowrap; +} + +/* Full-viewport layer (figma Mask 501:29946 #000@24%, no blur). */ +.overlay { + position: fixed; + inset: 0; + z-index: 1000; + display: flex; + align-items: center; + justify-content: center; +} + +.mask { + position: absolute; + inset: 0; + background: var(--dsw-alias-bg-mask-1); +} + +/* Panel (figma Settings 501:29947): 1080x700, r24, white, lv3 shadow + (figma effects match --dsw-shadow-lv3 exactly). */ +.panel { + position: relative; + z-index: 1; + display: flex; + width: 1080px; + height: 700px; + max-width: calc(100vw - 48px); + max-height: calc(100vh - 48px); + border-radius: 24px; + overflow: hidden; + background: var(--dsw-alias-bg-layer-1); + box-shadow: var(--dsw-shadow-lv3); +} + +/* Nav rail (figma .Setting-nav 501:29958): 188 wide, pad (12,22,12,0), + gap 18, no own fill — the panel white shows through. */ +.nav { + flex: none; + display: flex; + flex-direction: column; + gap: 18px; + width: 188px; + padding: 22px 12px 0; + box-sizing: border-box; +} + +/* Title row (figma 501:29959): 16/500 lh24, 12px side padding. */ +.navTitle { + padding: 0 12px; + font-size: 16px; + line-height: 24px; + font-weight: 500; + color: var(--dsw-alias-label-primary); +} + +/* Cell stack (figma 501:29961): gap 4. */ +.navList { + display: flex; + flex-direction: column; + gap: 4px; +} + +/* Nav cell (figma .Setting-nav-cell 501:29962): 164x40, r12, pad + (12,9,16,9), gap 8; label 14/400 lh22; selected fill #EBEEF2. */ +.navCell { + display: flex; + align-items: center; + gap: 8px; + height: 40px; + padding: 9px 16px 9px 12px; + box-sizing: border-box; + border: none; + border-radius: 12px; + background: transparent; + cursor: pointer; + font-family: inherit; + font-size: 14px; + line-height: 22px; + font-weight: 400; + color: var(--dsw-alias-label-primary); + text-align: left; +} + +.navCell:hover { + background: var(--dsw-specific-sidebar-nav-item-hover); +} + +.navCell.active { + background: var(--dsw-specific-sidebar-nav-item-active); +} + +.navIcon { + flex: none; +} + +.navLabel { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +/* Content column (figma Content 501:29980): header + options. */ +.content { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; +} + +/* Header (figma .Header 501:29981): h54, pad (10,20,14,8), close right. */ +.header { + flex: none; + display: flex; + align-items: flex-start; + justify-content: flex-end; + height: 54px; + padding: 20px 14px 8px 10px; + box-sizing: border-box; +} + +/* Close button (figma .Icon_container 501:29982): 28x28, r28, 14px glyph. */ +.close { + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + padding: 0; + border: none; + border-radius: 28px; + background: transparent; + cursor: pointer; + color: var(--dsw-alias-label-primary); +} + +.close:hover { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* Options area (figma Options 501:29983): pad (24,0,24,8), scrolls. */ +.options { + flex: 1; + min-height: 0; + padding: 0 24px 8px; + overflow-y: auto; +} diff --git a/packages/client/ui-settings/src/client/SettingsRoot.tsx b/packages/client/ui-settings/src/client/SettingsRoot.tsx new file mode 100644 index 0000000000..3a27acdf6c --- /dev/null +++ b/packages/client/ui-settings/src/client/SettingsRoot.tsx @@ -0,0 +1,125 @@ +/** + * Settings shell root: the sidebar-foot trigger row plus the centered modal + * panel (figma 501:29947, 1080x700) with the section nav rail. Modal open + * state and the active section id are component-local viewing state; the + * section ledger arrives through the injected face (nav labels are + * registrant-localized — the shell owns no locale/theme subscription). + */ +import { useCallback, useEffect, useRef, useState } from 'react' +import clsx from 'clsx' +import { + IconCloseOutline16, IconDataOutline16, IconSettingsOutline14, IconSettingsOutline16, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { SettingsRootComponentProps } from './contract/slots.ts' +import css from './SettingsRoot.module.css' + +/** Nav glyph by section id; unknown ids fall back to the settings gear. */ +function navIcon(id: string) { + if (id === 'models') return + return +} + +type PanelProps = { + translate: SettingsRootComponentProps['translate'] + rows: ReturnType + renderSlot: SettingsRootComponentProps['renderSlot'] + onClose: () => void +} + +/** + * The modal layer: full-viewport mask + centered panel. Close paths: the + * header button, a mask click, and document-level Escape (mounted only while + * open, so the listener lifetime is the panel's). + */ +function SettingsPanel({ translate, rows, renderSlot, onClose }: PanelProps) { + // Local selection; entries can unmount underneath it, so the render-time + // projection falls back to the first row when the id is gone. + const [activeId, setActiveId] = useState(undefined) + const active = rows.find((r) => r.id === activeId)?.id ?? rows[0]?.id + + useEffect(() => { + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Escape') onClose() + } + document.addEventListener('keydown', onKeyDown) + return () => { document.removeEventListener('keydown', onKeyDown) } + }, [onClose]) + + // Baseline focus management: entering the dialog lands on the close button. + const closeButton = useRef(null) + useEffect(() => { closeButton.current?.focus() }, []) + + return ( +
+ + ) +} + +/** + * Render the settings trigger and panel. + * @param props - composed slot props (contract/slots.ts). + * @returns the settings shell element tree. + */ +export function SettingsRoot(props: SettingsRootComponentProps) { + const { wide, translate, subscribeSections, sectionsVersion, sections, renderSlot } = props + const [open, setOpen] = useState(false) + const close = useCallback(() => { setOpen(false) }, []) + + // The ledger tick is the shell's only subscription: sections re-register + // with freshly localized labels on locale change, so the version bump also + // re-renders the shell's own translate()-read chrome copy. + // State = ledger version: same-version notifications dedupe to no render. + const [, setSectionsRev] = useState(() => sectionsVersion()) + useEffect( + () => subscribeSections(() => { setSectionsRev(sectionsVersion()) }), + [subscribeSections, sectionsVersion], + ) + const rows = sections() + + return ( + <> + + {open && } + + ) +} diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts new file mode 100644 index 0000000000..10e4e0ecbe --- /dev/null +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -0,0 +1,62 @@ +/** + * Settings shell slot contract: the shell occupies the sidebar-owned + * `sidebar.settings` hole and declares the `settings.section` list slot that + * section plugins (General, Models, …) contribute pages into. + */ +import type { PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +// Type-only: pulls ui-sidebar's SlotMap merge (the 'sidebar.settings' entry) +// into every program that sees this contract. +import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** + * One settings page per list entry. Registrant options carry the nav + * identity: `id` (section key, drives `only` filtering), `order` (nav + * position), `label` (registrant-localized display text — the registrant + * re-registers with fresh text on locale change, so the shell never + * subscribes locale/theme state; the ledger bump doubles as the shell's + * re-render trigger). Sections render inside the panel content column. + */ + 'settings.section': { kind: 'list'; scope: 'root'; owner: SettingsSectionOwnerProps } + } +} + +/** + * Owner share of a settings section entry. The shell owns modal visibility + * and navigation; sections receive nothing but the render site (their data + * arrives through their own inject faces and stores). + */ +export interface SettingsSectionOwnerProps { + /** Marker field: section owner props are intentionally empty for now. */ + children?: never +} + +/** + * Registrant-private injected share of the settings shell (assembled in + * apply): locale-resolved nav labels come through `translate`. + */ +export type SettingsRootInjected = { + /** + * Resolve a ":" locale reference to the active-locale text — + * shell chrome copy only (trigger/title/close); nav labels arrive already + * localized. Read at render time; the locale-change re-render rides the + * section ledger bump, not a shell-owned subscription. + */ + translate: (ref: string) => string + /** Read the settings.section ledger version (nav invalidation). */ + sectionsVersion: () => number + /** Subscribe to settings.section ledger changes. */ + subscribeSections: (listener: () => void) => () => void + /** Project the settings.section ledger into nav rows (id/order/label). */ + sections: () => readonly { id: string; order: number; label: string }[] +} + +/** + * Full component props of the settings shell root: the sidebar owner share + * (wide/rail state) plus the declared section render share and the injected + * face. No store is registered — modal open state and active section id are + * component-local viewing state. + */ +export type SettingsRootComponentProps = + PropsRuntime<'sidebar.settings'> & PropsRenderSlots<'settings.section'> & SettingsRootInjected diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts new file mode 100644 index 0000000000..d5135f373c --- /dev/null +++ b/packages/client/ui-settings/src/client/index.ts @@ -0,0 +1,66 @@ +/** + * Settings shell plugin, browser half. Occupies the sidebar-owned + * `sidebar.settings` hole with the trigger row + modal panel, declares the + * `settings.section` list slot, and projects that ledger into the panel + * navigation. Export discipline: packages/client/AGENTS.md. + */ +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +// Type-only: pulls the locale plugin's Context/Events merges (ctx.locale, +// 'locale/change') into this program. +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type { SettingsRootInjected } from './contract/slots.ts' +import { SettingsRoot } from './SettingsRoot.tsx' + +export type { SettingsRootComponentProps, SettingsRootInjected, SettingsSectionOwnerProps } from './contract/slots.ts' + +/** + * Required services (cordis fiber inject). The target slot is declared by + * ui-sidebar's apply, whose activation order relative to this one is NOT + * constrained (dshClient.inject edges are informational); registration goes + * through declaration-aware deferral. + */ +export const inject = ['slots', 'locale'] + +/** + * Register the settings shell into `sidebar.settings` once the declaration is + * on the ledger. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => { + const disposers = [ + ctx.locale.register('settings', 'zh', { trigger: '设置', title: '设置', close: '关闭' }), + ctx.locale.register('settings', 'en', { trigger: 'Settings', title: 'Settings', close: 'Close' }), + ] + return () => { for (const dispose of disposers) dispose() } + }, 'ui-settings: shell copy dictionaries') + const injected = (): SettingsRootInjected => ({ + translate: (ref) => { + const colon = ref.indexOf(':') + if (colon === -1) return ref + return ctx.locale.bind(ref.slice(0, colon))(ref.slice(colon + 1)) + }, + sectionsVersion: () => ctx.slots.getVersion('settings.section'), + subscribeSections: (listener) => ctx.slots.subscribe('settings.section', listener), + sections: () => ctx.slots.entries('settings.section') + .map(e => ({ id: e.options.id ?? '', order: e.options.order ?? 0, label: e.options.label ?? '' })) + .sort((a, b) => a.order - b.order), + }) + ctx.effect(() => { + let dispose: (() => void) | undefined + const tryRegister = (): void => { + if (ctx.slots.spec('sidebar.settings') === undefined || dispose !== undefined) return + dispose = ctx.slots.register({ + name: 'sidebar.settings', + children: { 'settings.section': { kind: 'list', scope: 'root' } }, + inject: injected, + }, SettingsRoot) + } + const unsubscribe = ctx.slots.subscribe('sidebar.settings', () => { tryRegister() }) + tryRegister() + return () => { + unsubscribe() + dispose?.() + } + }, 'ui-settings: shell registration') +} diff --git a/packages/client/ui-settings/src/css-modules.d.ts b/packages/client/ui-settings/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-settings/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-settings/src/index.ts b/packages/client/ui-settings/src/index.ts new file mode 100644 index 0000000000..52fe4c43e6 --- /dev/null +++ b/packages/client/ui-settings/src/index.ts @@ -0,0 +1,4 @@ +/** Host loader entry for the browser implementation exported from `./client`. */ + +/** Host plugin body — no host-side behavior for the settings shell plugin. */ +export function apply(): void {} diff --git a/packages/client/ui-settings/src/invariant.ts b/packages/client/ui-settings/src/invariant.ts new file mode 100644 index 0000000000..53d7fb066a --- /dev/null +++ b/packages/client/ui-settings/src/invariant.ts @@ -0,0 +1,32 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-settings`. + * @module @deepseek-ai/dsh-client-ui-settings/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-settings' + +/** Cordis companion plugin name. */ +export const name = 'client-ui-settings-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: a presentation shell projecting the settings.section + * ledger into navigation — it emits no cordis events and owns no cross-plugin + * mutable relation; slot declaration/registration conflicts already fail loud + * in the slot core at load time. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's invariant companion. + * @param ctx - Cordis context carrying the invariant service. + * @returns the installed registration's disposer after setup succeeds. + */ +export const apply = (ctx: Context): Promise<() => void> => + Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) +/* jscpd:ignore-end */ diff --git a/packages/client/ui-settings/tsconfig.json b/packages/client/ui-settings/tsconfig.json new file mode 100644 index 0000000000..db90b908bf --- /dev/null +++ b/packages/client/ui-settings/tsconfig.json @@ -0,0 +1,33 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../runtime" + }, + { + "path": "../ui-sidebar" + }, + { + "path": "../locale" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/client/ui-settings/tsdown.config.ts b/packages/client/ui-settings/tsdown.config.ts new file mode 100644 index 0000000000..ba06fdc7c9 --- /dev/null +++ b/packages/client/ui-settings/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-ui-settings', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index d8c2f61ee0..e42b226904 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -4,7 +4,9 @@ Sidebar plugin: real Host Workspaces in stable Host order, each containing its ` New Session starts the runtime's page-local frontend Session Intent; a real Workspace's "+" starts one targeted to that Workspace. The Workspace header "+" opens ui-workspace's shared picker, whose selection also targets a frontend Session. A Workspace Intent does not appear in the sidebar. -`SidebarRootComponentProps` composes the layout owner share, the global `useSessions` and `useWorkspaces` hooks, the declared `sidebar.workspace` child slot, and injected `startSession`, `open`, and sidebar-toggle callbacks. There is no plugin store: `deriveGroups` consumes object-layer snapshots and component-local expansion/search state. +`SidebarRootComponentProps` composes the layout owner share, the global `useSessions` and `useWorkspaces` hooks, the declared `sidebar.workspace` and `sidebar.settings` child slots, and injected `startSession`, `open`, and sidebar-toggle callbacks. There is no plugin store: `deriveGroups` consumes object-layer snapshots and component-local expansion/search state. + +The foot is the `sidebar.settings` seat: the sidebar renders only the bottom-pinned layout slot and shares its column state (`wide`); ui-settings registers the trigger row and settings panel there. The `/client` export surface is the plugin body (`apply`/`inject`) plus the contract types only — SidebarRoot, the row components, and the tree derivation are internal (the slot registration closes over them; tests import src paths directly). diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css index 591aef2330..20431e9d15 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css @@ -49,7 +49,7 @@ .railIn .iconButton, .railIn .newSession, .railIn .searchButton, -.railIn .foot { +.railIn .footArea { animation: rail-in 150ms var(--ds-ease-in-out) 100ms backwards; } @@ -372,45 +372,11 @@ font-size: 13px; } -/* Foot: settings entry (figma 133:7668, 49 hug): the former 18/10 vertical - margins fold into the row so the hover pill spans the full 49px. */ -.foot { +/* Foot seat: pure layout — the flex slot pinning the sidebar.settings slot + content to the column bottom. Row visuals belong to the slot occupant + (ui-settings). */ +.footArea { flex: none; - display: flex; - align-items: center; - gap: 8px; - height: 49px; - margin: 8px 0 0; /* + 49px row + root padBottom 6 keeps the old 57px band */ - padding: 0 2px 0 6px; - border-radius: 12px; - cursor: pointer; - overflow: hidden; - color: var(--dsw-alias-label-primary); -} - -.foot:hover { - background: var(--dsw-alias-interactive-bg-hover); -} - -/* Rail settings: the same 36x36 circle box as the other rail controls. */ -.collapsed .foot { - width: 36px; - height: 36px; - margin: 18px 0 10px; - justify-content: center; - gap: 0; - padding: 0; - border-radius: 50%; -} - -.footLabel { - max-width: 120px; - overflow: hidden; - white-space: nowrap; -} - -.collapsed .footLabel { - max-width: 0; } @media (prefers-reduced-motion: reduce) { @@ -419,7 +385,7 @@ .railIn .iconButton, .railIn .newSession, .railIn .searchButton, - .railIn .foot { + .railIn .footArea { transition: none; animation: none; } diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx index 931eb1ba17..490c3e7b8b 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx @@ -12,7 +12,7 @@ import clsx from 'clsx' import { BrandWordmark, FishLogo, IconCloseFill14, IconNewChatOutline16, IconPanelLeftOutline16, IconPersonalizationOutline16, - IconProjectAddOutline16, IconSearchOutline16, IconSettingsOutline14, + IconProjectAddOutline16, IconSearchOutline16, Menu, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' @@ -314,9 +314,10 @@ export function SidebarRoot({ )}
-
- - {wide && Settings} + {/* Foot seat: the flex slot pinning the settings entry to the column + bottom; ui-settings occupies it with the trigger row + panel. */} +
+ {renderSlot('sidebar.settings', { wide })}
) diff --git a/packages/client/ui-sidebar/src/client/contract/slots.ts b/packages/client/ui-sidebar/src/client/contract/slots.ts index 0334ca88c9..bb7c0caf07 100644 --- a/packages/client/ui-sidebar/src/client/contract/slots.ts +++ b/packages/client/ui-sidebar/src/client/contract/slots.ts @@ -20,9 +20,24 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * is claiming); ui-workspace registers the picker. */ 'sidebar.workspace': { kind: 'single'; scope: 'root'; owner: SidebarWorkspaceOwnerProps } + /** + * The settings seat at the sidebar foot. Declared by this package's + * 'sidebar' entry; ui-settings registers its trigger row + modal panel. + * The sidebar passes only its column state — it holds no settings state. + */ + 'sidebar.settings': { kind: 'single'; scope: 'root'; owner: SidebarSettingsOwnerProps } } } +/** + * Owner share of the sidebar settings seat: the column display state the + * occupant's trigger row must render against (wide row vs rail icon). + */ +export interface SidebarSettingsOwnerProps { + /** Whether the sidebar renders wide content (false = 56px rail). */ + wide: boolean +} + /** * Owner share of the sidebar workspace hole: popover geometry plus the * sidebar's pick semantics. The picked Host Workspace is already real; the @@ -62,8 +77,9 @@ export type SidebarRootInjected = { /** * Full component props: layout owner state/actions plus global useSessions - * and useWorkspaces, the declared Workspace picker render share, and this - * package's injected callback. No store is registered. + * and useWorkspaces, the declared child-slot render shares (Workspace picker + * and settings seat), and this package's injected callback. No store is + * registered. */ export type SidebarRootComponentProps = - PropsRuntime<'sidebar'> & PropsRenderSlots<'sidebar.workspace'> & SidebarRootInjected + PropsRuntime<'sidebar'> & PropsRenderSlots<'sidebar.workspace' | 'sidebar.settings'> & SidebarRootInjected diff --git a/packages/client/ui-sidebar/src/client/index.ts b/packages/client/ui-sidebar/src/client/index.ts index 0a1c8ebb12..ad847bb5a5 100644 --- a/packages/client/ui-sidebar/src/client/index.ts +++ b/packages/client/ui-sidebar/src/client/index.ts @@ -3,7 +3,7 @@ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import type { SidebarRootInjected } from './contract/slots.ts' import { SidebarRoot } from './SidebarRoot.tsx' -export type { SidebarRootComponentProps, SidebarRootInjected, SidebarWorkspaceOwnerProps } from './contract/slots.ts' +export type { SidebarRootComponentProps, SidebarRootInjected, SidebarSettingsOwnerProps, SidebarWorkspaceOwnerProps } from './contract/slots.ts' /** Services required by the sidebar plugin. */ export const inject = ['slots', 'layout', 'sessions', 'workspaces'] @@ -20,9 +20,12 @@ export function apply(ctx: ClientContext): void { ctx.effect( () => ctx.slots.register({ name: 'sidebar', - // SidebarRoot owns this picker site; ui-workspace registers the shared - // picker that selects a Host Workspace for a frontend Session Intent. - children: { 'sidebar.workspace': { kind: 'single', scope: 'root' } }, + // SidebarRoot owns these sites; ui-workspace registers the shared + // picker, ui-settings registers the settings trigger + panel. + children: { + 'sidebar.workspace': { kind: 'single', scope: 'root' }, + 'sidebar.settings': { kind: 'single', scope: 'root' }, + }, inject: injectProps, }, SidebarRoot), 'ui-sidebar: slot registration', diff --git a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx index 26adafd793..d4caa4e1be 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx @@ -32,16 +32,16 @@ const workspaces: WorkspaceListState = { function mount(sessionState: SessionListState = sessions) { const startSession = vi.fn() const open = vi.fn() - let pickerOwner: unknown + const owners: Record = {} const view = render( { pickerOwner = owner; return null }) as SidebarRootComponentProps['renderSlot']} + renderSlot={((key: string, owner: unknown) => { owners[key] = owner; return null }) as SidebarRootComponentProps['renderSlot']} />, ) - return { view, startSession, open, pickerOwner: () => pickerOwner } + return { view, startSession, open, pickerOwner: () => owners['sidebar.workspace'], settingsOwner: () => owners['sidebar.settings'] } } function mountSidebar({ @@ -58,14 +58,14 @@ function mountSidebar({ const startSession = vi.fn() const open = vi.fn() const toggleSidebar = vi.fn() - let pickerOwner: unknown + const owners: Record = {} let current = { sessionState, workspaceState, collapsed, width } const root = () => ( { pickerOwner = owner; return null }) as SidebarRootComponentProps['renderSlot']} + renderSlot={((key: string, owner: unknown) => { owners[key] = owner; return null }) as SidebarRootComponentProps['renderSlot']} /> ) const view = render(root()) @@ -73,7 +73,8 @@ function mountSidebar({ startSession, open, toggleSidebar, - pickerOwner: () => pickerOwner, + pickerOwner: () => owners['sidebar.workspace'], + settingsOwner: () => owners['sidebar.settings'], rerender(next: Partial) { current = { ...current, ...next } view.rerender(root()) @@ -246,6 +247,7 @@ describe('SidebarRoot', () => { it('keeps wide content during live collapse, then settles to the rail', () => { vi.useFakeTimers() const b = mountSidebar({ width: 320 }) + expect((b.settingsOwner() as { wide: boolean }).wide).toBe(true) fireEvent.click(screen.getByRole('button', { name: 'Collapse sidebar' })) expect(b.toggleSidebar).toHaveBeenCalledOnce() b.rerender({ collapsed: true, width: 56 }) @@ -253,6 +255,8 @@ describe('SidebarRoot', () => { act(() => { vi.advanceTimersByTime(150) }) expect(screen.queryByPlaceholderText('Search name, keywords...')).toBeNull() expect(screen.getByRole('button', { name: 'Open sidebar' })).toBeTruthy() + // The settings seat share tracks the settled column state. + expect((b.settingsOwner() as { wide: boolean }).wide).toBe(false) }) }) diff --git a/packages/client/ui-theme/README.md b/packages/client/ui-theme/README.md index 2ce5d9b9e6..be0b83a0d8 100644 --- a/packages/client/ui-theme/README.md +++ b/packages/client/ui-theme/README.md @@ -1,10 +1,10 @@ # @deepseek-ai/dsh-client-ui-theme -Theme plugin: ThemeService over the --dsw-* token base stylesheets (static scale + alias semantic layers); apply(id) toggles the `body[data-ds-dark-theme]` attribute, so theme switches are pure CSS cascade. Contract: api-contracts v3 §8. +Theme plugin: ThemeService over the --dsw-* token base stylesheets (static scale + alias semantic layers). The service owns the theme preference (`light`/`dark`/`system`, persisted under `dsh.theme`), resolves `system` through `prefers-color-scheme`, and publishes immutable `ThemeSnapshot`s on the `theme/change` event; it never touches the DOM — ui-layout's presenter applies the resolved snapshot (`body[data-ds-dark-theme]` + inline alias tokens). Contract: api-contracts v3 §8. ## Model Experience -None, as the theme service toggles browser CSS; nothing here reaches a model request. +None, as the theme service manages a browser preference; nothing here reaches a model request. #### KV Cache effect @@ -12,6 +12,5 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **No theme-switch control ships in P-I** — the service surface (register/apply/current) is complete but no UI owner mounts a toggle; switching happens programmatically. - **Third-party themes are a surface, not a product** — registering one means overriding same-named alias variables; no validation exists that an override set is complete. - **The token sheets are the sole color authority** — values absent from cssdesign (for example the design's #4176E6 tab blue) are deliberately not appended; the nearest semantic token wins (arbitrated 2026-07-22). diff --git a/packages/client/ui-theme/package.json b/packages/client/ui-theme/package.json index 4e601914e3..4c6ad92cd4 100644 --- a/packages/client/ui-theme/package.json +++ b/packages/client/ui-theme/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-theme", - "description": "Theme plugin: ThemeService (apply = toggle body[data-ds-dark-theme]), --dsw-* token base stylesheets", + "description": "Theme plugin: ThemeService (light/dark/system preference, prefers-color-scheme resolution, theme/change snapshots; no DOM), --dsw-* token base stylesheets", "version": "0.0.1", "private": true, "type": "module", @@ -44,5 +44,9 @@ "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" - ] + ], + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + } } diff --git a/packages/client/ui-theme/src/client/index.ts b/packages/client/ui-theme/src/client/index.ts index d9f5b70c3b..5ba5d40b35 100644 --- a/packages/client/ui-theme/src/client/index.ts +++ b/packages/client/ui-theme/src/client/index.ts @@ -1,71 +1,196 @@ /** - * Browser theme registry over the `--dsw-*` token stylesheets. Theme changes - * update CSS variables and `body[data-ds-dark-theme]` without React renders. + * Browser theme registry over the `--dsw-*` token stylesheets. The service + * owns the theme preference (light/dark/system), resolves `system` through + * `prefers-color-scheme`, and publishes immutable snapshots; it never touches + * the DOM — ui-layout's presenter consumes the resolved snapshot. */ import type { Context } from 'cordis' /** Theme token dictionary: --dsw-alias-* overrides keyed by variable name. */ export type ThemeTokens = Record +/** Theme preference: a concrete theme id or follow-the-OS. */ +export type ThemePreference = 'light' | 'dark' | 'system' + +/** One selectable theme: id, dark/light semantics, and alias-token overrides. */ +export interface ThemeDefinition { + /** Theme id (the setTheme argument for concrete themes). */ + id: string + /** + * Which base palette this theme builds on. The presenter switches + * `body[data-ds-dark-theme]` from this field — never from the id. + */ + colorScheme: 'light' | 'dark' + /** Alias-layer overrides applied as inline CSS variables over the base palette. */ + tokens: ThemeTokens +} + +/** Immutable theme state published on every change. */ +export interface ThemeSnapshot { + /** The persisted preference (may be `system`). */ + preference: ThemePreference + /** The resolved active theme (`system` resolved via prefers-color-scheme). */ + active: ThemeDefinition + /** Registered themes in registration order. */ + themes: readonly ThemeDefinition[] + /** Monotonic change counter (registry or active changes). */ + revision: number +} + declare module 'cordis' { interface Context { theme: ThemeService } + interface Events { + /** + * Theme state changed (preference switched, registry updated, or the OS + * color scheme changed while the preference is `system`). + * @param snapshot - Current immutable theme snapshot. + * @mode emit + */ + 'theme/change'(snapshot: ThemeSnapshot): void + } } +/** localStorage key holding the persisted theme preference. */ +export const STORAGE_KEY = 'dsh.theme' + +/** Default preference when nothing (or garbage) is persisted. */ +export const DEFAULT_PREFERENCE: ThemePreference = 'system' + +const BUILTIN_THEMES: readonly ThemeDefinition[] = Object.freeze([ + Object.freeze({ id: 'light', colorScheme: 'light' as const, tokens: Object.freeze({}) }), + Object.freeze({ id: 'dark', colorScheme: 'dark' as const, tokens: Object.freeze({}) }), +]) + /** - * Theme registry and switcher. `light`/`dark` are built in (the base - * stylesheets carry both palettes; the dark palette activates via the - * body[data-ds-dark-theme] attribute). Third-party themes register alias-layer - * overrides applied as inline CSS variables on body, cascading over whichever - * base palette the attribute selects. + * Theme registry and preference owner. `light`/`dark` are built in (the base + * stylesheets carry both palettes); third-party themes register alias-layer + * overrides. Reads go through {@link getTheme}; writes only through + * {@link setTheme}; continuous sync only through the `theme/change` event. + * The service holds the `prefers-color-scheme` media query (environment + * sensing, not presentation) and re-emits when the OS scheme flips while the + * preference is `system`. */ export class ThemeService { - private themes = new Map([['light', {}], ['dark', {}]]) - private appliedTokens: ThemeTokens = {} - private active = 'light' + private readonly ctx: Context + private themes: ThemeDefinition[] = [...BUILTIN_THEMES] + private preference: ThemePreference + private revision = 0 + private snapshot: ThemeSnapshot + private readonly media: MediaQueryList | undefined /** - * Register a theme. Duplicate id throws (single occupant per id; the - * built-in pair counts). - * @param id - theme id. - * @param tokens - alias-layer overrides (variable name to value). - * @returns disposer. Disposing the active theme reverts to `light` so the - * UI never keeps tokens of an unregistered theme. + * @param ctx - owning context (change events are emitted on it; the + * media-query listener is released through ctx.effect on dispose). */ - register(id: string, tokens: ThemeTokens): () => void { - if (this.themes.has(id)) throw new Error(`theme "${id}" is already registered`) - this.themes.set(id, tokens) - return () => { - if (!this.themes.delete(id)) return - if (this.active === id) this.apply('light') + constructor(ctx: Context) { + this.ctx = ctx + this.preference = restorePreference() + this.media = globalThis.matchMedia?.('(prefers-color-scheme: dark)') + this.snapshot = this.buildSnapshot() + if (this.media !== undefined) { + const media = this.media + const onChange = (): void => { + if (this.preference !== 'system') return + this.publish() + } + ctx.effect(() => { + media.addEventListener('change', onChange) + return () => { media.removeEventListener('change', onChange) } + }, 'ui-theme: prefers-color-scheme listener') } } /** - * Activate a theme: toggle body[data-ds-dark-theme] (set only for `dark`) - * and swap the previous theme's inline token overrides for this one's. - * Unregistered id throws. - * @param id - registered theme id. + * Read the current immutable theme snapshot. + * @returns the current snapshot (stable reference until the next change). */ - apply(id: string): void { - const tokens = this.themes.get(id) - if (!tokens) throw new Error(`theme "${id}" is not registered`) - const body = document.body - for (const name of Object.keys(this.appliedTokens)) body.style.removeProperty(name) - if (id === 'dark') body.setAttribute('data-ds-dark-theme', '') - else body.removeAttribute('data-ds-dark-theme') - for (const [name, value] of Object.entries(tokens)) body.style.setProperty(name, value) - this.appliedTokens = tokens - this.active = id + getTheme(): ThemeSnapshot { + return this.snapshot } /** - * Report the active theme id (initially `light`). - * @returns the active theme id. + * Switch the theme preference — the only preference write entry. Persists + * the preference and emits `theme/change`. + * @param id - a registered theme id or `system`; unknown ids throw. */ - current(): string { - return this.active + setTheme(id: string): void { + if (id !== 'system' && !this.themes.some(t => t.id === id)) { + throw new Error(`theme "${id}" is not registered`) + } + if (this.preference === id) return + this.preference = id as ThemePreference + persistPreference(this.preference) + this.publish() + } + + /** + * Register a theme. Duplicate id throws (single occupant per id; the + * built-in pair counts; `system` is a preference, not a registrable id). + * @param definition - theme id, colorScheme, and alias-token overrides. + * @returns disposer. Disposing the theme backing the active preference + * resets the preference to the default so the UI never keeps tokens of an + * unregistered theme. + */ + register(definition: ThemeDefinition): () => void { + if (definition.id === 'system') throw new Error('"system" is a preference, not a registrable theme id') + if (this.themes.some(t => t.id === definition.id)) { + throw new Error(`theme "${definition.id}" is already registered`) + } + this.themes = [...this.themes, definition] + this.publish() + return () => { + if (!this.themes.some(t => t.id === definition.id)) return + this.themes = this.themes.filter(t => t.id !== definition.id) + if (this.preference === definition.id) { + this.preference = DEFAULT_PREFERENCE + persistPreference(this.preference) + } + this.publish() + } + } + + private buildSnapshot(): ThemeSnapshot { + const resolvedId = this.preference === 'system' + ? (this.media?.matches === true ? 'dark' : 'light') + : this.preference + // Both built-ins always exist; a registered preference id resolves or has + // been reset by its disposer, so the lookup cannot miss. + const active = this.themes.find(t => t.id === resolvedId) ?? this.themes[0]! + return Object.freeze({ + preference: this.preference, + active, + themes: Object.freeze([...this.themes]), + revision: this.revision, + }) + } + + private publish(): void { + this.revision += 1 + this.snapshot = this.buildSnapshot() + this.ctx.emit('theme/change', this.snapshot) + } +} + +/** Read the persisted preference; unknown or unreadable values fall back to the default. */ +function restorePreference(): ThemePreference { + try { + const stored = globalThis.localStorage?.getItem(STORAGE_KEY) + if (stored === 'light' || stored === 'dark' || stored === 'system') return stored + } catch { + // Storage access can throw (privacy mode); the default below covers it. + } + return DEFAULT_PREFERENCE +} + +/** Persist the preference; storage failures are non-fatal (preference resets next boot). */ +function persistPreference(preference: ThemePreference): void { + try { + globalThis.localStorage?.setItem(STORAGE_KEY, preference) + } catch { + // Storage access can throw (privacy mode / quota); the preference simply + // does not survive the session. } } @@ -77,5 +202,5 @@ export const inject: string[] = [] * @param ctx - client cordis context. */ export function apply(ctx: Context): void { - ctx.provide('theme', new ThemeService()) + ctx.provide('theme', new ThemeService(ctx)) } diff --git a/packages/client/ui-theme/src/invariant.ts b/packages/client/ui-theme/src/invariant.ts index 292304cbaf..4ec3296cd6 100644 --- a/packages/client/ui-theme/src/invariant.ts +++ b/packages/client/ui-theme/src/invariant.ts @@ -15,9 +15,10 @@ export const name = 'client-ui-theme-invariant' export const inject = ['invariants'] /** - * No runtime invariant: a token-sheet registry whose apply() flips one body - * attribute — it emits no cordis events; registration/apply/current behavior - * is asserted directly by this package's behavior specs. + * No runtime invariant: the theme registry publishes immutable snapshots on + * its own `theme/change` event synchronously with the setter/registry + * mutation in the same service — snapshot/event agreement is asserted + * directly by this package's behavior specs. */ const install: InvariantInstaller = () => {} diff --git a/packages/client/ui-theme/tests/theme.spec.ts b/packages/client/ui-theme/tests/theme.spec.ts index 126957c5eb..9ab0ab8f0f 100644 --- a/packages/client/ui-theme/tests/theme.spec.ts +++ b/packages/client/ui-theme/tests/theme.spec.ts @@ -1,61 +1,90 @@ // @vitest-environment jsdom import { beforeEach, describe, expect, it } from 'vitest' -import { ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' +import { Context } from 'cordis' +import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' +import { STORAGE_KEY, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' + +const make = (): { ctx: Context; theme: ThemeService; events: ThemeSnapshot[] } => { + const ctx = new Context() + const events: ThemeSnapshot[] = [] + ctx.on('theme/change', (snapshot) => { events.push(snapshot) }) + return { ctx, theme: new ThemeService(ctx), events } +} describe('ThemeService', () => { beforeEach(() => { - document.body.removeAttribute('data-ds-dark-theme') - document.body.removeAttribute('style') + localStorage.clear() }) - it('starts on light; apply toggles the dark body attribute both ways', () => { - const theme = new ThemeService() - expect(theme.current()).toBe('light') - theme.apply('dark') - expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(true) - expect(theme.current()).toBe('dark') - theme.apply('light') + it('defaults to the system preference resolved against prefers-color-scheme', () => { + const { theme } = make() + const snapshot = theme.getTheme() + expect(snapshot.preference).toBe('system') + // jsdom matchMedia is absent; system resolves to light. + expect(snapshot.active.id).toBe('light') + expect(snapshot.active.colorScheme).toBe('light') + expect(snapshot.themes.map(t => t.id)).toEqual(['light', 'dark']) + }) + + it('setTheme switches, persists, republishes, and keeps DOM untouched', () => { + const { theme, events } = make() + theme.setTheme('dark') + expect(theme.getTheme().preference).toBe('dark') + expect(theme.getTheme().active.colorScheme).toBe('dark') + expect(localStorage.getItem(STORAGE_KEY)).toBe('dark') + expect(events).toHaveLength(1) + expect(events[0]).toBe(theme.getTheme()) + // The service never touches presentation state. expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(false) - expect(theme.current()).toBe('light') + // Same-value set is a no-op (no extra event). + theme.setTheme('dark') + expect(events).toHaveLength(1) }) - it('throws on unregistered apply and duplicate register (built-ins included)', () => { - const theme = new ThemeService() - expect(() => { theme.apply('sepia') }).toThrow('not registered') - expect(() => theme.register('light', {})).toThrow('already registered') - theme.register('sepia', {}) - expect(() => theme.register('sepia', {})).toThrow('already registered') + it('restores a persisted preference and falls back on garbage', () => { + localStorage.setItem(STORAGE_KEY, 'dark') + expect(make().theme.getTheme().preference).toBe('dark') + localStorage.setItem(STORAGE_KEY, 'sepia') + expect(make().theme.getTheme().preference).toBe('system') }) - it('applies third-party token overrides as body inline vars and swaps them on switch', () => { - const theme = new ThemeService() - theme.register('sepia', { '--dsw-alias-bg-base': 'rgb(1, 2, 3)' }) - theme.apply('sepia') - expect(document.body.style.getPropertyValue('--dsw-alias-bg-base')).toBe('rgb(1, 2, 3)') - expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(false) - theme.apply('dark') - expect(document.body.style.getPropertyValue('--dsw-alias-bg-base')).toBe('') - expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(true) + it('throws on unknown setTheme ids, duplicate registration, and the system id', () => { + const { theme } = make() + expect(() => { theme.setTheme('sepia') }).toThrow('not registered') + expect(() => theme.register({ id: 'light', colorScheme: 'light', tokens: {} })).toThrow('already registered') + expect(() => theme.register({ id: 'system', colorScheme: 'light', tokens: {} })).toThrow('preference') }) - it('disposing the active theme reverts to light; disposer is idempotent', () => { - const theme = new ThemeService() - const dispose = theme.register('sepia', { '--dsw-alias-bg-base': 'red' }) - theme.apply('sepia') + it('registered themes join the snapshot; disposing the active one resets to default', () => { + const { theme, events } = make() + const dispose = theme.register({ id: 'sepia', colorScheme: 'light', tokens: { '--dsw-alias-bg-base': 'red' } }) + expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark', 'sepia']) + theme.setTheme('sepia') + expect(theme.getTheme().active.tokens['--dsw-alias-bg-base']).toBe('red') dispose() - expect(theme.current()).toBe('light') - expect(document.body.style.getPropertyValue('--dsw-alias-bg-base')).toBe('') - expect(() => { theme.apply('sepia') }).toThrow('not registered') + expect(theme.getTheme().preference).toBe('system') + expect(theme.getTheme().themes.map(t => t.id)).toEqual(['light', 'dark']) + expect(localStorage.getItem(STORAGE_KEY)).toBe('system') + // register + set + dispose = three publishes; disposer is idempotent. + expect(events.length).toBe(3) dispose() - expect(theme.current()).toBe('light') + expect(events.length).toBe(3) }) - it('disposing an inactive theme leaves the active selection untouched', () => { - const theme = new ThemeService() - const dispose = theme.register('sepia', {}) - theme.apply('dark') + it('disposing an inactive theme keeps the active preference', () => { + const { theme } = make() + const dispose = theme.register({ id: 'sepia', colorScheme: 'light', tokens: {} }) + theme.setTheme('dark') dispose() - expect(theme.current()).toBe('dark') - expect(document.body.hasAttribute('data-ds-dark-theme')).toBe(true) + expect(theme.getTheme().preference).toBe('dark') + }) + + it('revision increases monotonically across every publish', () => { + const { theme, events } = make() + theme.setTheme('dark') + theme.setTheme('light') + const dispose = theme.register({ id: 'sepia', colorScheme: 'dark', tokens: {} }) + dispose() + expect(events.map(e => e.revision)).toEqual([1, 2, 3, 4]) }) }) diff --git a/packages/client/web/src/boot.tsx b/packages/client/web/src/boot.tsx index bd755a5fc1..61dbbd850e 100644 --- a/packages/client/web/src/boot.tsx +++ b/packages/client/web/src/boot.tsx @@ -21,7 +21,7 @@ * switches to the real UI in one pass. * * Entry creation waits for the whole immediately tier: materialization runs - * synchronous cross-package require edges (e.g. i18n → runtime/client) that + * synchronous cross-package require edges (e.g. locale → runtime/client) that * fiber inject waiting cannot protect — a bundle's factory must be * registered before any dependent entry materializes. Per-row prefetch * failures still resolve silently (the create-side import refetches and diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7f19dcce27..2410252eb0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -125,9 +125,9 @@ importers: '@deepseek-ai/dsh-client-hmr': specifier: workspace:^ version: link:../../packages/client/hmr - '@deepseek-ai/dsh-client-i18n': + '@deepseek-ai/dsh-client-locale': specifier: workspace:^ - version: link:../../packages/client/i18n + version: link:../../packages/client/locale '@deepseek-ai/dsh-client-modules': specifier: workspace:^ version: link:../../packages/client/modules @@ -143,6 +143,15 @@ importers: '@deepseek-ai/dsh-client-ui-question': specifier: workspace:^ version: link:../../packages/client/ui-question + '@deepseek-ai/dsh-client-ui-settings': + specifier: workspace:^ + version: link:../../packages/client/ui-settings + '@deepseek-ai/dsh-client-ui-settings-general': + specifier: workspace:^ + version: link:../../packages/client/ui-settings-general + '@deepseek-ai/dsh-client-ui-settings-models': + specifier: workspace:^ + version: link:../../packages/client/ui-settings-models '@deepseek-ai/dsh-client-ui-sidebar': specifier: workspace:^ version: link:../../packages/client/ui-sidebar @@ -740,11 +749,7 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@vendor+loader) - packages/client/i18n: - dependencies: - '@deepseek-ai/dsh-client-runtime': - specifier: workspace:^ - version: link:../runtime + packages/client/locale: devDependencies: '@deepseek-ai/dsh-invariants': specifier: workspace:^ @@ -844,6 +849,9 @@ importers: '@deepseek-ai/dsh-client-ui-slots': specifier: workspace:^ version: link:../ui-slots + '@deepseek-ai/dsh-client-ui-theme': + specifier: workspace:^ + version: link:../ui-theme '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants @@ -937,6 +945,104 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/client/ui-settings: + dependencies: + clsx: + specifier: ^2.0.0 + version: 2.1.1 + devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-sidebar': + specifier: workspace:^ + version: link:../ui-sidebar + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 + + packages/client/ui-settings-general: + dependencies: + clsx: + specifier: ^2.0.0 + version: 2.1.1 + devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-settings': + specifier: workspace:^ + version: link:../ui-settings + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots + '@deepseek-ai/dsh-client-ui-theme': + specifier: workspace:^ + version: link:../ui-theme + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 + + packages/client/ui-settings-models: + devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-ui-settings': + specifier: workspace:^ + version: link:../ui-settings + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 + packages/client/ui-sidebar: dependencies: clsx: diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 20d4195737..da5fe34dc4 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -59,7 +59,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-trajectory': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-workspace': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-theme': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, - 'packages/client/i18n': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, + 'packages/client/locale': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/web': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/examples/agent-spine-demo': { kind: 'indirect', reason: 'The bundle only mounts model-facing child plugins.' }, 'packages/fs/fs': { kind: 'indirect', reason: 'The service interface delegates model rendering to dsh-tool-fs.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index a449a34c4e..81e0fc989c 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -115,7 +115,10 @@ "@deepseek-ai/dsh-client-ui-trajectory": ["./packages/client/ui-trajectory/src"], "@deepseek-ai/dsh-client-ui-workspace": ["./packages/client/ui-workspace/src"], "@deepseek-ai/dsh-client-ui-theme": ["./packages/client/ui-theme/src"], - "@deepseek-ai/dsh-client-i18n": ["./packages/client/i18n/src"], + "@deepseek-ai/dsh-client-ui-settings": ["./packages/client/ui-settings/src"], + "@deepseek-ai/dsh-client-ui-settings-general": ["./packages/client/ui-settings-general/src"], + "@deepseek-ai/dsh-client-ui-settings-models": ["./packages/client/ui-settings-models/src"], + "@deepseek-ai/dsh-client-locale": ["./packages/client/locale/src"], "@deepseek-ai/dsh-client-web": ["./packages/client/web/src"], "@deepseek-ai/dsh-*": [ "./packages/core/*/src", diff --git a/tsconfig.client.json b/tsconfig.client.json index 17f34b601f..abe80b8b12 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -38,7 +38,10 @@ { "path": "./packages/client/ui-question" }, { "path": "./packages/client/ui-trajectory" }, { "path": "./packages/client/ui-theme" }, - { "path": "./packages/client/i18n" }, + { "path": "./packages/client/ui-settings" }, + { "path": "./packages/client/ui-settings-general" }, + { "path": "./packages/client/ui-settings-models" }, + { "path": "./packages/client/locale" }, { "path": "./packages/client/web" }, { "path": "./apps/web" } ] From 204a09b70fbfa6ebfd8ea39ac69ce7c0a7a2538e Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 00:30:20 +0800 Subject: [PATCH 077/113] fix(build): reuse TypeScript config host --- scripts/clean.ts | 14 ++------------ scripts/ts-project.ts | 5 +++-- 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/scripts/clean.ts b/scripts/clean.ts index 93b9b2519c..3cb3820db7 100644 --- a/scripts/clean.ts +++ b/scripts/clean.ts @@ -2,20 +2,10 @@ import { lstat, readdir, rm } from 'node:fs/promises' import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path' import { fileURLToPath } from 'node:url' import ts from 'typescript' +import { repositoryConfigHost } from './ts-project.ts' const knownOrphanEntries = new Set(['node_modules', 'lib', '.typecheck']) -const configHost: ts.ParseConfigFileHost = { - useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, - readDirectory: (...args) => ts.sys.readDirectory(...args), - fileExists: fileName => ts.sys.fileExists(fileName), - readFile: fileName => ts.sys.readFile(fileName), - getCurrentDirectory: () => ts.sys.getCurrentDirectory(), - onUnRecoverableConfigFileDiagnostic(diagnostic) { - throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')) - }, -} - function isMissing(error: unknown): boolean { return error instanceof Error && 'code' in error && error.code === 'ENOENT' } @@ -45,7 +35,7 @@ function repositoryPath(root: string, path: string): string { } function parseConfig(configPath: string): ts.ParsedCommandLine { - const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost) + const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, repositoryConfigHost) if (!parsed) throw new Error(`clean: cannot parse TypeScript config ${configPath}`) if (parsed.errors.length > 0) { throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n')) diff --git a/scripts/ts-project.ts b/scripts/ts-project.ts index 930c055d4f..9a0400a39d 100644 --- a/scripts/ts-project.ts +++ b/scripts/ts-project.ts @@ -11,7 +11,8 @@ interface ProjectGraph { options: ts.CompilerOptions } -const configHost: ts.ParseConfigFileHost = { +/** TypeScript config host shared by repository scripts. */ +export const repositoryConfigHost: ts.ParseConfigFileHost = { useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames, readDirectory: (...args) => ts.sys.readDirectory(...args), fileExists: fileName => ts.sys.fileExists(fileName), @@ -52,7 +53,7 @@ function loadProjectGraph(projectRoot: string): ProjectGraph { /** Parse one config file and fail loud on any config diagnostic. */ function parseConfig(configPath: string): ts.ParsedCommandLine { - const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost) + const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, repositoryConfigHost) if (!parsed) throw new Error(`cannot parse TypeScript config ${configPath}`) if (parsed.errors.length > 0) { throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n')) From 1317e4809f1cedf404a68a54a629efe08dadfbc5 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 00:30:38 +0800 Subject: [PATCH 078/113] fix(pty): recheck prompt handoff at idle boundary --- packages/pty/pty-local/README.md | 2 +- packages/pty/pty-local/src/session.ts | 7 +++++-- packages/pty/pty-local/tests/session.spec.ts | 2 +- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/pty/pty-local/README.md b/packages/pty/pty-local/README.md index a2b3aec391..cd11509b43 100644 --- a/packages/pty/pty-local/README.md +++ b/packages/pty/pty-local/README.md @@ -6,7 +6,7 @@ Local Linux/macOS `node-pty` backend for `ctx.pty`; loading it on another platfo The plugin injects `pty`, `sandbox`, and `sandboxPolicy`, then registers the configured backend type (`shell`). `danger-full-access` starts the shell directly; confined modes wrap the exact shell argv through `ctx.sandbox`. The effective session mode is resolved at spawn. A change to a different effective mode is rejected before its `sandbox/mode` event commits while that owner has an open PTY or a spawn in progress; the fence is attached to the exact owner and therefore outlives a local-provider reload that retains existing sessions. Wait for creation to settle and close the sessions before changing modes, so a terminal opened with wider access cannot survive a downgrade. -Linux readiness combines a foreground-verified private bash prompt marker, foreground-process-group syscall inspection, silence fallback, and absolute timeout. macOS uses the verified prompt marker plus silence/timeout because it has no `/proc` syscall surface. A marker is not ready until printable prompt text arrives, including when the OSC marker and `PS1` are split across data callbacks; when bash prints the marker before the kernel publishes its return to the foreground process group, polling retains the candidate until bash ownership is observable or the ordinary silence bound expires. An interactive child that inherits `PROMPT_COMMAND` therefore cannot suppress inferred-idle readiness until the absolute timeout. Unrecognized or unreadable process state is never a positive exact-idle signal. During unpublished startup, a fallback requires observed output; zero-output silence cannot publish an empty session, and timeout rejects the spawn. Cancellation closes the unpublished shell and rejects with the caller's exact abort reason even when its foreground process group is not observable yet; if that close fails, `PtyBackendCleanupError` separately preserves the cleanup failure for registry disposal. Incomplete terminal-control sequences are bounded by `maxReadBytes` and discarded through their terminator after crossing that limit; a trailing carriage return is carried across callbacks so split CRLF becomes one newline. +Linux readiness combines a foreground-verified private bash prompt marker, foreground-process-group syscall inspection, silence fallback, and absolute timeout. macOS uses the verified prompt marker plus silence/timeout because it has no `/proc` syscall surface. A marker is not ready until printable prompt text arrives, including when the OSC marker and `PS1` are split across data callbacks; when bash prints the marker before the kernel publishes its return to the foreground process group, polling retains the candidate through one final poll after the ordinary silence bound so a coincident handoff can win. An interactive child that inherits `PROMPT_COMMAND` therefore cannot suppress inferred-idle readiness until the absolute timeout. Unrecognized or unreadable process state is never a positive exact-idle signal. During unpublished startup, a fallback requires observed output; zero-output silence cannot publish an empty session, and timeout rejects the spawn. Cancellation closes the unpublished shell and rejects with the caller's exact abort reason even when its foreground process group is not observable yet; if that close fails, `PtyBackendCleanupError` separately preserves the cleanup failure for registry disposal. Incomplete terminal-control sequences are bounded by `maxReadBytes` and discarded through their terminator after crossing that limit; a trailing carriage return is carried across callbacks so split CRLF becomes one newline. Send cancellation resolves the current foreground process group and delivers a real `SIGINT`; it never emulates interruption by writing `\x03`, so raw-mode programs remain cancellable. Close sends `SIGTERM` to descendants, waits, then sends `SIGKILL` to the union of captured survivors and newly scanned descendants so reparenting cannot hide a process from teardown. It verifies that every retained identity is gone or, on Linux, a non-executing zombie before stopping the shell; zombie entries are quiescent and are reaped as the shell exits. A survivor failure does not cache a permanently rejected close; a later close retries the teardown. diff --git a/packages/pty/pty-local/src/session.ts b/packages/pty/pty-local/src/session.ts index 4b1faccc94..f05ad19e1d 100644 --- a/packages/pty/pty-local/src/session.ts +++ b/packages/pty/pty-local/src/session.ts @@ -331,8 +331,11 @@ export class LocalPtySession implements PtyBackendSession { // A prompt candidate can race bash's foreground handoff, but an interactive // child also inherits PROMPT_COMMAND. Silence therefore remains the bound // on waiting for shell ownership instead of letting a child marker suppress - // readiness until the absolute timeout. - if (startupHasOutput && Date.now() - this.lastOutputAt >= this.config.idleSilenceMs) { + // readiness until the absolute timeout. One final poll lets a foreground + // handoff coincident with that boundary win before the fallback settles. + const idleFor = Date.now() - this.lastOutputAt + const handoffGrace = this.promptSeen ? this.config.pollIntervalMs : 0 + if (startupHasOutput && idleFor >= this.config.idleSilenceMs && idleFor - this.config.idleSilenceMs >= handoffGrace) { this.settleActive('inferred_idle') return } diff --git a/packages/pty/pty-local/tests/session.spec.ts b/packages/pty/pty-local/tests/session.spec.ts index 4be21c79a6..3b76c9d71c 100644 --- a/packages/pty/pty-local/tests/session.spec.ts +++ b/packages/pty/pty-local/tests/session.spec.ts @@ -298,7 +298,7 @@ describe('LocalPtySession readiness and output', () => { void operation.done.then(() => { settled = true }) inspector.pgid = 789 terminal.emitData('\x1b]133;D;0\x07dsh> ') - await vi.advanceTimersByTimeAsync(40) + await vi.advanceTimersByTimeAsync(50) expect(settled).toBe(false) inspector.pgid = 456 From f1577d620e0a43007f00d709f65c145b1a7533c5 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 00:33:46 +0800 Subject: [PATCH 079/113] test(web): harden replay scaffold lifecycle --- .../2026-07-20-gui-testing-system.i18n.yaml | 4 +- .../process/2026-07-20-gui-testing-system.md | 2 +- .../2026-07-20-gui-testing-system.zh.md | 2 +- ...6-07-24-web-gui-browser-e2e-lane.i18n.yaml | 4 +- .../2026-07-24-web-gui-browser-e2e-lane.md | 24 +++--- .../2026-07-24-web-gui-browser-e2e-lane.zh.md | 24 +++--- apps/web/tests/replay-round-trip.e2e.ts | 13 ++- apps/web/tests/scaffold.ts | 82 ++++++++++++------- .../snapshots/fresh-round-trip/session.jsonl | 4 +- .../tests/snapshots/seeded-history/seed.jsonl | 4 +- packages/support/llm-replay/README.md | 2 +- scripts/doc-budgets.manifest.json | 2 +- 12 files changed, 97 insertions(+), 70 deletions(-) diff --git a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.i18n.yaml b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.i18n.yaml index ca443d7a16..ffa1e87103 100644 --- a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.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 -2026-07-20-gui-testing-system.md: b261bd2c84a628ab6fcdc29c59cf36a7b2428a76 -2026-07-20-gui-testing-system.zh.md: ecb8634695bd05359e6b590a825a4ad3604003b1 +2026-07-20-gui-testing-system.md: 546f65f065c0c2266773acc3c28b2833a094ba9b +2026-07-20-gui-testing-system.zh.md: 6601ae0a1c2bd1671af6f02961fbda81d30ab971 diff --git a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md index b261bd2c84..546f65f065 100644 --- a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md +++ b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.md @@ -20,7 +20,7 @@ Cut along the architecture's natural test seams into three tiers, bottom-up: |---|---|---|---| | 1 Protocol isomorphism | `AbstractApiClient` + `toFetchHandler` (bidirectional data / rpcId / zod types / SSE streams / batching / timeouts) | **The full chain at the isomorphic point**: `InProcessApiClient(toFetchHandler(脚本化 impl))` skips the network but genuinely runs the wire serialization — zero browser, pure node env | `packages/host/apiproxy/tests/client-handler.spec.ts` | | 2 Object-layer orchestration | `Session`/`SessionManager`/`ConnectionController` (state machines and timing: stitching / dedup / paging / optimistic draft clearing / pendingBuffers / reconnect / backoff) | **The "event sequence in → snapshot out" golden path**: programmable fakes + deferreds controlling timing + fake timers controlling backoff | `packages/client/{runtime,connection}/tests/` | -| 3 Assembled presentation | Built artifacts × the real client loader and plugin composition | App-owned semantic snapshots boot all eight built client plugins under jsdom for deterministic cross-plugin state changes; bare Playwright smoke separately proves the real browser/carrier boundary, with real-host cases self-skipping without a key; the keyless browser e2e lane replays recorded session fixtures through the real in-process web assembly (`llm: false` + dsh-llm-replay) against conversation aria goldens ([web e2e lane](../testing/2026-07-24-web-gui-browser-e2e-lane.md)) | `apps/web/tests/*.snapshot.ts`, `apps/web/tests/smoke-{fixture,real}.e2e.ts`, `apps/web/tests/{replay-round-trip,seeded-history}.e2e.ts` | +| 3 Assembled presentation | Built artifacts × the real client loader and plugin composition | App-owned semantic snapshots boot all eight built client plugins under jsdom for deterministic cross-plugin state changes; bare Playwright smoke separately proves the real browser/carrier boundary, with real-host cases self-skipping without a key; the keyless browser e2e lane disables the shipped model-adapter row and replays recorded session fixtures through `dsh-llm-replay` in the real in-process web assembly against conversation aria goldens ([web e2e lane](../testing/2026-07-24-web-gui-browser-e2e-lane.md)) | `apps/web/tests/*.snapshot.ts`, `apps/web/tests/smoke-{fixture,real}.e2e.ts`, `apps/web/tests/{replay-round-trip,seeded-history}.e2e.ts` | Inter-tier discipline: **each tier tests its own layer, upper tiers never re-test lower ones** — an app semantic snapshot pins only user-visible projection across the assembled plugin boundary, while Playwright smoke proves browser and carrier liveness; wire semantics belong to tier 1 and data semantics to tier 2. Pure-function layers (lineage/partial/notifier/fold-adapter) are tested directly with zero fakes in the same package's tests/ alongside tier 2. diff --git a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md index ecb8634695..6601ae0a1c 100644 --- a/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md +++ b/.agents/notes/implemented/process/2026-07-20-gui-testing-system.zh.md @@ -20,7 +20,7 @@ GUI 栈需要考虑多种应用形态,同应用形态内的不同运行环境 |---|---|---|---| | 1 协议同构层 | `AbstractApiClient` + `toFetchHandler`(双向数据/rpcId/ZOD类型/SSE 流/合批/超时) | **同构点全链**:`InProcessApiClient(toFetchHandler(脚本化 impl))` 不过网络但真跑 wire 序列化——零浏览器、纯 node env | `packages/host/apiproxy/tests/client-handler.spec.ts` | | 2 对象层编排 | `Session`/`SessionManager`/`ConnectionController`(状态机与时序:缝合/去重/翻页/乐观清稿/pendingBuffers/重连/退避) | **「事件序列进→快照出」黄金路径**:可编程假体 + deferred 控时序 + fake timers 控退避 | `packages/client/{runtime,connection}/tests/` | -| 3 组装呈现层 | 构建产物 × 真实 client loader 与插件组合 | 归应用所有的语义快照会在 jsdom 下启动全部 8 个已构建的 client 插件,以固定确定性的跨插件状态变化;独立使用 Playwright 裸库的冒烟测试负责验证真实浏览器/承载层边界,真 host 用例在无密钥时自行跳过;无密钥浏览器 e2e 车道把录制的会话 fixture 通过真实进程内 web 组装(`llm: false` + dsh-llm-replay)回放,与会话区 aria 期望输出比对([web e2e 车道](../testing/2026-07-24-web-gui-browser-e2e-lane.md)) | `apps/web/tests/*.snapshot.ts`、`apps/web/tests/smoke-{fixture,real}.e2e.ts`、`apps/web/tests/{replay-round-trip,seeded-history}.e2e.ts` | +| 3 组装呈现层 | 构建产物 × 真实 client loader 与插件组合 | 归应用所有的语义快照会在 jsdom 下启动全部 8 个已构建的 client 插件,以固定确定性的跨插件状态变化;独立使用 Playwright 裸库的冒烟测试负责验证真实浏览器/承载层边界,真 host 用例在无密钥时自行跳过;无密钥浏览器 e2e 车道会禁用交付配置中的模型适配器行,并通过 `dsh-llm-replay` 在真实进程内 web 组装中回放录制的会话 fixture,与会话区 aria 期望输出比对([web e2e 车道](../testing/2026-07-24-web-gui-browser-e2e-lane.md)) | `apps/web/tests/*.snapshot.ts`、`apps/web/tests/smoke-{fixture,real}.e2e.ts`、`apps/web/tests/{replay-round-trip,seeded-history}.e2e.ts` | 层间纪律:**下层各测各的,上层不重测下层**:应用语义快照只固定组装后插件边界上的用户可见投影,Playwright 冒烟测试负责验证浏览器与承载层是否存活;wire 语义归 1 层,数据语义归 2 层。纯函数层(lineage/partial/notifier/fold-adapter)随 2 层同包 tests/ 零假体直测。 diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml index e50541fa85..ef389fecb3 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.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 -2026-07-24-web-gui-browser-e2e-lane.md: b6e62f59e12c64dd5386eaaabe15e863ef52e291 -2026-07-24-web-gui-browser-e2e-lane.zh.md: 9f806c7030336bad4f7a9ca7695a03982d8a7878 +2026-07-24-web-gui-browser-e2e-lane.md: fb870c4bb2c85d8be7ac11f9f29f05bf24f446a4 +2026-07-24-web-gui-browser-e2e-lane.zh.md: c43e526d27fd4d8cf4f774e8a03480930682041d diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md index b6e62f59e1..fb870c4bb2 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.md @@ -6,7 +6,7 @@ English | [中文](2026-07-24-web-gui-browser-e2e-lane.zh.md) ## Problem -The web GUI ships as a real assembled chain — chromium page → client plugin bundles → HTTP unary RPC + two SSE streams → `toFetchHandler`/apiproxy → `bootHost`'s agent loop, tools, and JSONL persistence — and no test exercised that chain keylessly and deterministically. The [GUI testing system](../process/2026-07-20-gui-testing-system.md) covers tier 1 (wire isomorphism in node), tier 2 (object-layer state machines), and tier-3 smokes, but the keyless smoke drives `FixtureApiClient` — no host, no wire, no agent loop — while the full-chain smoke needs `DEEPSEEK_API_KEY` and a live model, so it is nondeterministic and self-skips in keyless CI. The snapshot philosophy of [docs/testing.md](../../../../docs/testing.md) — record once with a key, replay forever keyless, refresh on format churn — already covers the ACP, headless `stream-json`, and TUI transcript surfaces; the web surface was the one assembled product shape without it. The gap is exactly where the two confirmed GUI P0s hid: the wire carriage chain the fixture client short-circuits. +The web GUI ships as a real assembled chain — chromium page → client plugin bundles → HTTP unary RPC + two SSE streams → `toFetchHandler`/apiproxy → the host agent loop, tools, and JSONL persistence — and no test exercised that chain keylessly and deterministically. The [GUI testing system](../process/2026-07-20-gui-testing-system.md) covers tier 1 (wire isomorphism in node), tier 2 (object-layer state machines), and tier-3 smokes, but the keyless smoke drives `FixtureApiClient` — no host, no wire, no agent loop — while the full-chain smoke needs `DEEPSEEK_API_KEY` and a live model, so it is nondeterministic and self-skips in keyless CI. The snapshot philosophy of [docs/testing.md](../../../../docs/testing.md) — record once with a key, replay forever keyless, refresh on format churn — already covers the ACP, headless `stream-json`, and TUI transcript surfaces; the web surface was the one assembled product shape without it. The gap is exactly where the two confirmed GUI P0s hid: the wire carriage chain the fixture client short-circuits. ## Decision @@ -16,33 +16,33 @@ The web GUI ships as a real assembled chain — chromium page → client plugin A plain shared-fixture module (the [testing-policy sanctioned shape](../../../../docs/testing.md)), not a package: the gate-worthy logic — replay derivation, session parsing, log scrubbing, persistence — lives in the gated packages `dsh-llm-replay`, `dsh-acp-snapshot`, and `dsh-session-persistence-jsonl`; what remains is boot wiring and browser glue, and chromium-driving code cannot hold per-file 100% coverage on the browserless coverage runners. -`launchWebScaffold()` boots the real web composition: the shipped `apps/cli/cordis.yml` through the vendored Loader's include boot — the same tree and mechanism `AppCLIEntry` drives for `dsh web` (the config-tree boot landed upstream on 2026-07-25, superseding this lane's earlier in-process `startHost` assembly and resolving the original Loader-ization question in favor of Loader-izing). Divergences ride include patches over the SAME shipped tree, the ACP `cordis.snapshot.yml` pattern expressed in-process: temp `persistenceRoot`, `workspace-context` disabled (recorded fixtures must not embed this repo's AGENTS.md), `session-title-llm` disabled (its fire-and-forget title call would race the loop for the session's replay cursor), the webserver row pinned to port 0 with the built dist, and in keyless modes `llm-deepseek` disabled. A patch id that stops matching a row fails the boot sweep loudly instead of drifting. The boot runs `chdir`'d to the temp workspace so the api-gateway's `process.cwd()` session default, tool cwds, and fixtures agree; the `dsh web` bin's own glue (argv, profile json, AppCLIEntry) stays held by the keyless CLI smokes in `smoke-real.e2e.ts`. +`launchWebScaffold()` boots the real web composition from the shipped `apps/cli/cordis.yml` through the vendored Loader's include mechanism — the same tree and mechanism `AppCLIEntry` drives for `dsh web`. Divergences ride include patches over that tree, the ACP `cordis.snapshot.yml` pattern expressed in-process: temp `persistenceRoot`, `workspace-context` disabled (recorded fixtures must not embed this repo's AGENTS.md), `session-title-llm` disabled (its fire-and-forget title call would race the loop for the session's replay cursor), the webserver row pinned to port 0 with the built dist, and in keyless modes `llm-deepseek` disabled. A patch id that stops matching a row fails the boot sweep loudly instead of drifting. The boot runs `chdir`'d to the temp workspace so the api-gateway's `process.cwd()` session default, tool cwds, and fixtures agree; the `dsh web` bin's own glue (argv, profile json, AppCLIEntry) stays held by the keyless CLI smokes in `smoke-real.e2e.ts`. Setup rollback and ordinary close both dispose the Cordis tree before removing the two owned temp roots, attempt every cleanup independently, and report cleanup failures without masking the setup failure. -Keyless model displacement is the disabled adapter row plus `installLlmReplay` filling the open seam on the settled root ctx in providers-catalog mode — never catch-all: with the adapter row disabled no adapter exists, so catch-all would leave `resolveModelContext` unroutable and `compact-basic`'s post-step pressure check would warn every step instead of being provably inert (the published 128k `contextWindow` keeps it inert for small fixtures). The direct install rather than an inserted replay plugin row is deliberate: it returns the `ReplayHandle` the teardown consumption check needs. A scenario with no fixture leaves the seam empty, so a stray stream fails loud with NO_ADAPTER. (The first round's `BootHostOptions.llm: 'deepseek' | false` seam was superseded by the config-tree boot and removed with `bootHost`'s web role.) +Keyless model displacement is the disabled adapter row plus `installLlmReplay` filling the open seam on the settled root ctx in providers-catalog mode — never catch-all: with the adapter row disabled no adapter exists, so catch-all would leave `resolveModelContext` unroutable and `compact-basic`'s post-step pressure check would warn every step instead of being provably inert (the published 128k `contextWindow` keeps it inert for small fixtures). The direct install rather than an inserted replay plugin row is deliberate: it returns the `ReplayHandle` the teardown consumption check needs. A scenario with no fixture leaves the seam empty, so a stray stream fails loud with NO_ADAPTER. `seedSession()` seeds cold sessions through the real persistence API — a throwaway `Context` mounting `SessionStore` + `SessionPersistenceJsonl` against the host's root, `create()` + `append()`, one `utimes` backdate for deterministic sidebar order (the `semantic-checkpoint.snapshot.ts` precedent) — never raw file writes, so the seeder knows nothing of bucket hashing, filename encoding, or compression, and the host's zstd default needs no boot knob. Seeds are validated at seed time (parseable, ending in `turn/end` — an open final turn would be mutated by resume's crash repair). ### Determinism rules -The barrier stack for a prompted turn, in order: (1) host-side `await agent.whenIdle()` under a timeout, keyed off the in-process `turn/end` — the idle flip follows the persistence flush, so one await covers turn completion and durability; (2) browser settled poll (streaming detached, final text visible); (3) any log harvest after `host.dispose()`. An in-process `turn/end` listener alone is a wrong barrier (it fires before the SSE frame reaches the browser and before the fsync); file polling is banned (slow on NFS, superseded by `whenIdle`); `networkidle` is banned outright (never resolves while an SSE stream is open). +The barrier stack for replay-mode browser assertions is, in order: (1) host-side `await agent.whenIdle()` under a timeout, keyed off the in-process `turn/end` — the idle flip follows the persistence flush, so one await covers turn completion and durability; (2) browser settled poll (streaming detached, final text visible). Record-mode log harvest runs after `whenIdle()` and before scaffold disposal while the live session remains available. An in-process `turn/end` listener alone is a wrong barrier (it fires before the SSE frame reaches the browser and before the fsync); file polling is banned (slow on NFS, superseded by `whenIdle`); `networkidle` is banned outright (never resolves while an SSE stream is open). No single-shot transient-DOM assertions: every hop from replay yield to React commit can coalesce chunks, so sampling `[data-streaming]` is a race by construction. Streaming incrementality is asserted from the persisted `assistant/chunk` events (model-visible ⟺ logged makes the log the authoritative proof). `dsh-llm-replay`'s opt-in `paceMs` (default absent = burst) is a realism knob so the browser observes genuinely incremental SSE; correctness never leans on it, and abort during a pace wait cancels promptly. -Every scenario fails on any pageerror and on the client's connection-loss/gap-repair console warnings: the reconnect machine plus history resync would otherwise self-heal a dead SSE path and the suite would certify a broken wire. Scaffold `close()` calls the `ReplayHandle.assertConsumed()` teardown check (every recorded script bound, every cursor drained), converting silent underruns and shifted bindings into crisp diagnostics. No vitest retry on the lane; one chromium per file, fresh context per scenario, one host per scenario; viewport pinned; selectors anchor on roles, `data-*` attributes, and visible text. +Every scenario fails on any pageerror and on the client's connection-loss/gap-repair console warnings: the reconnect machine plus history resync would otherwise self-heal a dead SSE path and the suite would certify a broken wire. Scaffold `close()` calls the `ReplayHandle.assertConsumed()` teardown check (every recorded script bound, every cursor drained), converting silent underruns and shifted bindings into crisp diagnostics. No vitest retry on the lane; one chromium per file, fresh context per scenario, one host per scenario; viewport pinned; interaction selectors anchor on roles, `data-*` attributes, and visible text, while the frame and conversation-region captures use the existing CSS-module local-name anchors. ### Expected outputs -One committed golden per scenario: a normalized `ariaSnapshot()` of the conversation region (`ui.expected.md`) — uuid/cwd/workspace-basename/duration tokens normalized, captured poll-until-equal at the settled milestone — plus a few role/text anchor assertions that stay green under a semantics-preserving component rewrite while the golden churns reviewably. The aria tree is the mechanization of the client rule "assert what the user would see, never class names". World-state assertions ride `host.ctx` session events inline (which tools ran, `turn/end` completed) instead of a second committed log golden: the persisted-log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence, and re-pinning it here would double refresh cost against the tier discipline. `refresh` is the sole golden writer — a missing golden in replay mode fails with the healing command rather than self-bootstrapping. +One committed golden per scenario: a normalized `ariaSnapshot()` of the conversation region (`ui.expected.md`) — uuid/cwd/workspace-basename/duration tokens normalized, captured poll-until-equal at the settled milestone — plus a few role/text anchor assertions that stay green under a semantics-preserving component rewrite while the golden churns reviewably. The aria tree is the mechanization of the client rule "assert what the user would see, never class names". World-state assertions ride root-context session events inline (which tool call produced which durable result, whether `turn/end` completed) instead of a second committed log golden: the persisted-log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence, and re-pinning it here would double refresh cost against the tier discipline. `refresh` is the sole golden writer — a missing golden in replay mode fails with the healing command rather than self-bootstrapping. -The typecheck plane split is structural: `apps/web/tests/{scaffold,support,replay-round-trip.e2e,seeded-history.e2e}.ts` are host-plane programs (they boot the host spine), so they are excluded from the client-registered `apps/web` project and included file-by-file in `tsconfig.host.json` — one program cannot hold both sides of the cordis `Context` merges. +The typecheck plane split is structural: the three files that boot the host spine (`scaffold`, `replay-round-trip.e2e`, and `seeded-history.e2e`) are excluded from the client-registered `apps/web` project. Those files and their shared `support.ts` are included file-by-file in `tsconfig.host.json` — one program cannot hold both sides of the cordis `Context` merges. ### Modes and fixtures -`DSH_SNAPSHOT` selects replay (default, keyless), record (with key), or refresh (keyless) as inline spec branches — the TUI shape, not a suite factory: at two scenarios the acp-snapshot factory machinery has no owner, and the genuinely shared parts are already exported (`scrubRequestHeaders`, `parseSessionLog`, `installLlmReplay`). Each spec splits into drive steps (type, send, `whenTurnSettled` — run in all modes, never waiting on model-content selectors, so record cannot hang on a live model answering differently) and assertion steps (replay/refresh only). Record = drive live through the real composer + harvest the in-memory `session.header`/`session.events` (the TUI `rawSessionLog` shape — no file decompression) + `scrubRequestHeaders` + `{{sessionId}}`/`{{cwd}}` tokenization; a follow-up keyless refresh regenerates `ui.expected.md`. Both scenarios' fixtures were recorded against this assembly through this flow. A drift guard ties each spec's drive prompt to the fixture's recorded `user/message`. A fixture-inventory guard holds each scenario directory closed (exact file set, every JSONL a scrub fixed-point). Web fixtures scrub headers everywhere and pin no header class, following the TUI precedent over the strict [pinned-header](2026-07-06-pin-request-header-content-in-one-scenario.md) reading — see Deferred. +`DSH_SNAPSHOT` selects replay (default, keyless), record (with key), or refresh (keyless) as inline spec branches — the TUI shape, not a suite factory: at two scenarios the acp-snapshot factory machinery has no owner, and the genuinely shared parts are already exported (`scrubRequestHeaders`, `parseSessionLog`, `installLlmReplay`). Each spec splits into drive steps (type, send, `whenTurnSettled` — run in all modes, never waiting on model-content selectors, so record cannot hang on a live model answering differently) and assertion steps (replay/refresh only). Record = drive live through the real composer + harvest the in-memory `session.header`/`session.events` (the TUI `rawSessionLog` shape — no file decompression) + `scrubRequestHeaders` + `{{sessionId}}`/`{{cwd}}`/`{{rpcId}}` tokenization; a follow-up keyless refresh regenerates `ui.expected.md`. Both scenarios' fixtures were recorded against this assembly through this flow. A drift guard ties each spec's drive prompt to the fixture's recorded `user/message`. A fixture-inventory guard holds each scenario directory closed (exact file set, every JSONL a scrub fixed-point with no run-local `rpcId`). Web fixtures scrub headers everywhere and pin no header class, following the TUI precedent over the strict [pinned-header](2026-07-06-pin-request-header-content-in-one-scenario.md) reading — see Deferred. ### Scenarios -1. **`replay-round-trip`** — new session, prompt through the real composer, replay streams reasoning + a `bash` tool call that really executes in the temp workspace + final text (paced 15ms). Asserts settled markdown, the aria golden, and inline world state (bash `tool/call`, completed `turn/end`, >10 chunk events). +1. **`replay-round-trip`** — new session, prompt through the real composer, replay streams reasoning + a `bash` tool call that really executes in the temp workspace + final text (paced 15ms). Asserts settled markdown, the aria golden, and inline world state (the bash call's durable result is exactly `WEB_E2E_OK\n`, completed `turn/end`, >10 chunk events). 2. **`seeded-history`** — a recorded session seeded cold; the sidebar lists it (group row → session row, collapsed by default), opening renders tool cards and text purely from the log through the implicit cold-resume attach inside `session.history` — zero model calls in replay, so no binding constraints; record mode drives the same turn live (real `read` tool against seeded workspace files) to produce the seed. ### CI stance @@ -65,9 +65,9 @@ Surveyed AI-chat/agent web UIs and mocking layers (LibreChat, vercel/ai-chatbot **A `packages/support/web-snapshot` package with a `defineWebSnapshotSuite` factory.** Rejected: chromium-driving source cannot honestly hold per-file 100% coverage on browserless coverage runners, and at two scenarios a factory generalizes from one consumer while the genuinely shared logic is already exported from gated packages. Re-entry trigger: a second web-shaped consumer or ≥6 scenarios with demonstrably drifting inline branches; the package boundary would then be drawn browser-free. -**A committed normalized-session-log golden as a second expected surface.** Rejected: the log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence; here it would double refresh cost and re-test lower tiers. Inline world-state assertions on `host.ctx` events keep the world-verification duty. +**A committed normalized-session-log golden as a second expected surface.** Rejected: the log surface is pinned by the ACP/headless/TUI suites through the same loop and persistence; here it would double refresh cost and re-test lower tiers. Inline world-state assertions on root-context events keep the world-verification duty. -**Spawning the `dsh web` bin with a `DSH_SNAPSHOT` replay branch.** Rejected: it needs a test-mode branch plus env plumbing in the product bin where the in-process route uses exported production functions; the bin's thin glue is covered by the keyless CLI smokes. Becomes free only if the web host is ever Loader-ized — declined in review, with the app-assembly ruling reaffirmed. +**Spawning the `dsh web` bin with a `DSH_SNAPSHOT` replay branch.** Rejected: it needs a test-only replay branch plus environment plumbing in the shipped CLI. The in-process scaffold already loads the same `apps/cli/cordis.yml`; only argv, profile JSON, and `AppCLIEntry` glue remain outside it, and the keyless CLI smokes cover those paths. **Changing the wire protocol for testability.** Rejected: the contract already has a first-class keyless isomorphic seam (`InProcessApiClient(toFetchHandler(api))`), the per-event unbatched SSE is exactly what makes replay observable in a browser, and testing a wire we no longer ship would invert the tier's purpose. @@ -81,7 +81,7 @@ The lane itself: `pnpm run test:web` runs both scenarios keylessly alongside the ## Deferred -- **Web header-class pin**: web fixtures tokenize `{{system}}`/`{{tools}}` everywhere and no scenario pins bootHost's composed prompt/tool schemas (`TODO(web-header-pin)` — the scaffold `recordFixture` JSDoc marks it). Following the TUI scrub-everywhere precedent; revisit when the web assembly's header diverges from the repl composition it mirrors. +- **Web header-class pin**: web fixtures tokenize `{{system}}`/`{{tools}}` everywhere and no scenario pins the web composition's prompt/tool schemas (`TODO(web-header-pin)` — the scaffold `recordFixture` JSDoc marks it). Following the TUI scrub-everywhere precedent; revisit when the web assembly's header diverges from the repl composition it mirrors. - **CI browser provisioning**: reversal of the no-browser-in-CI ruling, staged criteria above (`TODO(ci-browser)`). - **Follow-up-prompt-after-resume scenario**: the history/live stitch path over the real wire; add as its own scenario when that code changes or regresses. diff --git a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md index 9f806c7030..c43e526d27 100644 --- a/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md +++ b/.agents/notes/implemented/testing/2026-07-24-web-gui-browser-e2e-lane.zh.md @@ -6,7 +6,7 @@ Status: implemented ## 问题 -Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bundle → HTTP 单次 RPC + 两条 SSE(Server-Sent Events)流 → `toFetchHandler`/apiproxy → `bootHost` 的 agent loop(智能体循环)、工具与 JSONL 持久化——却没有任何测试无密钥且确定性地检验这条链。[GUI 测试体系](../process/2026-07-20-gui-testing-system.md)覆盖第 1 层(Node 中的协议同构)、第 2 层(对象层状态机)与第 3 层冒烟测试,但无密钥冒烟驱动的是 `FixtureApiClient`——没有 host、没有 wire、没有 agent loop——而全链路冒烟需要 `DEEPSEEK_API_KEY` 和真实模型,因此不确定、在无密钥 CI 中自行跳过。[docs/testing.md](../../../../docs/testing.md) 的快照哲学——带密钥录制一次、永久无密钥回放、格式变动时刷新——已覆盖 ACP(Agent Client Protocol)、headless `stream-json` 与 TUI 三个文本记录(transcript)表面;web 表面是唯一没有这层保障的组装形态。而缺口恰恰是两起已实证 GUI P0 藏身之处:fixture(测试前置数据)客户端短路掉的 wire 承载链。 +Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bundle → HTTP 单次 RPC + 两条 SSE(Server-Sent Events)流 → `toFetchHandler`/apiproxy → host 端的 agent loop(智能体循环)、工具与 JSONL 持久化——却没有任何测试无密钥且确定性地检验这条链。[GUI 测试体系](../process/2026-07-20-gui-testing-system.md)覆盖第 1 层(Node 中的协议同构)、第 2 层(对象层状态机)与第 3 层冒烟测试,但无密钥冒烟驱动的是 `FixtureApiClient`——没有 host、没有 wire、没有 agent loop——而全链路冒烟需要 `DEEPSEEK_API_KEY` 和真实模型,因此不确定、在无密钥 CI 中自行跳过。[docs/testing.md](../../../../docs/testing.md) 的快照哲学——带密钥录制一次、永久无密钥回放、格式变动时刷新——已覆盖 ACP(Agent Client Protocol)、headless `stream-json` 与 TUI 三个文本记录(transcript)表面;web 表面是唯一没有这层保障的组装形态。而缺口恰恰是两起已实证 GUI P0 藏身之处:fixture(测试前置数据)客户端短路掉的 wire 承载链。 ## 决策 @@ -16,33 +16,33 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu 一个普通的共享 fixture 模块([测试政策认可的形态](../../../../docs/testing.md)),不是包:值得门禁把守的逻辑——回放推导、会话解析、日志脱敏、持久化——都在已受门禁的包 `dsh-llm-replay`、`dsh-acp-snapshot`、`dsh-session-persistence-jsonl` 中;剩下的只是启动接线和浏览器胶水,而驱动 chromium 的源码在无浏览器的覆盖率 runner 上无法诚实保持逐文件 100% 覆盖率。 -`launchWebScaffold()` 启动真实 web 组合:经 vendored Loader 的 include boot 加载交付的 `apps/cli/cordis.yml`——与 `AppCLIEntry` 为 `dsh web` 驱动的是同一棵树、同一套机制(配置树 boot 于 2026-07-25 在上游落地,取代了本车道第一轮的进程内 `startHost` 组装,也把当初的 Loader 化问题裁定为「Loader 化」)。差异全部经 include patch 骑在同一棵交付树上,即 ACP `cordis.snapshot.yml` 模式的进程内表达:临时 `persistenceRoot`;禁用 `workspace-context`(录制的 fixture 不得嵌入本仓库的 AGENTS.md);禁用 `session-title-llm`(其发后不管的标题调用会与循环争抢会话的回放游标);webserver 行钉到端口 0 加已构建 dist;无密钥模式下禁用 `llm-deepseek`。patch 的 id 一旦不再匹配任何行,boot 扫描会大声失败而不是漂移。boot 在临时工作区 `chdir` 下运行,使 api-gateway 的 `process.cwd()` 会话默认值、工具 cwd 与 fixture 一致;`dsh web` bin 自身的胶水(argv、profile json、AppCLIEntry)仍由 `smoke-real.e2e.ts` 中的无密钥 CLI 冒烟把守。 +`launchWebScaffold()` 通过 vendored Loader 的 include 机制,从交付的 `apps/cli/cordis.yml` 启动真实 web 组合——与 `AppCLIEntry` 为 `dsh web` 驱动的是同一棵树、同一套机制。差异全部经 include patch 覆盖在这棵树上,即 ACP `cordis.snapshot.yml` 模式的进程内表达:临时 `persistenceRoot`;禁用 `workspace-context`(录制的 fixture 不得嵌入本仓库的 AGENTS.md);禁用 `session-title-llm`(其发后不管的标题调用会与循环争抢会话的回放游标);webserver 行钉到端口 0 加已构建 dist;无密钥模式下禁用 `llm-deepseek`。patch 的 id 一旦不再匹配任何行,boot 扫描会大声失败而不是漂移。boot 在临时工作区 `chdir` 下运行,使 api-gateway 的 `process.cwd()` 会话默认值、工具 cwd 与 fixture 一致;`dsh web` bin 自身的胶水(argv、profile json、AppCLIEntry)仍由 `smoke-real.e2e.ts` 中的无密钥 CLI 冒烟把守。初始化回滚和正常关闭都会先对 Cordis 树执行 dispose(资源释放),再删除 scaffold 持有的两个临时根目录;每项清理都会独立尝试,并会报告清理失败而不掩盖初始化失败。 -无密钥的模型替换 = 禁用适配器行的 patch 加 `installLlmReplay` 在停稳的根 ctx 上以提供方目录(providers-catalog)模式填充开放的 seam——绝不用 catch-all:适配器行被禁用后不存在任何适配器,catch-all 会让 `resolveModelContext` 无路由可走,`compact-basic` 的步后压力检查将步步告警,而不是被可证明地闲置(发布的 128k `contextWindow` 使该路径对小 fixture 保持闲置)。选择直接安装而非插入回放插件行是刻意的:直接安装返回收尾消费检查所需的 `ReplayHandle`。没有 fixture 的场景让 seam 保持空置,任何离群的流式调用都会以 NO_ADAPTER 大声失败。(第一轮的 `BootHostOptions.llm: 'deepseek' | false` seam 已随配置树 boot 取代 `bootHost` 的 web 角色而移除。) +无密钥的模型替换 = 禁用适配器行的 patch 加 `installLlmReplay` 在停稳的根 ctx 上以提供方目录(providers-catalog)模式填充开放的 seam——绝不用 catch-all:适配器行被禁用后不存在任何适配器,catch-all 会让 `resolveModelContext` 无路由可走,`compact-basic` 的步后压力检查将步步告警,而不是被可证明地闲置(发布的 128k `contextWindow` 使该路径对小 fixture 保持闲置)。选择直接安装而非插入回放插件行是刻意的:直接安装返回收尾消费检查所需的 `ReplayHandle`。没有 fixture 的场景让 seam 保持空置,任何离群的流式调用都会以 NO_ADAPTER 大声失败。 `seedSession()` 通过真实持久化 API 播种冷会话——一次性 `Context` 挂载 `SessionStore` + `SessionPersistenceJsonl` 指向 host 的根目录,`create()` + `append()`,一次 `utimes` 回拨保证侧栏顺序确定(`semantic-checkpoint.snapshot.ts` 先例)——绝不裸写文件,因此播种器对桶哈希、文件名编码、压缩一无所知,host 的 zstd 默认值也无需任何启动开关。种子在播种时即校验(可解析、以 `turn/end` 结尾——未闭合的最终轮次会被恢复(resume)的崩溃修复改写)。 ### 确定性规则 -提示一轮对话的屏障栈,按序:(1)host 侧 `await agent.whenIdle()` 加超时,以进程内 `turn/end` 为锚——空闲翻转发生在持久化落盘之后,一次等待同时覆盖轮次完成与持久性;(2)浏览器安定轮询(流式输出节点已卸载、最终文本可见);(3)任何日志采收都在 `host.dispose()` 之后。单独监听进程内 `turn/end` 是错误屏障(它先于 SSE 帧到达浏览器、先于 fsync 触发);文件轮询被禁止(NFS 上慢,且被 `whenIdle` 取代);`networkidle` 被彻底禁止(SSE 流保持打开时它永不解析)。 +回放模式下浏览器断言的屏障栈,按序:(1)host 侧 `await agent.whenIdle()` 加超时,以进程内 `turn/end` 为锚——空闲翻转发生在持久化落盘之后,一次等待同时覆盖轮次完成与持久性;(2)浏览器安定轮询(流式输出节点已卸载、最终文本可见)。录制模式下,日志采收在 `whenIdle()` 之后、scaffold 释放之前进行,此时运行中的会话仍然可用。单独监听进程内 `turn/end` 是错误屏障(它先于 SSE 帧到达浏览器、先于 fsync 触发);文件轮询被禁止(NFS 上慢,且被 `whenIdle` 取代);`networkidle` 被彻底禁止(SSE 流保持打开时它永不解析)。 不做单次瞬态 DOM 断言:从回放产出到 React 提交的每一跳都可能合并分片,采样 `[data-streaming]` 天然就是竞态。流式输出的增量性由持久化的 `assistant/chunk` 事件断言(模型可见 ⟺ 已记录,使日志成为权威证据)。`dsh-llm-replay` 的可选 `paceMs`(默认缺省 = 突发)只是让浏览器观察到真正增量 SSE 的真实感旋钮;正确性绝不依赖它,且节奏等待期间中止会即时取消。 -每个场景都会因任何 pageerror 或客户端的连接丢失/间隙修复控制台警告而失败:否则重连机制加历史重同步会把一条死掉的 SSE 通路自愈掉,套件反而认证了坏 wire。Scaffold 的 `close()` 调用 `ReplayHandle.assertConsumed()` 收尾检查(每个已录脚本都被绑定、每个游标都耗尽),把静默的少放与错绑变成清晰诊断。车道不设 vitest 重试;每文件一个 chromium、每场景一个新 context、每场景一个 host;视口固定;选择器只锚定 role、`data-*` 属性和可见文本。 +每个场景都会因任何 pageerror 或客户端的连接丢失/间隙修复控制台警告而失败:否则重连机制加历史重同步会把一条死掉的 SSE 通路自愈掉,套件反而认证了坏 wire。Scaffold 的 `close()` 调用 `ReplayHandle.assertConsumed()` 收尾检查(每个已录脚本都被绑定、每个游标都耗尽),把静默的少放与错绑变成清晰诊断。车道不设 vitest 重试;每文件一个 chromium、每场景一个新 context、每场景一个 host;视口固定;交互选择器锚定 role、`data-*` 属性和可见文本,而 frame 与会话区采集则使用既有的 CSS 模块局部类名锚点。 ### 预期输出 -每场景一份提交的预期输出:会话区规范化 `ariaSnapshot()`(`ui.expected.md`)——uuid/cwd/工作区目录名/时长归一为稳定 token,在安定里程碑处轮询至两次相等再采集——外加几条 role/文本锚断言,让保语义的组件重写在预期输出可评审地变动时仍保持绿色锚点。aria 树是 client 规则「断言用户所见,绝不断言类名」的机械化。世界状态断言内联在 `host.ctx` 会话事件上(哪些工具运行了、`turn/end` 完成)而不是第二份提交的日志预期输出:持久化日志表面已由 ACP/headless/TUI 套件经同一循环和持久化钉住,在此重复钉住会违背分层纪律、翻倍刷新成本。`refresh` 是预期输出的唯一写入者——回放模式下预期输出缺失会连同修复命令一起报错,而不是静默自举。 +每场景一份提交的预期输出:会话区规范化 `ariaSnapshot()`(`ui.expected.md`)——uuid/cwd/工作区目录名/时长归一为稳定 token,在安定里程碑处轮询至两次相等再采集——外加几条 role/文本锚断言,让保语义的组件重写在预期输出可评审地变动时仍保持绿色锚点。aria 树是 client 规则「断言用户所见,绝不断言类名」的机械化。世界状态断言内联在根上下文的会话事件上(哪次工具调用产生了哪项已持久化的工具结果、`turn/end` 是否完成)而不是第二份提交的日志预期输出:持久化日志表面已由 ACP/headless/TUI 套件经同一循环和持久化钉住,在此重复钉住会违背分层纪律、翻倍刷新成本。`refresh` 是预期输出的唯一写入者——回放模式下预期输出缺失会连同修复命令一起报错,而不是静默自举。 -类型检查平面切分是结构性的:`apps/web/tests/{scaffold,support,replay-round-trip.e2e,seeded-history.e2e}.ts` 是 host 平面程序(它们启动 host 主干),因此被排除出注册在 client 侧的 `apps/web` 工程,逐文件纳入 `tsconfig.host.json`——一个程序不能同时持有 cordis `Context` 合并的两侧。 +类型检查平面切分是结构性的:启动 host 主干的三个文件(`scaffold`、`replay-round-trip.e2e` 和 `seeded-history.e2e`)被排除出注册在 client 侧的 `apps/web` 工程。这三个文件及其共享的 `support.ts` 逐文件纳入 `tsconfig.host.json`——一个程序不能同时持有 cordis `Context` 合并的两侧。 ### 模式与 fixture -`DSH_SNAPSHOT` 以内联 spec 分支选择 replay(默认,无密钥)、record(带密钥)或 refresh(无密钥)——TUI 的形态,不是套件工厂:两个场景撑不起 acp-snapshot 工厂机制,且真正共享的部分已被导出(`scrubRequestHeaders`、`parseSessionLog`、`installLlmReplay`)。每个 spec 切分为驱动步骤(输入、发送、`whenTurnSettled`——所有模式都执行,绝不等待模型内容选择器,因此 record 不会因真实模型答法不同而挂起)与断言步骤(仅 replay/refresh)。Record = 经真实输入框实时驱动 + 采收内存中的 `session.header`/`session.events`(TUI 的 `rawSessionLog` 形态——无需文件解压)+ `scrubRequestHeaders` + `{{sessionId}}`/`{{cwd}}` token 化;随后一次无密钥 refresh 重新生成 `ui.expected.md`。两个场景的 fixture 都经此流程对本组装录制。一条漂移防线把每个 spec 的驱动提示词与 fixture 录制的 `user/message` 绑定。fixture 清单防线保持每个场景目录封闭(精确文件集合,每个 JSONL 都是脱敏不动点)。Web fixture 全部脱敏请求头且不钉任何头类别,沿用 TUI 先例而非[钉住请求头](2026-07-06-pin-request-header-content-in-one-scenario.md)的严格读法——见「暂缓」。 +`DSH_SNAPSHOT` 以内联 spec 分支选择 replay(默认,无密钥)、record(带密钥)或 refresh(无密钥)——TUI 的形态,不是套件工厂:两个场景撑不起 acp-snapshot 工厂机制,且真正共享的部分已被导出(`scrubRequestHeaders`、`parseSessionLog`、`installLlmReplay`)。每个 spec 切分为驱动步骤(输入、发送、`whenTurnSettled`——所有模式都执行,绝不等待模型内容选择器,因此 record 不会因真实模型答法不同而挂起)与断言步骤(仅 replay/refresh)。Record = 经真实输入框实时驱动 + 采收内存中的 `session.header`/`session.events`(TUI 的 `rawSessionLog` 形态——无需文件解压)+ `scrubRequestHeaders` + `{{sessionId}}`/`{{cwd}}`/`{{rpcId}}` token 化;随后一次无密钥 refresh 重新生成 `ui.expected.md`。两个场景的 fixture 都经此流程对本组装录制。一条漂移防线把每个 spec 的驱动提示词与 fixture 录制的 `user/message` 绑定。fixture 清单防线保持每个场景目录封闭(精确文件集合,每个 JSONL 都是脱敏不动点,不含当次运行的 `rpcId`)。Web fixture 全部脱敏请求头且不钉任何头类别,沿用 TUI 先例而非[钉住请求头](2026-07-06-pin-request-header-content-in-one-scenario.md)的严格读法——见「暂缓」。 ### 场景 -1. **`replay-round-trip`**——新会话,经真实输入框发送提示词,回放流式输出推理(reasoning)+ 一次在临时工作区真实执行的 `bash` 工具调用 + 最终文本(15ms 节奏)。断言安定后的 markdown、aria 预期输出与内联世界状态(bash `tool/call`、完成的 `turn/end`、>10 个分片事件)。 +1. **`replay-round-trip`**——新会话,经真实输入框发送提示词,回放流式输出推理(reasoning)+ 一次在临时工作区真实执行的 `bash` 工具调用 + 最终文本(15ms 节奏)。断言安定后的 markdown、aria 预期输出与内联世界状态(这次 bash 调用的已持久化工具结果严格等于 `WEB_E2E_OK\n`、完成的 `turn/end`、>10 个分片事件)。 2. **`seeded-history`**——冷播种一份已录会话;侧栏列出它(分组行 → 会话行,默认折叠),打开后纯凭日志经 `session.history` 内的隐式冷恢复挂载渲染工具卡片与文本——replay 下零模型调用,因此没有任何绑定约束;record 模式实时驱动同一轮(真实 `read` 工具读取播种的工作区文件)来产出种子。 ### CI 立场 @@ -65,9 +65,9 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu **`packages/support/web-snapshot` 包 + `defineWebSnapshotSuite` 工厂。** 已否决:驱动 chromium 的源码在无浏览器的覆盖率 runner 上无法诚实保持逐文件 100%,且两个场景就上工厂是从单一消费方过度泛化,真正共享的逻辑已从受门禁的包中导出。重启条件:出现第二个 web 形态消费方,或 ≥6 个场景的内联分支被证实各自漂移;届时包边界将画在无浏览器一侧。 -**第二份提交的规范化会话日志预期输出。** 已否决:日志表面已由 ACP/headless/TUI 套件经同一循环与持久化钉住;在此只会翻倍刷新成本并重复测试下层。内联在 `host.ctx` 事件上的世界状态断言保住了验证世界的义务。 +**第二份提交的规范化会话日志预期输出。** 已否决:日志表面已由 ACP/headless/TUI 套件经同一循环与持久化钉住;在此只会翻倍刷新成本并重复测试下层。内联在根上下文事件上的世界状态断言保住了验证世界的义务。 -**以 `DSH_SNAPSHOT` 回放分支拉起 `dsh web` bin。** 已否决:它需要在产品 bin 里加测试模式分支和环境变量管道,而进程内路线用的是零产品改动的导出生产函数;bin 的薄胶水已由无密钥 CLI 冒烟覆盖。只有 web host 某天 Loader 化它才免费——评审中已否决,并重申了应用内组装的裁定。 +**以 `DSH_SNAPSHOT` 回放分支拉起 `dsh web` bin。** 已否决:它需要在交付的 CLI 中增加测试专用回放分支和环境变量管道。进程内 scaffold 已加载同一份 `apps/cli/cordis.yml`;只剩 argv、profile JSON 和 `AppCLIEntry` 胶水不在其覆盖范围内,而这些路径已由无密钥 CLI 冒烟覆盖。 **为可测试性改 wire 协议。** 已否决:契约已有第一等的无密钥同构 seam(`InProcessApiClient(toFetchHandler(api))`),逐事件不合批的 SSE 恰是回放在浏览器中可观测的原因,测试一条不再交付的 wire 会颠倒该层的存在意义。 @@ -81,7 +81,7 @@ Web GUI 以一条真实组装链交付——chromium 页面 → client 插件 bu ## 暂缓 -- **Web 头类别钉住**:web fixture 处处 token 化 `{{system}}`/`{{tools}}`,没有场景钉住 bootHost 组装的提示词/工具 schema(`TODO(web-header-pin)`——scaffold 的 `recordFixture` JSDoc 有标记)。沿用 TUI 处处脱敏先例;当 web 组装的请求头与其镜像的 repl 组合进一步分叉时重审。 +- **Web 头类别钉住**:web fixture 处处 token 化 `{{system}}`/`{{tools}}`,没有场景钉住 web 组合的提示词/工具 schema(`TODO(web-header-pin)`——scaffold 的 `recordFixture` JSDoc 有标记)。沿用 TUI 处处脱敏先例;当 web 组装的请求头与其镜像的 repl 组合进一步分叉时重审。 - **CI 浏览器供给**:推翻 CI 无浏览器裁定,分阶段标准见上(`TODO(ci-browser)`)。 - **恢复后追问场景**:真实 wire 上的历史/实时缝合路径;当该代码变更或回归时作为独立场景补充。 diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index 8baabde0ba..131f3fa5fd 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -80,9 +80,16 @@ describe('web e2e: fresh round trip through the real assembly', () => { // legal — the chunk-event assertions below carry incrementality. }) await expect.poll(() => page.getByText('DONE', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1) - // World state, not self-report: bash really ran and the turn closed clean. - const toolCalls = sessionEvents.filter(e => e.type === 'tool/call') - expect(toolCalls.map(e => (e as SessionEvent & { data: { name: string } }).data.name)).toContain('bash') + // World state, not self-report: the real bash executor returned the exact + // command output, and the turn closed cleanly. + const bashCall = sessionEvents.find(event => event.type === 'tool/call' && event.data.name === 'bash') + if (bashCall?.type !== 'tool/call') throw new Error('the replayed turn did not call the bash tool') + const bashResult = sessionEvents.find(event => + event.type === 'tool/result' && event.data.callId === bashCall.data.callId) + if (bashResult?.type !== 'tool/result') throw new Error('the bash tool call produced no durable result') + expect(bashResult.data.isError).toBe(false) + expect(bashResult.data.content.filter(block => block.type === 'text').map(block => block.text).join('')) + .toBe('WEB_E2E_OK\n') const turnEnds = sessionEvents.filter(e => e.type === 'turn/end') expect(turnEnds.length).toBe(1) expect((turnEnds[0] as SessionEvent & { data: { reason: { kind: string } } }).data.reason.kind).toBe('completed') diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index d858e0f7ad..babfbde919 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -105,6 +105,15 @@ export interface LaunchOptions { paceMs?: number } +/** Dispose the booted tree and remove both owned temp roots, reporting every independent cleanup failure. */ +async function cleanupScaffoldWorld(ctx: Context, workspaceCwd: string, persistenceRoot: string): Promise { + const failures: unknown[] = [] + await Promise.resolve(ctx.fiber.dispose()).catch((error: unknown) => failures.push(error)) + await rm(workspaceCwd, { recursive: true, force: true }).catch((error: unknown) => failures.push(error)) + await rm(persistenceRoot, { recursive: true, force: true }).catch((error: unknown) => failures.push(error)) + return failures +} + /** * Boot the real web composition under the current snapshot mode. * @param options - replay fixture selection and pacing. @@ -120,7 +129,15 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise failures.push(cleanupError)) + if (failures.length > 1) throw new AggregateError(failures, 'web scaffold temp-root setup failed') + throw error + } // The include patch set — the same mechanism AppCLIEntry and the ACP // snapshot overlay use, applied over the SAME shipped tree (a patch id that @@ -143,9 +160,11 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise undefined) - await rm(persistenceRoot, { recursive: true, force: true }).catch(() => undefined) + if (process.cwd() !== originalCwd) process.chdir(originalCwd) + const cleanupFailures = await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot) + if (cleanupFailures.length > 0) { + throw new AggregateError([error, ...cleanupFailures], 'web scaffold setup failed and cleanup was incomplete') + } throw error } finally { if (process.cwd() !== originalCwd) process.chdir(originalCwd) } - const port = ctx.get('httpServer')?.port - if (port === undefined) { - await ctx.fiber.dispose() - throw new Error('web e2e scaffold: httpServer service missing after settled boot') - } - // Fill the open llm seam on the settled root ctx (llm-deepseek is disabled - // in keyless modes; a scenario with no fixture leaves the seam empty so a - // stray stream fails loud with NO_ADAPTER). The direct install, unlike the - // plugin row, returns the ReplayHandle for the teardown consumption check. - let replayHandle: ReplayHandle | undefined - if (mode !== 'record' && options.replayFixture !== undefined) { - replayHandle = installLlmReplay(ctx, { - file: options.replayFixture, - providers: REPLAY_PROVIDERS, - ...(options.paceMs === undefined ? {} : { paceMs: options.paceMs }), - }) - } - return { mode, baseUrl: `http://127.0.0.1:${port}`, @@ -222,9 +241,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise failures.push(e)) - await rm(workspaceCwd, { recursive: true, force: true }).catch((e: unknown) => failures.push(e)) - await rm(persistenceRoot, { recursive: true, force: true }).catch((e: unknown) => failures.push(e)) + failures.push(...await cleanupScaffoldWorld(ctx, workspaceCwd, persistenceRoot)) if (failures.length > 0) throw new AggregateError(failures, 'web scaffold teardown failed') }, } @@ -247,9 +264,9 @@ function rawSessionLog(session: Session): string { * Record-mode fixture write-back: harvest the live session, scrub request * headers to {{system}}/{{tools}} (TODO(web-header-pin): the web lane pins no * header class — a deliberate deviation logged in the Agent Note's deferred - * work), tokenize the run-local session id and cwd ({{sessionId}}/{{cwd}}, - * the committed ACP fixture convention — re-records then diff only on real - * content), and write the committed fixture. + * work), tokenize the run-local session id, cwd, and browser RPC id + * ({{sessionId}}/{{cwd}}/{{rpcId}}, the committed fixture convention — + * re-records then diff only on real content), and write the fixture. * @param scaffold - the record-mode scaffold. * @param sessionId - the driven session. * @param fixturePath - the committed session.jsonl / seed.jsonl target. @@ -260,6 +277,7 @@ export async function recordFixture(scaffold: WebScaffold, sessionId: SessionId, const tokenized = scrubRequestHeaders(rawSessionLog(agent.session)) .split(sessionId).join('{{sessionId}}') .split(scaffold.workspaceCwd).join('{{cwd}}') + .replace(/"rpcId":"[^"]+"/g, '"rpcId":"{{rpcId}}"') await writeFile(fixturePath, tokenized) } @@ -389,7 +407,7 @@ export async function compareOrRefreshGolden(goldenPath: string, actual: string, /** * Fixture-inventory guard (the TUI afterAll shape): the scenario directory * holds exactly the expected files and every committed JSONL is a scrub - * fixed-point (no request-header bulk escaped the record write-back). + * fixed-point without a run-local browser RPC id. * @param dir - the scenario snapshot directory. * @param expected - the exact expected file inventory. */ @@ -399,6 +417,8 @@ export async function assertFixtureInventory(dir: string, expected: string[]): P for (const entry of entries.filter(name => name.endsWith('.jsonl'))) { const content = await readFile(join(dir, entry), 'utf8') expect(scrubRequestHeaders(content), `${dir}/${entry} carries request-header bulk`).toBe(content) + expect(content, `${dir}/${entry} carries a run-local rpcId`) + .not.toMatch(/"rpcId":"(?!\{\{rpcId\}\})[^"]+"/) } } diff --git a/apps/web/tests/snapshots/fresh-round-trip/session.jsonl b/apps/web/tests/snapshots/fresh-round-trip/session.jsonl index 9bd1959879..21218b459d 100644 --- a/apps/web/tests/snapshots/fresh-round-trip/session.jsonl +++ b/apps/web/tests/snapshots/fresh-round-trip/session.jsonl @@ -1,6 +1,6 @@ {"type":"session","version":0,"id":"{{sessionId}}","createdAt":1784973850091,"cwd":"{{cwd}}/workspace"} -{"type":"turn/start","seq":0,"time":1784973850102,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user","rpcId":"c4e068dc-c277-46ae-9713-6a2694027fb5"}}}} -{"type":"user/message","seq":1,"time":1784973850103,"data":{"content":[{"type":"text","text":"Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"c4e068dc-c277-46ae-9713-6a2694027fb5"}},"surfaceOp":"append"} +{"type":"turn/start","seq":0,"time":1784973850102,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user","rpcId":"{{rpcId}}"}}}} +{"type":"user/message","seq":1,"time":1784973850103,"data":{"content":[{"type":"text","text":"Use the bash tool to run exactly: echo WEB_E2E_OK. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpcId}}"}},"surfaceOp":"append"} {"type":"session/title","seq":2,"time":1784973850105,"data":{"title":"Use the bash tool to","messageSeqs":[1],"source":{"kind":"fallback"}}} {"type":"step/start","seq":3,"time":1784973850164,"data":{"turn":1,"step":1}} {"type":"request/header","seq":4,"time":1784973850165,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}","messagePrefix":["{{messagePrefix}}"]},"reason":"initial"}} diff --git a/apps/web/tests/snapshots/seeded-history/seed.jsonl b/apps/web/tests/snapshots/seeded-history/seed.jsonl index 0f61158a54..27e31004bc 100644 --- a/apps/web/tests/snapshots/seeded-history/seed.jsonl +++ b/apps/web/tests/snapshots/seeded-history/seed.jsonl @@ -1,6 +1,6 @@ {"type":"session","version":0,"id":"{{sessionId}}","createdAt":1784974100747,"cwd":"{{cwd}}/workspace"} -{"type":"turn/start","seq":0,"time":1784974100758,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user","rpcId":"f95c6f1c-f1b4-42bf-ba40-c05ae0647a70"}}}} -{"type":"user/message","seq":1,"time":1784974100759,"data":{"content":[{"type":"text","text":"Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"f95c6f1c-f1b4-42bf-ba40-c05ae0647a70"}},"surfaceOp":"append"} +{"type":"turn/start","seq":0,"time":1784974100758,"data":{"turn":1,"trigger":{"kind":"message","source":{"kind":"user","rpcId":"{{rpcId}}"}}}} +{"type":"user/message","seq":1,"time":1784974100759,"data":{"content":[{"type":"text","text":"Use the read tool twice in one assistant message: read a.txt and b.txt. Then reply with the single word DONE and stop."}],"source":{"kind":"user","rpcId":"{{rpcId}}"}},"surfaceOp":"append"} {"type":"session/title","seq":2,"time":1784974100761,"data":{"title":"Use the read tool twice","messageSeqs":[1],"source":{"kind":"fallback"}}} {"type":"step/start","seq":3,"time":1784974100827,"data":{"turn":1,"step":1}} {"type":"request/header","seq":4,"time":1784974100828,"data":{"header":{"config":{"provider":"deepseek","model":"deepseek-v4-flash"},"system":"{{system}}","tools":"{{tools}}","messagePrefix":["{{messagePrefix}}"]},"reason":"initial"}} diff --git a/packages/support/llm-replay/README.md b/packages/support/llm-replay/README.md index a8d811f35b..534d289b19 100644 --- a/packages/support/llm-replay/README.md +++ b/packages/support/llm-replay/README.md @@ -2,7 +2,7 @@ A replay LLM plugin for keyless snapshot tests. It yields model streams reconstructed from a recorded **session JSONL** fixture, so a test can boot the real agent against a fixed model transcript with no API key. With `providers` configured it registers a replay-only adapter whose catalog is available to scenarios that exercise model discovery; without `providers` it installs the catch-all `llm/stream` waterfall used by tests that do not need discovery. -Its consumers are the ACP snapshot harness in `examples/acp-agent` and the `stream-json` snapshot in `examples/headless-agent`; each loads this plugin in place of a real LLM adapter. Keeping derivation and replay here places that logic under the per-file 100% coverage gate on `packages/*/src`. +Its consumers are the ACP, headless `stream-json`, and TUI snapshot suites plus the web browser e2e lane. Loader-driven suites mount this plugin in place of a real LLM adapter; the web lane installs it directly to retain the teardown consumption handle. Keeping derivation and replay here places that logic under the per-file 100% coverage gate on `packages/*/src`. ## How the fixture works diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index f6f8a5c3fc..c2fee63c70 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -4,7 +4,7 @@ "docs/architecture.md": 1800, "docs/cordis-primer.md": 600, "docs/defensive-patterns.md": 550, - "docs/testing.md": 1040, + "docs/testing.md": 1100, "examples/AGENTS.md": 310, "packages/AGENTS.md": 660, "packages/README.md": 790 From ea8b1178cda98cc945a016d75bd3e4191b35e704 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 00:02:46 +0800 Subject: [PATCH 080/113] feat(web): session list one-list, hover card, row menus, rename, manual ordering Sidebar session list grows the figma 239-10458 feature set and the workspace/session browsing region moves wholesale into ui-workspace: - Group-by menu (WorkSpace / In one list): flat mode lists every session top-level, strictly newest-first; the choice persists across reloads. - Session rows get a 500ms hover detail card (title / relative time / status line) and a ... menu (Rename / Fork session / Delete session, visual-only for now); workspace headers get ... with Rename (wired) and Delete workspace (visual-only). - workspace.rename RPC: trims, rejects duplicate titles on the create chain (workspace-name-conflict), no-op on same title; modal dialog with client-side duplicate pre-check. - workspace.insertSessionBefore RPC (DOM-insertBefore semantics, omitted anchor appends): HTML5 drag reorder of root sessions inside a workspace group; order truth stays host-side, the view refreshes from the response/changed frame. - Activity pinning removed: the session/event touchSession chain is gone; workspace accounts are manually owned (new sessions prepend, explicit reordering only). Contracts and tests updated, api catalog regenerated. - ui-sidebar reduced to the column shell (brand, fold state machine, New Session, Settings) exposing one sidebar.workspaces hole with a two-fact owner share {wide, expandSidebar}; ui-workspace owns the whole region (header, search, grouped/flat lists, dialogs, drag) plus the picker via a shared WorkspaceCreateFlow. The old sidebar.workspace picker slot and its deferral indirection are gone. - ui-primitives: Menu gains label entries, danger rows, and closeOnPointerLeave; new HoverCard (portaled, open-delay, disabled guard). Hover card and row menu never coexist. --- docs/cordis-catalog/services.md | 11 - docs/event-producer-consumer.md | 2 +- .../client/connection/src/client/fixture.ts | 55 +++ packages/client/connection/tests/fake-api.ts | 6 + .../runtime/src/client/workspaces/manager.ts | 41 +- .../runtime/src/client/workspaces/service.ts | 31 +- packages/client/runtime/tests/fake-api.ts | 9 + .../ui-primitives/src/HoverCard.module.css | 22 + .../client/ui-primitives/src/HoverCard.tsx | 109 +++++ .../client/ui-primitives/src/Menu.module.css | 21 + packages/client/ui-primitives/src/Menu.tsx | 33 +- packages/client/ui-primitives/src/index.ts | 3 +- .../client/ui-sidebar/src/client/Rows.tsx | 143 ------ .../src/client/SidebarRoot.module.css | 186 +------- .../ui-sidebar/src/client/SidebarRoot.tsx | 248 +--------- .../ui-sidebar/src/client/contract/slots.ts | 59 +-- .../client/ui-sidebar/src/client/index.ts | 15 +- .../client/ui-sidebar/tests/apply.spec.tsx | 18 +- .../ui-sidebar/tests/sidebar-root.spec.tsx | 274 ++--------- packages/client/ui-workspace/package.json | 3 + .../src/client/WorkspaceBrowser.module.css | 265 +++++++++++ .../src/client/WorkspaceBrowser.tsx | 428 ++++++++++++++++++ .../src/client/WorkspacePicker.tsx | 63 ++- .../ui-workspace/src/client/contract/slots.ts | 63 ++- .../client/ui-workspace/src/client/index.ts | 95 ++-- .../src/client/rows}/Rows.module.css | 53 ++- .../ui-workspace/src/client/rows/Rows.tsx | 285 ++++++++++++ .../client/ui-workspace/src/client/stores.ts | 36 ++ .../src/client/tree.ts | 33 +- .../client/ui-workspace/tests/apply.spec.ts | 68 +-- .../tests/rows.spec.tsx | 4 +- .../tests/tree.spec.ts | 0 .../cordis/tool-cordis/src/api-catalog.ts | 6 +- packages/host/apiproxy/src/api-proxy.ts | 69 ++- packages/host/apiproxy/src/api/rpc-map.ts | 2 + packages/host/apiproxy/src/api/rpc.schema.ts | 1 + packages/host/apiproxy/src/api/rpc.ts | 1 + .../host/apiproxy/src/api/workspace.schema.ts | 26 ++ packages/host/apiproxy/src/api/workspace.ts | 28 +- packages/host/apiproxy/src/fetch/client.ts | 8 + packages/host/apiproxy/src/fetch/handler.ts | 4 + .../apiproxy/tests/client-handler.spec.ts | 2 + .../host/apiproxy/tests/fetch-carrier.spec.ts | 12 + packages/workspace/workspace/src/entity.ts | 56 ++- packages/workspace/workspace/src/index.ts | 37 +- packages/workspace/workspace/src/types.ts | 25 +- .../workspace/tests/workspace.spec.ts | 118 +---- pnpm-lock.yaml | 4 + 48 files changed, 1948 insertions(+), 1133 deletions(-) create mode 100644 packages/client/ui-primitives/src/HoverCard.module.css create mode 100644 packages/client/ui-primitives/src/HoverCard.tsx delete mode 100644 packages/client/ui-sidebar/src/client/Rows.tsx create mode 100644 packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css create mode 100644 packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx rename packages/client/{ui-sidebar/src/client => ui-workspace/src/client/rows}/Rows.module.css (79%) create mode 100644 packages/client/ui-workspace/src/client/rows/Rows.tsx create mode 100644 packages/client/ui-workspace/src/client/stores.ts rename packages/client/{ui-sidebar => ui-workspace}/src/client/tree.ts (89%) rename packages/client/{ui-sidebar => ui-workspace}/tests/rows.spec.tsx (97%) rename packages/client/{ui-sidebar => ui-workspace}/tests/tree.spec.ts (100%) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 2e30e8602b..474f587230 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -1981,15 +1981,6 @@ get(id: WorkspaceId): Workspace | undefined */ list(): Workspace[] -/** - * Move one accounted, cwd-validated session to the front of its workspace. - * Ungrouped sessions and candidates filtered by the header check are - * no-ops. The owning workspace's relative position never changes. - * @param sessionId - Session whose activity was observed. - * @returns resolution after the possible record write. - */ -async touchSession(sessionId: SessionId): Promise - /** * Resolve by canonical directory path without creating or mutating a * workspace. A missing path rejects during `realpath`; an existing unowned @@ -2000,8 +1991,6 @@ async touchSession(sessionId: SessionId): Promise async resolveByPath(path: string): Promise ``` -Types: [SessionId](../core-data-structures/core.md) - Source: [`packages/workspace/workspace/src/index.ts:75`](../../packages/workspace/workspace/src/index.ts) ## Inherited `ctx` members (cordis core + loader/hmr/timer) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d9521f7d67..7d1e6b691a 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -36,7 +36,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:52`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`llm-replay`](../packages/support/llm-replay), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-title`](../packages/session-title/session-title) | | `session/created` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `apiproxy`, [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`llm-retry`](../packages/llm/llm-retry), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`user-approval`](../packages/ui/user-approval) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:89`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `apiproxy`, [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:101`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), `apiproxy`, [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace`](../packages/workspace/workspace), [`workspace-context`](../packages/context/workspace-context) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:101`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), `apiproxy`, [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:111`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence`](../packages/session-persistence/session-persistence) | | `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:139`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`jsonrpc`](../packages/ui/jsonrpc), [`subagent`](../packages/subagent/subagent) | | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:113`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 53c18dca5c..d6f3fa61de 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -641,6 +641,59 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { emitHost({ type: 'host/workspace-changed', workspace: { ...created } }) return ok(request, { workspace: { ...created }, created: true }) }, + rename: (request) => { + const { workspaceId, title } = request.payload + const workspace = workspaces.find(w => w.workspaceId === workspaceId) + if (workspace === undefined) { + return err(request, { + code: 'workspace-not-found', + message: `no workspace ${workspaceId}`, + details: { workspaceId }, + }) + } + const trimmed = title.trim() + if (trimmed !== workspace.title) { + if (workspaces.some(w => w.workspaceId !== workspaceId && w.title === trimmed)) { + return err(request, { + code: 'workspace-name-conflict', + message: `workspace name '${trimmed}' is already in use`, + details: { name: trimmed }, + }) + } + workspace.title = trimmed + workspace.updatedAt = new Date().toISOString() + emitHost({ type: 'host/workspace-changed', workspace: { ...workspace } }) + } + return ok(request, { workspace: { ...workspace } }) + }, + insertSessionBefore: (request) => { + const { workspaceId, sessionId, beforeSessionId } = request.payload + const workspace = workspaces.find(w => w.workspaceId === workspaceId) + if (workspace === undefined) { + return err(request, { + code: 'workspace-not-found', + message: `no workspace ${workspaceId}`, + details: { workspaceId }, + }) + } + if (!workspace.sessionIds.includes(sessionId) + || (beforeSessionId !== undefined && !workspace.sessionIds.includes(beforeSessionId))) { + return err(request, { + code: 'workspace-move-invalid', + message: `session or anchor is not accounted by workspace ${workspaceId}`, + details: { workspaceId, sessionId, ...beforeSessionId === undefined ? {} : { beforeSessionId } }, + }) + } + const without = workspace.sessionIds.filter(id => id !== sessionId) + const at = beforeSessionId === undefined ? without.length : without.indexOf(beforeSessionId) + const sessionIds = [...without.slice(0, at), sessionId, ...without.slice(at)] + if (!sessionIds.every((id, index) => id === workspace.sessionIds[index])) { + workspace.sessionIds = sessionIds + workspace.updatedAt = new Date().toISOString() + emitHost({ type: 'host/workspace-changed', workspace: { ...workspace } }) + } + return ok(request, { workspace: { ...workspace } }) + }, }, events: { async *mux(_request, signal) { @@ -757,6 +810,8 @@ export class FixtureApiClient extends AbstractApiClient { case 'host.describe': return this.api.host.describe(request) case 'workspace.list': return this.api.workspace.list(request) case 'workspace.create': return this.api.workspace.create(request) + case 'workspace.rename': return this.api.workspace.rename(request) + case 'workspace.insertSessionBefore': return this.api.workspace.insertSessionBefore(request) } } diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index faca82d5c3..eecacc9581 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -77,6 +77,12 @@ export class FakeApiClient implements IApiClient { workspace: { workspaceId: 'fk-ws' as never, path: '/f/ws', title: 'ws', sessionIds: [], createdAt: '0', updatedAt: '0' }, created: true, }))), + rename: (payload: unknown) => this.record('workspace.rename', payload, Promise.resolve(ok({ + workspace: { workspaceId: 'fk-ws' as never, path: '/f/ws', title: 'ws', sessionIds: [], createdAt: '0', updatedAt: '0' }, + }))), + insertSessionBefore: (payload: unknown) => this.record('workspace.insertSessionBefore', payload, Promise.resolve(ok({ + workspace: { workspaceId: 'fk-ws' as never, path: '/f/ws', title: 'ws', sessionIds: [], createdAt: '0', updatedAt: '0' }, + }))), } /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */ diff --git a/packages/client/runtime/src/client/workspaces/manager.ts b/packages/client/runtime/src/client/workspaces/manager.ts index 6db4e54c79..c512694816 100644 --- a/packages/client/runtime/src/client/workspaces/manager.ts +++ b/packages/client/runtime/src/client/workspaces/manager.ts @@ -1,7 +1,7 @@ /** Workspace baseline, incremental-frame, and unary-action owner. */ import type { - HostFrame, IApiClient, RpcError, RpcRequest, RpcResult, WorkspaceView, + HostFrame, IApiClient, RpcError, RpcRequest, RpcResult, SessionId, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-connection/client' import { transportError } from '@deepseek-ai/dsh-host-apiproxy/api' import { mergeOrderedBaseline } from '../ordered-baseline.ts' @@ -143,6 +143,40 @@ export class WorkspaceManager { return result } + /** + * Rename a Workspace, then publish its returned snapshot without waiting + * for the changed frame. + * @param workspaceId - target workspace. + * @param title - new display title. + * @returns the wire result. + */ + async rename(workspaceId: WorkspaceId, title: string): Promise> { + const { result } = await this.api.workspace.rename({ workspaceId, title }) + if (result.ok) this.upsert(result.value.workspace) + return result + } + + /** + * Move a session within its Workspace's manual order, then publish the + * returned snapshot without waiting for the changed frame. + * @param workspaceId - owning workspace. + * @param sessionId - accounted session to move. + * @param beforeSessionId - accounted anchor to insert before; omitted appends. + * @returns the wire result. + */ + async insertSessionBefore( + workspaceId: WorkspaceId, + sessionId: SessionId, + beforeSessionId?: SessionId, + ): Promise> { + const { result } = await this.api.workspace.insertSessionBefore({ + workspaceId, sessionId, + ...beforeSessionId === undefined ? {} : { beforeSessionId }, + }) + if (result.ok) this.upsert(result.value.workspace) + return result + } + /** * Host-frame entry. Non-workspace frames are ignored so the runtime can * fan one host stream out to both object managers. @@ -189,6 +223,11 @@ export class WorkspaceManager { private upsert(view: WorkspaceView, identity?: Workspace): void { this.refreshFrames?.push(view) const index = this.items.findIndex(item => item.getSnapshot().view?.workspaceId === view.workspaceId) + // Mutation responses and changed frames race (two carriers, no ordering): + // reject a snapshot strictly older than the installed projection so a + // late unary response cannot roll back a newer frame. + const installed = index === -1 ? undefined : this.items[index]?.getSnapshot().view + if (installed !== undefined && Date.parse(view.updatedAt) < Date.parse(installed.updatedAt)) return if (identity !== undefined) { this.items = index === -1 ? [identity, ...this.items] diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index 854c53a75f..9768a3fac2 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -2,7 +2,7 @@ import type { Context } from 'cordis' import type { - IApiClient, RpcError, WorkspaceId, WorkspaceView, + IApiClient, RpcError, SessionId, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-connection/client' import type { SnapshotStore } from '../contract/store.ts' import { createSnapshotStore } from '../contract/store.ts' @@ -100,6 +100,35 @@ export class WorkspacesService { return result.value.workspace } + /** + * Rename a Workspace. + * @param workspaceId - target workspace. + * @param title - new display title (trimmed non-empty by the Host). + * @returns the renamed Workspace view. + */ + async rename(workspaceId: WorkspaceId, title: string): Promise { + const result = await this.manager.rename(workspaceId, title) + if (!result.ok) throw new Error(`workspace rename failed: ${result.error.code}: ${result.error.message}`) + return result.value.workspace + } + + /** + * Move a session within its Workspace's manual order (DOM-insertBefore-like). + * @param workspaceId - owning workspace. + * @param sessionId - accounted session to move. + * @param beforeSessionId - accounted anchor to insert before; omitted appends. + * @returns the updated Workspace view. + */ + async insertSessionBefore( + workspaceId: WorkspaceId, + sessionId: SessionId, + beforeSessionId?: SessionId, + ): Promise { + const result = await this.manager.insertSessionBefore(workspaceId, sessionId, beforeSessionId) + if (!result.ok) throw new Error(`workspace move failed: ${result.error.code}: ${result.error.message}`) + return result.value.workspace + } + /** * Refresh the workspace baseline, reusing an in-flight pull. * @returns completion of the current or newly started workspace baseline pull. diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index 45efcf9e36..a9fbda4907 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -92,9 +92,18 @@ export class FakeApiClient implements IApiClient { onWorkspaceCreate: (payload: unknown) => Promise> = () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws'), created: true })) + onWorkspaceRename: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') })) + + onWorkspaceInsertSessionBefore: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ workspace: fakeWorkspace('fk-ws') })) + readonly workspace: IApiClient['workspace'] = { list: (payload: unknown) => this.record('workspace.list', payload, this.onWorkspaceList(payload)), create: (payload: unknown) => this.record('workspace.create', payload, this.onWorkspaceCreate(payload)), + rename: (payload: unknown) => this.record('workspace.rename', payload, this.onWorkspaceRename(payload)), + insertSessionBefore: (payload: unknown) => + this.record('workspace.insertSessionBefore', payload, this.onWorkspaceInsertSessionBefore(payload)), } /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */ diff --git a/packages/client/ui-primitives/src/HoverCard.module.css b/packages/client/ui-primitives/src/HoverCard.module.css new file mode 100644 index 0000000000..8d8a52100e --- /dev/null +++ b/packages/client/ui-primitives/src/HoverCard.module.css @@ -0,0 +1,22 @@ +/* Block, not inline-flex: consumers wrap full-width list rows and an + * inline wrapper would shrink them; the card still measures this rect. */ +.root { + position: relative; + display: block; +} + +/* Preview card (figma session hover card): 244 wide, r12, pad 12/16, the + * menu card's elevation. Surface is #2C2C2E in both themes (figma value, + * light/dark identical), so a component-level variable, not a theme token. */ +.card { + --dsw-hovercard-bg: #2C2C2E; + position: fixed; + z-index: 100; + box-sizing: border-box; + width: 244px; + padding: 12px 16px; + border-radius: 12px; + background: var(--dsw-hovercard-bg); + box-shadow: var(--dsw-shadow-lv3); + pointer-events: none; +} diff --git a/packages/client/ui-primitives/src/HoverCard.tsx b/packages/client/ui-primitives/src/HoverCard.tsx new file mode 100644 index 0000000000..58e281778e --- /dev/null +++ b/packages/client/ui-primitives/src/HoverCard.tsx @@ -0,0 +1,109 @@ +// HoverCard: delayed hover-preview card portaled to document.body. +// Same portal mechanics as Menu: the wrapper span supplies the anchor rect, +// the card is fixed-positioned at its right edge and repositions on +// scroll/resize while open. Display-only — the card ignores pointer events +// and closes the instant the pointer leaves the anchor (no close delay). + +import { useEffect, useLayoutEffect, useRef, useState } from 'react' +import type { CSSProperties, ReactNode } from 'react' +import { createPortal } from 'react-dom' +import css from './HoverCard.module.css' + +/** + * Render an anchor with a hover-triggered preview card. + * @param props.anchor - the hover target (rendered in place inside a wrapper span). + * @param props.content - card content (display-only, no pointer interaction). + * @param props.openDelayMs - hover dwell before the card shows (default 500). + * @param props.disabled - suppress opening; turning true closes an open card. + * @returns anchor wrapper with the conditional portaled card. + */ +export function HoverCard({ anchor, content, openDelayMs = 500, disabled = false }: { + anchor: ReactNode + content: ReactNode + openDelayMs?: number + disabled?: boolean +}) { + const rootRef = useRef(null) + const cardRef = useRef(null) + const timerRef = useRef | null>(null) + const [open, setOpen] = useState(false) + const [pos, setPos] = useState(null) + + const clearTimer = () => { + if (timerRef.current !== null) { + clearTimeout(timerRef.current) + timerRef.current = null + } + } + + // Owner disabling mid-hover (menu opened, drag started) closes immediately. + useEffect(() => { + if (!disabled) return + clearTimer() + setOpen(false) + }, [disabled]) + + useEffect(() => clearTimer, []) + + // Fixed-position from the anchor rect before paint; track the anchor while + // open (capture-phase scroll catches nested panes), as in Menu portal mode. + useLayoutEffect(() => { + if (!open) { setPos(null); return } + const place = () => { + const r = rootRef.current?.getBoundingClientRect() ?? null + if (r === null) return + const h = cardRef.current?.offsetHeight ?? 0 + const top = r.top + h > window.innerHeight - 8 ? window.innerHeight - h - 8 : r.top + setPos({ left: r.right + 8, top }) + } + place() + window.addEventListener('scroll', place, true) + window.addEventListener('resize', place) + return () => { + window.removeEventListener('scroll', place, true) + window.removeEventListener('resize', place) + } + }, [open]) + + // The first placement ran before the card mounted (height read 0): once the + // card's real height is measurable, correct the bottom-edge clamp. + useLayoutEffect(() => { + if (!open || pos === null || typeof pos.top !== 'number') return + const h = cardRef.current?.offsetHeight ?? 0 + if (pos.top + h > window.innerHeight - 8) { + const top = window.innerHeight - h - 8 + if (pos.top !== top) setPos({ ...pos, top }) + } + }, [open, pos]) + + const card = open && pos !== null && ( +
+ {content} +
+ ) + + return ( + { + if (disabled) return + clearTimer() + timerRef.current = setTimeout(() => { setOpen(true) }, openDelayMs) + }} + onPointerLeave={() => { + clearTimer() + setOpen(false) + }} + // Any press inside the anchor (row click, menu trigger) dismisses the + // card immediately, without waiting for the owner to flip `disabled`. + onPointerDownCapture={() => { + clearTimer() + setOpen(false) + }} + > + {anchor} + {card !== false && createPortal(card, document.body)} + + ) +} diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index b55abe094d..28c3150335 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -109,6 +109,27 @@ background: transparent; } +/* Destructive row: error text/icon, danger hover fill. */ +.danger { + color: var(--dsw-alias-state-error-primary); +} + +.danger .itemIcon { + color: var(--dsw-alias-state-error-primary); +} + +.danger:hover:not(:disabled) { + background: var(--dsw-alias-interactive-bg-hover-danger); +} + +/* Heading row: non-interactive small grey text, padding aligned with items. */ +.label { + padding: 8px 10px; + font-size: 12px; + line-height: 16px; + color: var(--dsw-alias-label-tertiary); +} + /* Separator cell (figma 122:9481): py 4 / px 2 around the hairline. */ .separator { height: 1px; diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index de015ee534..9abb6a3bb2 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -4,6 +4,7 @@ // the anchor rect, for anchors inside overflow-clipping containers (sidebar). // The owner controls `open`; outside-click closing uses one document listener // active only while open. Submenus open on hover/focus inside the same root. +// Entries also cover non-interactive `label` headings and `danger` rows. import { useEffect, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode } from 'react' @@ -19,6 +20,8 @@ export interface MenuItem { disabled?: boolean /** Leading icon (figma .Menu_cell gap 8). */ icon?: ReactNode + /** Destructive row: error-colored text/icon and danger hover fill. */ + danger?: boolean /** Nested card opened to the right on hover/focus. */ submenu?: readonly MenuItem[] } @@ -29,13 +32,24 @@ export interface MenuSeparator { id: string } -/** One primary-menu entry: a row or a separator. */ -export type MenuEntry = MenuItem | MenuSeparator +/** Non-interactive heading row above a group of items. */ +export interface MenuLabel { + type: 'label' + id: string + text: string +} + +/** One primary-menu entry: a row, a separator, or a heading label. */ +export type MenuEntry = MenuItem | MenuSeparator | MenuLabel function isSeparator(entry: MenuEntry): entry is MenuSeparator { return 'type' in entry && entry.type === 'separator' } +function isLabel(entry: MenuEntry): entry is MenuLabel { + return 'type' in entry && entry.type === 'label' +} + /** * Render an anchored dropdown menu. * @param props.open - whether the list is showing (owner-controlled). @@ -50,6 +64,8 @@ function isSeparator(entry: MenuEntry): entry is MenuSeparator { * from the anchor rect (repositions on scroll/resize while open). Use when an * ancestor's overflow clipping would crop the in-place list; default false * keeps the pure-CSS in-place behavior. + * @param props.closeOnPointerLeave - close the list when the pointer leaves + * it (default false keeps it open until outside click/Escape/selection). * @param props.getAnchorRect - portal mode only: supply the anchor rect * directly (e.g. from a host-owned trigger button) instead of measuring the * Menu's own wrapper span. Required when the wrapper isn't itself laid out at @@ -58,7 +74,7 @@ function isSeparator(entry: MenuEntry): entry is MenuSeparator { * scroll/resize; return null to skip placement for that frame. * @returns anchor wrapper with the conditional list. */ -export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align = 'start', side = 'bottom', portal = false, getAnchorRect, className }: { +export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align = 'start', side = 'bottom', portal = false, closeOnPointerLeave = false, getAnchorRect, className }: { open: boolean anchor: ReactNode items: readonly MenuEntry[] @@ -68,6 +84,7 @@ export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align align?: 'start' | 'end' side?: 'bottom' | 'top' portal?: boolean + closeOnPointerLeave?: boolean getAnchorRect?: () => DOMRect | null className?: string }) { @@ -135,11 +152,19 @@ export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align className={clsx(css.list, portal && css.portal, side === 'top' && !portal && css.sideTop, align === 'end' && !portal && css.alignEnd)} style={fixedPos ?? undefined} role="menu" + onPointerLeave={closeOnPointerLeave ? () => { onClose() } : undefined} + // React portals bubble synthetic events through the REACT tree: without + // this stop, an item click re-fires the anchor row's own onClick + // (open/toggle) after onSelect. + onClick={(e) => { e.stopPropagation() }} > {items.map(entry => { if (isSeparator(entry)) { return
} + if (isLabel(entry)) { + return
{entry.text}
+ } const hasSub = entry.submenu !== undefined && entry.submenu.length > 0 const subOpen = hasSub && openSubmenuId === entry.id return ( @@ -152,7 +177,7 @@ export function Menu({ open, anchor, items, selectedId, onSelect, onClose, align - -
- ) -} - -/** - * The selected "New session" row for a frontend Session Intent targeted to a - * real Workspace. The row disappears when the Intent is replaced or connects. - * @returns the placeholder row element. - */ -export function IntentRowItem() { - return ( -
- - - New session -
- ) -} - -/** - * One session subtree: the node's own 34px row (indent by depth, expand - * twist when it has children, running dot, relative time) plus its visible - * children, recursively — the component tree mirrors the derived tree. - * @param props.node - derived session node. - * @param props.depth - 0 = directly under the group header. - * @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.onToggle - unfold/fold a subtree by id. - * @returns the node's row followed by its children. - */ -export function SessionNodeItem({ node, depth, currentId, now, onOpen, onToggle }: { - node: SessionNode - depth: number - currentId: string | undefined - now: number - onOpen: (id: SessionNode['id']) => void - onToggle: (id: SessionNode['id']) => void -}) { - const row = node - const selected = node.id === currentId - // Rail (figma session cell: pad 8, twist slot 16, status slot 16, gap 4 to - // the title): both slots are always reserved so titles align whether or not - // the twist/dot is lit. Extra depth rides the left padding. - const ownRow = ( -
{ onOpen(node.id) }} - > - {row.hasChildren - ? ( - - ) - : } - {row.running && } - {row.title} - {formatRelativeTime(row.updatedAt, now)} -
- ) - return ( - <> - {ownRow} - {node.children.map(child => ( - - ))} - - ) -} diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css index 591aef2330..729855cdde 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css @@ -48,7 +48,6 @@ refresh straight into the collapsed state renders statically. */ .railIn .iconButton, .railIn .newSession, -.railIn .searchButton, .railIn .foot { animation: rail-in 150ms var(--ds-ease-in-out) 100ms backwards; } @@ -184,133 +183,9 @@ max-width: 0; } -/* Section header: 36px, "WorkSpace" label + group-by / new-workspace buttons; - the right-anchored new-workspace button is the row's rail survivor. */ -.sectionHeader { - flex: none; - display: flex; - align-items: center; - justify-content: flex-end; - gap: 4px; - height: 36px; - padding-left: 12px; - margin-bottom: 4px; - box-sizing: border-box; - border-radius: 12px; - overflow: hidden; - color: var(--dsw-alias-label-tertiary); -} - -.collapsed .sectionHeader { - height: 36px; - padding-left: 0; - margin-bottom: 12px; -} - -.sectionLabel { - flex: 1; - min-width: 0; - overflow: hidden; - white-space: nowrap; - line-height: 20px; -} - -/* Search input: 38px capsule (figma 133:7649); collapsed it renders as the - rail's search control. Upstream binds a dedicated design-system variable (light - #F1F3F5 / dark #1B1B1C) matching no shipped alias — a component token - pinned to the static scale mirrors it (ruled compliant: indirect via - custom property, upstream-variable equivalent). */ -.search { - --dsh-search-input-fill: var(--dsw-static-neutral-bluish-75); - flex: none; - display: flex; - align-items: center; - gap: 8px; - height: 38px; - margin: 0 2px 12px; /* bottom: former listArea gap 4 + own 8 (spec padB12 to the first cell) */ - padding: 0 14px; - box-sizing: border-box; - border: 1px solid var(--dsw-alias-border-l2); - border-radius: 24px; - background: var(--dsh-search-input-fill); - color: var(--dsw-alias-label-caption); - overflow: hidden; -} - -:global(body[data-ds-dark-theme]) .search { - --dsh-search-input-fill: var(--dsw-static-neutral-bluish-900); -} - -.collapsed .search { - height: 36px; - padding: 0; - margin: 0 0 12px; - gap: 0; - border-color: transparent; - background: transparent; -} - -/* The capsule's leading icon, upgraded to the rail's search control. While - expanded it is decorative: pointer-events off so clicks reach the label - (native input focus); collapsed it becomes the hit target. */ -.searchButton { - flex: none; - display: inline-flex; - align-items: center; - justify-content: center; - border: none; - border-radius: 50%; - padding: 0; - background: transparent; - pointer-events: none; - color: inherit; -} - -.collapsed .searchButton { - width: 36px; - height: 36px; - pointer-events: auto; - cursor: pointer; - color: var(--dsw-alias-label-primary); -} - -.collapsed .searchButton:hover { - background: var(--dsw-alias-interactive-bg-hover); -} - -.searchInput { - flex: 1; - min-width: 0; - border: none; - outline: none; - background: transparent; - font-size: 14px; - line-height: 20px; - color: var(--dsw-alias-label-primary); -} - -.searchInput::placeholder { - color: var(--dsw-alias-label-tertiary); -} - -.clearButton { - flex: none; - display: inline-flex; - align-items: center; - justify-content: center; - width: 28px; - height: 28px; - border: none; - border-radius: 50%; - padding: 0; - background: transparent; - cursor: pointer; - color: var(--dsw-alias-label-secondary); -} - -/* Tree seat: always mounted so the foot never moves; the tree content inside - is wide-only and clips while the column squeezes. */ -.listArea { +/* Region seat: always mounted so the foot never moves; the browser inside + handles its own wide/rail content. */ +.regionArea { flex: 1; min-height: 0; display: flex; @@ -318,60 +193,6 @@ overflow: hidden; } -/* Relative for the bottom fade overlay. */ -.treeBody { - flex: 1; - min-height: 0; - display: flex; - flex-direction: column; - position: relative; -} - -/* Bottom fade (figma 133:7666): 72px overlay pinned to the visible bottom, - transparent -> sidebar fill so it tracks the theme. */ -.fade { - position: absolute; - left: 0; - right: 0; - bottom: 0; - height: 72px; - background: linear-gradient(to bottom, transparent, var(--dsw-specific-sidebar-fill)); - pointer-events: none; -} - -/* Tree list: the only scrolling region. Block, not a flex column: as flex - items the 54/34 rows would shrink under content overflow (scrollHeight - collapses onto clientHeight and wheel scrolling dies); block children keep - their design heights and the 4px rhythm rides margins instead of gap. */ -.list { - flex: 1; - min-height: 0; - overflow-y: auto; - padding-bottom: 12px; -} - -/* One workspace section: header row + expanded session run. Rows inside - keep the former flat-list 4px gap as sibling margins; the inter-group - breathing room (figma 133:7661 batch separator, 20px after an expanded - run) rides the NEXT section's top margin so the last group adds none. */ -.groupSection > * + * { - margin-top: 4px; -} - -.groupSection + .groupSection { - margin-top: 4px; -} - -.groupSection:has([aria-expanded='true']) + .groupSection { - margin-top: 20px; -} - -.empty { - padding: 16px 12px; - color: var(--dsw-alias-label-tertiary); - font-size: 13px; -} - /* Foot: settings entry (figma 133:7668, 49 hug): the former 18/10 vertical margins fold into the row so the hover pill spans the full 49px. */ .foot { @@ -418,7 +239,6 @@ .fading > *, .railIn .iconButton, .railIn .newSession, - .railIn .searchButton, .railIn .foot { transition: none; animation: none; diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx index 931eb1ba17..bcb03780d5 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx @@ -1,170 +1,38 @@ /** - * Collapse is a slide plus crossfade: content freezes at its expanded - * width (inline style) and fades out in place while the sliding column - * (AppFrame grid tracks) clips it — nothing reflows mid-slide. At settle - * the wide-only content (brand, labels, input, tree) unmounts, dropping - * the sessions subscription, and the control rows snap to the 56px rail - * (one icon each, same top-down order) fading in as the slide ends. Rail - * search expands and focuses the search box. + * Sidebar shell: column geometry only. Collapse is a slide plus crossfade: + * content freezes at its expanded width (inline style) and fades out in place + * while the sliding column (AppFrame grid tracks) clips it — nothing reflows + * mid-slide. At settle the wide-only content unmounts and the control rows + * snap to the 56px rail (one icon each, same top-down order) fading in as the + * slide ends. The workspace/session browsing region between the New Session + * button and the foot is the `sidebar.workspaces` registrant's; the shell + * hands it the wide flag and an expand request callback. */ -import { useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import clsx from 'clsx' import { BrandWordmark, FishLogo, - IconCloseFill14, IconNewChatOutline16, IconPanelLeftOutline16, IconPersonalizationOutline16, - IconProjectAddOutline16, IconSearchOutline16, IconSettingsOutline14, - Menu, Tooltip, + IconNewChatOutline16, IconPanelLeftOutline16, IconSettingsOutline14, + Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' import type { SidebarRootComponentProps } from './contract/slots.ts' -import { deriveGroups, UNGROUPED_KEY } from './tree.ts' -import { IntentRowItem, ProjectRowItem, SessionNodeItem } from './Rows.tsx' import css from './SidebarRoot.module.css' /** Wide-content unmount delay; matches the 150ms wide-content fade-out. */ const COLLAPSE_SETTLE_MS = 150 -/** Column slide length (--ds-transition-duration-slow): rail-search focus waits it out — focus() forces a synchronous layout and would jank the slide. */ -const EXPAND_SLIDE_MS = 300 - -const GROUP_BY_ITEMS = [ - { id: 'workspace', label: 'Workspace' }, - // Only workspace grouping is implemented. - { id: 'update', label: 'Update', disabled: true }, - { id: 'status', label: 'Status', disabled: true }, -] - -/** Immutable membership toggle for the local expansion arrays. */ -function toggled(list: readonly string[], key: string): string[] { - return list.includes(key) ? list.filter((k) => k !== key) : [...list, key] -} - -/** Group-by strategy menu; own open state so it resets with the wide chrome. */ -function GroupByMenu() { - const [open, setOpen] = useState(false) - return ( - { setOpen(false) }} - items={GROUP_BY_ITEMS} - selectedId="workspace" - onSelect={() => { setOpen(false) }} - align="end" - anchor={( - - )} - /> - ) -} - -type SessionTreeProps = Pick< - SidebarRootComponentProps, - 'useSessions' | 'startSession' | 'open' -> & { - workspaces: readonly WorkspaceView[] - /** Live search filter owned by the root (the query outlives the tree). */ - query: string -} - -/** The scrolling session tree; unmounting at collapse settle drops the sessions subscription and expansion state. */ -function SessionTree({ useSessions, startSession, open, workspaces, query }: SessionTreeProps) { - const list = useSessions((s) => s) - const current = list.current - const [expandedProjects, setExpandedProjects] = useState([]) - const [expandedSessions, setExpandedSessions] = useState([]) - // Re-expand when publication moves the selected intent into a real Workspace. - const intent = list.intent - const intentWorkspaceId = intent?.target.kind === 'workspace' - ? intent.target.workspaceId - : undefined - const currentGroup = current === undefined - ? undefined - : intent?.sessionId === current - ? intentWorkspaceId - : (workspaces.find(w => w.sessionIds.includes(current))?.workspaceId as string | undefined) - ?? UNGROUPED_KEY - useEffect(() => { - if (current === undefined || currentGroup === undefined) return - setExpandedProjects((l) => (l.includes(currentGroup) ? l : [...l, currentGroup])) - }, [current, currentGroup]) - const groups = useMemo( - () => deriveGroups(list, workspaces, { expandedProjects, expandedSessions, query }), - [list, workspaces, expandedProjects, expandedSessions, query], - ) - const now = Date.now() - - return ( -
-
- {groups.length === 0 && ( -
{query === '' ? 'No sessions yet' : 'No matches'}
- )} - {groups.map(group => ( - // Group section: header row + expanded session subtree. The - // inter-group breathing room (former flat-list batch separator) - // is the section's own margin (SidebarRoot.module.css). -
- { setExpandedProjects((l) => toggled(l, group.key)) }} - onCreate={() => { - if (group.workspaceId !== undefined) startSession(group.workspaceId) - }} - /> - {group.intentHere && } - {group.sessions.map(node => ( - { setExpandedSessions((l) => toggled(l, id)) }} - /> - ))} -
- ))} -
- -
- ) -} - /** - * Render the sidebar column. + * Render the sidebar column shell. * @param props - composed slot props (runtime share + injected callbacks, contract/slots.ts). * @returns the sidebar element tree. */ export function SidebarRoot({ collapsed, width, - useSessions, - useWorkspaces, startSession, - open, toggleSidebar, renderSlot, }: SidebarRootComponentProps) { - const workspaces = useWorkspaces(state => state.items) - // The query outlives the tree and the input (both wide-only) so collapsing - // does not silently drop an in-progress filter. - const [query, setQuery] = useState('') - const searchInput = useRef(null) - // Section-header + opens the workspace picker (same popover in wide and - // rail states; the hole sits beside the button and opens rightward). - const [wsPickerOpen, setWsPickerOpen] = useState(false) - // Placement anchor for the picker popover: the slot span renders elsewhere - // in the DOM, so the picker positions off this button's rect. - const wsPlusRef = useRef(null) - // Wide content stays mounted while the collapse animates (fading via // .collapsed .wide), unmounts at settle, and remounts right away on expand. const [settled, setSettled] = useState(collapsed) @@ -186,19 +54,6 @@ export function SidebarRoot({ const everWide = useRef(!collapsed) if (!collapsed) everWide.current = true - // Rail search = expand + land in the search box: the flag arms before the - // expand toggle; once expanded the input is mounted and takes focus. - const [searchOnExpand, setSearchOnExpand] = useState(false) - useEffect(() => { - if (!collapsed && searchOnExpand) { - const timer = window.setTimeout(() => { - searchInput.current?.focus({ preventScroll: true }) - setSearchOnExpand(false) - }, EXPAND_SLIDE_MS) - return () => { window.clearTimeout(timer) } - } - }, [collapsed, searchOnExpand]) - return (
-
- {wide && Workspaces} - {wide && } - - - - {/* Picker hole beside the + (same site in wide and rail states). */} - {renderSlot('sidebar.workspace', { - open: wsPickerOpen, - anchorRef: wsPlusRef, - onPick: (workspaceId) => { - setWsPickerOpen(false) - startSession(workspaceId) - }, - onClose: () => { setWsPickerOpen(false) }, + {/* The browsing region fills the column between the controls and the + foot in both states; its rail icon column rides the same slot. */} +
+ {renderSlot('sidebar.workspaces', { + wide, + expandSidebar: () => { if (collapsed) toggleSidebar() }, })}
- {/* Expanded: the row is a click-to-focus field (the leading icon is - decorative). Collapsed: the icon is the rail's search control. */} -
{ if (!collapsed) searchInput.current?.focus() }}> - - - - {wide && ( - { setQuery(e.target.value) }} - /> - )} - {wide && query !== '' && ( - - )} -
- - {/* Always-mounted seat: its flex slot pins the foot to the bottom in - both states while the tree itself is wide-only. */} -
- {wide && ( - - )} -
-
{wide && Settings} diff --git a/packages/client/ui-sidebar/src/client/contract/slots.ts b/packages/client/ui-sidebar/src/client/contract/slots.ts index 0334ca88c9..1fd84312fa 100644 --- a/packages/client/ui-sidebar/src/client/contract/slots.ts +++ b/packages/client/ui-sidebar/src/client/contract/slots.ts @@ -1,69 +1,54 @@ /** * Sidebar slot contract: the registrant-side props composition for the - * layout-owned `sidebar` slot and the Workspace picker hole declared here. - * The runtime share combines layout-owned page state and actions with the - * global useSessions and useWorkspaces hooks; the injected share adds the - * runtime navigation actions and sidebar toggle. + * layout-owned `sidebar` slot, plus the workspace-browser hole this shell + * declares. The shell owns column geometry (fold state machine, brand row, + * New Session, Settings); everything between the section header and the list + * bottom is the `sidebar.workspaces` registrant's (ui-workspace). */ -import type { RefObject } from 'react' import type { PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls ui-layout's SlotMap merge (the 'sidebar' entry) into every // program that sees this contract, so PropsRuntime<'sidebar'> resolves. import type {} from '@deepseek-ai/dsh-client-ui-layout/client' -import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' +import type { WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** - * The workspace picker hole in the sidebar section header (anchored at - * the + button). Declared by this package's 'sidebar' entry (declaring - * is claiming); ui-workspace registers the picker. + * The workspace/session browsing region: section header, search, the + * grouped/flat session list, and every workspace dialog. Declared by this + * package's 'sidebar' entry (declaring is claiming); ui-workspace + * registers the browser. */ - 'sidebar.workspace': { kind: 'single'; scope: 'root'; owner: SidebarWorkspaceOwnerProps } + 'sidebar.workspaces': { kind: 'single'; scope: 'root'; owner: SidebarSectionOwnerProps } } } /** - * Owner share of the sidebar workspace hole: popover geometry plus the - * sidebar's pick semantics. The picked Host Workspace is already real; the - * callback starts a frontend Session Intent targeted to it. + * Owner share of the browser hole — the only facts crossing the shell/region + * seam. Business data and actions arrive through the region's own inject. */ -export interface SidebarWorkspaceOwnerProps { - /** Popover visibility (+ button toggle state, host-local). */ - open: boolean - /** - * The + button element — the popover's placement anchor. The picker's - * slot span renders elsewhere in the DOM, so without this the menu - * positions off the zero-size placement span (order-dependent). Optional - * only until the host passes it; absent falls back to in-place placement. - */ - anchorRef?: RefObject - /** Start a frontend Session in a selected or newly created real Workspace. */ - onPick: (workspaceId: WorkspaceId) => void - /** Close the popover (outside click / Escape / post-pick). */ - onClose: () => void +export interface SidebarSectionOwnerProps { + /** Shell fold-state output: wide renders the full browser, rail the icon column. */ + wide: boolean + /** Rail icons request expansion; the browser rides the wide flip for focus. */ + expandSidebar: () => void } /** * Registrant-private injected share (arrives via the register inject - * factory). Host Workspace and Session data use the global framework hooks; - * navigation and panel actions are plain callbacks, and viewing state remains - * component-local. A type alias supplies the implicit index signature required - * by the registry. + * factory). The shell keeps only its own controls: starting a Session from + * the New Session button and toggling the column. */ export type SidebarRootInjected = { /** Start or replace the current frontend Session Intent. */ startSession: (workspaceId?: WorkspaceId, prompt?: string) => void - /** Open a real Session. */ - open: (sessionId: SessionId) => void /** Toggle the sidebar column through the layout service. */ toggleSidebar: () => void } /** - * Full component props: layout owner state/actions plus global useSessions - * and useWorkspaces, the declared Workspace picker render share, and this - * package's injected callback. No store is registered. + * Full component props: layout owner state/actions plus the browser hole's + * render share and this package's injected callbacks. No store is registered. */ export type SidebarRootComponentProps = - PropsRuntime<'sidebar'> & PropsRenderSlots<'sidebar.workspace'> & SidebarRootInjected + PropsRuntime<'sidebar'> & PropsRenderSlots<'sidebar.workspaces'> & SidebarRootInjected diff --git a/packages/client/ui-sidebar/src/client/index.ts b/packages/client/ui-sidebar/src/client/index.ts index 0a1c8ebb12..0493ef2279 100644 --- a/packages/client/ui-sidebar/src/client/index.ts +++ b/packages/client/ui-sidebar/src/client/index.ts @@ -1,28 +1,27 @@ -/** Registers the sidebar UI into the layout-owned slot. */ +/** Registers the sidebar shell into the layout-owned slot. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import type { SidebarRootInjected } from './contract/slots.ts' import { SidebarRoot } from './SidebarRoot.tsx' -export type { SidebarRootComponentProps, SidebarRootInjected, SidebarWorkspaceOwnerProps } from './contract/slots.ts' +export type { SidebarRootComponentProps, SidebarRootInjected, SidebarSectionOwnerProps } from './contract/slots.ts' /** Services required by the sidebar plugin. */ -export const inject = ['slots', 'layout', 'sessions', 'workspaces'] +export const inject = ['slots', 'layout', 'workspaces'] -/** Registers the sidebar component and its service callbacks. +/** Registers the sidebar shell and its service callbacks. * @param ctx - Client root context. */ export function apply(ctx: ClientContext): void { const injectProps = (): SidebarRootInjected => ({ startSession: (workspaceId, prompt) => { ctx.workspaces.startSession(workspaceId, prompt) }, - open: (sessionId) => { ctx.sessions.open(sessionId) }, toggleSidebar: () => { ctx.layout.toggleSidebar() }, }) ctx.effect( () => ctx.slots.register({ name: 'sidebar', - // SidebarRoot owns this picker site; ui-workspace registers the shared - // picker that selects a Host Workspace for a frontend Session Intent. - children: { 'sidebar.workspace': { kind: 'single', scope: 'root' } }, + // The shell owns geometry; ui-workspace registers the whole browsing + // region (header, search, session list, workspace dialogs) here. + children: { 'sidebar.workspaces': { kind: 'single', scope: 'root' } }, inject: injectProps, }, SidebarRoot), 'ui-sidebar: slot registration', diff --git a/packages/client/ui-sidebar/tests/apply.spec.tsx b/packages/client/ui-sidebar/tests/apply.spec.tsx index 5d285bd20c..681454691c 100644 --- a/packages/client/ui-sidebar/tests/apply.spec.tsx +++ b/packages/client/ui-sidebar/tests/apply.spec.tsx @@ -1,4 +1,4 @@ -/** Sidebar slot registration and its plain runtime/layout callbacks. */ +/** Sidebar shell slot registration and its plain runtime/layout callbacks. */ import { Context } from 'cordis' import { describe, expect, it, vi } from 'vitest' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' @@ -9,10 +9,8 @@ async function bench(declare = true) { const ctx = new Context() await ctx.plugin(SlotsService).await() const layout = { toggleSidebar: vi.fn() } - const sessions = { open: vi.fn() } const workspaces = { startSession: vi.fn() } ctx.provide('layout', layout) - ctx.provide('sessions', sessions as never) ctx.provide('workspaces', workspaces as never) const slots = ctx.get('slots') as SlotsService if (declare) { @@ -21,25 +19,23 @@ async function bench(declare = true) { () => null, ) } - return { ctx, slots, layout, sessions, workspaces } + return { ctx, slots, layout, workspaces } } describe('ui-sidebar apply', () => { it('declares only the services it uses', () => { - expect(inject).toEqual(['slots', 'layout', 'sessions', 'workspaces']) + expect(inject).toEqual(['slots', 'layout', 'workspaces']) }) - it('registers the sidebar and declares its Workspace picker hole', async () => { + it('registers the shell and declares the browsing-region hole', async () => { const b = await bench() await b.ctx.plugin({ inject: [...inject], apply }).await() expect(b.slots.entries('sidebar')).toHaveLength(1) - expect(b.slots.spec('sidebar.workspace')).toEqual({ kind: 'single', scope: 'root' }) + expect(b.slots.spec('sidebar.workspaces')).toEqual({ kind: 'single', scope: 'root' }) const injected = (b.slots.entries('sidebar')[0]!.inject as () => SidebarRootInjected)() - expect(Object.keys(injected)).toEqual(['startSession', 'open', 'toggleSidebar']) + expect(Object.keys(injected)).toEqual(['startSession', 'toggleSidebar']) injected.startSession('workspace' as never, 'prompt') expect(b.workspaces.startSession).toHaveBeenCalledWith('workspace', 'prompt') - injected.open('session' as never) - expect(b.sessions.open).toHaveBeenCalledWith('session') injected.toggleSidebar() expect(b.layout.toggleSidebar).toHaveBeenCalledOnce() }) @@ -55,6 +51,6 @@ describe('ui-sidebar apply', () => { await fiber.await() await fiber.dispose() expect(b.slots.entries('sidebar')).toHaveLength(0) - expect(b.slots.spec('sidebar.workspace')).toBeUndefined() + expect(b.slots.spec('sidebar.workspaces')).toBeUndefined() }) }) diff --git a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx index 26adafd793..6bdba770eb 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx @@ -1,79 +1,42 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import type { - SessionId, SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView, -} from '@deepseek-ai/dsh-client-runtime/client' -import type { SidebarRootComponentProps } from '../src/client/contract/slots.ts' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import type { SidebarRootComponentProps, SidebarSectionOwnerProps } from '../src/client/contract/slots.ts' import { SidebarRoot } from '../src/client/SidebarRoot.tsx' afterEach(() => { cleanup() vi.useRealTimers() }) -const sid = (id: string) => id as SessionId -const wid = (id: string) => id as WorkspaceId -const hook = (snapshot: T) => (selector: (state: T) => S): S => selector(snapshot) -const workspace: WorkspaceView = { - workspaceId: wid('project'), path: '/projects/project', title: 'Project', sessionIds: [sid('s1')], - createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', -} -const sessions: SessionListState = { - ids: [sid('s1')], - byId: { [sid('s1')]: { id: sid('s1'), displayTitle: 'First session', running: false, updatedAt: 1 } }, - current: undefined, phase: 'ready', - intent: undefined, -} -const workspaces: WorkspaceListState = { - items: [workspace], state: 'idle', phase: 'ready', error: null, - intent: undefined, baselinesReady: true, recentWorkspaceId: workspace.workspaceId, -} -function mount(sessionState: SessionListState = sessions) { - const startSession = vi.fn() - const open = vi.fn() - let pickerOwner: unknown - const view = render( - { pickerOwner = owner; return null }) as SidebarRootComponentProps['renderSlot']} - />, - ) - return { view, startSession, open, pickerOwner: () => pickerOwner } -} +// The shell never reads the global hooks itself, but they ride the standard +// props share; stub them as never-called functions. +const neverHook = (() => { throw new Error('shell must not read global hooks') }) as never -function mountSidebar({ - sessionState = sessions, - workspaceState = workspaces, - collapsed = false, - width = 300, -}: { - sessionState?: SessionListState - workspaceState?: WorkspaceListState - collapsed?: boolean - width?: number -} = {}) { +function mountShell({ collapsed = false, width = 300 }: { collapsed?: boolean; width?: number } = {}) { const startSession = vi.fn() - const open = vi.fn() const toggleSidebar = vi.fn() - let pickerOwner: unknown - let current = { sessionState, workspaceState, collapsed, width } + let regionOwner: SidebarSectionOwnerProps | undefined + let current = { collapsed, width } const root = () => ( { pickerOwner = owner; return null }) as SidebarRootComponentProps['renderSlot']} + useSessions={neverHook} useWorkspaces={neverHook} + startSession={startSession} toggleSidebar={toggleSidebar} + renderSlot={((_key: string, owner: SidebarSectionOwnerProps) => { + regionOwner = owner + return
+ }) as SidebarRootComponentProps['renderSlot']} /> ) const view = render(root()) return { startSession, - open, toggleSidebar, - pickerOwner: () => pickerOwner, + regionOwner: () => { + if (regionOwner === undefined) throw new Error('region owner not rendered') + return regionOwner + }, rerender(next: Partial) { current = { ...current, ...next } view.rerender(root()) @@ -81,181 +44,40 @@ function mountSidebar({ } } -describe('SidebarRoot', () => { - it('renders real Workspaces from useWorkspaces and routes New Session', () => { - const b = mount() - expect(screen.getByText('Project')).toBeTruthy() +describe('SidebarRoot shell', () => { + it('routes New Session and the column toggle', () => { + const b = mountShell() fireEvent.click(screen.getByRole('button', { name: 'New session' })) expect(b.startSession).toHaveBeenCalledWith() - }) - - it('shows a frontend Session under its real Workspace and routes its row plus', () => { - const intent = { sessionId: sid('intent'), target: { kind: 'workspace' as const, workspaceId: workspace.workspaceId }, prompt: '', phase: 'connecting' as const } - const b = mount({ - ...sessions, - current: intent.sessionId, - intent, - }) - expect(screen.getByText('New session')).toBeTruthy() - expect(screen.getByText('2 sessions')).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: 'New session in Project' })) - expect(b.startSession).toHaveBeenCalledWith(workspace.workspaceId) - }) - - it('forwards Workspace picker selection and closes the picker', () => { - const b = mount() - fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) - const owner = b.pickerOwner() as { open: boolean; onPick(id: WorkspaceId): void } - expect(owner.open).toBe(true) - owner.onPick(workspace.workspaceId) - expect(b.startSession).toHaveBeenCalledWith(workspace.workspaceId) - }) - - it('opens a real Session through the owner action', () => { - const b = mount({ ...sessions, current: sid('intent'), intent: { - sessionId: sid('intent'), target: { kind: 'workspace', workspaceId: workspace.workspaceId }, prompt: '', phase: 'ready', - } }) - fireEvent.click(screen.getByText('Project')) - fireEvent.click(screen.getByText('First session')) - expect(b.open).toHaveBeenCalledWith(sid('s1')) - }) - - it('opens, selects, dismisses, and toggles the group-by menu', () => { - mount() - const button = screen.getByRole('button', { name: 'Group by' }) - - fireEvent.click(button) - fireEvent.click(screen.getByRole('menuitem', { name: 'Workspace' })) - expect(screen.queryByRole('menu')).toBeNull() - - fireEvent.click(button) - fireEvent.keyDown(document, { key: 'Escape' }) - expect(screen.queryByRole('menu')).toBeNull() - - fireEvent.click(button) - fireEvent.click(button) - expect(screen.queryByRole('menu')).toBeNull() - }) - - it('routes every Workspace picker close path', () => { - const b = mount() - fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) - const owner = b.pickerOwner() as { open: boolean; onClose(): void } - expect(owner.open).toBe(true) - act(() => { owner.onClose() }) - expect((b.pickerOwner() as { open: boolean }).open).toBe(false) - }) - - it('focuses, filters, and clears search while distinguishing both empty states', () => { - mount() - const input = screen.getByPlaceholderText('Search name, keywords...') - fireEvent.click(input.parentElement!) - expect(document.activeElement).toBe(input) - fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) - - fireEvent.change(input, { target: { value: 'missing' } }) - expect(screen.getByText('No matches')).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: 'Clear search' })) - expect(screen.queryByText('No matches')).toBeNull() - - cleanup() - const emptySessions = listState() - const emptyWorkspaces: WorkspaceListState = { ...workspaces, items: [], recentWorkspaceId: undefined } - mountSidebar({ sessionState: emptySessions, workspaceState: emptyWorkspaces }) - expect(screen.getByText('No sessions yet')).toBeTruthy() - }) - - it('toggles Workspace and nested Session expansion in both directions', () => { - const parent = sid('parent') - const child = sid('child') - const nestedSessions: SessionListState = { - ...sessions, - ids: [parent, child], - byId: { - [parent]: { id: parent, displayTitle: 'Parent', running: false, updatedAt: 2 }, - [child]: { id: child, displayTitle: 'Child', running: false, updatedAt: 1, parentId: parent }, - }, - } - const nestedWorkspace: WorkspaceListState = { - ...workspaces, - items: [{ ...workspace, sessionIds: [parent, child] }], - } - mountSidebar({ sessionState: nestedSessions, workspaceState: nestedWorkspace }) - - fireEvent.click(screen.getByText('Project')) - fireEvent.click(screen.getByRole('button', { name: 'Expand' })) - expect(screen.getByText('Child')).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: 'Collapse' })) - expect(screen.queryByText('Child')).toBeNull() - fireEvent.click(screen.getByText('Project')) - expect(screen.queryByText('Parent')).toBeNull() - }) - - it('does not start a Session from an Ungrouped row create action', () => { - const loose = sid('loose') - const looseSessions: SessionListState = { - ...listState(), - ids: [loose], - byId: { [loose]: { id: loose, displayTitle: 'Loose', running: false, updatedAt: 1 } }, - current: loose, - } - const b = mountSidebar({ - sessionState: looseSessions, - workspaceState: { ...workspaces, items: [], recentWorkspaceId: undefined }, - }) - fireEvent.click(screen.getByRole('button', { name: 'New session in Ungrouped' })) - expect(b.startSession).not.toHaveBeenCalled() - }) - - it('keeps an already expanded selected Workspace open and resolves later Workspace matches', () => { - const b = mountSidebar() - fireEvent.click(screen.getByText('Project')) - const other = { ...workspace, workspaceId: wid('other'), title: 'Other', sessionIds: [] } - b.rerender({ - sessionState: { ...sessions, current: sid('s1') }, - workspaceState: { ...workspaces, items: [other, workspace] }, - }) - expect(screen.getByText('First session')).toBeTruthy() - - b.rerender({ - sessionState: { - ...sessions, - current: sid('draft'), - intent: { sessionId: sid('draft'), target: { kind: 'workspace-intent' }, prompt: '', phase: 'ready' }, - }, - }) - expect(screen.getByText('Project')).toBeTruthy() - }) - - it('renders the static collapsed rail and expands rail search into focused input', () => { - vi.useFakeTimers() - const b = mountSidebar({ collapsed: true }) - expect(screen.getByRole('button', { name: 'Open sidebar' })).toBeTruthy() - expect(screen.queryByPlaceholderText('Search name, keywords...')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'Open sidebar' })) - expect(b.toggleSidebar).toHaveBeenCalledOnce() - - fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) - expect(b.toggleSidebar).toHaveBeenCalledTimes(2) - b.rerender({ collapsed: false }) - const input = screen.getByPlaceholderText('Search name, keywords...') - act(() => { vi.advanceTimersByTime(300) }) - expect(document.activeElement).toBe(input) - }) - - it('keeps wide content during live collapse, then settles to the rail', () => { - vi.useFakeTimers() - const b = mountSidebar({ width: 320 }) fireEvent.click(screen.getByRole('button', { name: 'Collapse sidebar' })) expect(b.toggleSidebar).toHaveBeenCalledOnce() - b.rerender({ collapsed: true, width: 56 }) - expect(screen.getByPlaceholderText('Search name, keywords...')).toBeTruthy() - act(() => { vi.advanceTimersByTime(150) }) - expect(screen.queryByPlaceholderText('Search name, keywords...')).toBeNull() + }) + + it('hands the region its wide flag and clamps expandSidebar to the collapsed state', () => { + const b = mountShell() + expect(b.regionOwner().wide).toBe(true) + // Expanded: the request is a no-op (no accidental collapse). + b.regionOwner().expandSidebar() + expect(b.toggleSidebar).not.toHaveBeenCalled() + }) + + it('keeps the region mounted through collapse and expands on its request', () => { + vi.useFakeTimers() + const b = mountShell() + b.rerender({ collapsed: true }) + // Wide content survives the crossfade window, then settles into the rail. + expect(b.regionOwner().wide).toBe(true) + vi.advanceTimersByTime(200) + b.rerender({}) + expect(b.regionOwner().wide).toBe(false) + expect(screen.getByTestId('region')).toBeTruthy() + b.regionOwner().expandSidebar() + expect(b.toggleSidebar).toHaveBeenCalledOnce() + }) + + it('renders statically collapsed on a cold start (no crossfade classes)', () => { + const b = mountShell({ collapsed: true }) + expect(b.regionOwner().wide).toBe(false) expect(screen.getByRole('button', { name: 'Open sidebar' })).toBeTruthy() }) }) - -function listState(): SessionListState { - return { ids: [], byId: {}, current: undefined, phase: 'ready', intent: undefined } -} diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index 0a6c82c0cf..c36486d2fd 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -35,6 +35,9 @@ "watch": "tsdown --watch" }, "license": "BSD-3-Clause", + "dependencies": { + "clsx": "^2.0.0" + }, "peerDependencies": { "@deepseek-ai/dsh-client-runtime": "^0.0.1", "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css b/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css new file mode 100644 index 0000000000..d6375cb698 --- /dev/null +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css @@ -0,0 +1,265 @@ +/* Workspace browsing region (fills the sidebar shell's hole): section + header, search capsule, and the scrolling session list. Wide/rail + variants ride the shell's fold state through the `wide` owner prop — + rail state renders only the two 36x36 icon controls. */ + +.root { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; +} + +.iconButton { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border: none; + border-radius: 50%; + padding: 0; + background: transparent; + cursor: pointer; + color: var(--dsw-alias-label-secondary); +} + +.iconButton:hover { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* Section header: 36px, "Workspaces/Sessions" label + group-by / + new-workspace buttons; the right-anchored new-workspace button is the + row's rail survivor. */ +.sectionHeader { + flex: none; + display: flex; + align-items: center; + justify-content: flex-end; + gap: 4px; + height: 36px; + padding-left: 12px; + margin-bottom: 4px; + box-sizing: border-box; + border-radius: 12px; + overflow: hidden; + color: var(--dsw-alias-label-tertiary); +} + +.sectionLabel { + flex: 1; + min-width: 0; + overflow: hidden; + white-space: nowrap; + line-height: 20px; +} + +/* Search input: 38px capsule (figma 133:7649); rail state renders it as the + region's search control. Upstream binds a dedicated design-system variable + (light #F1F3F5 / dark #1B1B1C) matching no shipped alias — a component + token pinned to the static scale mirrors it. */ +.search { + --dsh-search-input-fill: var(--dsw-static-neutral-bluish-75); + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 38px; + margin: 0 2px 12px; + padding: 0 14px; + box-sizing: border-box; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 24px; + background: var(--dsh-search-input-fill); + color: var(--dsw-alias-label-caption); + overflow: hidden; +} + +:global(body[data-ds-dark-theme]) .search { + --dsh-search-input-fill: var(--dsw-static-neutral-bluish-900); +} + +/* The capsule's leading icon: decorative while wide (pointer-events off so + clicks reach the input), the hit target in rail state. */ +.searchButton { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + border: none; + border-radius: 50%; + padding: 0; + background: transparent; + pointer-events: none; + color: inherit; +} + +.searchInput { + flex: 1; + min-width: 0; + border: none; + outline: none; + background: transparent; + font-size: 14px; + line-height: 20px; + color: var(--dsw-alias-label-primary); +} + +.searchInput::placeholder { + color: var(--dsw-alias-label-tertiary); +} + +.clearButton { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + border: none; + border-radius: 50%; + padding: 0; + background: transparent; + cursor: pointer; + color: var(--dsw-alias-label-secondary); +} + +/* Rail variant (own .rail class from the wide owner prop — the region never + reads the shell's class names): the two icon controls stack as 36x36 + circles matching the shell's rail rhythm. */ +.rail .sectionHeader { + padding-left: 0; + margin-bottom: 12px; +} + +.rail .iconButton { + width: 36px; + height: 36px; + color: var(--dsw-alias-label-primary); +} + +.rail .search { + height: 36px; + padding: 0; + margin: 0 0 12px; + gap: 0; + border-color: transparent; + background: transparent; +} + +.rail .searchButton { + width: 36px; + height: 36px; + pointer-events: auto; + cursor: pointer; + color: var(--dsw-alias-label-primary); +} + +.rail .searchButton:hover { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* List seat: always mounted so the shell foot never moves. */ +.listArea { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; +} + +/* Relative for the bottom fade overlay. */ +.treeBody { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + position: relative; +} + +/* Bottom fade (figma 133:7666): 72px overlay pinned to the visible bottom, + transparent -> sidebar fill so it tracks the theme. */ +.fade { + position: absolute; + left: 0; + right: 0; + bottom: 0; + height: 72px; + background: linear-gradient(to bottom, transparent, var(--dsw-specific-sidebar-fill)); + pointer-events: none; +} + +/* Wide-only content fades back in on expand remount (mirrors the shell). */ +.wide { + animation: wide-in 200ms var(--ds-ease-in-out); +} + +@keyframes wide-in { + from { opacity: 0; } +} + +/* List: the only scrolling region. Block, not a flex column: as flex items + the 54/34 rows would shrink under content overflow; block children keep + their design heights and the 4px rhythm rides margins instead of gap. */ +.list { + flex: 1; + min-height: 0; + overflow-y: auto; + padding-bottom: 12px; +} + +/* One workspace section: header row + expanded session run. Rows inside + keep the former flat-list 4px gap as sibling margins; the inter-group + breathing room (figma 133:7661 batch separator, 20px after an expanded + run) rides the NEXT section's top margin so the last group adds none. */ +.groupSection > * + * { + margin-top: 4px; +} + +.groupSection + .groupSection { + margin-top: 4px; +} + +.groupSection:has([aria-expanded='true']) + .groupSection { + margin-top: 20px; +} + +.empty { + padding: 16px 12px; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; +} + +/* Rename dialog form (same figma dialog family as the create modals). */ +.renameInput { + box-sizing: border-box; + width: 100%; + height: 44px; + padding: 7px 14px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 22px; + outline: none; + background: transparent; + font-size: 14px; + font-weight: 400; + line-height: 22px; + color: var(--dsw-alias-label-primary); +} + +.renameInput:disabled { + color: var(--dsw-alias-label-dimmed); +} + +.renameError { + margin-top: 8px; + font-size: 12px; + line-height: 18px; + color: var(--dsw-alias-state-error-primary); +} + +@media (prefers-reduced-motion: reduce) { + .wide { + animation: none; + } +} diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx new file mode 100644 index 0000000000..e7d0cdc38c --- /dev/null +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -0,0 +1,428 @@ +/** + * The workspace/session browsing region filling the sidebar shell's + * `sidebar.workspaces` hole: section header (title + group-by + new + * workspace), search, the grouped tree or flat list, and the workspace + * dialogs. Wide state renders the full browser; rail state renders the two + * region icons (search / new workspace), each requesting shell expansion + * through the owner share. The picker menu and create dialogs live in + * WorkspacePicker (same package — direct composition, no slot between them). + */ +import { useEffect, useMemo, useRef, useState } from 'react' +import clsx from 'clsx' +import { + Button, IconCloseFill14, IconPersonalizationOutline16, + IconProjectAddOutline16, IconSearchOutline16, Menu, Modal, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { WorkspaceBrowserProps } from './contract/slots.ts' +import type { SessionNode } from './tree.ts' +import { deriveFlat, deriveGroups, UNGROUPED_KEY } from './tree.ts' +import { IntentRowItem, ProjectRowItem, SessionNodeItem } from './rows/Rows.tsx' +import { WorkspaceCreateFlow } from './WorkspacePicker.tsx' +import css from './WorkspaceBrowser.module.css' + +/** Column slide length (--ds-transition-duration-slow): rail-search focus waits it out — focus() forces a synchronous layout and would jank the slide. */ +const EXPAND_SLIDE_MS = 300 + +const GROUP_BY_ITEMS = [ + { type: 'label' as const, id: 'group-by', text: 'Group by' }, + { id: 'workspace', label: 'WorkSpace' }, + { id: 'flat', label: 'In one list' }, +] + +/** Immutable membership toggle for the local expansion arrays. */ +function toggled(list: readonly string[], key: string): string[] { + return list.includes(key) ? list.filter((k) => k !== key) : [...list, key] +} + +/** Group-by strategy menu; own open state so it resets with the wide chrome. */ +function GroupByMenu({ groupBy, onPick }: { + groupBy: 'workspace' | 'flat' + onPick: (mode: 'workspace' | 'flat') => void +}) { + const [open, setOpen] = useState(false) + return ( + { setOpen(false) }} + items={GROUP_BY_ITEMS} + selectedId={groupBy} + onSelect={(id) => { + if (id === 'workspace' || id === 'flat') onPick(id) + setOpen(false) + }} + align="end" + // Portal: the section header clips overflow, so an in-place list would + // be cut off at the header's bounds. + portal + anchor={( + + )} + /> + ) +} + +/** In-flight root-row drag: source identity plus the current insert marker. */ +interface DragState { + workspaceId: WorkspaceId + sessionId: SessionNode['id'] + /** Row the marker sits on and which half (insert above/below it). */ + over: { id: SessionNode['id']; half: 'before' | 'after' } | null +} + +type SessionTreeProps = Pick< + WorkspaceBrowserProps, + 'useSessions' | 'startSession' | 'open' | 'insertSessionBefore' +> & { + workspaces: readonly WorkspaceView[] + /** Live search filter owned by the browser root (the query outlives the tree). */ + query: string + /** Open the browser-owned rename dialog for a real Workspace group. */ + onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void +} + +/** The scrolling session tree; unmounting at collapse settle drops the sessions subscription and expansion state. */ +function SessionTree({ useSessions, startSession, open, workspaces, query, onRenameRequest, insertSessionBefore }: SessionTreeProps) { + const list = useSessions((s) => s) + const current = list.current + const [expandedProjects, setExpandedProjects] = useState([]) + const [expandedSessions, setExpandedSessions] = useState([]) + // Transient drag viewing state (never store-bound; order truth stays Host-side). + const [drag, setDrag] = useState(null) + // Re-expand when publication moves the selected intent into a real Workspace. + const intent = list.intent + const intentWorkspaceId = intent?.target.kind === 'workspace' + ? intent.target.workspaceId + : undefined + const currentGroup = current === undefined + ? undefined + : intent?.sessionId === current + ? intentWorkspaceId + : (workspaces.find(w => w.sessionIds.includes(current))?.workspaceId as string | undefined) + ?? UNGROUPED_KEY + useEffect(() => { + if (current === undefined || currentGroup === undefined) return + setExpandedProjects((l) => (l.includes(currentGroup) ? l : [...l, currentGroup])) + }, [current, currentGroup]) + const groups = useMemo( + () => deriveGroups(list, workspaces, { expandedProjects, expandedSessions, query }), + [list, workspaces, expandedProjects, expandedSessions, query], + ) + const now = Date.now() + + return ( +
+
+ {groups.length === 0 && ( +
{query === '' ? 'No sessions yet' : 'No matches'}
+ )} + {groups.map(group => ( + // Group section: header row + expanded session subtree. The + // inter-group breathing room (former flat-list batch separator) + // is the section's own margin (WorkspaceBrowser.module.css). +
+ { setExpandedProjects((l) => toggled(l, group.key)) }} + onCreate={() => { + if (group.workspaceId !== undefined) startSession(group.workspaceId) + }} + onRename={group.workspaceId === undefined + ? undefined + : () => { + if (group.workspaceId !== undefined) onRenameRequest(group.workspaceId, group.label) + }} + /> + {group.expanded && group.intentHere && } + {group.sessions.map((node, index) => { + // Draggable: real-workspace group roots outside search. The drag + // never leaves its group — rows of other groups show no markers + // and reject drops (visual movement confined to this section). + const draggable = group.workspaceId !== undefined && query === '' + const sameGroupDrag = drag !== null && drag.workspaceId === group.workspaceId + const dragProps = !draggable || group.workspaceId === undefined ? undefined : { + start: () => { + setDrag({ workspaceId: group.workspaceId as WorkspaceId, sessionId: node.id, over: null }) + }, + active: sameGroupDrag, + marker: sameGroupDrag && drag.over?.id === node.id ? drag.over.half : null, + hover: (half: 'before' | 'after') => { + setDrag(d => (d === null ? d : { ...d, over: { id: node.id, half } })) + }, + drop: (half: 'before' | 'after') => { + if (drag === null) return + const roots = group.sessions + // Anchor = the row the insert line points at ('after' means + // the next root; end-of-list omits the anchor → append). + const anchor = half === 'before' ? node.id : roots[index + 1]?.id + setDrag(null) + if (anchor === drag.sessionId) return + // No-op when the drop lands back on the source position. + const sourceIndex = roots.findIndex(r => r.id === drag.sessionId) + const anchorIndex = anchor === undefined ? roots.length : roots.findIndex(r => r.id === anchor) + if (sourceIndex !== -1 && (anchorIndex === sourceIndex || anchorIndex === sourceIndex + 1)) return + insertSessionBefore(drag.workspaceId, drag.sessionId, anchor).catch((reason: unknown) => { + console.warn('session reorder rejected:', reason) + }) + }, + end: () => { setDrag(null) }, + } + return ( + { setExpandedSessions((l) => toggled(l, id)) }} + drag={dragProps} + /> + ) + })} +
+ ))} +
+ +
+ ) +} + +/** The flat "In one list" body: every session a top-level row, newest-first. */ +function FlatList({ useSessions, open, query }: Pick) { + const list = useSessions((s) => s) + const rows = useMemo(() => deriveFlat(list, { query }), [list, query]) + const now = Date.now() + // The intent placeholder renders outside search only; it suppresses the + // empty state only while actually rendered (a query hides both). + const intentRow = query === '' && list.intent !== undefined + return ( +
+
+ {rows.length === 0 && !intentRow && ( +
{query === '' ? 'No sessions yet' : 'No matches'}
+ )} + {intentRow && } + {rows.map(node => ( + {}} + flat + /> + ))} +
+ +
+ ) +} + +/** + * Render the browsing region. + * @param props - composed slot props (shell owner share + store + injected actions). + * @returns the region element tree. + */ +export function WorkspaceBrowser({ + wide, + expandSidebar, + useSessions, + useWorkspaces, + useStore, + actions, + startSession, + open, + renameWorkspace, + insertSessionBefore, + createWorkspace, +}: WorkspaceBrowserProps) { + const workspaces = useWorkspaces(state => state.items) + const groupBy = useStore(s => s.groupBy) + // The query outlives the tree and the input (both wide-only) so collapsing + // does not silently drop an in-progress filter. + const [query, setQuery] = useState('') + const searchInput = useRef(null) + // Section-header + opens the picker menu (same popover in wide and rail + // states; the menu anchors on this button). + const [wsPickerOpen, setWsPickerOpen] = useState(false) + const wsPlusRef = useRef(null) + + // Rail search = expand + land in the search box: the flag arms before the + // expand request; once the shell flips wide the input mounts and takes focus. + const [searchOnExpand, setSearchOnExpand] = useState(false) + useEffect(() => { + if (wide && searchOnExpand) { + const timer = window.setTimeout(() => { + searchInput.current?.focus({ preventScroll: true }) + setSearchOnExpand(false) + }, EXPAND_SLIDE_MS) + return () => { window.clearTimeout(timer) } + } + }, [wide, searchOnExpand]) + + // Rename dialog (browser-owned so it outlives row unmounts during collapse). + const [renameTarget, setRenameTarget] = useState<{ workspaceId: WorkspaceId; currentTitle: string } | null>(null) + const [renameDraft, setRenameDraft] = useState('') + const [renaming, setRenaming] = useState(false) + const [renameError, setRenameError] = useState(null) + const renameTrimmed = renameDraft.trim() + const renameDuplicate = renameTarget !== null && renameTrimmed !== '' && renameTrimmed !== renameTarget.currentTitle + && workspaces.some(w => w.title === renameTrimmed) + const renameBlocked = renaming || renameTrimmed === '' + || renameTarget === null || renameTrimmed === renameTarget.currentTitle || renameDuplicate + const closeRename = () => { + if (renaming) return + setRenameTarget(null) + setRenameError(null) + } + const confirmRename = () => { + if (renameBlocked || renameTarget === null) return + setRenaming(true) + setRenameError(null) + renameWorkspace(renameTarget.workspaceId, renameTrimmed).then(() => { + setRenaming(false) + setRenameTarget(null) + }).catch((reason: unknown) => { + setRenaming(false) + setRenameError(reason instanceof Error ? reason.message : String(reason)) + }) + } + + return ( +
+
+ {wide && ( + + {groupBy === 'flat' ? 'Sessions' : 'Workspaces'} + + )} + {wide && { actions.setGroupBy(mode) }} />} + + + + {/* Picker menu + create dialogs (same package — direct composition). */} + { + setWsPickerOpen(false) + startSession(workspaceId) + }} + onClose={() => { setWsPickerOpen(false) }} + /> +
+ + {/* Expanded: the row is a click-to-focus field (the leading icon is + decorative). Rail: the icon is the region's search control. */} +
{ if (wide) searchInput.current?.focus() }}> + + + + {wide && ( + { setQuery(e.target.value) }} + /> + )} + {wide && query !== '' && ( + + )} +
+ + {/* Always-mounted seat keeps the region's flex slot while the list + itself is wide-only. */} +
+ {wide && (groupBy === 'flat' + ? + : ( + { + setRenameTarget({ workspaceId, currentTitle }) + setRenameDraft(currentTitle) + setRenameError(null) + }} + /> + ))} +
+ + + + + + )} + > + { setRenameDraft(e.target.value); setRenameError(null) }} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault() + confirmRename() + } + }} + /> + {renameDuplicate && ( +
A workspace named “{renameTrimmed}” already exists.
+ )} + {renameError !== null &&
{renameError}
} +
+
+ ) +} diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 8f6f483580..2be39875bc 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -1,9 +1,15 @@ -/** Shared Workspace picker for the sidebar and New Session hero. */ +/** + * Workspace pick/create flow. WorkspaceCreateFlow is the reusable core + * (menu + path/create dialogs) consumed directly by WorkspaceBrowser (same + * package) and wrapped by WorkspacePicker for the conversation empty-state + * slot registration. + */ +import type { RefObject } from 'react' import { useCallback, useState } from 'react' import { Button, IconFolderClose16, IconPlusOutline16, Menu, Modal, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' +import type { WorkspaceId, WorkspaceListState, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' import type { WorkspacePickerProps } from './contract/slots.ts' import css from './WorkspacePicker.module.css' @@ -13,14 +19,35 @@ const CREATE_NEW = '::create-new' type ModalKind = 'path' | 'create' | null -export function WorkspacePicker({ +/** Core flow props: the owner supplies popover control and pick semantics. */ +export interface WorkspaceCreateFlowProps { + /** Popover visibility (anchor button toggle state, owner-local). */ + open: boolean + /** The anchor button element — the popover's placement anchor. */ + anchorRef?: RefObject | undefined + /** Selector hook over the workspace list (framework standard hook). */ + useWorkspaces: (selector: (state: WorkspaceListState) => S) => S + /** Create or adopt a real Host Workspace. */ + createWorkspace: (input: { name: string } | { path: string }) => Promise + /** A real Workspace was picked or created. */ + onPick: (workspaceId: WorkspaceId) => void + /** Close the popover (outside click / Escape / post-pick). */ + onClose: () => void +} + +/** + * Render the pick menu plus the two create dialogs. + * @param props - owner-controlled flow props. + * @returns menu + dialog elements. + */ +export function WorkspaceCreateFlow({ open, anchorRef, useWorkspaces, + createWorkspace, onPick, onClose, - createWorkspace, -}: WorkspacePickerProps) { +}: WorkspaceCreateFlowProps) { const workspaceSnapshot = useWorkspaces(state => state) const workspaces = workspaceSnapshot.items const getAnchorRect = useCallback( @@ -194,3 +221,29 @@ export function WorkspacePicker({ ) } + +/** + * The conversation empty-state registration: adapts the owner share to the + * core flow (all state and semantics live in the flow / the owner). + * @param props - empty-state slot props (owner share + injected creation callback). + * @returns the flow element. + */ +export function WorkspacePicker({ + open, + anchorRef, + useWorkspaces, + onPick, + onClose, + createWorkspace, +}: WorkspacePickerProps) { + return ( + + ) +} diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index a3045e5070..121e5d60f1 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -1,30 +1,59 @@ /** - * Shared Workspace picker contract for the sidebar and page-local Session Intent hero - * slots. Each runtime share provides its owner's popover controls plus the - * global useWorkspaces hook; this package adds the injected Host Workspace - * creation callback. + * ui-workspace contracts. Two registrations share this package: + * + * - WorkspaceBrowser fills the sidebar shell's `sidebar.workspaces` hole — + * the whole browsing region (section header, search, grouped/flat session + * list, workspace dialogs). It registers this package's viewing store and + * consumes the shell's two-fact owner share (wide / expandSidebar). + * - WorkspacePicker fills the conversation empty-state hole (menu + + * create dialogs shared with the browser). */ -import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -// Type-only: pull both owner SlotMap merges into programs that resolve the -// picker runtime union below. +import type { PropsRuntime, PropsStore } 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 { WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { createWorkspaceViewStore } from '../stores.ts' /** - * Registrant-private injected share. Pick semantics remain in each owner's - * onPick callback; this callback creates only the real Host Workspace. A type - * alias supplies the implicit index signature required by the registry. + * Browser-private injected share (arrives via the register inject factory). + * Data reads use the global framework hooks; these are the Host actions the + * browsing region drives. + */ +export type WorkspaceBrowserInjected = { + /** Start or replace the current frontend Session Intent. */ + startSession: (workspaceId?: WorkspaceId, prompt?: string) => void + /** Open a real Session. */ + open: (sessionId: SessionId) => void + /** Rename a Host Workspace (rejects on name conflict; resolves on durability). */ + renameWorkspace: (workspaceId: WorkspaceId, title: string) => Promise + /** + * Reorder a session inside its Workspace account (DOM-insertBefore + * semantics: omitted anchor appends to the end). The view refreshes from + * the Host response/changed frame; failures leave the order unchanged. + */ + insertSessionBefore: (workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId) => Promise + /** Explicitly create or adopt a real Workspace before targeting a Session. */ + createWorkspace: (input: { name: string } | { path: string }) => Promise +} + +/** Full browser props: shell owner share + viewing store + injected actions. */ +export type WorkspaceBrowserProps = + PropsRuntime<'sidebar.workspaces'> + & PropsStore> + & WorkspaceBrowserInjected + +/** + * Picker-private injected share. Pick semantics remain in the owner's onPick + * callback; this callback creates only the real Host Workspace. A type alias + * supplies the implicit index signature required by the registry. */ export type WorkspacePickerInjected = { /** Explicitly create or adopt a real Workspace before targeting a Session. */ createWorkspace(input: { name: string } | { path: string }): Promise } -/** - * Full picker props: either owner's runtime share, including useWorkspaces, - * plus this package's injected creation callback. - */ +/** Full picker props: the empty-state owner share plus the creation callback. */ export type WorkspacePickerProps = - (PropsRuntime<'sidebar.workspace'> | PropsRuntime<'conversation.empty.workspace'>) - & WorkspacePickerInjected + PropsRuntime<'conversation.empty.workspace'> & WorkspacePickerInjected diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index aa54587650..50ccb3564c 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -1,54 +1,85 @@ /** - * Shared Workspace picker plugin, browser half. WorkspacePicker registers in - * the sidebar and page-local Session Intent hero slots, reads real Host Workspaces - * through the global useWorkspaces hook, and delegates selection semantics to - * each owner. Its injected share creates a Workspace without creating a - * Session. Export discipline: packages/client/AGENTS.md. + * Workspace plugin, browser half. Two registrations: WorkspaceBrowser fills + * the sidebar shell's `sidebar.workspaces` hole (the whole browsing region), + * and WorkspacePicker fills the conversation empty-state hole. Both read real + * Host Workspaces through the global useWorkspaces hook. Export discipline: + * packages/client/AGENTS.md. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' -import type { WorkspacePickerInjected } from './contract/slots.ts' +import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from './contract/slots.ts' +import { createWorkspaceViewStore } from './stores.ts' +import { WorkspaceBrowser } from './WorkspaceBrowser.tsx' import { WorkspacePicker } from './WorkspacePicker.tsx' -export type { WorkspacePickerInjected, WorkspacePickerProps } from './contract/slots.ts' +export type { + WorkspaceBrowserInjected, WorkspaceBrowserProps, WorkspacePickerInjected, WorkspacePickerProps, +} from './contract/slots.ts' /** - * Required services (cordis fiber inject). The target slot is declared by - * the ui-sidebar apply, whose activation order relative to this one is NOT - * constrained: dshClient.inject edges are informational (loading/prefetch - * metadata, never apply sequencing) and the sidebar provides no waitable - * service. apply therefore registers via declaration-aware deferral instead - * of assuming order. + * Required services (cordis fiber inject). The target slots are declared by + * the ui-sidebar / ui-conversation applies, whose activation order relative + * to this one is NOT constrained: dshClient.inject edges are informational + * (loading/prefetch metadata, never apply sequencing) and neither owner + * provides a waitable service. apply therefore registers via + * declaration-aware deferral instead of assuming order. */ -export const inject = ['slots', 'workspaces'] +export const inject = ['slots', 'sessions', 'workspaces'] /** - * Register WorkspacePicker in both owner slots once their declarations are on - * the ledger. The inject factory returns a plain Workspace creation callback; - * data reads use the framework's global useWorkspaces hook. + * Register the browser and picker once their slot declarations are on the + * ledger. Inject factories return plain callbacks; data reads use the + * framework's global hooks. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { - const injected = (): WorkspacePickerInjected => ({ + const browserInjected = (): WorkspaceBrowserInjected => ({ + startSession: (workspaceId, prompt) => { ctx.workspaces.startSession(workspaceId, prompt) }, + open: (sessionId) => { ctx.sessions.open(sessionId) }, + renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) }, + insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => { + await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId) + }, createWorkspace: input => ctx.workspaces.create(input), }) - // Declaration-aware registration: the sidebar's declaring apply may - // activate after this one (entry activation order is unconstrained), and a - // register into an undeclared slot throws. Register once the declaration - // is on the ledger; the subscription also re-registers after an HMR - // collapse re-declares the slot (the cascade disposed our entry with it). + const pickerInjected = (): WorkspacePickerInjected => ({ + createWorkspace: input => ctx.workspaces.create(input), + }) + // Declaration-aware registration: each owner's declaring apply may activate + // after this one (entry activation order is unconstrained), and a register + // into an undeclared slot throws. Register once the declaration is on the + // ledger; the subscription also re-registers after an HMR collapse + // re-declares the slot (the cascade disposed our entry with it). ctx.effect(() => { - const slotNames = ['sidebar.workspace', 'conversation.empty.workspace'] as const - const disposers = new Map<(typeof slotNames)[number], () => void>() - const tryRegister = (name: (typeof slotNames)[number]): void => { - if (ctx.slots.spec(name) === undefined) return - if (ctx.slots.entries(name).some(e => e.component === WorkspacePicker)) return - disposers.set(name, ctx.slots.register({ name, inject: injected }, WorkspacePicker)) + const registrations = [ + { + name: 'sidebar.workspaces' as const, + component: WorkspaceBrowser, + register: () => ctx.slots.register( + { name: 'sidebar.workspaces', store: createWorkspaceViewStore(), inject: browserInjected }, + WorkspaceBrowser, + ), + }, + { + name: 'conversation.empty.workspace' as const, + component: WorkspacePicker, + register: () => ctx.slots.register( + { name: 'conversation.empty.workspace', inject: pickerInjected }, + WorkspacePicker, + ), + }, + ] + const disposers = new Map void>() + const tryRegister = (entry: (typeof registrations)[number]): void => { + if (ctx.slots.spec(entry.name) === undefined) return + if (ctx.slots.entries(entry.name).some(e => e.component === entry.component)) return + disposers.set(entry.name, entry.register()) } - const unsubscribers = slotNames.map(name => ctx.slots.subscribe(name, () => { tryRegister(name) })) - for (const name of slotNames) tryRegister(name) + const unsubscribers = registrations.map(entry => + ctx.slots.subscribe(entry.name, () => { tryRegister(entry) })) + for (const entry of registrations) tryRegister(entry) return () => { for (const unsubscribe of unsubscribers) unsubscribe() for (const dispose of disposers.values()) dispose() } - }, 'ui-workspace: picker registrations') + }, 'ui-workspace: browser + picker registrations') } diff --git a/packages/client/ui-sidebar/src/client/Rows.module.css b/packages/client/ui-workspace/src/client/rows/Rows.module.css similarity index 79% rename from packages/client/ui-sidebar/src/client/Rows.module.css rename to packages/client/ui-workspace/src/client/rows/Rows.module.css index f996f03348..7b19284b66 100644 --- a/packages/client/ui-sidebar/src/client/Rows.module.css +++ b/packages/client/ui-workspace/src/client/rows/Rows.module.css @@ -150,14 +150,63 @@ } .projectRow:hover .rowActions, -.sessionRow:hover .rowActions { +.sessionRow:hover .rowActions, +.projectRow.menuOpen .rowActions, +.sessionRow.menuOpen .rowActions { display: inline-flex; } -.sessionRow:hover .time { +.sessionRow:hover .time, +.sessionRow.menuOpen .time { display: none; } +/* An open row menu pins the hover affordances (figma: the row keeps its + hover fill while its dropdown is up). */ +.projectRow.menuOpen, +.sessionRow.menuOpen { + background: var(--dsw-alias-interactive-bg-hover); +} + +/* Drag reorder insert line (workspace-group roots): 2px accent above or + below the hovered row, drawn with box-shadow so no layout shift. */ +.sessionRow.dropBefore { + box-shadow: 0 -2px 0 0 var(--dsw-alias-state-business-primary); +} + +.sessionRow.dropAfter { + box-shadow: 0 2px 0 0 var(--dsw-alias-state-business-primary); +} + +/* Hover-card body (figma 169:16903): dark surface, fixed colors both themes. */ +.hoverContent { + display: flex; + flex-direction: column; + gap: 8px; +} + +.hoverTitle { + font-size: 14px; + line-height: 20px; + color: #FFFFFF; + overflow-wrap: break-word; +} + +.hoverTime { + font-size: 12px; + line-height: 16px; + color: #CFD3D6; +} + +.hoverStatus { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + line-height: 20px; + color: #ADB2B8; +} + .iconButton { flex: none; display: inline-flex; diff --git a/packages/client/ui-workspace/src/client/rows/Rows.tsx b/packages/client/ui-workspace/src/client/rows/Rows.tsx new file mode 100644 index 0000000000..5a3f923be0 --- /dev/null +++ b/packages/client/ui-workspace/src/client/rows/Rows.tsx @@ -0,0 +1,285 @@ +/** + * 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. Row ... menus are visual-only + * except workspace Rename; the session hover card is suppressed while a menu + * is open. + */ +import { useState } from 'react' +import clsx from 'clsx' +import { + HoverCard, IconBranchOutline16, IconEditOutline16, IconEllipsisOutline16, + IconFolderClose16, IconFolderOpen16, IconPlusOutline16, + IconTrashOutline16, IconTriangleRightFill14, Menu, StateDot, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { GroupNode, SessionNode } from '../tree.ts' +import { formatRelativeTime } from '../tree.ts' +import css from './Rows.module.css' + +/** Indent step per tree level: one 16px slot (figma session cell). */ +const INDENT_STEP = 16 + +const SESSION_MENU_ITEMS = [ + { id: 'rename', label: 'Rename', icon: }, + { id: 'fork', label: 'Fork session', icon: }, + { id: 'delete', label: 'Delete session', icon: , danger: true }, +] + +const WORKSPACE_MENU_ITEMS = [ + { id: 'rename', label: 'Rename', icon: }, + { id: 'delete', label: 'Delete workspace', icon: , danger: true }, +] + +/** + * Project (workspace) header row: 54px, folder + title + session count; + * hover reveals the chevron and create button. `containsCurrent` arrives on + * the node (derivation fact, no renderer scan). + * @param props.group - derived group node. + * @param props.onToggle - expand/collapse the group. + * @param props.onCreate - start a frontend Session inside this Workspace. + * @returns the row element. + */ +export function ProjectRowItem({ group, onToggle, onCreate, onRename }: { + group: GroupNode + onToggle: () => void + onCreate: () => void + /** Open the rename dialog; absent for the ungrouped bucket (no menu shown). */ + onRename?: (() => void) | undefined +}) { + const row = group + const active = group.expanded && group.containsCurrent + const count = `${row.sessionCount} ${row.sessionCount === 1 ? 'session' : 'sessions'}` + const [menuOpen, setMenuOpen] = useState(false) + return ( +
+ + {row.expanded ? : } + + + + + + {row.label} + {count} + + + {onRename !== undefined && ( + { setMenuOpen(false) }} + items={WORKSPACE_MENU_ITEMS} + onSelect={(id) => { + setMenuOpen(false) + if (id === 'rename') onRename() + // Delete is visual-only for now. + }} + portal + closeOnPointerLeave + anchor={( + + )} + /> + )} + + +
+ ) +} + +/** + * The selected "New session" row for a frontend Session Intent targeted to a + * real Workspace. The row disappears when the Intent is replaced or connects. + * @param props.flat - flat-list variant: no twist slot (figma flat cell), so + * only the status slot indents the title. + * @returns the placeholder row element. + */ +export function IntentRowItem({ flat = false }: { flat?: boolean } = {}) { + return ( +
+ {!flat && } + + New session +
+ ) +} + +/** + * One session subtree: the node's own 34px row (indent by depth, expand + * twist when it has children, running dot, relative time) plus its visible + * children, recursively — the component tree mirrors the derived tree. + * @param props.node - derived session node. + * @param props.depth - 0 = directly under the group header. + * @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.onToggle - unfold/fold a subtree by id. + * @returns the node's row followed by its children. + */ +/** Hover-card body: full title, relative time, and the status line (running/idle until wire status lands). */ +function SessionHoverContent({ node, now }: { node: SessionNode; now: number }) { + return ( +
+
{node.title}
+
{`${formatRelativeTime(node.updatedAt, now)} ago`}
+
+ + {node.running ? 'Running' : 'Idle'} +
+
+ ) +} + +/** + * Root-row drag wiring supplied by the group owner (workspace groups only). + * `drop` reports the half of the row the pointer released on: 'before' + * inserts above this row, 'after' below it (the owner resolves the anchor). + */ +export interface RowDragProps { + /** Start dragging this row. */ + start: () => void + /** A drag from the same group is in flight (rows show insert markers). */ + active: boolean + /** Current marker on this row: insert line above, below, or none. */ + marker: 'before' | 'after' | null + /** Report the hovered half while a same-group drag passes over this row. */ + hover: (half: 'before' | 'after') => void + drop: (half: 'before' | 'after') => void + end: () => void +} + +/** Pointer-position half of a row (insert line above or below). */ +function rowHalf(e: { clientY: number; currentTarget: HTMLElement }): 'before' | 'after' { + const rect = e.currentTarget.getBoundingClientRect() + return e.clientY < rect.top + rect.height / 2 ? 'before' : 'after' +} + +export function SessionNodeItem({ node, depth, currentId, now, onOpen, onToggle, drag, flat = false }: { + node: SessionNode + depth: number + currentId: string | undefined + now: number + onOpen: (id: SessionNode['id']) => void + onToggle: (id: SessionNode['id']) => void + /** Present only on draggable rows (workspace-group roots outside search). */ + drag?: RowDragProps | undefined + /** Flat-list variant: no twist slot (figma flat cell) — titles align on the status slot. */ + flat?: boolean +}) { + const row = node + const selected = node.id === currentId + const [menuOpen, setMenuOpen] = useState(false) + // Rail (figma session cell: pad 8, twist slot 16, status slot 16, gap 4 to + // the title): both slots are always reserved so titles align whether or not + // the twist/dot is lit. Extra depth rides the left padding. + const ownRow = ( +
{ onOpen(node.id) }} + draggable={drag !== undefined} + onDragStart={drag === undefined + ? undefined + : (e) => { + e.dataTransfer.effectAllowed = 'move' + drag.start() + }} + onDragEnd={drag?.end} + onDragOver={drag === undefined + ? undefined + : (e) => { + if (!drag.active) return + e.preventDefault() + e.dataTransfer.dropEffect = 'move' + drag.hover(rowHalf(e)) + }} + onDrop={drag === undefined + ? undefined + : (e) => { + if (!drag.active) return + e.preventDefault() + drag.drop(rowHalf(e)) + }} + > + {row.hasChildren && !flat + ? ( + + ) + : null} + {row.running && } + {row.title} + {formatRelativeTime(row.updatedAt, now)} + + { setMenuOpen(false) }} + items={SESSION_MENU_ITEMS} + onSelect={() => { setMenuOpen(false) }} // Visual-only for now. + portal + closeOnPointerLeave + anchor={( + + )} + /> + +
+ ) + return ( + <> + } + disabled={menuOpen || drag?.active === true} + /> + {node.children.map(child => ( + + ))} + + ) +} diff --git a/packages/client/ui-workspace/src/client/stores.ts b/packages/client/ui-workspace/src/client/stores.ts new file mode 100644 index 0000000000..ed89d80d9e --- /dev/null +++ b/packages/client/ui-workspace/src/client/stores.ts @@ -0,0 +1,36 @@ +/** + * The workspace browser's viewing store: the session-list grouping mode, + * persisted across reloads. Module level exports the factory only (a + * module-level handle would pin the store identity across plugin reloads); + * register() receives the factory and the browser derives its PropsStore + * share from the return type. + */ +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client' + +/** Session-list grouping mode: workspace sections or one flat recency list. */ +export type WorkspaceGroupBy = 'workspace' | 'flat' + +/** Workspace browser viewing state (grouping mode only; transient UI facts stay component-local). */ +type WorkspaceViewState = { groupBy: WorkspaceGroupBy } + +/** + * Annotation twin of the actions literal below (the export needs a declared + * return type); drift fails assignability at the defineStore call. + */ +type WorkspaceViewActions = { + setGroupBy: (draft: WorkspaceViewState, mode: WorkspaceGroupBy) => void +} + +/** + * Create the workspace browser viewing store handle. + * @returns the store handle (spec + type + identity + factory in one). + */ +export function createWorkspaceViewStore(): EngineStoreHandle { + return defineStore({ + init: (): WorkspaceViewState => ({ groupBy: 'workspace' }), + persist: 'dsh.workspace.view', + actions: { + setGroupBy: (d, mode: WorkspaceGroupBy) => { d.groupBy = mode }, + }, + }) +} diff --git a/packages/client/ui-sidebar/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts similarity index 89% rename from packages/client/ui-sidebar/src/client/tree.ts rename to packages/client/ui-workspace/src/client/tree.ts index 64fda519e6..39a479f3b3 100644 --- a/packages/client/ui-sidebar/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -1,5 +1,5 @@ /** - * Derives the sidebar tree from Host Workspace order and membership. + * Derives the workspace browser tree from Host Workspace order and membership. * Unassigned Sessions trail under Ungrouped; only Intents targeting real Workspaces render. */ import type { SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' @@ -223,11 +223,11 @@ function buildSearch(g: Group, visible: ReadonlySet): SessionNode[] { } /** - * Derive the nested sidebar group structure. + * Derive the nested workspace browser group structure. * * Normal mode: every group shows; sessions populate under expanded groups, * descending only into expanded sessions. A frontend Session Intent targeting - * a real Workspace marks that group `intentHere` and forces it expanded. Search mode (non-blank query, + * a real Workspace marks that group `intentHere` (rendered only while the group is expanded; expansion stays viewer-owned). Search mode (non-blank query, * case-insensitive display-title substring): expansion state is ignored — * matched sessions and their ancestor chains are forced visible, groups * without a display-title or label hit are dropped, a label-only hit keeps @@ -263,7 +263,9 @@ export function deriveGroups( && g.workspaceId !== undefined && intentWorkspaceId === g.workspaceId const intentHere = q === '' && hasIntent if (q === '') { - const expanded = intentHere || expandedProjects.has(g.key) + // The intent never forces expansion — the viewer auto-expands the + // target group once (current-group effect); the toggle stays live. + const expanded = expandedProjects.has(g.key) groups.push({ key: g.key, workspaceId: g.workspaceId, @@ -294,6 +296,29 @@ export function deriveGroups( return groups } +/** + * Derive the flat session list ("In one list" mode): every session — fork + * children included — as a top-level row, strictly newest-first. No grouping, + * no parent/child adjacency; rows reuse SessionNode with children always + * empty so the renderer stays branch-free. Search mode filters by + * case-insensitive display-title substring. + * @param list - sessions list snapshot. + * @param view - the search query (expansion state does not apply). + * @returns flat rows in render order. + */ +export function deriveFlat(list: SessionListState, view: Pick): SessionNode[] { + const q = view.query.trim().toLowerCase() + const rows: SessionSummary[] = [] + for (const id of list.ids) { + const s = list.byId[id] + if (s === undefined) continue + if (q !== '' && !s.displayTitle.toLowerCase().includes(q)) continue + rows.push(s) + } + rows.sort(byRecency) + return rows.map(s => sessionNode(s, [], false, false)) +} + /** * Compact relative time for session rows ("now", "5min", "3h", "2d", "4mo", "1y"). * @param updatedAt - epoch ms of the session's last activity. diff --git a/packages/client/ui-workspace/tests/apply.spec.ts b/packages/client/ui-workspace/tests/apply.spec.ts index 9352caa0b4..6e1c7a3a3f 100644 --- a/packages/client/ui-workspace/tests/apply.spec.ts +++ b/packages/client/ui-workspace/tests/apply.spec.ts @@ -2,7 +2,8 @@ import { Context } from 'cordis' import { describe, expect, it, vi } from 'vitest' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' -import type { WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client' +import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepseek-ai/dsh-client-ui-workspace/client' +import { WorkspaceBrowser } from '../src/client/WorkspaceBrowser.tsx' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' async function bench() { @@ -13,32 +14,33 @@ async function bench() { path: 'name' in input ? `/projects/${input.name}` : input.path, title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0', })) - ctx.provide('workspaces', { create }) - return { ctx, slots: ctx.get('slots') as SlotsService, create } + const startSession = vi.fn() + const rename = vi.fn(async () => ({})) + const insertSessionBefore = vi.fn(async () => ({})) + const open = vi.fn() + ctx.provide('workspaces', { create, startSession, rename, insertSessionBefore } as never) + ctx.provide('sessions', { open } as never) + return { ctx, slots: ctx.get('slots') as SlotsService, create, startSession, rename, insertSessionBefore, open } } -function declare(slots: SlotsService, name: 'sidebar.workspace' | 'conversation.empty.workspace'): () => void { - return slots.register( - { name: 'root', children: { [name]: { kind: 'single', scope: 'root' } } } as never, - () => null, - ) -} +type HoleName = 'sidebar.workspaces' | 'conversation.empty.workspace' -function injectedOf(slots: SlotsService, name: 'sidebar.workspace' | 'conversation.empty.workspace'): WorkspacePickerInjected { - const entry = slots.entries(name)[0]! - return (entry.inject as () => WorkspacePickerInjected)() +/** Declare one or both holes with a single root registration ('root' is a single slot). */ +function declare(slots: SlotsService, ...names: HoleName[]): () => void { + const children = Object.fromEntries(names.map(name => [name, { kind: 'single', scope: 'root' }])) + return slots.register({ name: 'root', children } as never, () => null) } describe('ui-workspace apply', () => { - it('declares the independent Workspace service', () => { - expect(inject).toEqual(['slots', 'workspaces']) + it('declares the services it drives', () => { + expect(inject).toEqual(['slots', 'sessions', 'workspaces']) }) - it('registers the shared picker for declarations that arrive before or after apply', async () => { + it('registers browser and picker for declarations arriving before or after apply', async () => { const before = await bench() - declare(before.slots, 'sidebar.workspace') + declare(before.slots, 'sidebar.workspaces') await before.ctx.plugin({ inject: [...inject], apply }).await() - expect(before.slots.entries('sidebar.workspace')[0]!.component).toBe(WorkspacePicker) + expect(before.slots.entries('sidebar.workspaces')[0]!.component).toBe(WorkspaceBrowser) const after = await bench() await after.ctx.plugin({ inject: [...inject], apply }).await() @@ -47,23 +49,35 @@ describe('ui-workspace apply', () => { expect(after.slots.entries('conversation.empty.workspace')[0]!.component).toBe(WorkspacePicker) }) - it('routes name and path creation to WorkspacesService', async () => { + it('routes browser actions and picker creation to the services', async () => { const b = await bench() - declare(b.slots, 'sidebar.workspace') + declare(b.slots, 'sidebar.workspaces', 'conversation.empty.workspace') await b.ctx.plugin({ inject: [...inject], apply }).await() - const injected = injectedOf(b.slots, 'sidebar.workspace') - await injected.createWorkspace({ name: 'project' }) - await injected.createWorkspace({ path: '/tmp/project' }) - expect(b.create).toHaveBeenNthCalledWith(1, { name: 'project' }) - expect(b.create).toHaveBeenNthCalledWith(2, { path: '/tmp/project' }) + + const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)() + browser.startSession('ws' as never, 'prompt') + expect(b.startSession).toHaveBeenCalledWith('ws', 'prompt') + browser.open('session' as never) + expect(b.open).toHaveBeenCalledWith('session') + await browser.renameWorkspace('ws' as never, 'renamed') + expect(b.rename).toHaveBeenCalledWith('ws', 'renamed') + await browser.insertSessionBefore('ws' as never, 's1' as never, 's2' as never) + expect(b.insertSessionBefore).toHaveBeenCalledWith('ws', 's1', 's2') + await browser.createWorkspace({ name: 'project' }) + expect(b.create).toHaveBeenCalledWith({ name: 'project' }) + + const picker = (b.slots.entries('conversation.empty.workspace')[0]!.inject as () => WorkspacePickerInjected)() + await picker.createWorkspace({ path: '/tmp/project' }) + expect(b.create).toHaveBeenCalledWith({ path: '/tmp/project' }) }) - it('unregisters picker entries on teardown', async () => { + it('unregisters both entries on teardown', async () => { const b = await bench() - declare(b.slots, 'sidebar.workspace') + declare(b.slots, 'sidebar.workspaces', 'conversation.empty.workspace') const fiber = b.ctx.plugin({ inject: [...inject], apply }) await fiber.await() await fiber.dispose() - expect(b.slots.entries('sidebar.workspace')).toHaveLength(0) + expect(b.slots.entries('sidebar.workspaces')).toHaveLength(0) + expect(b.slots.entries('conversation.empty.workspace')).toHaveLength(0) }) }) diff --git a/packages/client/ui-sidebar/tests/rows.spec.tsx b/packages/client/ui-workspace/tests/rows.spec.tsx similarity index 97% rename from packages/client/ui-sidebar/tests/rows.spec.tsx rename to packages/client/ui-workspace/tests/rows.spec.tsx index 468ce550d9..fdc5c43b8e 100644 --- a/packages/client/ui-sidebar/tests/rows.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.spec.tsx @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' -import { IntentRowItem, ProjectRowItem, SessionNodeItem } from '../src/client/Rows.tsx' +import { IntentRowItem, ProjectRowItem, SessionNodeItem } from '../src/client/rows/Rows.tsx' import type { GroupNode, SessionNode } from '../src/client/tree.ts' afterEach(cleanup) @@ -10,7 +10,7 @@ afterEach(cleanup) const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId -describe('sidebar rows', () => { +describe('workspace browser rows', () => { it('renders an active Workspace and keeps its create action separate from toggling', () => { const onToggle = vi.fn() const onCreate = vi.fn() diff --git a/packages/client/ui-sidebar/tests/tree.spec.ts b/packages/client/ui-workspace/tests/tree.spec.ts similarity index 100% rename from packages/client/ui-sidebar/tests/tree.spec.ts rename to packages/client/ui-workspace/tests/tree.spec.ts diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 2b76d407f7..200e0811ce 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -934,10 +934,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: 'list(): Workspace[]', jsDoc: '/**\n * Synchronous workspace projection in durable registry order. Every\n * entity\'s `sessionIds` getter is already filtered by the startup/live\n * canonical-cwd header index; this method performs no persistence reads.\n * @returns a fresh ordered array of workspace entities.\n */', }, - { - signature: 'async touchSession(sessionId: SessionId): Promise', - jsDoc: '/**\n * Move one accounted, cwd-validated session to the front of its workspace.\n * Ungrouped sessions and candidates filtered by the header check are\n * no-ops. The owning workspace\'s relative position never changes.\n * @param sessionId - Session whose activity was observed.\n * @returns resolution after the possible record write.\n */', - }, { signature: 'async resolveByPath(path: string): Promise', jsDoc: '/**\n * Resolve by canonical directory path without creating or mutating a\n * workspace. A missing path rejects during `realpath`; an existing unowned\n * directory returns `undefined`.\n * @param path - Existing directory path in any spelling.\n * @returns the workspace owning the canonical path, when one exists.\n */', @@ -2498,7 +2494,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'Workspace', - declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', + declaration: 'export interface Workspace {\n readonly id: WorkspaceId;\n readonly path: string;\n readonly title: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly sessionIds: readonly SessionId[];\n setTitle(title: string): Promise;\n attachSession(sessionId: SessionId): Promise;\n insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise;\n detachSession(sessionId: SessionId): Promise;\n status(): Promise<\'ok\' | \'missing-dir\'>;\n}', }, ] diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 201bc555a9..d50dd000e1 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -14,7 +14,8 @@ import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' import type { Workspace, WorkspaceRecord } from '@deepseek-ai/dsh-workspace' import { - workspaceDomainState, workspaceRecord, WorkspaceId as brandWorkspaceId, WorkspaceNameConflictError, + workspaceDomainState, workspaceRecord, WorkspaceId as brandWorkspaceId, + WorkspaceMoveInvalidError, WorkspaceNameConflictError, } from '@deepseek-ai/dsh-workspace' // Type-only: brings the `ctx.tools` Context merge into this program (viewFor reads presenters). import type {} from '@deepseek-ai/dsh-tools' @@ -680,6 +681,72 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro } }, + async rename(request) { + const { payload } = request + const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId)) + if (workspace === undefined) { + return err(request, { + code: 'workspace-not-found', + message: `workspace "${payload.workspaceId}" not found`, + details: { workspaceId: payload.workspaceId }, + }) + } + const title = payload.title.trim() + // Uniqueness AND the same-title no-op both ride the create chain so + // they observe the state left by earlier queued renames — checked + // up front, a queued A→A could report success while an earlier A→B + // still lands afterwards. + const operation = workspaceCreationChain.then(async () => { + if (title === workspace.title) return + if (ctx.workspace.list().some(other => other.id !== workspace.id && other.title === title)) { + throw new WorkspaceNameConflictError(title) + } + await workspace.setTitle(title) + }) + workspaceCreationChain = operation.then(() => undefined, () => undefined) + try { + await operation + } catch (error: unknown) { + if (error instanceof WorkspaceNameConflictError) { + return err(request, { + code: 'workspace-name-conflict', + message: error.message, + details: { name: error.workspaceName }, + }) + } + throw error + } + return ok(request, { workspace: workspaceView(workspace) }) + }, + + async insertSessionBefore(request) { + const { payload } = request + const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId)) + if (workspace === undefined) { + return err(request, { + code: 'workspace-not-found', + message: `workspace "${payload.workspaceId}" not found`, + details: { workspaceId: payload.workspaceId }, + }) + } + try { + await workspace.insertSessionBefore(payload.sessionId, payload.beforeSessionId) + } catch (error: unknown) { + // Only the entity's unaccounted-id rejection is the business code; + // storage/durability failures propagate as internal errors. + if (!(error instanceof WorkspaceMoveInvalidError)) throw error + return err(request, { + code: 'workspace-move-invalid', + message: error.message, + details: { + workspaceId: payload.workspaceId, + sessionId: payload.sessionId, + ...payload.beforeSessionId === undefined ? {} : { beforeSessionId: payload.beforeSessionId }, + }, + }) + } + return ok(request, { workspace: workspaceView(workspace) }) + }, }, host: { diff --git a/packages/host/apiproxy/src/api/rpc-map.ts b/packages/host/apiproxy/src/api/rpc-map.ts index 1f0f9acef4..68b6289858 100644 --- a/packages/host/apiproxy/src/api/rpc-map.ts +++ b/packages/host/apiproxy/src/api/rpc-map.ts @@ -19,6 +19,8 @@ export interface RpcMethodMap { 'host.describe': HostApi['describe'] 'workspace.list': WorkspaceApi['list'] 'workspace.create': WorkspaceApi['create'] + 'workspace.rename': WorkspaceApi['rename'] + 'workspace.insertSessionBefore': WorkspaceApi['insertSessionBefore'] } /** Business request payload of method K (reaches through the RpcRequest narrow form to payload). */ diff --git a/packages/host/apiproxy/src/api/rpc.schema.ts b/packages/host/apiproxy/src/api/rpc.schema.ts index 3b290e18c3..d83ae2ce98 100644 --- a/packages/host/apiproxy/src/api/rpc.schema.ts +++ b/packages/host/apiproxy/src/api/rpc.schema.ts @@ -40,6 +40,7 @@ export const rpcErrorSchema: z.ZodType = z.discriminatedUnion('code', z.object({ code: z.literal('workspace-not-found'), message: z.string(), details: z.object({ workspaceId: z.string() }) }), z.object({ code: z.literal('workspace-invalid-path'), message: z.string(), details: z.object({ path: z.string() }) }), z.object({ code: z.literal('workspace-name-conflict'), message: z.string(), details: z.object({ name: z.string() }) }), + z.object({ code: z.literal('workspace-move-invalid'), message: z.string(), details: z.object({ workspaceId: z.string(), sessionId: z.string(), beforeSessionId: z.string().optional() }) }), z.object({ code: z.literal('agent-busy'), message: z.string(), details: z.object({ reason: z.string() }) }), z.object({ code: z.literal('internal'), message: z.string(), details: z.object({}) }), ]) as unknown as z.ZodType diff --git a/packages/host/apiproxy/src/api/rpc.ts b/packages/host/apiproxy/src/api/rpc.ts index dbcc975d04..ad06c42fbe 100644 --- a/packages/host/apiproxy/src/api/rpc.ts +++ b/packages/host/apiproxy/src/api/rpc.ts @@ -37,6 +37,7 @@ export interface RpcErrorDetailsMap { 'workspace-not-found': { workspaceId: string } 'workspace-invalid-path': { path: string } 'workspace-name-conflict': { name: string } + 'workspace-move-invalid': { workspaceId: string; sessionId: SessionId; beforeSessionId?: SessionId } 'agent-busy': { reason: string } 'internal': {} } diff --git a/packages/host/apiproxy/src/api/workspace.schema.ts b/packages/host/apiproxy/src/api/workspace.schema.ts index a193fb0c57..47c3ae6d59 100644 --- a/packages/host/apiproxy/src/api/workspace.schema.ts +++ b/packages/host/apiproxy/src/api/workspace.schema.ts @@ -44,3 +44,29 @@ export const workspaceCreateValueSchema = z.object({ workspace: workspaceViewSchema, created: z.boolean(), }) satisfies z.ZodType>> + +/** workspace.rename request payload: the new title must be non-blank. */ +export const workspaceRenameRequestSchema = z.object({ + workspaceId: workspaceIdSchema, + title: z.string(), +}).refine( + payload => payload.title.trim() !== '', + { message: 'workspace.rename requires a non-blank title' }, +) satisfies z.ZodType>> + +/** workspace.rename response value. */ +export const workspaceRenameValueSchema = z.object({ + workspace: workspaceViewSchema, +}) satisfies z.ZodType>> + +/** workspace.insertSessionBefore request payload (anchor omitted = append to end). */ +export const workspaceInsertSessionBeforeRequestSchema = z.object({ + workspaceId: workspaceIdSchema, + sessionId: sessionIdSchema, + beforeSessionId: sessionIdSchema.optional(), +}) satisfies z.ZodType>> + +/** workspace.insertSessionBefore response value. */ +export const workspaceInsertSessionBeforeValueSchema = z.object({ + workspace: workspaceViewSchema, +}) satisfies z.ZodType>> diff --git a/packages/host/apiproxy/src/api/workspace.ts b/packages/host/apiproxy/src/api/workspace.ts index 86c20e2ff5..6ec636126b 100644 --- a/packages/host/apiproxy/src/api/workspace.ts +++ b/packages/host/apiproxy/src/api/workspace.ts @@ -24,7 +24,10 @@ export interface WorkspaceView { path: string /** Unique display title (defaults to the path basename at create). */ title: string - /** Sessions accounted under this workspace, newest-first for display. */ + /** + * Sessions accounted under this workspace, in manually owned order + * (attach prepends, insertSessionBefore reorders; activity never does). + */ sessionIds: SessionId[] /** ISO-8601 creation instant. */ createdAt: string @@ -52,4 +55,27 @@ export interface WorkspaceApi { */ create(request: RpcRequest<{ path?: string; name?: string }>): Promise> + + /** + * Renames a workspace. `title` is trimmed and must be non-empty + * (schema-enforced). An unknown id fails with `workspace-not-found`; a + * title equal to another workspace's fails with `workspace-name-conflict`. + * Renaming to the current title is a no-op success (no durable write). + */ + rename(request: RpcRequest<{ workspaceId: WorkspaceId; title: string }>): + Promise> + + /** + * Moves an accounted session within its workspace's manual order, + * DOM-insertBefore-like: with `beforeSessionId` the session is inserted + * before that anchor; omitted appends to the end. An unknown workspace + * fails with `workspace-not-found`; a session or anchor not accounted by + * the workspace fails with `workspace-move-invalid`. A move to the current + * position is a no-op success. + */ + insertSessionBefore(request: RpcRequest<{ + workspaceId: WorkspaceId + sessionId: SessionId + beforeSessionId?: SessionId + }>): Promise> } diff --git a/packages/host/apiproxy/src/fetch/client.ts b/packages/host/apiproxy/src/fetch/client.ts index 81749fc219..91c4405ace 100644 --- a/packages/host/apiproxy/src/fetch/client.ts +++ b/packages/host/apiproxy/src/fetch/client.ts @@ -23,7 +23,9 @@ import { } from '../api/sessions.schema.ts' import { workspaceCreateValueSchema, + workspaceInsertSessionBeforeValueSchema, workspaceListValueSchema, + workspaceRenameValueSchema, } from '../api/workspace.schema.ts' /** @@ -55,6 +57,8 @@ export interface IApiClient { workspace: { list(payload: RequestPayload<'workspace.list'>, signal?: AbortSignal): Promise>> create(payload: RequestPayload<'workspace.create'>, signal?: AbortSignal): Promise>> + rename(payload: RequestPayload<'workspace.rename'>, signal?: AbortSignal): Promise>> + insertSessionBefore(payload: RequestPayload<'workspace.insertSessionBefore'>, signal?: AbortSignal): Promise>> } events: { mux(payload: Parameters[0]['payload'], signal: AbortSignal, onOpen?: () => void): AsyncIterable> @@ -77,6 +81,8 @@ const UNARY_VALUE_SCHEMAS: { [K in keyof RpcMethodMap]: z.ZodType this.callUnary('workspace.list', payload, signal), create: (payload, signal) => this.callUnary('workspace.create', payload, signal), + rename: (payload, signal) => this.callUnary('workspace.rename', payload, signal), + insertSessionBefore: (payload, signal) => this.callUnary('workspace.insertSessionBefore', payload, signal), } readonly events: IApiClient['events'] = { diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index e876d664b2..91762810e8 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -24,7 +24,9 @@ import { import { hostDescribeRequestSchema } from '../api/host.schema.ts' import { workspaceCreateRequestSchema, + workspaceInsertSessionBeforeRequestSchema, workspaceListRequestSchema, + workspaceRenameRequestSchema, } from '../api/workspace.schema.ts' /** @@ -50,6 +52,8 @@ const UNARY_ROUTES: UnaryRoutes = { 'host.describe': { schema: hostDescribeRequestSchema, invoke: (api, r) => api.host.describe(r) }, 'workspace.list': { schema: workspaceListRequestSchema, invoke: (api, r) => api.workspace.list(r) }, 'workspace.create': { schema: workspaceCreateRequestSchema, invoke: (api, r) => api.workspace.create(r) }, + 'workspace.rename': { schema: workspaceRenameRequestSchema, invoke: (api, r) => api.workspace.rename(r) }, + 'workspace.insertSessionBefore': { schema: workspaceInsertSessionBeforeRequestSchema, invoke: (api, r) => api.workspace.insertSessionBefore(r) }, } /** Route lookup that narrows an arbitrary path segment to a map key (single cast point for the string→key refinement). */ diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index 7dec5980eb..25b095b99f 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -37,6 +37,8 @@ function scriptedApi(overrides: { workspace: { list: r => ok(r, { items: [] }), create: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' }, created: true }), + rename: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' } }), + insertSessionBefore: r => ok(r, { workspace: { workspaceId: 'w1' as never, path: '/t', title: 't', sessionIds: [], createdAt: '0', updatedAt: '0' } }), }, events: { mux: () => empty(), host: () => empty(), ...overrides.events }, respond: overrides.respond ?? (() => Promise.resolve({ accepted: false as const, reason: 'not-pending' as const })), diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index ede6acb9ac..e4b1d33e87 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -52,6 +52,18 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra result: { ok: true, value: { workspace: { workspaceId: 'w1' as never, path: '/w', title: 'w', sessionIds: [], createdAt: 't', updatedAt: 't' }, created: true } }, } }, + async rename(request) { + return { + rpcId: request.rpcId, + result: { ok: true, value: { workspace: { workspaceId: 'w1' as never, path: '/w', title: 'w', sessionIds: [], createdAt: 't', updatedAt: 't' } } }, + } + }, + async insertSessionBefore(request) { + return { + rpcId: request.rpcId, + result: { ok: true, value: { workspace: { workspaceId: 'w1' as never, path: '/w', title: 'w', sessionIds: [], createdAt: 't', updatedAt: 't' } } }, + } + }, }, events: { mux: (_request, signal) => stream(muxFrames, signal), diff --git a/packages/workspace/workspace/src/entity.ts b/packages/workspace/workspace/src/entity.ts index 7f213db0b8..1df3eacb3d 100644 --- a/packages/workspace/workspace/src/entity.ts +++ b/packages/workspace/workspace/src/entity.ts @@ -15,6 +15,17 @@ import type { WorkspaceRecord } from './spec.ts' import type { Workspace, WorkspaceId } from './types.ts' import { realpathNormalize } from './paths.ts' +/** An insertSessionBefore request named a session or anchor not on the account (storage failures stay plain errors). */ +export class WorkspaceMoveInvalidError extends Error { + /** + * @param message - Which id was unaccounted and where. + */ + constructor(message: string) { + super(message) + this.name = 'WorkspaceMoveInvalidError' + } +} + /** * The registry-owned machinery an entity mutates through. Entities never see * the registry itself — only the open table, the canonical session-path @@ -137,30 +148,27 @@ export class WorkspaceEntity implements Workspace { : { ...record, sessionIds: [sessionId, ...record.sessionIds] }) } - /** - * Test the durable candidate account without applying header projection. - * @param sessionId - Candidate session id. - * @returns whether this workspace's stored account contains the id. - */ - hasSession(sessionId: SessionId): boolean { - return this.record.sessionIds.includes(sessionId) - } - - /** - * Move one validated accounted session to the front without touching peers. - * @param sessionId - Accounted session whose activity was observed. - */ - async touchSession(sessionId: SessionId): Promise { - if ( - this.host.sessionPath(sessionId) !== this.record.path - || this.record.sessionIds[0] === sessionId - ) return - await this.mutate(record => !record.sessionIds.includes(sessionId) || record.sessionIds[0] === sessionId - ? record - : { - ...record, - sessionIds: [sessionId, ...record.sessionIds.filter(id => id !== sessionId)], - }) + async insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise { + await this.mutate((record) => { + if (!record.sessionIds.includes(sessionId)) { + throw new WorkspaceMoveInvalidError( + `cannot move session '${sessionId}' in workspace '${record.path}': the session is not accounted`, + ) + } + if (beforeSessionId !== undefined && !record.sessionIds.includes(beforeSessionId)) { + throw new WorkspaceMoveInvalidError( + `cannot move session '${sessionId}' before '${beforeSessionId}' in workspace '${record.path}': ` + + 'the anchor session is not accounted', + ) + } + if (beforeSessionId === sessionId) return record + const without = record.sessionIds.filter(id => id !== sessionId) + const at = beforeSessionId === undefined ? without.length : without.indexOf(beforeSessionId) + const sessionIds = [...without.slice(0, at), sessionId, ...without.slice(at)] + return sessionIds.every((id, index) => id === record.sessionIds[index]) + ? record + : { ...record, sessionIds } + }) } async detachSession(sessionId: SessionId): Promise { diff --git a/packages/workspace/workspace/src/index.ts b/packages/workspace/workspace/src/index.ts index c20c2143c6..0f849e7374 100644 --- a/packages/workspace/workspace/src/index.ts +++ b/packages/workspace/workspace/src/index.ts @@ -14,6 +14,8 @@ import type {} from '@deepseek-ai/dsh-session-persistence' import type { DomainGlobal, KvTable } from '@deepseek-ai/dsh-storage-domain' import { WorkspaceEntity } from './entity.ts' import type { WorkspaceEntityHost } from './entity.ts' + +export { WorkspaceMoveInvalidError } from './entity.ts' import { realpathNormalize } from './paths.ts' import { workspaceDomainSpec } from './spec.ts' import type { WorkspaceDomainState, WorkspaceRecord } from './spec.ts' @@ -47,6 +49,7 @@ export class WorkspaceNameConflictError extends Error { } } + declare module 'cordis' { interface Context { workspace: WorkspaceRegistry @@ -82,7 +85,6 @@ export class WorkspaceRegistry extends Service { private readonly headers = new Map() private readonly sessionPaths = new Map() private readonly invalidSessionPaths = new Map() - private readonly pendingTouches = new Map>() private operationTail: Promise = Promise.resolve() private readonly host: WorkspaceEntityHost = { @@ -120,13 +122,6 @@ export class WorkspaceRegistry extends Service { this.validateStoredState(this.requireState()) this.rebuildEntities() this.reportFilteredCandidates() - // Session activity is authoritative even when no RPC/SSE consumer is - // connected. This service-owned listener is disposed with the registry. - this.ctx.on('session/event', (session) => { - void this.touchSession(session.id).catch((error: unknown) => { - this.ctx.logger.warn(`workspace activity touch failed for session '${session.id}': ${String(error)}`) - }) - }) } /** @@ -173,32 +168,6 @@ export class WorkspaceRegistry extends Service { }) } - /** - * Move one accounted, cwd-validated session to the front of its workspace. - * Ungrouped sessions and candidates filtered by the header check are - * no-ops. The owning workspace's relative position never changes. - * @param sessionId - Session whose activity was observed. - * @returns resolution after the possible record write. - */ - async touchSession(sessionId: SessionId): Promise { - const pending = this.pendingTouches.get(sessionId) - if (pending !== undefined) { - await pending - return - } - for (const entity of this.entities.values()) { - if (!entity.hasSession(sessionId)) continue - const touch = entity.touchSession(sessionId) - this.pendingTouches.set(sessionId, touch) - try { - await touch - } finally { - this.pendingTouches.delete(sessionId) - } - return - } - } - /** * Resolve by canonical directory path without creating or mutating a * workspace. A missing path rejects during `realpath`; an existing unowned diff --git a/packages/workspace/workspace/src/types.ts b/packages/workspace/workspace/src/types.ts index ca254ca2cb..09d37213cc 100644 --- a/packages/workspace/workspace/src/types.ts +++ b/packages/workspace/workspace/src/types.ts @@ -41,10 +41,12 @@ export interface Workspace { readonly updatedAt: string /** - * Header-validated sessions in newest-first display order. The durable - * candidate account is filtered synchronously: missing headers, invalid - * cwd values, and canonical cwd mismatches are never returned. A subsequent - * workspace mutation prunes those filtered candidates durably. + * Header-validated sessions in manually owned order: a new session is + * prepended at attach, explicit reordering goes through + * `insertSessionBefore`, and activity never reorders. The durable candidate + * account is filtered synchronously: missing headers, invalid cwd values, + * and canonical cwd mismatches are never returned. A subsequent workspace + * mutation prunes those filtered candidates durably. */ readonly sessionIds: readonly SessionId[] @@ -57,8 +59,7 @@ export interface Workspace { /** * Prepend a session to this workspace's candidate account. An already - * accounted id resolves without writing; activity-driven reordering uses - * `WorkspaceRegistry.touchSession` instead. A new id's live or persisted + * accounted id resolves without writing. A new id's live or persisted * header cwd must resolve to an existing directory equal to {@link path}; * unknown ids, missing or invalid cwd values, and mismatches reject without * writing. @@ -67,6 +68,18 @@ export interface Workspace { */ attachSession(sessionId: SessionId): Promise + /** + * Move an accounted session within the manual order, DOM-insertBefore-like: + * with an anchor the session lands before it, without one it appends to the + * end. Only the moved id changes position. A session or anchor absent from + * the account rejects without writing; a move to the current position + * resolves without writing (decided on the domain write chain). + * @param sessionId - The accounted session to move. + * @param beforeSessionId - Accounted anchor to insert before; omitted appends. + * @returns resolution after durability. + */ + insertSessionBefore(sessionId: SessionId, beforeSessionId?: SessionId): Promise + /** * Remove a session from this workspace's account. Idempotent: an id not on * the account resolves without writing (decided on the domain write chain, diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index cde0b35098..bdefc2ec82 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -10,7 +10,6 @@ import type { DomainChanged } from '@deepseek-ai/dsh-storage-domain' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionHeader } from '@deepseek-ai/dsh-session' import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts' -import { WorkspaceEntity } from '../src/entity.ts' import WorkspaceRegistry, { WorkspaceId, WorkspaceNameConflictError } from '../src/index.ts' import type { WorkspaceDomainState, WorkspaceRecord } from '../src/index.ts' @@ -434,13 +433,12 @@ describe('WorkspaceRegistry create and lookup', () => { }) describe('Workspace session ordering', () => { - it('prepends new attaches, keeps repeat attach idempotent, and touches one id only', async () => { + it('prepends new attaches and keeps repeat attach idempotent', async () => { const dir = await makeDir('attach-order') const result = await harness() result.setSessions([ header('s1', dir, 1), header('s2', dir, 2), - header('ungrouped', dir, 3), ]) const workspace = await result.registry.create(dir) await workspace.attachSession(SessionId('s1')) @@ -448,59 +446,7 @@ describe('Workspace session ordering', () => { expect(workspace.sessionIds).toEqual(['s2', 's1']) await workspace.attachSession(SessionId('s1')) expect(workspace.sessionIds).toEqual(['s2', 's1']) - - const beforeTouch = result.changes.length - await Promise.all([ - result.registry.touchSession(SessionId('s1')), - result.registry.touchSession(SessionId('s1')), - ]) - expect(workspace.sessionIds).toEqual(['s1', 's2']) - expect(result.changes).toHaveLength(beforeTouch + 1) - await result.registry.touchSession(SessionId('s1')) - expect(result.changes).toHaveLength(beforeTouch + 1) - await result.registry.touchSession(SessionId('ungrouped')) - expect(result.changes).toHaveLength(beforeTouch + 1) - expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s1', 's2']) - }) - - it('does not resurrect a session detached before its queued touch', async () => { - const dir = await makeDir('detach-touch-race') - const result = await harness({ sessions: [header('s1', dir), header('s2', dir)] }) - const workspace = await result.registry.create(dir) - await workspace.attachSession(SessionId('s1')) - await workspace.attachSession(SessionId('s2')) - await Promise.all([ - workspace.detachSession(SessionId('s1')), - result.registry.touchSession(SessionId('s1')), - ]) - const written = result.changes.length - await workspace.detachSession(SessionId('absent')) - expect(result.changes).toHaveLength(written) - expect(workspace.sessionIds).toEqual(['s2']) - }) - - it('does not reinsert a candidate absent at the durable touch slot', async () => { - const dir = await makeDir('stale-touch') - const id = WorkspaceId('00000000-0000-4000-8000-000000000030') - let durable = record(dir, ['s2', 's1']) - const table = { - update: async ( - _id: WorkspaceId, - update: (current: WorkspaceRecord) => WorkspaceRecord, - ): Promise => { - durable = { ...durable, sessionIds: [SessionId('s2')] } - durable = update(durable) - return durable - }, - } - const entity = new WorkspaceEntity({ - table: () => table as never, - sessionPath: () => dir, - readSessionHeader: async () => header('s1', dir), - rememberSessionPath: () => {}, - }, id, record(dir, ['s2', 's1'])) - await entity.touchSession(SessionId('s1')) - expect(durable.sessionIds).toEqual(['s2']) + expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s2', 's1']) }) it('validates a lazy live session without requiring it in persistence.list()', async () => { @@ -546,66 +492,6 @@ describe('Workspace session ordering', () => { expect(workspace.sessionIds).toEqual(['s1']) }) - it('keeps workspace order stable while touch order survives reload', async () => { - const older = await makeDir('stable-older') - const newer = await makeDir('stable-newer') - const sessions = [ - header('old-1', older, 100), - header('old-2', older, 200), - header('new-1', newer, 300), - ] - const pool = new MemoryMediaPool() - const first = await harness({ pool, sessions }) - const originalWorkspaceIds = first.registry.list().map(workspace => workspace.id) - const oldWorkspace = first.registry.list().find(workspace => workspace.path === older)! - expect(oldWorkspace.sessionIds).toEqual(['old-2', 'old-1']) - await first.registry.touchSession(SessionId('old-1')) - expect(oldWorkspace.sessionIds).toEqual(['old-1', 'old-2']) - expect(first.registry.list().map(workspace => workspace.id)).toEqual(originalWorkspaceIds) - await first.fiber.dispose() - - const reloaded = await harness({ pool, sessions }) - expect(reloaded.registry.list().map(workspace => workspace.id)).toEqual(originalWorkspaceIds) - expect(reloaded.registry.list().find(workspace => workspace.path === older)!.sessionIds) - .toEqual(['old-1', 'old-2']) - }) - - it('persists activity order from session/event without any stream consumer', async () => { - const dir = await makeDir('event-touch') - const result = await harness({ sessionStore: true }) - const workspace = await result.registry.create(dir) - const first = result.ctx.sessions.create(SessionId('event-first'), { meta: { cwd: dir } }) - result.ctx.sessions.create(SessionId('event-second'), { meta: { cwd: dir } }) - await workspace.attachSession(SessionId('event-first')) - await workspace.attachSession(SessionId('event-second')) - expect(workspace.sessionIds).toEqual(['event-second', 'event-first']) - - first.append('turn/start', { - turn: 1, - trigger: { kind: 'message', source: { kind: 'user' } }, - }) - await vi.waitFor(() => { expect(workspace.sessionIds).toEqual(['event-first', 'event-second']) }) - expect(storedRecord(result.pool, workspace.id).sessionIds) - .toEqual(['event-first', 'event-second']) - }) - - it('contains a background activity write failure at the service listener', async () => { - const dir = await makeDir('event-touch-failure') - const result = await harness({ sessionStore: true }) - const workspace = await result.registry.create(dir) - const first = result.ctx.sessions.create(SessionId('failed-first'), { meta: { cwd: dir } }) - result.ctx.sessions.create(SessionId('failed-second'), { meta: { cwd: dir } }) - await workspace.attachSession(SessionId('failed-first')) - await workspace.attachSession(SessionId('failed-second')) - const warn = vi.spyOn(result.ctx.logger, 'warn') - result.pool.failNextWrites = 1 - first.append('turn/start', { - turn: 1, - trigger: { kind: 'message', source: { kind: 'user' } }, - }) - await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith(expect.stringContaining('touch failed')) }) - expect(workspace.sessionIds).toEqual(['failed-second', 'failed-first']) - }) }) describe('header-validated membership projection', () => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7f19dcce27..7301079cd1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1014,6 +1014,10 @@ importers: version: 18.3.1 packages/client/ui-workspace: + dependencies: + clsx: + specifier: ^2.0.0 + version: 2.1.1 devDependencies: '@deepseek-ai/dsh-client-runtime': specifier: workspace:^ From b1b180e098aef9e39e3c2e889dca7dcd48fea6c1 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 00:57:21 +0800 Subject: [PATCH 081/113] =?UTF-8?q?fix(gui):=20CI=20gate=20repairs=20?= =?UTF-8?q?=E2=80=94=20docs,=20coverage,=20HMR=20re-registration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Regenerate the module-graph/config-catalog/event-graph docs for the locale rename and new packages; allowlist the three settings READMEs; complete the RFC code block and add its English pair. Cover the ThemeService media-query paths (stubbed matchMedia) and mark the unreachable registry fallback. General section re-registration now judges presence on the slot ledger instead of a local disposer, which went stale when an HMR collapse removed the entry. --- ...-25-client-settings-locale-theme.i18n.yaml | 6 + ...2026-07-25-client-settings-locale-theme.md | 112 ++++++++++++++++++ ...6-07-25-client-settings-locale-theme.zh.md | 13 ++ docs/config-catalog.md | 5 +- docs/event-producer-consumer.md | 2 + docs/module-graph.md | 26 +++- .../ui-settings-general/src/client/index.ts | 20 ++-- packages/client/ui-theme/src/client/index.ts | 1 + packages/client/ui-theme/tests/theme.spec.ts | 51 +++++++- .../verify-package-readme-model-experience.ts | 3 + 10 files changed, 225 insertions(+), 14 deletions(-) create mode 100644 .agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml create mode 100644 .agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml new file mode 100644 index 0000000000..54fb6ee9ee --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.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 +2026-07-25-client-settings-locale-theme.md: 25e22c728ea509613c4d7f6cdfcd09faf4685760 +2026-07-25-client-settings-locale-theme.zh.md: 9c2457b254aa826291d4c5a4e115e9ba2d391974 diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md new file mode 100644 index 0000000000..25e22c728e --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md @@ -0,0 +1,112 @@ +# Agent Note: Client Settings, Locale, and Theme layering + +Status: proposed + +English | [中文](2026-07-25-client-settings-locale-theme.zh.md) + +## Problem + +The browser client's existing Settings is written directly inside the Sidebar, and language and theme are applied by component-local state mutating the DOM directly. As a result Settings cannot be extended by independent plugins, preference state has no stable cross-plugin service contract, and the theme registry carries both state and presentation responsibilities. + +## Proposal + +The Sidebar declares the `sidebar.settings` single slot; `ui-settings` occupies it and declares the `settings.section` list slot. Each section is contributed by an independent plugin; the Settings shell only reads entry metadata from the slot ledger to build the navigation, rendering the current section via `only`. + +The Settings entry is the Settings row in the sidebar Foot; clicking it directly opens a 1080×700 centered overlay (black 24% mask); the close button, a mask click, and ESC all close it. There is no intermediate menu form of any kind. + +`@deepseek-ai/dsh-client-locale` provides `ctx.locale`; `ui-theme` provides `ctx.theme`. Both services read through a getter, write through a setter, and publish immutable snapshots via typed Cordis change events; each service persists its own preference (storing only the id, with bad values falling back to the default). + +General's apply layer subscribes to `locale/change` and `theme/change` and projects the snapshots into the Zustand store declared by that section. React components only read `useStore` and write through the injected setter callbacks, never reading ctx or the services. + +The theme preference has three states — `light`, `dark`, `system` — defaulting to `system` (when no persisted preference exists or the value is bad). Resolving system belongs to the theme domain: ThemeService holds the `prefers-color-scheme` matchMedia listener (environment sensing, not DOM presentation) and re-emits the snapshot when the preference is system and the system color scheme changes; the snapshot carries both `preference` and the resolved `active` definition. + +The theme service never touches the DOM. `ui-layout` reads the Theme getter initially and then subscribes to `theme/change`; the presenter owned by Layout updates `body[data-ds-dark-theme]` and the theme tokens according to `active`. The presenter has no notion of system — it consumes only resolved results. + +### First-phase section scope + +| section | Plugin | First-phase content | +|---|---|---| +| General | `ui-settings-general` | Language (Selector dropdown) and Appearance (Light/Dark/System three cubes) genuinely switch; Permission and Tool Call are visual skeletons only, with no write operations | +| Models | `ui-settings-models` | Navigation item only; the content area is empty | +| Plugin | no package | Not built this phase, and the navigation does not show the item (an external-link entry with no target never renders; once a later plugin registers the section it appears automatically) | + +The first phase localizes only the copy inside the Settings overlay (the General rows plus the navigation); copy on other pages is untouched. + +### Slot topology + +```text +root +└─ sidebar + └─ sidebar.settings single/root + └─ ui-settings + └─ settings.section list/root + ├─ general ui-settings-general + └─ models ui-settings-models +``` + +Section contributions use declaration-aware deferral and do not depend on the client manifest's apply order. + +### Service contracts + +```ts +type ThemePreference = 'light' | 'dark' | 'system' + +interface ThemeDefinition { + id: string + colorScheme: 'light' | 'dark' + tokens: Record +} + +interface ThemeSnapshot { + preference: ThemePreference + active: ThemeDefinition // system 已解析为具体 light/dark 定义 + themes: readonly ThemeDefinition[] + revision: number +} + +interface LocaleDefinition { + id: 'zh' | 'en' + label: string +} + +interface LocaleSnapshot { + active: 'zh' | 'en' + locales: readonly LocaleDefinition[] + revision: number +} + +interface Events { + /** @param snapshot - Current locale registry snapshot. @mode emit */ + 'locale/change'(snapshot: LocaleSnapshot): void + /** @param snapshot - Current theme registry snapshot. @mode emit */ + 'theme/change'(snapshot: ThemeSnapshot): void +} +``` + +Locale ships with 中文 and English built in; `setLocale`/`setTheme` are the only write entry points, and an unknown id fails. + +## Alternatives considered + +**Having the app shell subscribe to preferences centrally and re-render the root slot tree.** A language or theme change only needs to update the actual consumers; a whole-tree refresh amplifies the blast radius and wires business preferences into the shell. + +**The theme service mutating the DOM directly.** The registry service would then depend on the presentation environment, with unclear lifecycle and global-style ownership; Layout already owns the page-root presentation boundary. + +**Resolving system in the Layout presenter.** The presenter would need its own matchMedia subscription and would pick the concrete definition out of the themes list, forcing the presentation layer to understand preference semantics; resolving on the service side gives every consumer the same resolved snapshot. + +**Settings importing and enumerating the sections.** Adding a page would require modifying the shell plugin, breaking the composition model where each feature occupies a slot from its own plugin. + +**Injecting the Locale/Theme snapshots into React directly.** Inject results are cached by entry identity, so volatile values go stale; hand-rolling a React hook per service also bypasses the slot store's unified binding. + +## Acceptance criteria + +- The Settings shell depends only on the slot ledger, never on any section implementation. +- Locale and Theme writes go only through the setters; ongoing synchronization goes only through the change events. +- The General store initializes from the getters and is thereafter updated by the two events with local re-renders. +- Layout applies the theme snapshot on its own and the theme service never accesses the DOM; no system branch appears in the presenter. +- 中文/English and Light/Dark/System switch and are restored after a refresh; with the preference on system, a system color-scheme change takes effect immediately. +- Models has only a navigation item and an empty content area; the Permission and Tool Call skeletons perform no writes. +- The overlay closes via the close button, a mask click, and ESC. + +## Risks + +The apply order of slot declarations and contributions is not fixed, so every new section must keep declaration-aware registration and idempotence guards. Service events may fire before a section's first render, so both the General store's init and the controller attach must align to the current snapshot from the getters. Layout must clean up the global attributes it set on unmount, and ThemeService must remove its matchMedia listener on dispose, so nothing lingers after HMR. diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md index d3c61794b9..9c2457b254 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md @@ -2,6 +2,8 @@ Status: proposed +[English](2026-07-25-client-settings-locale-theme.md) | 中文 + ## Problem 浏览器端已有的 Settings 直接写在 Sidebar 内,语言和主题也由组件本地状态直接改 DOM。这使 Settings 无法由独立插件扩展,偏好状态没有稳定的跨插件服务契约,主题 registry 同时承担状态与呈现职责。 @@ -49,6 +51,12 @@ section contribution 使用 declaration-aware deferral,不依赖 client manife ```ts type ThemePreference = 'light' | 'dark' | 'system' +interface ThemeDefinition { + id: string + colorScheme: 'light' | 'dark' + tokens: Record +} + interface ThemeSnapshot { preference: ThemePreference active: ThemeDefinition // system 已解析为具体 light/dark 定义 @@ -56,6 +64,11 @@ interface ThemeSnapshot { revision: number } +interface LocaleDefinition { + id: 'zh' | 'en' + label: string +} + interface LocaleSnapshot { active: 'zh' | 'en' locales: readonly LocaleDefinition[] diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6c7627aca4..ede904e1a5 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2017,12 +2017,15 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-agent` ([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts)) - `@deepseek-ai/dsh-client-connection` — requires `httpServer` · `apiProxy` ([`packages/client/connection/src/index.ts`](../packages/client/connection/src/index.ts)) -- `@deepseek-ai/dsh-client-i18n` ([`packages/client/i18n/src/index.ts`](../packages/client/i18n/src/index.ts)) +- `@deepseek-ai/dsh-client-locale` ([`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts)) - `@deepseek-ai/dsh-client-modules` — requires `httpServer` · `loader` ([`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts)) - `@deepseek-ai/dsh-client-runtime` ([`packages/client/runtime/src/index.ts`](../packages/client/runtime/src/index.ts)) - `@deepseek-ai/dsh-client-ui-conversation` ([`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts)) - `@deepseek-ai/dsh-client-ui-layout` ([`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts)) - `@deepseek-ai/dsh-client-ui-question` — requires `tools` · `userInteraction` ([`packages/client/ui-question/src/index.ts`](../packages/client/ui-question/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-settings` ([`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-settings-general` ([`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-settings-models` ([`packages/client/ui-settings-models/src/index.ts`](../packages/client/ui-settings-models/src/index.ts)) - `@deepseek-ai/dsh-client-ui-sidebar` ([`packages/client/ui-sidebar/src/index.ts`](../packages/client/ui-sidebar/src/index.ts)) - `@deepseek-ai/dsh-client-ui-theme` ([`packages/client/ui-theme/src/index.ts`](../packages/client/ui-theme/src/index.ts)) - `@deepseek-ai/dsh-client-ui-trajectory` ([`packages/client/ui-trajectory/src/index.ts`](../packages/client/ui-trajectory/src/index.ts)) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d9521f7d67..2c1e85fb3c 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -63,6 +63,8 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `internal/dispatch` | - | [`compact`](../packages/compact/compact), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`pty-local`](../packages/pty/pty-local), `runtime`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`workflow`](../packages/workflow/workflow) | | `internal/plugin` | - | `hmr`, `modules`, `webserver` | | `internal/status` | - | [`agent`](../packages/core/agent) | +| `locale/change` | `locale` (`emit`) | `ui-settings-general`, `ui-settings-models` | | `slots/changed` | `runtime` (`emit`) | - | +| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-settings-general` | Maintenance mode: generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program. diff --git a/docs/module-graph.md b/docs/module-graph.md index 9e8b3adf8a..c47bd92d83 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -136,13 +136,16 @@ flowchart TD subgraph group_client["packages/client"] pkg_client_connection["client-connection"] pkg_client_hmr["client-hmr"] - pkg_client_i18n["client-i18n"] + pkg_client_locale["client-locale"] pkg_client_modules["client-modules"] pkg_client_runtime["client-runtime"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_layout["client-ui-layout"] pkg_client_ui_primitives["client-ui-primitives"] pkg_client_ui_question["client-ui-question"] + pkg_client_ui_settings["client-ui-settings"] + pkg_client_ui_settings_general["client-ui-settings-general"] + pkg_client_ui_settings_models["client-ui-settings-models"] pkg_client_ui_sidebar["client-ui-sidebar"] pkg_client_ui_slots["client-ui-slots"] pkg_client_ui_theme["client-ui-theme"] @@ -225,7 +228,7 @@ flowchart TD pkg_subagent_subprocess --> pkg_invariants pkg_acp_snapshot --> pkg_invariants pkg_loader_smoke --> pkg_invariants - pkg_client_i18n --> pkg_invariants + pkg_client_locale --> pkg_invariants pkg_client_modules --> pkg_invariants pkg_client_runtime --> pkg_invariants pkg_client_ui_primitives --> pkg_invariants @@ -253,7 +256,19 @@ flowchart TD pkg_client_ui_conversation --> pkg_invariants pkg_client_ui_layout --> pkg_client_runtime pkg_client_ui_layout --> pkg_client_ui_slots + pkg_client_ui_layout --> pkg_client_ui_theme pkg_client_ui_layout --> pkg_invariants + pkg_client_ui_settings --> pkg_client_runtime + pkg_client_ui_settings --> pkg_client_ui_primitives + pkg_client_ui_settings --> pkg_client_ui_slots + pkg_client_ui_settings --> pkg_invariants + pkg_client_ui_settings_general --> pkg_client_runtime + pkg_client_ui_settings_general --> pkg_client_ui_primitives + pkg_client_ui_settings_general --> pkg_client_ui_slots + pkg_client_ui_settings_general --> pkg_invariants + pkg_client_ui_settings_models --> pkg_client_runtime + pkg_client_ui_settings_models --> pkg_client_ui_slots + pkg_client_ui_settings_models --> pkg_invariants pkg_client_ui_sidebar --> pkg_client_runtime pkg_client_ui_sidebar --> pkg_client_ui_primitives pkg_client_ui_sidebar --> pkg_client_ui_slots @@ -798,7 +813,7 @@ flowchart TD | [`subagent-subprocess`](../packages/subagent/subagent-subprocess) | `subagent` | [`invariants`](../packages/support/invariants) | | [`acp-snapshot`](../packages/support/acp-snapshot) | `support` | [`invariants`](../packages/support/invariants) | | [`loader-smoke`](../packages/support/loader-smoke) | `support` | [`invariants`](../packages/support/invariants) | -| [`client-i18n`](../packages/client/i18n) | `client` | [`invariants`](../packages/support/invariants) | +| [`client-locale`](../packages/client/locale) | `client` | [`invariants`](../packages/support/invariants) | | [`client-modules`](../packages/client/modules) | `client` | [`invariants`](../packages/support/invariants) | | [`client-runtime`](../packages/client/runtime) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-primitives`](../packages/client/ui-primitives) | `client` | [`invariants`](../packages/support/invariants) | @@ -817,7 +832,10 @@ flowchart TD | [`client-connection`](../packages/client/connection) | `client` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/support/invariants) | | [`client-hmr`](../packages/client/hmr) | `client` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/support/invariants) | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-theme`](../packages/client/ui-theme), [`invariants`](../packages/support/invariants) | +| [`client-ui-settings`](../packages/client/ui-settings) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`client-ui-settings-models`](../packages/client/ui-settings-models) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`helper`](../packages/sdk/helper) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts index 0e59ce2116..f8f8a73304 100644 --- a/packages/client/ui-settings-general/src/client/index.ts +++ b/packages/client/ui-settings-general/src/client/index.ts @@ -79,7 +79,14 @@ export function apply(ctx: ClientContext): void { ctx.effect(() => { let dispose: (() => void) | undefined - const register = (): void => { + // Presence is judged on the ledger, not on the local disposer: an HMR + // collapse of the declaring entry removes this entry from the slot core + // while `dispose` stays set (the stale disposer is a no-op), so a local + // guard would block the re-registration when the declaration returns. + const registered = (): boolean => + ctx.slots.entries('settings.section').some(e => e.component === GeneralSection) + const tryRegister = (): void => { + if (ctx.slots.spec('settings.section') === undefined || registered()) return dispose = ctx.slots.register({ name: 'settings.section', id: 'general', @@ -89,16 +96,13 @@ export function apply(ctx: ClientContext): void { inject: injected, }, GeneralSection) } - const tryRegister = (): void => { - if (ctx.slots.spec('settings.section') === undefined || dispose !== undefined) return - register() - } // Nav labels are registrant-localized: re-register on locale change so // the ledger carries fresh text (the version bump re-renders the shell). const offLocale = ctx.on('locale/change', () => { - if (dispose === undefined) return - dispose() - register() + if (!registered()) return + dispose?.() + dispose = undefined + tryRegister() }) const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) tryRegister() diff --git a/packages/client/ui-theme/src/client/index.ts b/packages/client/ui-theme/src/client/index.ts index 5ba5d40b35..b8a75c4bed 100644 --- a/packages/client/ui-theme/src/client/index.ts +++ b/packages/client/ui-theme/src/client/index.ts @@ -157,6 +157,7 @@ export class ThemeService { : this.preference // Both built-ins always exist; a registered preference id resolves or has // been reset by its disposer, so the lookup cannot miss. + /* v8 ignore next -- the ?? arm needs a registry without light/dark, which register()/dispose() cannot produce */ const active = this.themes.find(t => t.id === resolvedId) ?? this.themes[0]! return Object.freeze({ preference: this.preference, diff --git a/packages/client/ui-theme/tests/theme.spec.ts b/packages/client/ui-theme/tests/theme.spec.ts index 9ab0ab8f0f..fdac111e73 100644 --- a/packages/client/ui-theme/tests/theme.spec.ts +++ b/packages/client/ui-theme/tests/theme.spec.ts @@ -1,5 +1,5 @@ // @vitest-environment jsdom -import { beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' import { STORAGE_KEY, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' @@ -87,4 +87,53 @@ describe('ThemeService', () => { dispose() expect(events.map(e => e.revision)).toEqual([1, 2, 3, 4]) }) + + describe('prefers-color-scheme resolution (stubbed matchMedia)', () => { + type Listener = () => void + const stubMedia = (initialMatches: boolean) => { + const listeners = new Set() + const media = { + matches: initialMatches, + addEventListener: (_: 'change', fn: Listener) => { listeners.add(fn) }, + removeEventListener: (_: 'change', fn: Listener) => { listeners.delete(fn) }, + flip() { + this.matches = !this.matches + for (const fn of listeners) fn() + }, + listenerCount: () => listeners.size, + } + vi.stubGlobal('matchMedia', () => media) + return media + } + + afterEach(() => { vi.unstubAllGlobals() }) + + it('system resolves against the media query and follows OS flips', () => { + const media = stubMedia(true) + const { theme, events } = make() + expect(theme.getTheme().preference).toBe('system') + expect(theme.getTheme().active.id).toBe('dark') + media.flip() + expect(theme.getTheme().active.id).toBe('light') + expect(events).toHaveLength(1) + }) + + it('OS flips do not republish while a concrete preference is set', () => { + const media = stubMedia(false) + const { theme, events } = make() + theme.setTheme('light') + expect(events).toHaveLength(1) + media.flip() + expect(events).toHaveLength(1) + expect(theme.getTheme().active.id).toBe('light') + }) + + it('context dispose releases the media listener', async () => { + const media = stubMedia(false) + const { ctx } = make() + expect(media.listenerCount()).toBe(1) + await ctx.fiber.dispose() + expect(media.listenerCount()).toBe(0) + }) + }) }) diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index da5fe34dc4..cb8ebb6a48 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -59,6 +59,9 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-trajectory': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-workspace': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-theme': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, + 'packages/client/ui-settings': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, + 'packages/client/ui-settings-general': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, + 'packages/client/ui-settings-models': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/locale': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/web': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/examples/agent-spine-demo': { kind: 'indirect', reason: 'The bundle only mounts model-facing child plugins.' }, From c5cc348816bb27536ca1ba34928c33d771b3c8dc Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 01:10:23 +0800 Subject: [PATCH 082/113] test(gui): settings package suites; ledger-judged re-registration Full per-file coverage for the three settings packages: invariant companions, store mirroring with revision guards, behavior-shaped section/shell specs (props-fed, real store engine), and apply-level suites on a real Context + SlotCore covering declaration-aware deferral and HMR collapse recovery. All three registrants now judge presence on the slot ledger instead of a local disposer, which went stale when a parent redeclaration cascade removed the entry (ds-review-bot finding); the locale re-register path keeps the same idempotence. --- .../ui-settings-general/src/client/index.ts | 6 +- .../ui-settings-general/tests/apply.spec.ts | 139 ++++++++++++++++ .../tests/general-section.spec.tsx | 112 +++++++++++++ .../tests/invariant.spec.ts | 18 ++ .../ui-settings-general/tests/store.spec.ts | 56 +++++++ .../ui-settings-models/src/client/index.ts | 20 ++- .../ui-settings-models/tests/apply.spec.ts | 95 +++++++++++ .../tests/invariant.spec.ts | 23 +++ .../client/ui-settings/src/client/index.ts | 14 +- .../client/ui-settings/tests/apply.spec.ts | 120 ++++++++++++++ .../ui-settings/tests/invariant.spec.ts | 18 ++ .../ui-settings/tests/settings-root.spec.tsx | 155 ++++++++++++++++++ 12 files changed, 764 insertions(+), 12 deletions(-) create mode 100644 packages/client/ui-settings-general/tests/apply.spec.ts create mode 100644 packages/client/ui-settings-general/tests/general-section.spec.tsx create mode 100644 packages/client/ui-settings-general/tests/invariant.spec.ts create mode 100644 packages/client/ui-settings-general/tests/store.spec.ts create mode 100644 packages/client/ui-settings-models/tests/apply.spec.ts create mode 100644 packages/client/ui-settings-models/tests/invariant.spec.ts create mode 100644 packages/client/ui-settings/tests/apply.spec.ts create mode 100644 packages/client/ui-settings/tests/invariant.spec.ts create mode 100644 packages/client/ui-settings/tests/settings-root.spec.tsx diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts index f8f8a73304..52655be7fa 100644 --- a/packages/client/ui-settings-general/src/client/index.ts +++ b/packages/client/ui-settings-general/src/client/index.ts @@ -98,9 +98,11 @@ export function apply(ctx: ClientContext): void { } // Nav labels are registrant-localized: re-register on locale change so // the ledger carries fresh text (the version bump re-renders the shell). + // The ledger check mirrors tryRegister: after an HMR collapse `dispose` + // stays set while the entry is gone — relabeling then must stay quiet. const offLocale = ctx.on('locale/change', () => { - if (!registered()) return - dispose?.() + if (dispose === undefined || !registered()) return + dispose() dispose = undefined tryRegister() }) diff --git a/packages/client/ui-settings-general/tests/apply.spec.ts b/packages/client/ui-settings-general/tests/apply.spec.ts new file mode 100644 index 0000000000..8654275831 --- /dev/null +++ b/packages/client/ui-settings-general/tests/apply.spec.ts @@ -0,0 +1,139 @@ +/** apply wiring: dictionary registration, declaration-aware section entry, + * snapshot projection into the slot store, locale-driven relabeling, and + * recovery after an HMR collapse of the declaring entry. */ +import { Context } from 'cordis' +import { describe, expect, it } from 'vitest' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' +import { ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-general/client' +import type { GeneralSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-general/client' +import { GeneralSection } from '../src/client/GeneralSection.tsx' +import type { createGeneralSettingsStore } from '../src/client/store.ts' + +const NS = 'settings.general' + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + const locale = new LocaleService(ctx) + const theme = new ThemeService(ctx) + ctx.provide('locale', locale) + ctx.provide('theme', theme) + return { ctx, slots: ctx.get('slots') as SlotsService, locale, theme } +} + +/** Stand in for the settings shell: declare the section list slot from root. */ +function declareSection(slots: SlotsService): () => void { + return slots.register( + { name: 'root', children: { 'settings.section': { kind: 'list', scope: 'root' } } } as never, + () => null, + ) +} + +/** Mirror the framework's inject choreography: bake a real instance from the + * declared handle and hand its actions to the entry's inject factory. */ +function faceOf(slots: SlotsService) { + const entry = slots.entries('settings.section')[0]! + const handle = entry.store as ReturnType + const instance = handle.create() + const face = (entry.inject as unknown as (a: typeof instance.actions) => GeneralSectionInjected)(instance.actions) + return { entry, instance, face } +} + +describe('ui-settings-general apply', () => { + it('declares the slot, locale, and theme services', () => { + expect(inject).toEqual(['slots', 'locale', 'theme']) + }) + + it('registers dictionaries and the section entry for declarations before or after apply', async () => { + const before = await bench() + declareSection(before.slots) + await before.ctx.plugin({ inject: [...inject], apply }).await() + const entry = before.slots.entries('settings.section')[0]! + expect(entry.component).toBe(GeneralSection) + expect(entry.options).toMatchObject({ id: 'general', order: 0, label: '通用设置' }) + expect(before.locale.bind(NS)('nav')).toBe('通用设置') + + const after = await bench() + const fiber = after.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(after.slots.entries('settings.section')).toHaveLength(0) + declareSection(after.slots) + await Promise.resolve() + expect(after.slots.entries('settings.section')[0]!.component).toBe(GeneralSection) + // Teardown without a live registration exercises the undefined-disposer arm. + await fiber.dispose() + expect(after.slots.entries('settings.section')).toHaveLength(0) + }) + + it('projects service snapshots into the store and routes face writes back', async () => { + const b = await bench() + declareSection(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + // Events ahead of any inject hit the unbound-actions arm without a store. + b.theme.setTheme('dark') + + const { instance, face } = faceOf(b.slots) + // The inject-time re-sync sealed the init window: both mirrors are current. + expect(instance.getSnapshot().localeActive).toBe('zh') + expect(instance.getSnapshot().localeOptions.map(l => l.id)).toEqual(['zh', 'en']) + expect(instance.getSnapshot().themePreference).toBe('dark') + expect(face.t('nav')).toBe('通用设置') + + face.setLocale('en') + expect(b.locale.getLocale().active).toBe('en') + expect(instance.getSnapshot().localeActive).toBe('en') + expect(face.t('nav')).toBe('General') + + face.setTheme('system') + expect(b.theme.getTheme().preference).toBe('system') + expect(instance.getSnapshot().themePreference).toBe('system') + }) + + it('re-registers with a fresh ledger label when the locale changes', async () => { + const b = await bench() + declareSection(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries('settings.section')[0]!.options.label).toBe('通用设置') + b.locale.setLocale('en') + const entry = b.slots.entries('settings.section')[0]! + expect(entry.options.label).toBe('General') + expect(entry.component).toBe(GeneralSection) + }) + + it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => { + const b = await bench() + const host = declareSection(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries('settings.section')).toHaveLength(1) + + // Collapse: the declarer dies, the cascade removes our entry while the + // apply closure still holds its (now stale) disposer. + host() + expect(b.slots.entries('settings.section')).toHaveLength(0) + + // A locale change inside the collapsed window must stay quiet. + b.locale.setLocale('en') + expect(b.slots.entries('settings.section')).toHaveLength(0) + + // Redeclaration restores the entry — with the current locale's label. + declareSection(b.slots) + await Promise.resolve() + const entry = b.slots.entries('settings.section')[0]! + expect(entry.component).toBe(GeneralSection) + expect(entry.options.label).toBe('General') + }) + + it('removes the entry and the dictionaries on teardown', async () => { + const b = await bench() + declareSection(b.slots) + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(b.slots.entries('settings.section')).toHaveLength(1) + await fiber.dispose() + expect(b.slots.entries('settings.section')).toHaveLength(0) + // Dictionary disposal: translation falls back to the bare key. + expect(b.locale.bind(NS)('nav')).toBe('nav') + }) +}) diff --git a/packages/client/ui-settings-general/tests/general-section.spec.tsx b/packages/client/ui-settings-general/tests/general-section.spec.tsx new file mode 100644 index 0000000000..e82ed0b1fc --- /dev/null +++ b/packages/client/ui-settings-general/tests/general-section.spec.tsx @@ -0,0 +1,112 @@ +// @vitest-environment jsdom +/** GeneralSection behavior: skeleton rows stay inert, Language menu drives + * setLocale, Appearance cubes follow the preference and drive setTheme. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { createSnapshotStore, type SessionListState, type WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import { GeneralSection } from '../src/client/GeneralSection.tsx' +import { createGeneralSettingsStore } from '../src/client/store.ts' +import { en } from '../src/client/locales.ts' +import type { GeneralSectionComponentProps } from '../src/client/contract.ts' + +afterEach(cleanup) + +const LOCALES = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }] + +/** Empty global standard-kit hooks (the section reads neither). */ +function emptySessions() { + const store = createSnapshotStore( + { ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' }) + return bindSnapshotSelector(store) +} +function emptyWorkspaces() { + const store = createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) + return bindSnapshotSelector(store) +} + +function mount(init?: { active?: string; preference?: 'light' | 'dark' | 'system' }) { + // Real store instance — the sanctioned zero-machinery path for tests. + const store = createGeneralSettingsStore().create() + store.actions.syncLocale(init?.active ?? 'en', LOCALES, 0) + store.actions.syncTheme(init?.preference ?? 'system', 0) + const setLocale = vi.fn() + const setTheme = vi.fn() + const props: GeneralSectionComponentProps = { + useSessions: emptySessions(), + useWorkspaces: emptyWorkspaces(), + useStore: bindSnapshotSelector(store), + actions: store.actions, + t: (key: string) => en[key] ?? key, + setLocale, + setTheme, + } + render() + return { store, setLocale, setTheme } +} + +const pressed = (name: RegExp): string | null => + screen.getByRole('button', { name }).getAttribute('aria-pressed') + +describe('GeneralSection', () => { + it('renders the four groups with skeleton rows inert', () => { + const b = mount() + // Permission: disabled selector showing the fixed value. + const permission = screen.getByRole('button', { name: /Read only/ }) as HTMLButtonElement + expect(permission.disabled).toBe(true) + fireEvent.click(permission) + // Tool Call: both mode cubes render as plain text, no buttons. + expect(screen.getByText('Schema mode')).toBeDefined() + expect(screen.getByText('Code mode')).toBeDefined() + expect(screen.queryByRole('button', { name: /Schema mode/ })).toBeNull() + expect(b.setLocale).not.toHaveBeenCalled() + expect(b.setTheme).not.toHaveBeenCalled() + }) + + it('opens the language menu, selects a locale, and closes', () => { + const b = mount({ active: 'en' }) + const trigger = screen.getByRole('button', { name: /English/ }) + expect(trigger.getAttribute('aria-expanded')).toBe('false') + fireEvent.click(trigger) + expect(trigger.getAttribute('aria-expanded')).toBe('true') + fireEvent.click(screen.getByRole('menuitem', { name: '中文' })) + expect(b.setLocale).toHaveBeenCalledWith('zh') + expect(trigger.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull() + }) + + it('closes the language menu on outside pointerdown without selecting', () => { + const b = mount({ active: 'en' }) + const trigger = screen.getByRole('button', { name: /English/ }) + fireEvent.click(trigger) + expect(screen.getByRole('menuitem', { name: '中文' })).toBeDefined() + fireEvent.pointerDown(document.body) + expect(trigger.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull() + expect(b.setLocale).not.toHaveBeenCalled() + }) + + it('reflects a store locale change in the trigger label (unknown id falls back to the id)', () => { + const b = mount({ active: 'en' }) + act(() => { b.store.actions.syncLocale('zh', LOCALES, 1) }) + expect(screen.getByRole('button', { name: /中文/ })).toBeDefined() + act(() => { b.store.actions.syncLocale('fr', LOCALES, 2) }) + expect(screen.getByRole('button', { name: /fr/ })).toBeDefined() + }) + + it('marks the appearance cube matching the preference and switches on click', () => { + const b = mount({ preference: 'dark' }) + expect(pressed(/Dark/)).toBe('true') + expect(pressed(/Light/)).toBe('false') + expect(pressed(/System/)).toBe('false') + fireEvent.click(screen.getByRole('button', { name: /Light/ })) + expect(b.setTheme).toHaveBeenCalledWith('light') + // Selection follows the store mirror, not the click echo. + act(() => { b.store.actions.syncTheme('light', 1) }) + expect(pressed(/Light/)).toBe('true') + expect(pressed(/Dark/)).toBe('false') + }) +}) diff --git a/packages/client/ui-settings-general/tests/invariant.spec.ts b/packages/client/ui-settings-general/tests/invariant.spec.ts new file mode 100644 index 0000000000..7b0527c0ff --- /dev/null +++ b/packages/client/ui-settings-general/tests/invariant.spec.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import * as GeneralInvariant from '@deepseek-ai/dsh-client-ui-settings-general/invariant' +import InvariantService from '@deepseek-ai/dsh-invariants' + +describe('invariant companion', () => { + it('registers under the package name with an empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + await expect(ctx.plugin(GeneralInvariant).await()).resolves.toBeDefined() + }) + + it('node-half apply is a no-op host placeholder', async () => { + const { apply } = await import('@deepseek-ai/dsh-client-ui-settings-general') + apply() + expect(true).toBe(true) // reaching here without throw is the contract + }) +}) diff --git a/packages/client/ui-settings-general/tests/store.spec.ts b/packages/client/ui-settings-general/tests/store.spec.ts new file mode 100644 index 0000000000..b291418471 --- /dev/null +++ b/packages/client/ui-settings-general/tests/store.spec.ts @@ -0,0 +1,56 @@ +/** General settings store: snapshot-mirror actions and the revision guard. */ +import { describe, expect, it } from 'vitest' +import { createGeneralSettingsStore } from '../src/client/store.ts' + +const LOCALES = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }] + +describe('createGeneralSettingsStore', () => { + it('init shape: empty mirrors with revisions at -1', () => { + const store = createGeneralSettingsStore().create() + expect(store.getSnapshot()).toEqual({ + localeActive: '', + localeOptions: [], + localeRevision: -1, + themePreference: 'system', + themeRevision: -1, + }) + }) + + it('syncLocale mirrors the snapshot and advances the revision', () => { + const store = createGeneralSettingsStore().create() + store.actions.syncLocale('zh', LOCALES, 0) + expect(store.getSnapshot().localeActive).toBe('zh') + expect(store.getSnapshot().localeOptions).toEqual(LOCALES) + expect(store.getSnapshot().localeRevision).toBe(0) + + store.actions.syncLocale('en', LOCALES, 1) + expect(store.getSnapshot().localeActive).toBe('en') + expect(store.getSnapshot().localeRevision).toBe(1) + }) + + it('syncLocale revision guard drops stale and duplicate writes', () => { + const store = createGeneralSettingsStore().create() + store.actions.syncLocale('en', LOCALES, 5) + // Stale (lower) and duplicate (equal) revisions leave the mirror intact. + store.actions.syncLocale('zh', LOCALES, 4) + store.actions.syncLocale('zh', LOCALES, 5) + expect(store.getSnapshot().localeActive).toBe('en') + expect(store.getSnapshot().localeRevision).toBe(5) + }) + + it('syncTheme mirrors the preference and guards its revision independently', () => { + const store = createGeneralSettingsStore().create() + store.actions.syncTheme('dark', 0) + expect(store.getSnapshot().themePreference).toBe('dark') + expect(store.getSnapshot().themeRevision).toBe(0) + + store.actions.syncTheme('light', 2) + expect(store.getSnapshot().themePreference).toBe('light') + + // Stale theme write is dropped; the locale revision axis is untouched. + store.actions.syncTheme('system', 1) + expect(store.getSnapshot().themePreference).toBe('light') + expect(store.getSnapshot().themeRevision).toBe(2) + expect(store.getSnapshot().localeRevision).toBe(-1) + }) +}) diff --git a/packages/client/ui-settings-models/src/client/index.ts b/packages/client/ui-settings-models/src/client/index.ts index 8ad2ebb750..c35946fcc8 100644 --- a/packages/client/ui-settings-models/src/client/index.ts +++ b/packages/client/ui-settings-models/src/client/index.ts @@ -31,9 +31,15 @@ export function apply(ctx: ClientContext): void { ] return () => { for (const dispose of disposers) dispose() } }, 'ui-settings-models: nav copy dictionaries') + // Declaration-aware registration; the LEDGER is the has-registered judge + // (not a local flag): after an HMR collapse re-declares the slot, the + // cascade already removed our entry, and a stale disposer must not block + // the re-registration. ctx.effect(() => { let dispose: (() => void) | undefined - const register = (): void => { + const tryRegister = (): void => { + if (ctx.slots.spec('settings.section') === undefined) return + if (ctx.slots.entries('settings.section').some(e => e.component === ModelsSection)) return dispose = ctx.slots.register({ name: 'settings.section', id: 'models', @@ -41,16 +47,14 @@ export function apply(ctx: ClientContext): void { label: ctx.locale.bind('settings.models')('nav'), }, ModelsSection) } - const tryRegister = (): void => { - if (ctx.slots.spec('settings.section') === undefined || dispose !== undefined) return - register() - } // Nav labels are registrant-localized: re-register on locale change so // the ledger carries fresh text (the version bump re-renders the shell). + // Dispose-then-requery: after an HMR collapse the disposer is stale and + // the ledger/spec re-check keeps this path an idempotent no-op. const offLocale = ctx.on('locale/change', () => { - if (dispose === undefined) return - dispose() - register() + dispose?.() + dispose = undefined + tryRegister() }) const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) tryRegister() diff --git a/packages/client/ui-settings-models/tests/apply.spec.ts b/packages/client/ui-settings-models/tests/apply.spec.ts new file mode 100644 index 0000000000..b7aa3cf2ab --- /dev/null +++ b/packages/client/ui-settings-models/tests/apply.spec.ts @@ -0,0 +1,95 @@ +/** Models section registration: declaration-aware deferral, locale re-registration, and HMR recovery. */ +import { Context } from 'cordis' +import { describe, expect, it } from 'vitest' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-models/client' +import { ModelsSection } from '../src/client/ModelsSection.tsx' + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + const locale = new LocaleService(ctx) + ctx.provide('locale', locale) + return { ctx, slots: ctx.get('slots') as SlotsService, locale } +} + +function declare(slots: SlotsService): () => void { + return slots.register( + { name: 'root', children: { 'settings.section': { kind: 'list', scope: 'root' } } } as never, + () => null, + ) +} + +describe('ui-settings-models apply', () => { + it('declares the services it uses', () => { + expect(inject).toEqual(['slots', 'locale']) + }) + + it('registers the models nav entry for declarations before or after apply', async () => { + const before = await bench() + declare(before.slots) + await before.ctx.plugin({ inject: [...inject], apply }).await() + const entry = before.slots.entries('settings.section')[0]! + expect(entry.component).toBe(ModelsSection) + expect(entry.options).toEqual({ id: 'models', order: 10, label: '模型' }) + + const after = await bench() + await after.ctx.plugin({ inject: [...inject], apply }).await() + expect(after.slots.entries('settings.section')).toHaveLength(0) + declare(after.slots) + await Promise.resolve() + expect(after.slots.entries('settings.section')[0]!.component).toBe(ModelsSection) + // The self-inflicted ledger notifications hit the duplicate guard. + expect(after.slots.entries('settings.section')).toHaveLength(1) + }) + + it('re-registers with fresh label text on locale change', async () => { + const b = await bench() + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + b.locale.setLocale('en') + expect(b.slots.entries('settings.section')[0]!.options.label).toBe('Models') + b.locale.setLocale('zh') + expect(b.slots.entries('settings.section')[0]!.options.label).toBe('模型') + }) + + it('locale change while the slot is undeclared stays a no-op', async () => { + const b = await bench() + await b.ctx.plugin({ inject: [...inject], apply }).await() + b.locale.setLocale('en') + expect(b.slots.entries('settings.section')).toHaveLength(0) + b.locale.setLocale('zh') + }) + + it('re-registers after an HMR collapse re-declares the slot (stale disposer must not block)', async () => { + const b = await bench() + const redeclare = declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries('settings.section')).toHaveLength(1) + // Declarer unload: the cascade removes our entry while our local + // disposer variable goes stale. + redeclare() + expect(b.slots.entries('settings.section')).toHaveLength(0) + declare(b.slots) + await Promise.resolve() + expect(b.slots.entries('settings.section')[0]!.component).toBe(ModelsSection) + // The locale path also recovers through the same ledger re-check. + b.locale.setLocale('en') + expect(b.slots.entries('settings.section')[0]!.options.label).toBe('Models') + b.locale.setLocale('zh') + }) + + it('registers the zh/en nav dictionaries and disposes everything with the fiber', async () => { + const b = await bench() + declare(b.slots) + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(b.locale.bind('settings.models')('nav')).toBe('模型') + await fiber.dispose() + expect(b.slots.entries('settings.section')).toHaveLength(0) + // The (ns, locale) seats are free again — the dictionary disposers ran. + expect(() => b.locale.register('settings.models', 'zh', {})).not.toThrow() + expect(() => b.locale.register('settings.models', 'en', {})).not.toThrow() + }) +}) diff --git a/packages/client/ui-settings-models/tests/invariant.spec.ts b/packages/client/ui-settings-models/tests/invariant.spec.ts new file mode 100644 index 0000000000..65c7c1094a --- /dev/null +++ b/packages/client/ui-settings-models/tests/invariant.spec.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import * as ModelsInvariant from '@deepseek-ai/dsh-client-ui-settings-models/invariant' +import InvariantService from '@deepseek-ai/dsh-invariants' +import { ModelsSection } from '../src/client/ModelsSection.tsx' + +describe('invariant companion', () => { + it('registers under the package name with an empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + await expect(ctx.plugin(ModelsInvariant).await()).resolves.toBeDefined() + }) + + it('node-half apply is a no-op host placeholder', async () => { + const { apply } = await import('@deepseek-ai/dsh-client-ui-settings-models') + apply() + expect(true).toBe(true) // reaching here without throw is the contract + }) + + it('the section content column is intentionally empty this phase', () => { + expect(ModelsSection()).toBeNull() + }) +}) diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index d5135f373c..688436c25b 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -43,13 +43,23 @@ export function apply(ctx: ClientContext): void { sectionsVersion: () => ctx.slots.getVersion('settings.section'), subscribeSections: (listener) => ctx.slots.subscribe('settings.section', listener), sections: () => ctx.slots.entries('settings.section') - .map(e => ({ id: e.options.id ?? '', order: e.options.order ?? 0, label: e.options.label ?? '' })) + .map(e => ({ + /* v8 ignore next -- list-slot registration requires id (SlotCore rejects an entry without one) */ + id: e.options.id ?? '', + order: e.options.order ?? 0, + label: e.options.label ?? '', + })) .sort((a, b) => a.order - b.order), }) + // Declaration-aware registration; the LEDGER is the has-registered judge + // (not a local flag): after an HMR collapse re-declares the slot, the + // cascade already removed our entry, and a stale disposer must not block + // the re-registration. ctx.effect(() => { let dispose: (() => void) | undefined const tryRegister = (): void => { - if (ctx.slots.spec('sidebar.settings') === undefined || dispose !== undefined) return + if (ctx.slots.spec('sidebar.settings') === undefined) return + if (ctx.slots.entries('sidebar.settings').some(e => e.component === SettingsRoot)) return dispose = ctx.slots.register({ name: 'sidebar.settings', children: { 'settings.section': { kind: 'list', scope: 'root' } }, diff --git a/packages/client/ui-settings/tests/apply.spec.ts b/packages/client/ui-settings/tests/apply.spec.ts new file mode 100644 index 0000000000..a94406e4ce --- /dev/null +++ b/packages/client/ui-settings/tests/apply.spec.ts @@ -0,0 +1,120 @@ +/** Settings shell registration: declaration-aware deferral, the injected face, and HMR recovery. */ +import { Context } from 'cordis' +import { describe, expect, it, vi } from 'vitest' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings/client' +import type { SettingsRootInjected } from '@deepseek-ai/dsh-client-ui-settings/client' +import { SettingsRoot } from '../src/client/SettingsRoot.tsx' + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + const locale = new LocaleService(ctx) + ctx.provide('locale', locale) + return { ctx, slots: ctx.get('slots') as SlotsService, locale } +} + +function declare(slots: SlotsService): () => void { + return slots.register( + { name: 'root', children: { 'sidebar.settings': { kind: 'single', scope: 'root' } } } as never, + () => null, + ) +} + +function injectedOf(slots: SlotsService): SettingsRootInjected { + const entry = slots.entries('sidebar.settings')[0]! + return (entry.inject as () => SettingsRootInjected)() +} + +describe('ui-settings apply', () => { + it('declares the services it uses', () => { + expect(inject).toEqual(['slots', 'locale']) + }) + + it('registers the shell for declarations that arrive before or after apply', async () => { + const before = await bench() + declare(before.slots) + await before.ctx.plugin({ inject: [...inject], apply }).await() + expect(before.slots.entries('sidebar.settings')[0]!.component).toBe(SettingsRoot) + expect(before.slots.spec('settings.section')).toEqual({ kind: 'list', scope: 'root' }) + + const after = await bench() + await after.ctx.plugin({ inject: [...inject], apply }).await() + expect(after.slots.entries('sidebar.settings')).toHaveLength(0) + declare(after.slots) + await Promise.resolve() + expect(after.slots.entries('sidebar.settings')[0]!.component).toBe(SettingsRoot) + // The self-inflicted ledger notifications hit the duplicate guard. + expect(after.slots.entries('sidebar.settings')).toHaveLength(1) + }) + + it('registers the zh/en shell dictionaries and disposes them with the fiber', async () => { + const b = await bench() + declare(b.slots) + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(b.locale.bind('settings')('title')).toBe('设置') + b.locale.setLocale('en') + expect(b.locale.bind('settings')('close')).toBe('Close') + await fiber.dispose() + // The (ns, locale) seats are free again — the dictionary disposers ran. + expect(() => b.locale.register('settings', 'zh', {})).not.toThrow() + expect(() => b.locale.register('settings', 'en', {})).not.toThrow() + }) + + it('exposes translate over ":" refs with literal echo for plain text', async () => { + const b = await bench() + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const injected = injectedOf(b.slots) + expect(injected.translate('settings:title')).toBe('设置') + expect(injected.translate('no colon ref')).toBe('no colon ref') + }) + + it('projects the section ledger into ordered nav rows with option defaults', async () => { + const b = await bench() + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const injected = injectedOf(b.slots) + expect(injected.sections()).toEqual([]) + b.slots.register({ name: 'settings.section', id: 'z', order: 20, label: 'Z' } as never, () => null) + b.slots.register({ name: 'settings.section', id: 'a' } as never, () => null) + expect(injected.sections()).toEqual([ + { id: 'a', order: 0, label: '' }, + { id: 'z', order: 20, label: 'Z' }, + ]) + expect(injected.sectionsVersion()).toBe(b.slots.getVersion('settings.section')) + const listener = vi.fn() + const off = injected.subscribeSections(listener) + b.slots.register({ name: 'settings.section', id: 'b', order: 1, label: 'B' } as never, () => null) + await Promise.resolve() + expect(listener).toHaveBeenCalled() + off() + }) + + it('re-registers after an HMR collapse re-declares the slot (stale disposer must not block)', async () => { + const b = await bench() + const redeclare = declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries('sidebar.settings')).toHaveLength(1) + // Declarer unload: the cascade removes our entry and the slot spec while + // our local disposer variable goes stale. + redeclare() + expect(b.slots.entries('sidebar.settings')).toHaveLength(0) + declare(b.slots) + await Promise.resolve() + expect(b.slots.entries('sidebar.settings')[0]!.component).toBe(SettingsRoot) + expect(b.slots.spec('settings.section')).toEqual({ kind: 'list', scope: 'root' }) + }) + + it('unregisters the shell and collapses settings.section on teardown', async () => { + const b = await bench() + declare(b.slots) + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + await fiber.dispose() + expect(b.slots.entries('sidebar.settings')).toHaveLength(0) + expect(b.slots.spec('settings.section')).toBeUndefined() + }) +}) diff --git a/packages/client/ui-settings/tests/invariant.spec.ts b/packages/client/ui-settings/tests/invariant.spec.ts new file mode 100644 index 0000000000..c3474d5bdd --- /dev/null +++ b/packages/client/ui-settings/tests/invariant.spec.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import * as SettingsInvariant from '@deepseek-ai/dsh-client-ui-settings/invariant' +import InvariantService from '@deepseek-ai/dsh-invariants' + +describe('invariant companion', () => { + it('registers under the package name with an empty installer', async () => { + const ctx = new Context() + await ctx.plugin(InvariantService, { enabled: true }) + await expect(ctx.plugin(SettingsInvariant).await()).resolves.toBeDefined() + }) + + it('node-half apply is a no-op host placeholder', async () => { + const { apply } = await import('@deepseek-ai/dsh-client-ui-settings') + apply() + expect(true).toBe(true) // reaching here without throw is the contract + }) +}) diff --git a/packages/client/ui-settings/tests/settings-root.spec.tsx b/packages/client/ui-settings/tests/settings-root.spec.tsx new file mode 100644 index 0000000000..ab56365075 --- /dev/null +++ b/packages/client/ui-settings/tests/settings-root.spec.tsx @@ -0,0 +1,155 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import type { SettingsRootComponentProps } from '../src/client/contract/slots.ts' +import { SettingsRoot } from '../src/client/SettingsRoot.tsx' + +afterEach(cleanup) + +const DICT: Record = { + 'settings:trigger': 'Settings', + 'settings:title': 'Settings', + 'settings:close': 'Close', +} + +type Row = { id: string; order: number; label: string } + +function mount({ + wide = true, + rows = [ + { id: 'general', order: 0, label: 'General' }, + { id: 'models', order: 10, label: 'Models' }, + ], +}: { wide?: boolean; rows?: Row[] } = {}) { + // Mutable row store standing in for the ledger; bump() plays a change. + let current = rows + let version = 0 + const listeners = new Set<() => void>() + const renderSlot = vi.fn( + ((_key: string, _owner: unknown, opts?: { only?: string }) => +
) as SettingsRootComponentProps['renderSlot'], + ) + // Global standard kit stubs: the shell consumes neither hook. + const unusedHook = (() => { throw new Error('unused by SettingsRoot') }) as never + const props: SettingsRootComponentProps = { + useSessions: unusedHook, + useWorkspaces: unusedHook, + wide, + translate: (ref) => DICT[ref] ?? ref, + sectionsVersion: () => version, + subscribeSections: (listener) => { + listeners.add(listener) + return () => { listeners.delete(listener) } + }, + sections: () => current, + renderSlot, + } + const view = render() + const bump = (next: Row[]) => { + act(() => { + current = next + version += 1 + for (const fn of [...listeners]) fn() + }) + } + return { view, renderSlot, bump, listeners } +} + +function openPanel() { + fireEvent.click(screen.getByRole('button', { name: 'Settings' })) +} + +describe('SettingsRoot trigger', () => { + it('renders the wide row with the label and opens the dialog', () => { + mount() + const trigger = screen.getByRole('button', { name: 'Settings' }) + expect(trigger.textContent).toContain('Settings') + expect(trigger.getAttribute('aria-expanded')).toBe('false') + fireEvent.click(trigger) + expect(screen.getByRole('dialog')).toBeTruthy() + expect(screen.getByRole('button', { name: 'Settings', expanded: true })).toBeTruthy() + }) + + it('drops the label in the rail state', () => { + mount({ wide: false }) + expect(screen.getByRole('button', { name: 'Settings' }).textContent).toBe('') + }) +}) + +describe('SettingsPanel close paths', () => { + it('closes via the header button', () => { + mount() + openPanel() + fireEvent.click(screen.getByRole('button', { name: 'Close' })) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('closes via a mask click', () => { + mount() + openPanel() + const dialog = screen.getByRole('dialog') + fireEvent.click(dialog.parentElement!.firstElementChild!) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('closes via document-level Escape and unhooks the listener with the panel', () => { + mount() + openPanel() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('dialog')).toBeNull() + // Ignored while closed (listener removed with the panel) and non-Escape + // keys are ignored while open. + fireEvent.keyDown(document, { key: 'Escape' }) + openPanel() + fireEvent.keyDown(document, { key: 'Enter' }) + expect(screen.getByRole('dialog')).toBeTruthy() + }) + + it('lands focus on the close button when the dialog opens', () => { + mount() + openPanel() + expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Close' })) + }) +}) + +describe('SettingsPanel navigation', () => { + it('projects rows, marks the first active, and renders only that section', () => { + mount() + openPanel() + expect(screen.getByRole('button', { name: 'General' }).getAttribute('aria-current')).toBe('true') + expect(screen.getByRole('button', { name: 'Models' }).getAttribute('aria-current')).toBeNull() + expect(screen.getByTestId('section-general')).toBeTruthy() + }) + + it('switches the rendered section on nav click', () => { + mount() + openPanel() + fireEvent.click(screen.getByRole('button', { name: 'Models' })) + expect(screen.getByRole('button', { name: 'Models' }).getAttribute('aria-current')).toBe('true') + expect(screen.getByTestId('section-models')).toBeTruthy() + expect(screen.queryByTestId('section-general')).toBeNull() + }) + + it('falls back to the first row when the active entry unregisters', () => { + const { bump } = mount() + openPanel() + fireEvent.click(screen.getByRole('button', { name: 'Models' })) + bump([{ id: 'general', order: 0, label: 'General' }]) + expect(screen.queryByRole('button', { name: 'Models' })).toBeNull() + expect(screen.getByTestId('section-general')).toBeTruthy() + }) + + it('renders an empty content column when the ledger is empty', () => { + const { renderSlot } = mount({ rows: [] }) + openPanel() + expect(screen.getByRole('dialog')).toBeTruthy() + expect(renderSlot).not.toHaveBeenCalled() + }) + + it('drops the ledger subscription on unmount', () => { + const { view, listeners } = mount() + expect(listeners.size).toBe(1) + view.unmount() + expect(listeners.size).toBe(0) + }) +}) From f1b877e3c61ded6f94a1a07bbdb95555297af63f Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 01:11:17 +0800 Subject: [PATCH 083/113] fix(web): review-bot round one + regenerate doc catalogs - rename same-title no-op moves inside the serialized creation chain - insertSessionBefore maps only the typed WorkspaceMoveInvalidError to workspace-move-invalid; storage failures stay internal - workspace upsert rejects snapshots older than the installed projection - flat-mode empty state shows when the query hides the intent row - intent row no longer forces group expansion; header twist stays live - group-by menu rides a portal; menu clicks stop propagating to the row - intent row uses the same single-slot indent in both list modes - regenerate cordis api/catalog + doc graphs --- ...ssion-list-browsing-and-manual-order.zh.md | 60 +++++++++++++++++++ docs/cordis-catalog/services.md | 2 +- .../src/client/WorkspaceBrowser.tsx | 2 +- .../ui-workspace/src/client/rows/Rows.tsx | 7 +-- 4 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md diff --git a/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md new file mode 100644 index 0000000000..e897903f83 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md @@ -0,0 +1,60 @@ +# Agent Note: Session List Browsing and Manual Workspace Order + +Status: implemented + +[English](2026-07-25-session-list-browsing-and-manual-order.md) | 中文 + +## Problem + +[Workspace UI 完整产品流](2026-07-25-workspace-ui-product-flow.zh.md)交付了分组 session 列表的首个形态,并把 Rename、拖拽排序等操作明确划出当期范围。设计稿(figma 239-10458 及关联画面)随后补齐了这些交互:列表要能切换成不分组的平铺视图、session 行悬停要出详情卡与操作菜单、workspace 要能改名、组内 session 要能手动排序。 + +两条既有机制挡在前面。其一,host 在每条 `session/event` 上把活跃 session durable 地提到 workspace 账本最前(活动置顶),任何手动排序都会被下一次活动打乱——两种排序权威不可调和。其二,浏览区域被劈在两个包里:ui-sidebar 拥有列表、搜索和组头行,ui-workspace 只借一个 picker 坑放弹层;每加一个 workspace 域的对话框都要跨包接线,归属越来越拧。 + +## Decision + +### 平铺视图与浏览态 + +group-by 菜单提供 WorkSpace / In one list 两种模式。平铺模式把所有 session(含 fork 子)一律作为顶层行,严格按 `updatedAt` 新→旧排序,不保持父子相邻;Intent 占位行渲染在列表首行。模式选择持久化在浏览器(`dsh.workspace.view`),刷新保持。 + +### 行交互 + +- session 行悬停 500ms 出详情卡(全名/相对时间/状态行;状态本期只有 running/idle 两态,枚举扩展待 wire 增补 status 字段)。卡片与行菜单互斥:菜单开启或拖拽进行中不出卡。 +- session 行 … 菜单:Rename / Fork session / Delete session,本期纯视觉;workspace 组头 … 菜单:Rename(已接线)/ Delete workspace(纯视觉)。菜单鼠标移出即关。 +- 支撑件:`Menu` 新增 label 条目、danger 行、`closeOnPointerLeave`;新增 `HoverCard`(portal 定位、开启延时、disabled 守卫)。 + +### workspace.rename + +`workspace.rename({ workspaceId, title })`:title trim 后非空;同名 no-op 与重名查重都在 host 的 workspace 创建串行链内求值(与 create 共链,并发 create/rename 不能穿插出重名或乱序假成功),冲突回 `workspace-name-conflict`。落盘经 `setTitle` 的 mutate 通道,`domain/changed` 监听自动广播 `host/workspace-changed` 帧。UI 为标准 Modal,client 侧另做重名预检。 + +### 手动排序:insertSessionBefore 取代活动置顶 + +`session/event` → `touchSession` 活动置顶链整体删除;workspace 账本序改为纯手动拥有——新 session attach 时前插,显式重排走 `workspace.insertSessionBefore({ workspaceId, sessionId, beforeSessionId? })`(DOM insertBefore 语义:锚给了插锚前,缺省 append 到末尾)。实体只对不在账的 session/锚抛类型化的 `WorkspaceMoveInvalidError`,handler 仅把它映射为业务码 `workspace-move-invalid`,存储故障保持 internal。 + +UI 为组内 root 行的 HTML5 拖拽(仅 workspace 分组、非搜索态;fork 子随父不单独拖)。顺序权威完全在 host:drop 只发 RPC,client 零本地重排,视图靠响应体 upsert 与 changed 帧刷新;失败即无事发生。client 的 upsert 拒绝比已装载投影更旧(`updatedAt`)的快照,防迟到的一元响应回滚更新的帧。 + +### 壳/区域切分 + +ui-sidebar 缩为列几何壳:品牌行、折叠状态机、New Session、Settings,以及一个 `sidebar.workspaces` 洞;壳与区域的契约只有两个事实 `{ wide, expandSidebar }`。ui-workspace 全权拥有浏览区域(section header、搜索、分组树与平铺、全部 workspace 对话框、拖拽)及其 groupBy store;rail 态的搜索/新建图标也归区域,经 `expandSidebar()` 请求壳展开。picker 拆为核心件 `WorkspaceCreateFlow`(区域内直接组件组合)与薄包装 `WorkspacePicker`(继续填 ui-conversation 的 hero 坑);原 `sidebar.workspace` picker 坑与声明感知延迟注册随之删除。 + +## Alternatives considered + +**保留活动置顶、拖拽仅作临时调整** —— 手动序在下一次 session 活动即被打乱,形同虚设;两种排序权威并存无法向用户解释。也考虑过「拖过一次即冻结该 workspace 的活动置顶」的折中,状态多一档、语义更难讲,直接删除更干净。 + +**排序报文用数字下标** —— `{ index }` 在拖拽窗口期会漂移:host 前插新 session(如 Intent 材料化)后同一下标指向别的行。锚点式 insertBefore 对前插与过滤投影天然免疫。 + +**drop 后乐观重排** —— client 先行重排需失败回滚,对象层多一块纠缠态;本地/局域网往返毫秒级,等 host 响应的简单方案肉眼无感。顺序权威单一化(完全信 host)后,前端永不发明顺序。 + +**rename 对话框留在 ui-sidebar(最小改动)** —— 正是问题本身:workspace 域的对话框散落在借来的坑里,每加一个(Delete 确认框将至)都重演跨包接线。评审中先议了「只挪 rename Modal」的中间态,最终裁定整个浏览区域归 ui-workspace,壳只留几何。 + +**平铺模式保持父子相邻成组** —— 与「严格按时间」矛盾(子新于兄则插不进相邻位),且平铺本意就是取消层级;拉平并禁用平铺下的拖拽(无持久化载体)更一致。 + +## Consequences + +- 手动序是唯一的 workspace 账本序权威:用户排好的顺序不再被活动打乱;代价是「最近活跃浮到最上」的行为消失,活跃感知转由行内状态点与时间标签承担。`WorkspaceView.sessionIds` 的 wire 契约随之改为手动序措辞。 +- 壳/区域两事实契约把 workspace 域的后续功能(Delete 确认、跨组移动、Ungrouped 收编)全部收进 ui-workspace 单包;ui-sidebar 不再随 session 列表功能演进。 +- 平铺模式不支持排序与分组入口(建到指定 workspace 需切回分组视图),是拍板接受的范围收窄。 +- session 菜单三项与 workspace Delete 的功能接线、状态枚举扩 wire,留待后续迭代。 + +## Testing + +包级用例覆盖派生(deriveGroups/deriveFlat)、行组件、两处 apply 注册与透传、host 实体移位语义、rename/insertSessionBefore 的 RPC 实现与 fixture 桩;`apps/web` keyless snapshot 回归覆盖装配后的应用;交付验收另以 playwright(chromium headless)过 12 项清单(分组默认、平铺切换与持久化、hover 卡出现与抑制、双菜单、rename 全链、拖拽落盘),并对真 host 直打 wire 验证 rename 成功/重名拒绝/`workspace-move-invalid` 三径。 diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 474f587230..387ff39c3e 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -1991,7 +1991,7 @@ list(): Workspace[] async resolveByPath(path: string): Promise ``` -Source: [`packages/workspace/workspace/src/index.ts:75`](../../packages/workspace/workspace/src/index.ts) +Source: [`packages/workspace/workspace/src/index.ts:78`](../../packages/workspace/workspace/src/index.ts) ## Inherited `ctx` members (cordis core + loader/hmr/timer) diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx index e7d0cdc38c..57de2cbaf5 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -209,7 +209,7 @@ function FlatList({ useSessions, open, query }: Pick{query === '' ? 'No sessions yet' : 'No matches'}
)} - {intentRow && } + {intentRow && } {rows.map(node => ( - {!flat && } New session
From 8cc46e602504fc562427b1614545d5dcf27c290c Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 01:16:39 +0800 Subject: [PATCH 084/113] docs(notes): export settings note contract types Both sides of the bilingual pair compile in one doc-typecheck program; module-scoped (exported) declarations keep the shared identifiers from colliding across the pair. --- ...2026-07-25-client-settings-locale-theme.i18n.yaml | 4 ++-- .../2026-07-25-client-settings-locale-theme.md | 12 ++++++------ .../2026-07-25-client-settings-locale-theme.zh.md | 12 ++++++------ 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml index 54fb6ee9ee..8583642403 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.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 -2026-07-25-client-settings-locale-theme.md: 25e22c728ea509613c4d7f6cdfcd09faf4685760 -2026-07-25-client-settings-locale-theme.zh.md: 9c2457b254aa826291d4c5a4e115e9ba2d391974 +2026-07-25-client-settings-locale-theme.md: e1245a9e1fac82fb0feb84af7a59945b17fa1daf +2026-07-25-client-settings-locale-theme.zh.md: 195b2e5ffa3556dd1b8bf2dd6ec8ae84115fbdb2 diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md index 25e22c728e..e1245a9e1f 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md @@ -49,33 +49,33 @@ Section contributions use declaration-aware deferral and do not depend on the cl ### Service contracts ```ts -type ThemePreference = 'light' | 'dark' | 'system' +export type ThemePreference = 'light' | 'dark' | 'system' -interface ThemeDefinition { +export interface ThemeDefinition { id: string colorScheme: 'light' | 'dark' tokens: Record } -interface ThemeSnapshot { +export interface ThemeSnapshot { preference: ThemePreference active: ThemeDefinition // system 已解析为具体 light/dark 定义 themes: readonly ThemeDefinition[] revision: number } -interface LocaleDefinition { +export interface LocaleDefinition { id: 'zh' | 'en' label: string } -interface LocaleSnapshot { +export interface LocaleSnapshot { active: 'zh' | 'en' locales: readonly LocaleDefinition[] revision: number } -interface Events { +export interface Events { /** @param snapshot - Current locale registry snapshot. @mode emit */ 'locale/change'(snapshot: LocaleSnapshot): void /** @param snapshot - Current theme registry snapshot. @mode emit */ diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md index 9c2457b254..195b2e5ffa 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md @@ -49,33 +49,33 @@ section contribution 使用 declaration-aware deferral,不依赖 client manife ### Service contracts ```ts -type ThemePreference = 'light' | 'dark' | 'system' +export type ThemePreference = 'light' | 'dark' | 'system' -interface ThemeDefinition { +export interface ThemeDefinition { id: string colorScheme: 'light' | 'dark' tokens: Record } -interface ThemeSnapshot { +export interface ThemeSnapshot { preference: ThemePreference active: ThemeDefinition // system 已解析为具体 light/dark 定义 themes: readonly ThemeDefinition[] revision: number } -interface LocaleDefinition { +export interface LocaleDefinition { id: 'zh' | 'en' label: string } -interface LocaleSnapshot { +export interface LocaleSnapshot { active: 'zh' | 'en' locales: readonly LocaleDefinition[] revision: number } -interface Events { +export interface Events { /** @param snapshot - Current locale registry snapshot. @mode emit */ 'locale/change'(snapshot: LocaleSnapshot): void /** @param snapshot - Current theme registry snapshot. @mode emit */ From ba5c1368710709b5b524f1de3a544bd93c281953 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 01:30:14 +0800 Subject: [PATCH 085/113] docs(notes): record the session-list browsing and manual-order decisions --- ...n-list-browsing-and-manual-order.i18n.yaml | 6 ++ ...-session-list-browsing-and-manual-order.md | 60 +++++++++++++++++++ ...ssion-list-browsing-and-manual-order.zh.md | 2 +- 3 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 .agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.md diff --git a/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.i18n.yaml b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.i18n.yaml new file mode 100644 index 0000000000..590d9227b8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.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 +2026-07-25-session-list-browsing-and-manual-order.md: 586995bf459aeaee88672863977f7acf2a7061a3 +2026-07-25-session-list-browsing-and-manual-order.zh.md: 432d5167a57d30bc04a0b4faf213e4341f07bd2f diff --git a/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.md b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.md new file mode 100644 index 0000000000..586995bf45 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.md @@ -0,0 +1,60 @@ +# Agent Note: Session List Browsing and Manual Workspace Order + +Status: implemented + +English | [中文](2026-07-25-session-list-browsing-and-manual-order.zh.md) + +## Problem + +[Workspace UI Complete Product Flow](2026-07-25-workspace-ui-product-flow.md) shipped the first form of the grouped session list and explicitly scoped out operations such as Rename and drag ordering. The design file (figma 239-10458 and its companion screens) has since filled in those interactions: the list must switch to an ungrouped flat view, session rows need a hover detail card and an action menu, workspaces need renaming, and sessions need manual ordering inside their group. + +Two existing mechanisms stood in the way. First, the host durably promoted the active session to the front of its workspace account on every `session/event` (activity pinning), so any manual order would be scrambled by the next activity — two ordering authorities cannot coexist. Second, the browsing area was split across two packages: ui-sidebar owned the list, search, and header rows while ui-workspace only borrowed a picker slot for its popover; every new workspace-domain dialog required cross-package wiring, and ownership grew more twisted with each one. + +## Decision + +### Flat view and viewing state + +The group-by menu offers two modes, WorkSpace / In one list. Flat mode renders every session (fork children included) as a top-level row, strictly newest-first by `updatedAt`, with no parent/child adjacency; the Intent placeholder renders as the first row. The mode choice persists in the browser (`dsh.workspace.view`) across reloads. + +### Row interactions + +- Session rows show a detail card after a 500ms hover dwell (full title / relative time / status line; the status line has only running/idle until the wire grows a status field). The card and the row menu are mutually exclusive: no card while a menu is open or a drag is in flight. +- Session-row … menu: Rename / Fork session / Delete session, visual-only this iteration; workspace-header … menu: Rename (wired) / Delete workspace (visual-only). Menus close when the pointer leaves them. +- Supporting primitives: `Menu` gains label entries, danger rows, and `closeOnPointerLeave`; a new `HoverCard` (portaled placement, open delay, disabled guard). + +### workspace.rename + +`workspace.rename({ workspaceId, title })`: the title is trimmed and must be non-blank; both the same-title no-op and the duplicate check evaluate inside the host's serialized workspace-creation chain (shared with create, so concurrent create/rename cannot interleave a duplicate or an out-of-order fake success), and a conflict returns `workspace-name-conflict`. Durability goes through `setTitle`'s mutate path, and the `domain/changed` listener broadcasts the `host/workspace-changed` frame automatically. The UI is a standard modal with a client-side duplicate pre-check. + +### Manual order: insertSessionBefore replaces activity pinning + +The `session/event` → `touchSession` activity-pinning chain is deleted wholesale; the workspace account order is now manually owned — new sessions prepend at attach, and explicit reordering goes through `workspace.insertSessionBefore({ workspaceId, sessionId, beforeSessionId? })` (DOM insertBefore semantics: with an anchor it inserts before it, omitted appends to the end). The entity throws a typed `WorkspaceMoveInvalidError` only for unaccounted session/anchor ids; the handler maps exactly that to the business code `workspace-move-invalid`, while storage failures stay internal. + +The UI is HTML5 drag on root rows inside a group (workspace grouping only, outside search; fork children ride with their parent and are not draggable). Order authority stays entirely host-side: drop only sends the RPC, the client performs zero local reordering, and the view refreshes from the response upsert and the changed frame; a failed move changes nothing. The client's upsert rejects snapshots older (`updatedAt`) than the installed projection so a late unary response cannot roll back a newer frame. + +### Shell/region split + +ui-sidebar shrinks to the column-geometry shell: brand row, fold state machine, New Session, Settings, and one `sidebar.workspaces` hole; the shell↔region contract is two facts, `{ wide, expandSidebar }`. ui-workspace fully owns the browsing region (section header, search, grouped tree and flat list, every workspace dialog, drag) plus its groupBy store; the rail-state search/new-workspace icons belong to the region too and request shell expansion via `expandSidebar()`. The picker splits into the core `WorkspaceCreateFlow` (composed directly inside the region) and the thin `WorkspacePicker` wrapper (still filling ui-conversation's hero slot); the old `sidebar.workspace` picker slot and its declaration-aware deferral are deleted with it. + +## Alternatives considered + +**Keep activity pinning; treat drag as a transient adjustment** — the manual order would be scrambled by the next session activity, making it a fiction; two coexisting ordering authorities cannot be explained to the user. A middle ground — freeze pinning per workspace after the first drag — adds a state tier with murkier semantics; deleting outright is cleaner. + +**Numeric index in the reorder payload** — `{ index }` drifts during the drag window: after the host prepends a new session (e.g. Intent materialization) the same index points at a different row. Anchor-style insertBefore is naturally immune to prepends and filtered projections. + +**Optimistic reordering on drop** — client-first reordering needs failure rollback, one more entangled state in the object layer; local/LAN round-trips are millisecond-scale, so waiting for the host response is imperceptible. With a single order authority (trust the host completely), the frontend never invents an order. + +**Keep the rename dialog in ui-sidebar (smallest change)** — that is the problem itself: workspace-domain dialogs scattered in a borrowed slot, with each addition (the Delete confirmation is coming) repeating the cross-package wiring. Review first considered moving only the rename modal; the ruling was to give the whole browsing region to ui-workspace and leave the shell geometry-only. + +**Keep parent/child adjacency in flat mode** — contradicts strict recency (a child newer than its parent's sibling cannot slot adjacently), and the flat view's purpose is dropping the hierarchy; flattening fully and disabling drag in flat mode (no persistence carrier) is more consistent. + +## Consequences + +- Manual order is the sole authority over the workspace account: an order the user arranges is never scrambled by activity; the cost is losing float-to-top-on-activity, whose signal now rides the row status dot and time label. The `WorkspaceView.sessionIds` wire contract is reworded to the manual-order semantics. +- The two-fact shell/region contract funnels every future workspace-domain feature (Delete confirmation, cross-group moves, Ungrouped adoption) into the single ui-workspace package; ui-sidebar no longer evolves with session-list features. +- Flat mode supports neither reordering nor a create-in-workspace entry point (switching back to grouped view is required) — an accepted scope reduction. +- Wiring the three session-menu items and workspace Delete, and growing the wire status enum, remain future iterations. + +## Testing + +Package-level suites cover the derivations (deriveGroups/deriveFlat), row components, both apply registrations and passthroughs, host entity move semantics, and the rename/insertSessionBefore RPC implementations with their fixture stubs; the `apps/web` keyless snapshots regress the assembled application; delivery acceptance additionally runs a 12-item playwright (chromium headless) checklist (grouped default, flat switch and persistence, hover-card appearance and suppression, both menus, the full rename chain, drag persistence) and drives the real host over the wire for rename success / duplicate rejection / `workspace-move-invalid`. diff --git a/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md index e897903f83..432d5167a5 100644 --- a/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md +++ b/.agents/notes/implemented/feature/2026-07-25-session-list-browsing-and-manual-order.zh.md @@ -6,7 +6,7 @@ Status: implemented ## Problem -[Workspace UI 完整产品流](2026-07-25-workspace-ui-product-flow.zh.md)交付了分组 session 列表的首个形态,并把 Rename、拖拽排序等操作明确划出当期范围。设计稿(figma 239-10458 及关联画面)随后补齐了这些交互:列表要能切换成不分组的平铺视图、session 行悬停要出详情卡与操作菜单、workspace 要能改名、组内 session 要能手动排序。 +[Workspace UI 完整产品流](2026-07-25-workspace-ui-product-flow.md)交付了分组 session 列表的首个形态,并把 Rename、拖拽排序等操作明确划出当期范围。设计稿(figma 239-10458 及关联画面)随后补齐了这些交互:列表要能切换成不分组的平铺视图、session 行悬停要出详情卡与操作菜单、workspace 要能改名、组内 session 要能手动排序。 两条既有机制挡在前面。其一,host 在每条 `session/event` 上把活跃 session durable 地提到 workspace 账本最前(活动置顶),任何手动排序都会被下一次活动打乱——两种排序权威不可调和。其二,浏览区域被劈在两个包里:ui-sidebar 拥有列表、搜索和组头行,ui-workspace 只借一个 picker 坑放弹层;每加一个 workspace 域的对话框都要跨包接线,归属越来越拧。 From 2ee4cda0667d990525938dd559c90fcd52e35f3d Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 01:30:46 +0800 Subject: [PATCH 086/113] fix(client): lint conformance for the preference services Replace optional chains on always-present globals with the repo's typeof guards (store.ts precedent), drop the non-null assertion by failing loud on an impossible registry miss, and fix two arrow-parens slips; cover the no-localStorage boot path in both service suites. --- packages/client/locale/src/client/index.ts | 7 +++++-- packages/client/locale/tests/locale.spec.ts | 14 +++++++++++++- packages/client/ui-layout/src/client/index.ts | 2 +- packages/client/ui-settings/src/client/index.ts | 2 +- packages/client/ui-theme/src/client/index.ts | 15 ++++++++++----- packages/client/ui-theme/tests/theme.spec.ts | 12 ++++++++++++ 6 files changed, 42 insertions(+), 10 deletions(-) diff --git a/packages/client/locale/src/client/index.ts b/packages/client/locale/src/client/index.ts index e01d69ea25..35f29a0e52 100644 --- a/packages/client/locale/src/client/index.ts +++ b/packages/client/locale/src/client/index.ts @@ -161,8 +161,10 @@ export class LocaleService { /** Read the persisted locale id; unknown or unreadable values fall back to zh. */ function restorePreference(): LocaleId { + // Non-browser runs (node e2e booting the client tree) have no localStorage. + if (typeof localStorage === 'undefined') return FALLBACK_LOCALE try { - const stored = globalThis.localStorage?.getItem(STORAGE_KEY) + const stored = localStorage.getItem(STORAGE_KEY) if (stored === 'zh' || stored === 'en') return stored } catch { // Storage access can throw (privacy mode); the default below covers it. @@ -172,8 +174,9 @@ function restorePreference(): LocaleId { /** Persist the locale id; storage failures are non-fatal (preference resets next boot). */ function persistPreference(id: LocaleId): void { + if (typeof localStorage === 'undefined') return try { - globalThis.localStorage?.setItem(STORAGE_KEY, id) + localStorage.setItem(STORAGE_KEY, id) } catch { // Storage access can throw (privacy mode / quota); the preference simply // does not survive the session. diff --git a/packages/client/locale/tests/locale.spec.ts b/packages/client/locale/tests/locale.spec.ts index 750c2452e8..3f9efaed19 100644 --- a/packages/client/locale/tests/locale.spec.ts +++ b/packages/client/locale/tests/locale.spec.ts @@ -1,5 +1,5 @@ // @vitest-environment jsdom -import { beforeEach, describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' import { Context } from 'cordis' import type { LocaleSnapshot } from '@deepseek-ai/dsh-client-locale/client' import { LocaleService, STORAGE_KEY } from '@deepseek-ai/dsh-client-locale/client' @@ -80,6 +80,18 @@ describe('LocaleService', () => { expect(make().svc.getLocale().active).toBe('zh') }) + it('runs without localStorage (node boots): defaults on read, no-op on write', () => { + vi.stubGlobal('localStorage', undefined) + try { + const { svc } = make() + expect(svc.getLocale().active).toBe('zh') + svc.setLocale('en') + expect(svc.getLocale().active).toBe('en') + } finally { + vi.unstubAllGlobals() + } + }) + it('exposes the two shipped locales with self-described labels', () => { const { svc } = make() expect(svc.getLocale().locales).toEqual([ diff --git a/packages/client/ui-layout/src/client/index.ts b/packages/client/ui-layout/src/client/index.ts index 39fee1fb52..7474cd69c3 100644 --- a/packages/client/ui-layout/src/client/index.ts +++ b/packages/client/ui-layout/src/client/index.ts @@ -107,7 +107,7 @@ export function apply(ctx: ClientContext): void { ctx.effect(() => { const presenter = new ThemePresenter() presenter.apply(ctx.theme.getTheme()) - const off = ctx.on('theme/change', snapshot => { presenter.apply(snapshot) }) + const off = ctx.on('theme/change', (snapshot) => { presenter.apply(snapshot) }) return () => { off() presenter.dispose() diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index 688436c25b..3613476ede 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -41,7 +41,7 @@ export function apply(ctx: ClientContext): void { return ctx.locale.bind(ref.slice(0, colon))(ref.slice(colon + 1)) }, sectionsVersion: () => ctx.slots.getVersion('settings.section'), - subscribeSections: (listener) => ctx.slots.subscribe('settings.section', listener), + subscribeSections: listener => ctx.slots.subscribe('settings.section', listener), sections: () => ctx.slots.entries('settings.section') .map(e => ({ /* v8 ignore next -- list-slot registration requires id (SlotCore rejects an entry without one) */ diff --git a/packages/client/ui-theme/src/client/index.ts b/packages/client/ui-theme/src/client/index.ts index b8a75c4bed..5c7ca3fe12 100644 --- a/packages/client/ui-theme/src/client/index.ts +++ b/packages/client/ui-theme/src/client/index.ts @@ -87,7 +87,8 @@ export class ThemeService { constructor(ctx: Context) { this.ctx = ctx this.preference = restorePreference() - this.media = globalThis.matchMedia?.('(prefers-color-scheme: dark)') + // Non-browser runs (node e2e booting the client tree) have no matchMedia. + this.media = typeof matchMedia === 'undefined' ? undefined : matchMedia('(prefers-color-scheme: dark)') this.snapshot = this.buildSnapshot() if (this.media !== undefined) { const media = this.media @@ -157,8 +158,9 @@ export class ThemeService { : this.preference // Both built-ins always exist; a registered preference id resolves or has // been reset by its disposer, so the lookup cannot miss. - /* v8 ignore next -- the ?? arm needs a registry without light/dark, which register()/dispose() cannot produce */ - const active = this.themes.find(t => t.id === resolvedId) ?? this.themes[0]! + const active = this.themes.find(t => t.id === resolvedId) + /* v8 ignore next 2 -- needs a registry without light/dark, which register()/dispose() cannot produce */ + if (active === undefined) throw new Error(`theme registry lost "${resolvedId}"`) return Object.freeze({ preference: this.preference, active, @@ -176,8 +178,10 @@ export class ThemeService { /** Read the persisted preference; unknown or unreadable values fall back to the default. */ function restorePreference(): ThemePreference { + // Non-browser runs (node e2e booting the client tree) have no localStorage. + if (typeof localStorage === 'undefined') return DEFAULT_PREFERENCE try { - const stored = globalThis.localStorage?.getItem(STORAGE_KEY) + const stored = localStorage.getItem(STORAGE_KEY) if (stored === 'light' || stored === 'dark' || stored === 'system') return stored } catch { // Storage access can throw (privacy mode); the default below covers it. @@ -187,8 +191,9 @@ function restorePreference(): ThemePreference { /** Persist the preference; storage failures are non-fatal (preference resets next boot). */ function persistPreference(preference: ThemePreference): void { + if (typeof localStorage === 'undefined') return try { - globalThis.localStorage?.setItem(STORAGE_KEY, preference) + localStorage.setItem(STORAGE_KEY, preference) } catch { // Storage access can throw (privacy mode / quota); the preference simply // does not survive the session. diff --git a/packages/client/ui-theme/tests/theme.spec.ts b/packages/client/ui-theme/tests/theme.spec.ts index fdac111e73..c853c9fd67 100644 --- a/packages/client/ui-theme/tests/theme.spec.ts +++ b/packages/client/ui-theme/tests/theme.spec.ts @@ -88,6 +88,18 @@ describe('ThemeService', () => { expect(events.map(e => e.revision)).toEqual([1, 2, 3, 4]) }) + it('runs without localStorage (node boots): defaults on read, no-op on write', () => { + vi.stubGlobal('localStorage', undefined) + try { + const { theme } = make() + expect(theme.getTheme().preference).toBe('system') + theme.setTheme('dark') + expect(theme.getTheme().preference).toBe('dark') + } finally { + vi.unstubAllGlobals() + } + }) + describe('prefers-color-scheme resolution (stubbed matchMedia)', () => { type Listener = () => void const stubMedia = (initialMatches: boolean) => { From 9fc8a616a9acc9ca303fdadb41313c7f6b1e0454 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 01:48:36 +0800 Subject: [PATCH 087/113] test(web): close the per-file coverage gate for the session-list surfaces New and touched sources reach the CI per-file 100% thresholds: HoverCard (timers, placement clamp, disabled guard), Menu label/danger/pointer-leave branches, WorkspaceBrowser (mode switch, search, rail icons, rename dialog, drag), rows and tree derivations, the workspace fixture stubs, the rename/ insertSessionBefore wire rows, and the entity move semantics. HoverCard's position state narrows to {left, top} (equivalent refactor, no behavior change). --- .../client/connection/tests/fixture.spec.ts | 63 +++ .../client/ui-primitives/src/HoverCard.tsx | 19 +- .../client/ui-primitives/tests/atoms.spec.tsx | 45 ++ .../ui-primitives/tests/hover-card.spec.tsx | 148 ++++++ .../src/client/WorkspaceBrowser.tsx | 5 + .../client/ui-workspace/tests/rows.spec.tsx | 177 ++++++- .../client/ui-workspace/tests/tree.spec.ts | 42 +- .../tests/workspace-browser.spec.tsx | 458 ++++++++++++++++++ .../apiproxy/tests/client-handler.spec.ts | 13 + .../host/apiproxy/tests/rpc-schemas.spec.ts | 29 +- .../workspace/tests/workspace.spec.ts | 52 +- 11 files changed, 1037 insertions(+), 14 deletions(-) create mode 100644 packages/client/ui-primitives/tests/hover-card.spec.tsx create mode 100644 packages/client/ui-workspace/tests/workspace-browser.spec.tsx diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 16fa4b4ed6..0baabaf617 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -311,6 +311,60 @@ describe('createFixtureApi', () => { expect(rootPath.result.value.workspace.title).toBe('/') }) + it('workspace.rename covers not-found, conflict, no-op, and the changed frame', async () => { + const api = createFixtureApi() + const abort = new AbortController() + const seen: HostFrame[] = [] + const consuming = (async () => { + for await (const envelope of api.events.host(req({}), abort.signal)) { + seen.push(envelope.payload) + if (seen.length >= 2) abort.abort() + } + })() + await new Promise(resolve => setTimeout(resolve, 10)) + const wsid = 'fx-ws-fixture' as WorkspaceId + const missing = await api.workspace.rename(req({ workspaceId: 'fx-ws-void' as WorkspaceId, title: 'x' })) + expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found', details: { workspaceId: 'fx-ws-void' } } }) + + await api.workspace.create(req({ name: 'occupied' })) + const conflict = await api.workspace.rename(req({ workspaceId: wsid, title: ' occupied ' })) + expect(conflict.result).toMatchObject({ ok: false, error: { code: 'workspace-name-conflict', details: { name: 'occupied' } } }) + + const noop = await api.workspace.rename(req({ workspaceId: wsid, title: ' fixture ' })) + if (!noop.result.ok) throw new Error('no-op rename failed') + expect(noop.result.value.workspace.title).toBe('fixture') + + const renamed = await api.workspace.rename(req({ workspaceId: wsid, title: 'renamed' })) + if (!renamed.result.ok) throw new Error('rename failed') + expect(renamed.result.value.workspace.title).toBe('renamed') + await consuming + // Only the create and the effective rename emit frames; the no-op stays silent. + expect(seen.map(f => f.type)).toEqual(['host/workspace-changed', 'host/workspace-changed']) + }) + + it('workspace.insertSessionBefore moves, appends, no-ops, and rejects invalid ids', async () => { + const api = createFixtureApi() + const wsid = 'fx-ws-fixture' as WorkspaceId + const missing = await api.workspace.insertSessionBefore(req({ workspaceId: 'fx-ws-void' as WorkspaceId, sessionId: sid('fx-alpha') })) + expect(missing.result).toMatchObject({ ok: false, error: { code: 'workspace-not-found' } }) + const ghost = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-ghost') })) + expect(ghost.result).toMatchObject({ ok: false, error: { code: 'workspace-move-invalid', details: { sessionId: 'fx-ghost' } } }) + const badAnchor = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha'), beforeSessionId: sid('fx-ghost') })) + expect(badAnchor.result).toMatchObject({ ok: false, error: { code: 'workspace-move-invalid', details: { beforeSessionId: 'fx-ghost' } } }) + + const moved = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-gamma'), beforeSessionId: sid('fx-beta') })) + if (!moved.result.ok) throw new Error('move failed') + expect(moved.result.value.workspace.sessionIds).toEqual(['fx-alpha', 'fx-gamma', 'fx-beta']) + const appended = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha') })) + if (!appended.result.ok) throw new Error('append failed') + expect(appended.result.value.workspace.sessionIds).toEqual(['fx-gamma', 'fx-beta', 'fx-alpha']) + const before = appended.result.value.workspace.updatedAt + const noop = await api.workspace.insertSessionBefore(req({ workspaceId: wsid, sessionId: sid('fx-alpha') })) + if (!noop.result.ok) throw new Error('no-op move failed') + expect(noop.result.value.workspace.sessionIds).toEqual(['fx-gamma', 'fx-beta', 'fx-alpha']) + expect(noop.result.value.workspace.updatedAt).toBe(before) + }) + it('session.create({workspaceId}) lands on the account and unknown ids error', async () => { const api = createFixtureApi() const abort = new AbortController() @@ -558,6 +612,15 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => { const workspace = await client.workspace.create({ name: 'via-client' }) if (!workspace.result.ok) throw new Error('workspace create failed') expect(workspace.result.value.workspace.title).toBe('via-client') + const wsid = workspace.result.value.workspace.workspaceId + const renamed = await client.workspace.rename({ workspaceId: wsid, title: 'via-client-2' }) + if (!renamed.result.ok) throw new Error('workspace rename failed') + expect(renamed.result.value.workspace.title).toBe('via-client-2') + const attached = await client.sessions.create({ workspaceId: wsid }) + if (!attached.result.ok) throw new Error('attached create failed') + const moved = await client.workspace.insertSessionBefore({ workspaceId: wsid, sessionId: attached.result.value.sessionId }) + if (!moved.result.ok) throw new Error('workspace move failed') + expect(moved.result.value.workspace.sessionIds).toEqual([attached.result.value.sessionId]) }) it('maps empty, prompt-reject, and workspace-first query scenarios', async () => { diff --git a/packages/client/ui-primitives/src/HoverCard.tsx b/packages/client/ui-primitives/src/HoverCard.tsx index 58e281778e..1720a0b79c 100644 --- a/packages/client/ui-primitives/src/HoverCard.tsx +++ b/packages/client/ui-primitives/src/HoverCard.tsx @@ -5,7 +5,7 @@ // and closes the instant the pointer leaves the anchor (no close delay). import { useEffect, useLayoutEffect, useRef, useState } from 'react' -import type { CSSProperties, ReactNode } from 'react' +import type { ReactNode } from 'react' import { createPortal } from 'react-dom' import css from './HoverCard.module.css' @@ -27,7 +27,7 @@ export function HoverCard({ anchor, content, openDelayMs = 500, disabled = false const cardRef = useRef(null) const timerRef = useRef | null>(null) const [open, setOpen] = useState(false) - const [pos, setPos] = useState(null) + const [pos, setPos] = useState<{ left: number; top: number } | null>(null) const clearTimer = () => { if (timerRef.current !== null) { @@ -50,8 +50,10 @@ export function HoverCard({ anchor, content, openDelayMs = 500, disabled = false useLayoutEffect(() => { if (!open) { setPos(null); return } const place = () => { - const r = rootRef.current?.getBoundingClientRect() ?? null - if (r === null) return + const wrapper = rootRef.current + /* v8 ignore next -- the ref is attached before the layout effect runs and the listeners die with it. */ + if (wrapper === null) return + const r = wrapper.getBoundingClientRect() const h = cardRef.current?.offsetHeight ?? 0 const top = r.top + h > window.innerHeight - 8 ? window.innerHeight - h - 8 : r.top setPos({ left: r.right + 8, top }) @@ -66,13 +68,14 @@ export function HoverCard({ anchor, content, openDelayMs = 500, disabled = false }, [open]) // The first placement ran before the card mounted (height read 0): once the - // card's real height is measurable, correct the bottom-edge clamp. + // card's real height is measurable, correct the bottom-edge clamp. The + // correction converges — a clamped top satisfies the guard, so it runs once. useLayoutEffect(() => { - if (!open || pos === null || typeof pos.top !== 'number') return + if (!open || pos === null) return + /* v8 ignore next -- the card is mounted whenever pos is set, so the ref is attached here. */ const h = cardRef.current?.offsetHeight ?? 0 if (pos.top + h > window.innerHeight - 8) { - const top = window.innerHeight - h - 8 - if (pos.top !== top) setPos({ ...pos, top }) + setPos({ left: pos.left, top: window.innerHeight - h - 8 }) } }, [open, pos]) diff --git a/packages/client/ui-primitives/tests/atoms.spec.tsx b/packages/client/ui-primitives/tests/atoms.spec.tsx index 440f4ba6ef..9e298d057a 100644 --- a/packages/client/ui-primitives/tests/atoms.spec.tsx +++ b/packages/client/ui-primitives/tests/atoms.spec.tsx @@ -136,6 +136,51 @@ describe('Menu', () => { expect(screen.getByRole('separator')).toBeDefined() }) + it('renders a non-interactive heading label and a danger row', () => { + const onSelect = vi.fn() + render( + trigger} + items={[ + { type: 'label', id: 'h', text: 'Group by' }, + { id: 'del', label: 'Delete', danger: true }, + ]} + onSelect={onSelect} + onClose={() => {}} + />) + const heading = screen.getByText('Group by') + expect(heading.getAttribute('role')).toBe('presentation') + // The heading is not a menu item — only the danger row is interactive. + expect(screen.getAllByRole('menuitem')).toHaveLength(1) + const danger = screen.getByRole('menuitem', { name: 'Delete' }) + expect(danger.className).toMatch(/danger/) + fireEvent.click(danger) + expect(onSelect).toHaveBeenCalledWith('del') + }) + + it('closeOnPointerLeave closes when the pointer leaves the list; default stays open', () => { + const onClose = vi.fn() + const { rerender } = render( + trigger} items={items} onSelect={() => {}} onClose={onClose} />) + fireEvent.pointerLeave(screen.getByRole('menu')) + expect(onClose).toHaveBeenCalledTimes(1) + rerender( + trigger} items={items} onSelect={() => {}} onClose={onClose} />) + fireEvent.pointerLeave(screen.getByRole('menu')) + expect(onClose).toHaveBeenCalledTimes(1) + }) + + it('a list click does not bubble to the anchor row (portal synthetic-event path)', () => { + const rowClick = vi.fn() + render( +
+ trigger} items={items} onSelect={() => {}} onClose={() => {}} /> +
) + fireEvent.click(screen.getByRole('menuitem', { name: 'Alpha' })) + expect(rowClick).not.toHaveBeenCalled() + }) + it('opens a submenu on hover and selects a nested item', () => { const onSelect = vi.fn() render( diff --git a/packages/client/ui-primitives/tests/hover-card.spec.tsx b/packages/client/ui-primitives/tests/hover-card.spec.tsx new file mode 100644 index 0000000000..c7a95f49fb --- /dev/null +++ b/packages/client/ui-primitives/tests/hover-card.spec.tsx @@ -0,0 +1,148 @@ +// @vitest-environment jsdom +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { HoverCard } from '@deepseek-ai/dsh-client-ui-primitives' + +afterEach(cleanup) +beforeEach(() => { vi.useFakeTimers() }) +afterEach(() => { vi.useRealTimers() }) + +/** Anchor wrapper rect: the card positions from this (jsdom rects are all-zero by default). */ +function stubAnchorRect(anchor: HTMLElement, rect: { top: number; right: number }): void { + const wrapper = anchor.parentElement as HTMLElement + wrapper.getBoundingClientRect = () => ({ + top: rect.top, right: rect.right, left: rect.right - 100, bottom: rect.top + 34, + width: 100, height: 34, x: rect.right - 100, y: rect.top, toJSON: () => ({}), + } as DOMRect) +} + +function mount(props: { openDelayMs?: number; disabled?: boolean } = {}) { + const view = render( + row} content={
card body
} {...props} />, + ) + const anchor = screen.getByText('row') + stubAnchorRect(anchor, { top: 40, right: 200 }) + return { view, anchor, wrapper: anchor.parentElement as HTMLElement } +} + +describe('HoverCard', () => { + it('opens after the dwell delay, positioned right of the anchor', () => { + const { wrapper } = mount() + fireEvent.pointerEnter(wrapper) + expect(screen.queryByText('card body')).toBeNull() + act(() => { vi.advanceTimersByTime(499) }) + expect(screen.queryByText('card body')).toBeNull() + act(() => { vi.advanceTimersByTime(1) }) + const card = screen.getByText('card body').parentElement as HTMLElement + expect(card.parentElement).toBe(document.body) + expect(card.style.left).toBe('208px') + expect(card.style.top).toBe('40px') + }) + + it('honors a custom openDelayMs', () => { + const { wrapper } = mount({ openDelayMs: 50 }) + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(50) }) + expect(screen.getByText('card body')).toBeTruthy() + }) + + it('pointerleave before the delay cancels the pending open', () => { + const { wrapper } = mount() + fireEvent.pointerEnter(wrapper) + fireEvent.pointerLeave(wrapper) + act(() => { vi.advanceTimersByTime(1000) }) + expect(screen.queryByText('card body')).toBeNull() + }) + + it('pointerleave closes an open card immediately; re-enter restarts the dwell', () => { + const { wrapper } = mount() + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.getByText('card body')).toBeTruthy() + fireEvent.pointerLeave(wrapper) + expect(screen.queryByText('card body')).toBeNull() + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.getByText('card body')).toBeTruthy() + }) + + it('a press inside the anchor dismisses the card without waiting for disabled', () => { + const { wrapper } = mount() + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.getByText('card body')).toBeTruthy() + fireEvent.pointerDown(screen.getByText('row')) + expect(screen.queryByText('card body')).toBeNull() + // The pending timer is also cleared: no reopen after the dwell. + act(() => { vi.advanceTimersByTime(1000) }) + expect(screen.queryByText('card body')).toBeNull() + }) + + it('disabled suppresses opening entirely', () => { + const { wrapper } = mount({ disabled: true }) + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(1000) }) + expect(screen.queryByText('card body')).toBeNull() + }) + + it('flipping disabled true closes an open card', () => { + const { view, wrapper } = mount() + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.getByText('card body')).toBeTruthy() + view.rerender(row} content={
card body
} disabled />) + expect(screen.queryByText('card body')).toBeNull() + }) + + it('corrects the bottom-edge clamp once the mounted card height is measurable', () => { + // First placement reads height 0 (card not yet mounted) and keeps the + // anchor top; the post-mount correction re-clamps with the real height. + window.innerHeight = 300 + const offsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')! + Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, get: () => 120 }) + try { + const { wrapper } = mount() + stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + const card = screen.getByText('card body').parentElement as HTMLElement + // 300 - 120 - 8 = 172, instead of the anchor top 280. + expect(card.style.top).toBe('172px') + } finally { + Object.defineProperty(HTMLElement.prototype, 'offsetHeight', offsetHeight) + } + }) + + it('clamps inside placement itself when the card is already measured (resize path)', () => { + window.innerHeight = 300 + const { wrapper } = mount() + stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + const card = screen.getByText('card body').parentElement as HTMLElement + Object.defineProperty(card, 'offsetHeight', { value: 120 }) + act(() => { fireEvent.resize(window) }) + expect(card.style.top).toBe('172px') + }) + + it('repositions on capture-phase scroll while open and stops listening after close', () => { + const { wrapper } = mount() + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + stubAnchorRect(screen.getByText('row'), { top: 90, right: 300 }) + act(() => { fireEvent.scroll(document) }) + const card = screen.getByText('card body').parentElement as HTMLElement + expect(card.style.left).toBe('308px') + expect(card.style.top).toBe('90px') + fireEvent.pointerLeave(wrapper) + expect(screen.queryByText('card body')).toBeNull() + }) + + it('unmount clears a pending open timer', () => { + const { view, wrapper } = mount() + fireEvent.pointerEnter(wrapper) + view.unmount() + act(() => { vi.advanceTimersByTime(1000) }) + expect(screen.queryByText('card body')).toBeNull() + }) +}) diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx index 57de2cbaf5..d051df2fdb 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -48,6 +48,7 @@ function GroupByMenu({ groupBy, onPick }: { items={GROUP_BY_ITEMS} selectedId={groupBy} onSelect={(id) => { + /* v8 ignore next -- narrowing guard: the heading label is not selectable, so the only arriving ids are the two modes. */ if (id === 'workspace' || id === 'flat') onPick(id) setOpen(false) }} @@ -137,6 +138,7 @@ function SessionTree({ useSessions, startSession, open, workspaces, query, onRen onRename={group.workspaceId === undefined ? undefined : () => { + /* v8 ignore next -- narrowing guard: the closure is only created for real-workspace groups. */ if (group.workspaceId !== undefined) onRenameRequest(group.workspaceId, group.label) }} /> @@ -154,9 +156,11 @@ function SessionTree({ useSessions, startSession, open, workspaces, query, onRen active: sameGroupDrag, marker: sameGroupDrag && drag.over?.id === node.id ? drag.over.half : null, hover: (half: 'before' | 'after') => { + /* v8 ignore next -- narrowing guard: Rows gates hover on `active`, which is false while the drag state is null. */ setDrag(d => (d === null ? d : { ...d, over: { id: node.id, half } })) }, drop: (half: 'before' | 'after') => { + /* v8 ignore next -- narrowing guard: Rows gates drop on `active`, which is false while the drag state is null. */ if (drag === null) return const roots = group.sessions // Anchor = the row the insert line points at ('after' means @@ -218,6 +222,7 @@ function FlatList({ useSessions, open, query }: Pick {}} flat /> diff --git a/packages/client/ui-workspace/tests/rows.spec.tsx b/packages/client/ui-workspace/tests/rows.spec.tsx index fdc5c43b8e..b90fb9a601 100644 --- a/packages/client/ui-workspace/tests/rows.spec.tsx +++ b/packages/client/ui-workspace/tests/rows.spec.tsx @@ -1,7 +1,8 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { act, cleanup, createEvent, fireEvent, render, screen } from '@testing-library/react' import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client' +import type { RowDragProps } from '../src/client/rows/Rows.tsx' import { IntentRowItem, ProjectRowItem, SessionNodeItem } from '../src/client/rows/Rows.tsx' import type { GroupNode, SessionNode } from '../src/client/tree.ts' @@ -10,6 +11,32 @@ afterEach(cleanup) const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId +/** Half detection reads the row rect; jsdom rects are all-zero by default. */ +function stubRect(row: HTMLElement): void { + row.getBoundingClientRect = () => ({ + top: 100, bottom: 134, left: 0, right: 200, width: 200, height: 34, + x: 0, y: 100, toJSON: () => ({}), + } as DOMRect) +} + +function dragProps(overrides: Partial = {}): RowDragProps { + return { + start: vi.fn(), active: false, marker: null, + hover: vi.fn(), drop: vi.fn(), end: vi.fn(), + ...overrides, + } +} + +const dataTransfer = { effectAllowed: '', dropEffect: '' } + +/** jsdom lacks DragEvent — the fireEvent fallback drops clientY, so pin it on the built event. */ +function fireDrag(row: HTMLElement, kind: 'dragOver' | 'drop', clientY: number): void { + const event = kind === 'dragOver' ? createEvent.dragOver(row) : createEvent.drop(row) + Object.defineProperty(event, 'clientY', { value: clientY }) + Object.defineProperty(event, 'dataTransfer', { value: { ...dataTransfer } }) + fireEvent(row, event) +} + describe('workspace browser rows', () => { it('renders an active Workspace and keeps its create action separate from toggling', () => { const onToggle = vi.fn() @@ -73,4 +100,152 @@ describe('workspace browser rows', () => { expect(screen.getByRole('treeitem').getAttribute('aria-selected')).toBe('false') expect(screen.getByRole('treeitem').style.paddingLeft).toBe('24px') }) + + it('workspace row menu opens on the ellipsis, renames, and shows the danger delete row', () => { + const onRename = vi.fn() + const onToggle = vi.fn() + const group: GroupNode = { + key: 'project', workspaceId: wid('project'), cwd: '/projects/project', label: 'Project', + sessionCount: 0, expanded: false, containsCurrent: false, intentHere: false, sessions: [], + } + render() + fireEvent.click(screen.getByRole('button', { name: 'Workspace actions for Project' })) + // Opening the menu neither toggles the group nor renames yet. + expect(onToggle).not.toHaveBeenCalled() + expect(screen.getByRole('menuitem', { name: 'Delete workspace' }).className).toMatch(/danger/) + fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' })) + expect(onRename).toHaveBeenCalledOnce() + expect(screen.queryByRole('menu')).toBeNull() + // Delete stays visual-only: selecting it just closes the menu. + fireEvent.click(screen.getByRole('button', { name: 'Workspace actions for Project' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Delete workspace' })) + expect(screen.queryByRole('menu')).toBeNull() + expect(onRename).toHaveBeenCalledOnce() + // Escape closes without selecting (Menu onClose path). + fireEvent.click(screen.getByRole('button', { name: 'Workspace actions for Project' })) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('ungrouped bucket renders no workspace menu', () => { + const group: GroupNode = { + key: '', workspaceId: undefined, cwd: undefined, label: 'Ungrouped', + sessionCount: 0, expanded: false, containsCurrent: false, intentHere: false, sessions: [], + } + render() + expect(screen.queryByRole('button', { name: /Workspace actions/ })).toBeNull() + }) + + it('session row menu opens without opening the session and closes on selection', () => { + const onOpen = vi.fn() + const node: SessionNode = { + id: sid('s1'), title: 'One', children: [], hasChildren: false, + expanded: false, running: false, updatedAt: 0, + } + render() + fireEvent.click(screen.getByRole('button', { name: 'Session actions for One' })) + expect(onOpen).not.toHaveBeenCalled() + expect(screen.getByRole('menuitem', { name: 'Delete session' }).className).toMatch(/danger/) + fireEvent.click(screen.getByRole('menuitem', { name: 'Fork session' })) + expect(screen.queryByRole('menu')).toBeNull() + expect(onOpen).not.toHaveBeenCalled() + // Escape closes without selecting (Menu onClose path). + fireEvent.click(screen.getByRole('button', { name: 'Session actions for One' })) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('flat variant renders no twist even for a parent and ignores toggling', () => { + const node: SessionNode = { + id: sid('p'), title: 'Parent', children: [], hasChildren: true, + expanded: false, running: false, updatedAt: 0, + } + render() + expect(screen.queryByRole('button', { name: 'Expand' })).toBeNull() + }) + + it('shows the hover card after the dwell and suppresses it while the row menu is open', () => { + vi.useFakeTimers() + try { + const node: SessionNode = { + id: sid('s1'), title: 'Hovered', children: [], hasChildren: false, + expanded: false, running: true, updatedAt: 0, + } + render() + const wrapper = screen.getByRole('treeitem').parentElement as HTMLElement + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + // Card body: full title + relative time + running status. + expect(screen.getAllByText('Hovered')).toHaveLength(2) + expect(screen.getByText('1min ago')).toBeTruthy() + expect(screen.getByText('Running')).toBeTruthy() + fireEvent.pointerLeave(wrapper) + // Menu open (disabled=true) suppresses the card for the same hover. + fireEvent.click(screen.getByRole('button', { name: 'Session actions for Hovered' })) + fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(1000) }) + expect(screen.queryByText('1min ago')).toBeNull() + } finally { + vi.useRealTimers() + } + }) + + it('idle hover card shows the Idle status line', () => { + vi.useFakeTimers() + try { + const node: SessionNode = { + id: sid('s1'), title: 'Quiet', children: [], hasChildren: false, + expanded: false, running: false, updatedAt: 0, + } + render() + fireEvent.pointerEnter(screen.getByRole('treeitem').parentElement as HTMLElement) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.getByText('Idle')).toBeTruthy() + expect(screen.getByText('now ago')).toBeTruthy() + } finally { + vi.useRealTimers() + } + }) + + it('draggable row wires start/end and gates hover/drop on an active same-group drag', () => { + const node: SessionNode = { + id: sid('s1'), title: 'Drag me', children: [], hasChildren: false, + expanded: false, running: false, updatedAt: 0, + } + const inactive = dragProps() + const { rerender } = render( + , + ) + const row = screen.getByRole('treeitem') + stubRect(row) + expect(row.getAttribute('draggable')).toBe('true') + fireEvent.dragStart(row, { dataTransfer }) + expect(inactive.start).toHaveBeenCalledOnce() + // Inactive drag: hover and drop are rejected. + fireEvent.dragOver(row, { dataTransfer }) + fireEvent.drop(row, { dataTransfer }) + expect(inactive.hover).not.toHaveBeenCalled() + expect(inactive.drop).not.toHaveBeenCalled() + fireEvent.dragEnd(row) + expect(inactive.end).toHaveBeenCalledOnce() + + const active = dragProps({ active: true, marker: 'before' }) + rerender( + , + ) + stubRect(screen.getByRole('treeitem')) + // Top half hovers/drops 'before'; bottom half 'after' (row mid = 117). + fireDrag(screen.getByRole('treeitem'), 'dragOver', 105) + expect(active.hover).toHaveBeenCalledWith('before') + fireDrag(screen.getByRole('treeitem'), 'dragOver', 130) + expect(active.hover).toHaveBeenCalledWith('after') + fireDrag(screen.getByRole('treeitem'), 'drop', 130) + expect(active.drop).toHaveBeenCalledWith('after') + + const after = dragProps({ active: true, marker: 'after' }) + rerender( + , + ) + expect(screen.getByRole('treeitem').className).toMatch(/dropAfter/) + }) }) diff --git a/packages/client/ui-workspace/tests/tree.spec.ts b/packages/client/ui-workspace/tests/tree.spec.ts index d114d43dea..b314e14571 100644 --- a/packages/client/ui-workspace/tests/tree.spec.ts +++ b/packages/client/ui-workspace/tests/tree.spec.ts @@ -2,7 +2,8 @@ import { describe, expect, it } from 'vitest' import type { SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' -import { deriveGroups, formatRelativeTime, projectLabel, UNGROUPED_KEY, UNGROUPED_LABEL } from '../src/client/tree.ts' +import { deriveFlat, deriveGroups, formatRelativeTime, projectLabel, UNGROUPED_KEY, UNGROUPED_LABEL } from '../src/client/tree.ts' +import { createWorkspaceViewStore } from '../src/client/stores.ts' const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId @@ -52,6 +53,12 @@ describe('deriveGroups', () => { expect(deriveGroups({ ...list(), intent: hiddenIntent }, [target], view())[0]!.intentHere).toBe(false) }) + it('an Intent no longer forces its target group expanded (viewer owns expansion)', () => { + const intent = { sessionId: sid('intent'), target: { kind: 'workspace' as const, workspaceId: wid('first') }, prompt: '', phase: 'connecting' as const } + const groups = deriveGroups({ ...list(), intent }, [workspace('first', [])], view()) + expect(groups[0]).toEqual(expect.objectContaining({ intentHere: true, expanded: false })) + }) + it('search filters real Sessions and omits the Intent placeholder', () => { const intent = { sessionId: sid('intent'), target: { kind: 'workspace' as const, workspaceId: wid('first') }, prompt: '', phase: 'ready' as const } const groups = deriveGroups({ ...list(summary('match', 1)), intent }, [workspace('first', ['match'])], view([], 'match')) @@ -135,6 +142,39 @@ describe('deriveGroups', () => { }) }) +describe('deriveFlat', () => { + it('flattens every session — fork children included — newest-first with id tiebreak', () => { + const parent = summary('parent', 10) + const child = { ...summary('child', 30), parentId: parent.id } + const tieB = summary('tie-b', 20) + const tieA = summary('tie-a', 20) + const rows = deriveFlat(list(parent, child, tieB, tieA), { query: '' }) + expect(rows.map(row => row.id)).toEqual([sid('child'), sid('tie-a'), sid('tie-b'), sid('parent')]) + // Rows are branch-free: no children, no expansion. + expect(rows.every(row => row.children.length === 0 && !row.hasChildren && !row.expanded)).toBe(true) + }) + + it('search filters by case-insensitive display-title substring', () => { + const hit = { ...summary('hit', 2), displayTitle: 'Needle row' } + const miss = { ...summary('miss', 1), displayTitle: 'Other' } + expect(deriveFlat(list(hit, miss), { query: ' NEEDLE ' }).map(row => row.id)).toEqual([sid('hit')]) + }) + + it('tolerates ids whose summary has not landed yet', () => { + const partial: SessionListState = { ...list(summary('present', 1)), ids: [sid('ghost'), sid('present')] } + expect(deriveFlat(partial, { query: '' }).map(row => row.id)).toEqual([sid('present')]) + }) +}) + +describe('createWorkspaceViewStore', () => { + it('defaults to workspace grouping; setGroupBy is the sole mutation', () => { + const store = createWorkspaceViewStore().create() + expect(store.getSnapshot().groupBy).toBe('workspace') + store.actions.setGroupBy('flat') + expect(store.getSnapshot().groupBy).toBe('flat') + }) +}) + describe('projectLabel', () => { it('uses the Ungrouped fallback and extracts POSIX and Windows basenames', () => { expect(projectLabel(undefined)).toBe(UNGROUPED_LABEL) diff --git a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx new file mode 100644 index 0000000000..3e592c3168 --- /dev/null +++ b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx @@ -0,0 +1,458 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, createEvent, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import type { + SessionId, SessionListState, SessionSummary, WorkspaceId, WorkspaceListState, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' +import type { WorkspaceBrowserProps } from '../src/client/contract/slots.ts' +import { createWorkspaceViewStore } from '../src/client/stores.ts' +import { WorkspaceBrowser } from '../src/client/WorkspaceBrowser.tsx' + +afterEach(cleanup) +beforeEach(() => { localStorage.clear() }) + +const sid = (id: string) => id as SessionId +const wid = (id: string) => id as WorkspaceId +const summary = (id: string, updatedAt: number, overrides: Partial = {}): SessionSummary => ({ + id: sid(id), displayTitle: id, running: false, updatedAt, ...overrides, +}) +const sessionState = (items: readonly SessionSummary[], overrides: Partial = {}): SessionListState => ({ + ids: items.map(item => item.id), + byId: Object.fromEntries(items.map(item => [item.id, item])), + current: undefined, + phase: 'ready', + intent: undefined, + ...overrides, +}) +const workspace = (id: string, sessionIds: string[], title = id): WorkspaceView => ({ + workspaceId: wid(id), path: `/projects/${id}`, title, + sessionIds: sessionIds.map(sid), createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', +}) +const workspaceState = (items: readonly WorkspaceView[]): WorkspaceListState => ({ + items, intent: undefined, state: 'idle', phase: 'ready', error: null, baselinesReady: true, + recentWorkspaceId: items[0]?.workspaceId, +}) +const hook = (snapshot: T) => (selector: (state: T) => S): S => selector(snapshot) + +/** jsdom lacks DragEvent — the fireEvent fallback drops clientY, so pin it on the built event. */ +function fireDrag(row: HTMLElement, kind: 'dragOver' | 'drop', clientY: number): void { + const event = kind === 'dragOver' ? createEvent.dragOver(row) : createEvent.drop(row) + Object.defineProperty(event, 'clientY', { value: clientY }) + Object.defineProperty(event, 'dataTransfer', { value: { effectAllowed: '', dropEffect: '' } }) + fireEvent(row, event) +} + +function mount(overrides: Partial = {}) { + const store = createWorkspaceViewStore().create() + const props: WorkspaceBrowserProps = { + wide: true, + expandSidebar: vi.fn(), + useSessions: hook(sessionState([])), + useWorkspaces: hook(workspaceState([])), + useStore: bindSnapshotSelector(store), + actions: store.actions, + startSession: vi.fn(), + open: vi.fn(), + renameWorkspace: vi.fn(async () => {}), + insertSessionBefore: vi.fn(async () => {}), + createWorkspace: vi.fn(async () => workspace('created', [])), + ...overrides, + } + const view = render() + return { view, props, store } +} + +/** Re-render with (possibly) changed props — WorkspaceBrowser has no side channel. */ +function rerender(b: ReturnType, overrides: Partial) { + Object.assign(b.props, overrides) + b.view.rerender() +} + +describe('WorkspaceBrowser', () => { + it('renders the grouped tree by default and switches to the flat list via Group by', () => { + const sessions = sessionState([summary('alpha-s', 2), summary('beta-s', 1)]) + const b = mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['alpha-s']), workspace('beta', ['beta-s'])])), + }) + expect(screen.getByText('Workspaces')).toBeTruthy() + expect(screen.getByText('alpha')).toBeTruthy() + // Sessions hidden while their group is folded. + expect(screen.queryByText('alpha-s')).toBeNull() + + fireEvent.click(screen.getByRole('button', { name: 'Group by' })) + expect(screen.getByText('Group by')).toBeTruthy() // the menu heading label + fireEvent.click(screen.getByRole('menuitem', { name: 'In one list' })) + // Store-driven flip: title changes, rows flatten newest-first, headers gone. + expect(b.store.getSnapshot().groupBy).toBe('flat') + expect(screen.getByText('Sessions')).toBeTruthy() + expect(screen.queryByText('alpha')).toBeNull() + expect(screen.getByText('alpha-s')).toBeTruthy() + expect(screen.getByText('beta-s')).toBeTruthy() + + // Back to workspace grouping through the same menu. + fireEvent.click(screen.getByRole('button', { name: 'Group by' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'WorkSpace' })) + expect(b.store.getSnapshot().groupBy).toBe('workspace') + expect(screen.getByText('Workspaces')).toBeTruthy() + + // Escape closes the menu without picking. + fireEvent.click(screen.getByRole('button', { name: 'Group by' })) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + expect(b.store.getSnapshot().groupBy).toBe('workspace') + }) + + it('expands a group on click and opens a session row', () => { + const open = vi.fn() + mount({ + useSessions: hook(sessionState([summary('alpha-s', 1)])), + useWorkspaces: hook(workspaceState([workspace('alpha', ['alpha-s'])])), + open, + }) + fireEvent.click(screen.getByText('alpha')) + fireEvent.click(screen.getByText('alpha-s')) + expect(open).toHaveBeenCalledWith(sid('alpha-s')) + // Collapse hides the row again. + fireEvent.click(screen.getByText('alpha')) + expect(screen.queryByText('alpha-s')).toBeNull() + }) + + it('unfolds a session subtree through the row twist', () => { + const parent = summary('parent-s', 2) + const child = { ...summary('child-s', 1), parentId: parent.id } + mount({ + useSessions: hook(sessionState([parent, child])), + useWorkspaces: hook(workspaceState([workspace('alpha', ['parent-s', 'child-s'])])), + }) + fireEvent.click(screen.getByText('alpha')) + expect(screen.queryByText('child-s')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Expand' })) + expect(screen.getByText('child-s')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Collapse' })) + expect(screen.queryByText('child-s')).toBeNull() + }) + + it('auto-expands the selected session group and starts a session from the group +', () => { + const startSession = vi.fn() + mount({ + useSessions: hook(sessionState([summary('alpha-s', 1)], { current: sid('alpha-s') })), + useWorkspaces: hook(workspaceState([workspace('alpha', ['alpha-s'])])), + startSession, + }) + // The current-group effect expanded the owning group without a click. + expect(screen.getByText('alpha-s')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'New session in alpha' })) + expect(startSession).toHaveBeenCalledWith(wid('alpha')) + }) + + it('auto-expands the Ungrouped bucket for a loose current session; its header has no menu and its + is inert', () => { + const startSession = vi.fn() + mount({ + useSessions: hook(sessionState([summary('loose', 1)], { current: sid('loose') })), + useWorkspaces: hook(workspaceState([workspace('alpha', [])])), + startSession, + }) + // The loose session's group is UNGROUPED_KEY: expanded by the effect. + expect(screen.getByText('loose')).toBeTruthy() + expect(screen.queryByRole('button', { name: 'Workspace actions for Ungrouped' })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'New session in Ungrouped' })) + expect(startSession).not.toHaveBeenCalled() + }) + + it('keeps an already-expanded group when the selection moves within it', () => { + const first = sessionState([summary('a', 2), summary('b', 1)], { current: sid('a') }) + const b = mount({ + useSessions: hook(first), + useWorkspaces: hook(workspaceState([workspace('alpha', ['a', 'b'])])), + }) + expect(screen.getByText('a')).toBeTruthy() + // Selection hop inside the same group: the effect re-runs and leaves the + // expansion list unchanged (no duplicate key, group still open). + rerender(b, { useSessions: hook({ ...first, current: sid('b') }) }) + expect(screen.getByText('b')).toBeTruthy() + fireEvent.click(screen.getByText('alpha')) + expect(screen.queryByText('b')).toBeNull() + }) + + it('renders the intent placeholder in both modes', () => { + const intent = { sessionId: sid('intent'), target: { kind: 'workspace' as const, workspaceId: wid('alpha') }, prompt: '', phase: 'connecting' as const } + const sessions = sessionState([], { intent, current: sid('intent') }) + const b = mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', [])])), + }) + // Grouped: the current-group effect expands the target group. + expect(screen.getByText('New session')).toBeTruthy() + b.store.actions.setGroupBy('flat') + rerender(b, {}) + expect(screen.getByText('New session')).toBeTruthy() + }) + + it('searches across groups, clears via the clear button, and shows the empty states', () => { + const sessions = sessionState([ + summary('needle-row', 2, { displayTitle: 'Needle row' }), + summary('other-row', 1, { displayTitle: 'Other row' }), + ]) + mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['needle-row', 'other-row'])])), + }) + const input = screen.getByPlaceholderText('Search name, keywords...') + fireEvent.change(input, { target: { value: 'needle' } }) + // Search forces matches visible without expansion state. + expect(screen.getByText('Needle row')).toBeTruthy() + expect(screen.queryByText('Other row')).toBeNull() + fireEvent.change(input, { target: { value: 'zzz' } }) + expect(screen.getByText('No matches')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Clear search' })) + expect(input.value).toBe('') + // Clicking the field row focuses the input (wide mode). + fireEvent.click(input.parentElement as HTMLElement) + expect(document.activeElement).toBe(input) + }) + + it('shows the no-sessions empty state in both modes', () => { + const b = mount() + expect(screen.getByText('No sessions yet')).toBeTruthy() + b.store.actions.setGroupBy('flat') + rerender(b, {}) + expect(screen.getByText('No sessions yet')).toBeTruthy() + // Flat search misses show No matches. + fireEvent.change(screen.getByPlaceholderText('Search name, keywords...'), { target: { value: 'x' } }) + expect(screen.getByText('No matches')).toBeTruthy() + }) + + it('rail state renders icon controls that request expansion', () => { + vi.useFakeTimers() + try { + const expandSidebar = vi.fn() + const b = mount({ wide: false, expandSidebar }) + // No wide chrome in rail state. + expect(screen.queryByText('Workspaces')).toBeNull() + expect(screen.queryByPlaceholderText('Search name, keywords...')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) + expect(expandSidebar).toHaveBeenCalledTimes(1) + // The wide flip mounts the input and focuses it after the slide. + rerender(b, { wide: true }) + const input = screen.getByPlaceholderText('Search name, keywords...') + act(() => { vi.advanceTimersByTime(300) }) + expect(document.activeElement).toBe(input) + // Wide search button is decorative (tabIndex -1, no expand call). + fireEvent.click(screen.getByRole('button', { name: 'Search sessions' })) + expect(expandSidebar).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) + + it('rail create-workspace expands the shell and opens the picker; wide toggles in place', () => { + const expandSidebar = vi.fn() + const b = mount({ wide: false, expandSidebar, useWorkspaces: hook(workspaceState([workspace('alpha', [])])) }) + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + expect(expandSidebar).toHaveBeenCalledTimes(1) + rerender(b, { wide: true }) + // The picker menu is open (anchored on the +); picking starts a session. + fireEvent.click(screen.getByRole('menuitem', { name: 'alpha' })) + expect(b.props.startSession).toHaveBeenCalledWith(wid('alpha')) + expect(screen.queryByRole('menu')).toBeNull() + // Wide toggle: open and close without expand requests. + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + expect(screen.getByRole('menu')).toBeTruthy() + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + expect(screen.queryByRole('menu')).toBeNull() + expect(expandSidebar).toHaveBeenCalledTimes(1) + + // Escape closes the picker through its own onClose. + fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.queryByRole('menu')).toBeNull() + }) + + it('drag reorder reports the anchor to insertSessionBefore and skips no-op drops', () => { + const insertSessionBefore = vi.fn(async () => {}) + const sessions = sessionState([summary('one', 3), summary('two', 2), summary('three', 1)]) + mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two', 'three'])])), + insertSessionBefore, + }) + fireEvent.click(screen.getByText('alpha')) + const rows = screen.getAllByRole('treeitem').slice(1) // drop the group header + const [one, , three] = rows as [HTMLElement, HTMLElement, HTMLElement] + three.getBoundingClientRect = () => ({ + top: 200, bottom: 234, left: 0, right: 200, width: 200, height: 34, x: 0, y: 200, toJSON: () => ({}), + } as DOMRect) + const dataTransfer = { effectAllowed: '', dropEffect: '' } + fireEvent.dragStart(one, { dataTransfer }) + // Drop on the top half of "three": insert one before three. + fireDrag(three, 'dragOver', 205) + fireDrag(three, 'drop', 205) + expect(insertSessionBefore).toHaveBeenCalledWith(wid('alpha'), sid('one'), sid('three')) + + // Dropping right back onto its own position is a no-op — top half + // (anchor = itself) and bottom half (anchor = the next root) alike. + fireEvent.dragStart(one, { dataTransfer }) + one.getBoundingClientRect = () => ({ + top: 100, bottom: 134, left: 0, right: 200, width: 200, height: 34, x: 0, y: 100, toJSON: () => ({}), + } as DOMRect) + fireDrag(one, 'dragOver', 105) + fireDrag(one, 'drop', 105) + expect(insertSessionBefore).toHaveBeenCalledTimes(1) + fireEvent.dragStart(one, { dataTransfer }) + fireDrag(one, 'drop', 130) + expect(insertSessionBefore).toHaveBeenCalledTimes(1) + }) + + it('still sends the reorder when the dragged row left the group mid-drag', () => { + const insertSessionBefore = vi.fn(async () => {}) + const sessions = sessionState([summary('one', 2), summary('two', 1)]) + const b = mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two'])])), + insertSessionBefore, + }) + fireEvent.click(screen.getByText('alpha')) + const one = screen.getByText('one').closest('[role="treeitem"]') as HTMLElement + fireEvent.dragStart(one, { dataTransfer: { effectAllowed: '', dropEffect: '' } }) + // The host dropped "one" from the workspace account while the drag is in + // flight: the source index is gone but the drop still resolves its anchor. + rerender(b, { useWorkspaces: hook(workspaceState([workspace('alpha', ['two'])])) }) + const two = screen.getByText('two').closest('[role="treeitem"]') as HTMLElement + two.getBoundingClientRect = () => ({ + top: 150, bottom: 184, left: 0, right: 200, width: 200, height: 34, x: 0, y: 150, toJSON: () => ({}), + } as DOMRect) + fireDrag(two, 'drop', 155) + expect(insertSessionBefore).toHaveBeenCalledWith(wid('alpha'), sid('one'), sid('two')) + }) + + it('drag end without a drop clears markers; bottom-half drop appends past the last row', () => { + const insertSessionBefore = vi.fn(async () => {}) + const sessions = sessionState([summary('one', 2), summary('two', 1)]) + mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two'])])), + insertSessionBefore, + }) + fireEvent.click(screen.getByText('alpha')) + const [one, two] = screen.getAllByRole('treeitem').slice(1) as [HTMLElement, HTMLElement] + two.getBoundingClientRect = () => ({ + top: 150, bottom: 184, left: 0, right: 200, width: 200, height: 34, x: 0, y: 150, toJSON: () => ({}), + } as DOMRect) + const dataTransfer = { effectAllowed: '', dropEffect: '' } + fireEvent.dragStart(one, { dataTransfer }) + fireEvent.dragEnd(one) + // The drag ended: rows no longer accept drops. + fireDrag(two, 'drop', 180) + expect(insertSessionBefore).not.toHaveBeenCalled() + + // Bottom half of the last row: append (anchor omitted). + fireEvent.dragStart(one, { dataTransfer }) + fireDrag(two, 'dragOver', 180) + fireDrag(two, 'drop', 180) + expect(insertSessionBefore).toHaveBeenCalledWith(wid('alpha'), sid('one'), undefined) + }) + + it('logs and keeps the order when the reorder call rejects', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + try { + const insertSessionBefore = vi.fn(async () => { throw new Error('stale anchor') }) + const sessions = sessionState([summary('one', 2), summary('two', 1)]) + mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['one', 'two'])])), + insertSessionBefore, + }) + fireEvent.click(screen.getByText('alpha')) + const [one, two] = screen.getAllByRole('treeitem').slice(1) as [HTMLElement, HTMLElement] + two.getBoundingClientRect = () => ({ + top: 150, bottom: 184, left: 0, right: 200, width: 200, height: 34, x: 0, y: 150, toJSON: () => ({}), + } as DOMRect) + const dataTransfer = { effectAllowed: '', dropEffect: '' } + fireEvent.dragStart(one, { dataTransfer }) + fireDrag(two, 'drop', 180) + await waitFor(() => { expect(warn).toHaveBeenCalledWith('session reorder rejected:', expect.any(Error)) }) + } finally { + warn.mockRestore() + } + }) + + it('renames a workspace through the row menu dialog', async () => { + let resolveRename!: () => void + const renameWorkspace = vi.fn(() => new Promise((resolve) => { resolveRename = resolve })) + mount({ + useWorkspaces: hook(workspaceState([workspace('alpha', [], 'Alpha'), workspace('beta', [], 'Beta')])), + renameWorkspace, + }) + fireEvent.click(screen.getByRole('button', { name: 'Workspace actions for Alpha' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' })) + const input = screen.getByLabelText('Workspace name') + expect(input.value).toBe('Alpha') + // Unchanged and blank names stay blocked. + expect((screen.getByRole('button', { name: 'Rename' }) as HTMLButtonElement).disabled).toBe(true) + fireEvent.change(input, { target: { value: ' ' } }) + expect((screen.getByRole('button', { name: 'Rename' }) as HTMLButtonElement).disabled).toBe(true) + // A duplicate of another workspace's title shows the inline conflict. + fireEvent.change(input, { target: { value: ' Beta ' } }) + expect(screen.getByRole('alert').textContent).toBe('A workspace named “Beta” already exists.') + expect((screen.getByRole('button', { name: 'Rename' }) as HTMLButtonElement).disabled).toBe(true) + fireEvent.change(input, { target: { value: 'Gamma' } }) + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + expect(renameWorkspace).toHaveBeenCalledWith(wid('alpha'), 'Gamma') + // While renaming: input disabled, close blocked, Enter ignored. + expect(input.disabled).toBe(true) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(screen.getByRole('dialog')).toBeTruthy() + await act(async () => { resolveRename() }) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('rename via Enter, failure surfaces the error, Cancel closes', async () => { + const renameWorkspace = vi.fn(async () => { throw new Error('rename conflict') }) + mount({ + useWorkspaces: hook(workspaceState([workspace('alpha', [], 'Alpha')])), + renameWorkspace, + }) + fireEvent.click(screen.getByRole('button', { name: 'Workspace actions for Alpha' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' })) + const input = screen.getByLabelText('Workspace name') + // Enter with a blocked draft (unchanged) does nothing. + fireEvent.keyDown(input, { key: 'Enter' }) + expect(renameWorkspace).not.toHaveBeenCalled() + fireEvent.change(input, { target: { value: 'Renamed' } }) + fireEvent.keyDown(input, { key: 'a' }) + fireEvent.keyDown(input, { key: 'Enter' }) + expect(renameWorkspace).toHaveBeenCalledWith(wid('alpha'), 'Renamed') + await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('rename conflict') }) + // The dialog stays for retry; typing clears the error; Cancel closes. + fireEvent.change(input, { target: { value: 'Renamed2' } }) + expect(screen.queryByRole('alert')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('reports non-Error rename failures as text', async () => { + const renameWorkspace = vi.fn(async () => { throw 'denied' }) + mount({ + useWorkspaces: hook(workspaceState([workspace('alpha', [], 'Alpha')])), + renameWorkspace, + }) + fireEvent.click(screen.getByRole('button', { name: 'Workspace actions for Alpha' })) + fireEvent.click(screen.getByRole('menuitem', { name: 'Rename' })) + fireEvent.change(screen.getByLabelText('Workspace name'), { target: { value: 'Other' } }) + fireEvent.click(screen.getByRole('button', { name: 'Rename' })) + await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('denied') }) + }) + + it('search hides drag affordances (rows are not draggable during search)', () => { + const sessions = sessionState([summary('needle-a', 2, { displayTitle: 'Needle A' })]) + mount({ + useSessions: hook(sessions), + useWorkspaces: hook(workspaceState([workspace('alpha', ['needle-a'])])), + }) + fireEvent.change(screen.getByPlaceholderText('Search name, keywords...'), { target: { value: 'needle' } }) + const row = screen.getByText('Needle A').closest('[role="treeitem"]') as HTMLElement + expect(row.getAttribute('draggable')).toBe('false') + }) +}) diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index 25b095b99f..a81aadd94b 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -68,6 +68,19 @@ describe('unary round trip', () => { expect(response.result).toEqual({ ok: true, value: { items: [{ sessionId: 's1', updatedAt: 7, running: false }] } }) }) + it('routes workspace rename and insertSessionBefore through the wire', async () => { + const api = scriptedApi() + const c = client(api) + const renamed = await c.workspace.rename({ workspaceId: 'w1' as never, title: 'next' }) + expect(renamed.result.ok).toBe(true) + const blankTitle = await c.workspace.rename({ workspaceId: 'w1' as never, title: ' ' }) + expect(blankTitle.result).toMatchObject({ ok: false, error: { code: 'bad-request' } }) + const anchored = await c.workspace.insertSessionBefore({ workspaceId: 'w1' as never, sessionId: sid('s1'), beforeSessionId: sid('s2') }) + expect(anchored.result.ok).toBe(true) + const appended = await c.workspace.insertSessionBefore({ workspaceId: 'w1' as never, sessionId: sid('s1') }) + expect(appended.result.ok).toBe(true) + }) + it('passes business errors through as 200 + err result, not a throw', async () => { const api = scriptedApi({ sessions: { diff --git a/packages/host/apiproxy/tests/rpc-schemas.spec.ts b/packages/host/apiproxy/tests/rpc-schemas.spec.ts index d0f2ddd128..ebb7931e6e 100644 --- a/packages/host/apiproxy/tests/rpc-schemas.spec.ts +++ b/packages/host/apiproxy/tests/rpc-schemas.spec.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { RpcId } from '../src/api/rpc.ts' +import { RpcId, transportError } from '../src/api/rpc.ts' import { clientRequestSchema, clientResponseSchema, rpcErrorSchema, rpcIdSchema, rpcMessageSchema, rpcReceiptSchema, rpcResultSchema, serverRequestSchema, serverResponseSchema, @@ -13,8 +13,10 @@ import { } from '../src/api/sessions.schema.ts' import { hostDescribeRequestSchema, hostDescribeValueSchema } from '../src/api/host.schema.ts' import { - workspaceCreateRequestSchema, workspaceCreateValueSchema, workspaceIdSchema, workspaceListRequestSchema, - workspaceListValueSchema, workspaceViewSchema, + workspaceCreateRequestSchema, workspaceCreateValueSchema, workspaceIdSchema, + workspaceInsertSessionBeforeRequestSchema, workspaceInsertSessionBeforeValueSchema, + workspaceListRequestSchema, workspaceListValueSchema, + workspaceRenameRequestSchema, workspaceRenameValueSchema, workspaceViewSchema, } from '../src/api/workspace.schema.ts' import { hostFrameSchema, muxFrameSchema, askUserQuestionItemSchema } from '../src/api/events.schema.ts' import { approvalRequestIdSchema, approvalResponsePayloadSchema } from '../src/api/approvals.schema.ts' @@ -30,6 +32,13 @@ describe('RpcId', () => { }) }) +describe('transportError', () => { + it('folds Error and non-Error throws into the internal error branch', () => { + expect(transportError(new Error('wire down'))).toEqual({ ok: false, error: { code: 'internal', message: 'wire down', details: {} } }) + expect(transportError('raw')).toMatchObject({ ok: false, error: { code: 'internal', message: 'raw' } }) + }) +}) + describe('rpcErrorSchema', () => { it('accepts every code branch with its required details', () => { expect(rpcErrorSchema.parse({ code: 'bad-request', message: 'm', details: { issues: [] } }).code).toBe('bad-request') @@ -40,6 +49,7 @@ describe('rpcErrorSchema', () => { expect(rpcErrorSchema.parse({ code: 'workspace-not-found', message: 'm', details: { workspaceId: 'w' } }).code).toBe('workspace-not-found') expect(rpcErrorSchema.parse({ code: 'workspace-invalid-path', message: 'm', details: { path: '/x' } }).code).toBe('workspace-invalid-path') expect(rpcErrorSchema.parse({ code: 'workspace-name-conflict', message: 'm', details: { name: 'x' } }).code).toBe('workspace-name-conflict') + expect(rpcErrorSchema.parse({ code: 'workspace-move-invalid', message: 'm', details: { workspaceId: 'w', sessionId: 's' } }).code).toBe('workspace-move-invalid') expect(rpcErrorSchema.parse({ code: 'agent-busy', message: 'm', details: { reason: 'r' } }).code).toBe('agent-busy') expect(rpcErrorSchema.parse({ code: 'internal', message: 'm', details: {} }).code).toBe('internal') }) @@ -154,6 +164,19 @@ describe('workspace domain schemas', () => { expect(workspaceCreateValueSchema.parse({ workspace: view, created: false }).created).toBe(false) }) + it('rename requires a non-blank title (both refine arms)', () => { + expect(workspaceRenameRequestSchema.parse({ workspaceId: 'w1', title: 'new' }).title).toBe('new') + expect(() => workspaceRenameRequestSchema.parse({ workspaceId: 'w1', title: ' ' })).toThrow(/non-blank/) + expect(workspaceRenameValueSchema.parse({ workspace: view }).workspace.workspaceId).toBe('w1') + }) + + it('insertSessionBefore accepts an anchored and an anchorless move', () => { + expect(workspaceInsertSessionBeforeRequestSchema.parse({ workspaceId: 'w1', sessionId: 's1', beforeSessionId: 's2' }).beforeSessionId).toBe('s2') + expect(workspaceInsertSessionBeforeRequestSchema.parse({ workspaceId: 'w1', sessionId: 's1' }).beforeSessionId).toBeUndefined() + expect(() => workspaceInsertSessionBeforeRequestSchema.parse({ workspaceId: 'w1' })).toThrow() + expect(workspaceInsertSessionBeforeValueSchema.parse({ workspace: view }).workspace.workspaceId).toBe('w1') + }) + }) describe('events frame schemas', () => { diff --git a/packages/workspace/workspace/tests/workspace.spec.ts b/packages/workspace/workspace/tests/workspace.spec.ts index bdefc2ec82..8ce70cc7d5 100644 --- a/packages/workspace/workspace/tests/workspace.spec.ts +++ b/packages/workspace/workspace/tests/workspace.spec.ts @@ -10,7 +10,7 @@ import type { DomainChanged } from '@deepseek-ai/dsh-storage-domain' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import type { SessionHeader } from '@deepseek-ai/dsh-session' import { MemoryMediaPool, MemoryStorageBackend } from '../../../storage/storage-domain/tests/helpers/memory-backend.ts' -import WorkspaceRegistry, { WorkspaceId, WorkspaceNameConflictError } from '../src/index.ts' +import WorkspaceRegistry, { WorkspaceId, WorkspaceMoveInvalidError, WorkspaceNameConflictError } from '../src/index.ts' import type { WorkspaceDomainState, WorkspaceRecord } from '../src/index.ts' const DOMAIN_VERSION = 2 @@ -449,6 +449,56 @@ describe('Workspace session ordering', () => { expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s2', 's1']) }) + it('moves one id before an anchor or to the end, durably', async () => { + const dir = await makeDir('insert-before') + const result = await harness() + result.setSessions([header('s1', dir, 1), header('s2', dir, 2), header('s3', dir, 3)]) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('s1')) + await workspace.attachSession(SessionId('s2')) + await workspace.attachSession(SessionId('s3')) + expect(workspace.sessionIds).toEqual(['s3', 's2', 's1']) + + await workspace.insertSessionBefore(SessionId('s1'), SessionId('s2')) + expect(workspace.sessionIds).toEqual(['s3', 's1', 's2']) + await workspace.insertSessionBefore(SessionId('s3')) + expect(workspace.sessionIds).toEqual(['s1', 's2', 's3']) + expect(storedRecord(result.pool, workspace.id).sessionIds).toEqual(['s1', 's2', 's3']) + }) + + it('treats self-anchored and already-in-place moves as no-ops without writing', async () => { + const dir = await makeDir('insert-noop') + const result = await harness() + result.setSessions([header('s1', dir, 1), header('s2', dir, 2)]) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('s1')) + await workspace.attachSession(SessionId('s2')) + const written = result.changes.length + + await workspace.insertSessionBefore(SessionId('s1'), SessionId('s1')) + await workspace.insertSessionBefore(SessionId('s2'), SessionId('s1')) + await workspace.insertSessionBefore(SessionId('s1')) + await workspace.detachSession(SessionId('absent')) + expect(result.changes).toHaveLength(written) + expect(workspace.sessionIds).toEqual(['s2', 's1']) + }) + + it('rejects moves naming an unaccounted session or anchor', async () => { + const dir = await makeDir('insert-invalid') + const result = await harness() + result.setSessions([header('s1', dir, 1)]) + const workspace = await result.registry.create(dir) + await workspace.attachSession(SessionId('s1')) + const written = result.changes.length + + await expect(workspace.insertSessionBefore(SessionId('ghost'))) + .rejects.toBeInstanceOf(WorkspaceMoveInvalidError) + await expect(workspace.insertSessionBefore(SessionId('s1'), SessionId('ghost'))) + .rejects.toThrow(/anchor session is not accounted/) + expect(result.changes).toHaveLength(written) + expect(workspace.sessionIds).toEqual(['s1']) + }) + it('validates a lazy live session without requiring it in persistence.list()', async () => { const dir = await makeDir('live') const result = await harness({ sessions: [], liveSessions: [header('live', dir, 1)] }) From d147673dfdcdf393ccf6a62ed0549a291831b18d Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 01:58:53 +0800 Subject: [PATCH 088/113] refactor(apiproxy): share the workspace-not-found response The rename/insertSessionBefore lookups tripped the cross-file clone gate; one helper owns the error row now. --- packages/host/apiproxy/src/api-proxy.ts | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index d50dd000e1..c7d3cb7ef9 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -299,6 +299,15 @@ class SessionCwdConflict extends Error { /** Host failed before the registry could adopt a name-created directory. */ class WorkspaceDirectoryCreationError extends Error {} +/** Shared workspace-not-found error response of the workspace.* mutation rows. */ +function workspaceNotFound(request: RpcRequest, workspaceId: string): RpcResponse { + return err(request, { + code: 'workspace-not-found', + message: `workspace "${workspaceId}" not found`, + details: { workspaceId }, + }) +} + /** Wire projection of one workspace entity (the workspace.* value row). */ function workspaceView(workspace: Workspace): WorkspaceView { return { @@ -684,13 +693,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro async rename(request) { const { payload } = request const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId)) - if (workspace === undefined) { - return err(request, { - code: 'workspace-not-found', - message: `workspace "${payload.workspaceId}" not found`, - details: { workspaceId: payload.workspaceId }, - }) - } + if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId) const title = payload.title.trim() // Uniqueness AND the same-title no-op both ride the create chain so // they observe the state left by earlier queued renames — checked @@ -722,13 +725,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro async insertSessionBefore(request) { const { payload } = request const workspace = ctx.workspace.get(brandWorkspaceId(payload.workspaceId)) - if (workspace === undefined) { - return err(request, { - code: 'workspace-not-found', - message: `workspace "${payload.workspaceId}" not found`, - details: { workspaceId: payload.workspaceId }, - }) - } + if (workspace === undefined) return workspaceNotFound(request, payload.workspaceId) try { await workspace.insertSessionBefore(payload.sessionId, payload.beforeSessionId) } catch (error: unknown) { From 4ae86001a5cdd6f6a03a34909a49f417151d9836 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:03:05 +0800 Subject: [PATCH 089/113] style(web): wrap a long tree.ts doc line --- packages/client/ui-workspace/src/client/tree.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/client/ui-workspace/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts index 39a479f3b3..7de4d14e8d 100644 --- a/packages/client/ui-workspace/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -227,7 +227,8 @@ function buildSearch(g: Group, visible: ReadonlySet): SessionNode[] { * * Normal mode: every group shows; sessions populate under expanded groups, * descending only into expanded sessions. A frontend Session Intent targeting - * a real Workspace marks that group `intentHere` (rendered only while the group is expanded; expansion stays viewer-owned). Search mode (non-blank query, + * a real Workspace marks that group `intentHere` (rendered only while the + * group is expanded; expansion stays viewer-owned). Search mode (non-blank query, * case-insensitive display-title substring): expansion state is ignored — * matched sessions and their ancestor chains are forced visible, groups * without a display-title or label hit are dropped, a label-only hit keeps From 2cfc38fb70c9128c3a80c5a5dd753769cf7ef4fd Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:10:24 +0800 Subject: [PATCH 090/113] docs(agent-notes): clarify superseded ACP rendering --- .../2026-06-20-drop-acp-terminal-meta.i18n.yaml | 4 ++-- .../2026-06-20-drop-acp-terminal-meta.md | 8 ++++---- .../2026-06-20-drop-acp-terminal-meta.zh.md | 8 ++++---- .../2026-06-20-generic-tool-rendering.i18n.yaml | 4 ++-- .../2026-06-20-generic-tool-rendering.md | 12 +++++++----- .../2026-06-20-generic-tool-rendering.zh.md | 12 +++++++----- 6 files changed, 26 insertions(+), 22 deletions(-) diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.i18n.yaml index 8b3e3f7391..b7b5632e38 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.i18n.yaml +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.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 -2026-06-20-drop-acp-terminal-meta.md: d957ba1173af28cb526c92f959a8552f77360a57 -2026-06-20-drop-acp-terminal-meta.zh.md: 3a748c8fdf2ef37d35a14519fee5284af417dd78 +2026-06-20-drop-acp-terminal-meta.md: 84b9028392f967e72f7b5585d013d669735631de +2026-06-20-drop-acp-terminal-meta.zh.md: 6ac7ba46bce20bcf2593ef422057e0562f8a1557 diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md index d957ba1173..84b9028392 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.md @@ -1,14 +1,14 @@ # Agent Note: Drop ACP terminal `_meta` rendering -Status: rejected — Zed is the current target client, and the terminal `_meta` convention is intentional Zed UX with a plain ACP fallback for other clients. +Status: rejected — removing only Zed terminal metadata was rejected while ACP remained an editor bridge; automation-only ACP later removed the whole editor projection. English | [中文](2026-06-20-drop-acp-terminal-meta.zh.md) ## Problem -The former ACP editor bridge implemented a Zed-specific terminal-card convention through `_meta.terminal_info`, `_meta.terminal_output`, and `_meta.terminal_exit`. The current [render-intent decision](../../implemented/architecture/2026-07-02-tool-render-intent-union.md) preserves the underlying rule that bash execution belongs in the harness and terminal cards are display-only. The later [automation-only ACP decision](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md) removes the `_meta` projection, bridge state, capability negotiation, terminal ids, special update mapping, text fallback tests, and exit-pill parsing from ACP. +The former ACP editor bridge implemented a Zed-specific terminal-card convention through `_meta.terminal_info`, `_meta.terminal_output`, and `_meta.terminal_exit`. The current [render-intent decision](../../implemented/architecture/2026-07-02-tool-render-intent-union.md) preserves the underlying rule that bash execution belongs in the harness and terminal cards are display-only. The later [automation-only ACP decision](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md) removes the `_meta` projection, bridge state, capability negotiation, terminal ids, special update mapping, text fallback tests, and exit-pill parsing from ACP. TUI and the Web host/client runtime retain the tagged presentation contract, while ACP no longer renders editor cards. -The fallback path already exists: render the tool call and completed output as normal ACP content blocks. Non-Zed clients rely on that path anyway, but the Zed terminal card is a current target-client feature rather than speculative decoration. +At proposal time, the fallback path already existed: render the tool call and completed output as normal ACP content blocks. Non-Zed clients relied on that path, but the Zed terminal card was a target-client feature rather than speculative decoration. ## Proposal @@ -26,6 +26,6 @@ This proposal is narrower than [collapsing tool-owned UI presentation](2026-06-2 ## What we give up -Zed users lose the dedicated terminal card: no cwd header, terminal display, or exit pill. They still see the command and output as plain content. That is a reasonable simplification while the ACP bridge is still unreleased and the `_meta` keys are a convention rather than a standard. +Under this proposal, Zed users would lose the dedicated terminal card: no cwd header, terminal display, or exit pill. They would still see the command and output as plain content. That was a reasonable simplification to consider while the ACP bridge was unreleased and the `_meta` keys were a convention rather than a standard. diff --git a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.zh.md b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.zh.md index 3a748c8fdf..6ac7ba46bc 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.zh.md +++ b/.agents/notes/rejected/simplification/2026-06-20-drop-acp-terminal-meta.zh.md @@ -1,14 +1,14 @@ # Agent Note: 移除 ACP(Agent Client Protocol)终端 `_meta` 渲染 -Status: rejected — Zed 是当前目标客户端,terminal `_meta` 约定是有意设计的 Zed UX,同时为其他客户端保留普通 ACP 回退。 +Status: rejected — 在 ACP 仍是编辑器桥接层时,仅移除 Zed 终端元数据的方案被否决;后续仅面向自动化的 ACP 则移除了整个编辑器投影。 [English](2026-06-20-drop-acp-terminal-meta.md) | 中文 ## 问题 -原 ACP 编辑器桥接层通过 `_meta.terminal_info`、`_meta.terminal_output` 和 `_meta.terminal_exit` 实现了一套 Zed 特有的终端卡片约定。当前的 [render-intent 决策](../../implemented/architecture/2026-07-02-tool-render-intent-union.md)保留了底层规则:bash 执行属于 harness,terminal 卡片只用于展示。后续的[仅面向自动化 ACP 决策](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md)从 ACP 中移除了 `_meta` 投影、桥接状态、能力协商、终端 id、特殊 update 映射、文本回退测试和 exit-pill 解析。 +原 ACP 编辑器桥接层通过 `_meta.terminal_info`、`_meta.terminal_output` 和 `_meta.terminal_exit` 实现了一套 Zed 特有的终端卡片约定。当前的 [render-intent 决策](../../implemented/architecture/2026-07-02-tool-render-intent-union.md)保留了底层规则:bash 执行属于 harness,terminal 卡片只用于展示。后续的[仅面向自动化 ACP 决策](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md)从 ACP 中移除了 `_meta` 投影、桥接状态、能力协商、终端 id、特殊 update 映射、文本回退测试和 exit-pill 解析。TUI 与 Web 宿主/客户端运行时保留带标签的展示契约,而 ACP 不再渲染编辑器卡片。 -回退路径已经存在:将工具调用和完成输出渲染为普通 ACP 内容块。非 Zed 客户端本来就依赖这条路径,但 Zed 终端卡片是当前目标客户端的功能特性,而非推测性装饰。 +本提案提出时,回退路径已经存在:将工具调用和完成输出渲染为普通 ACP 内容块。当时,非 Zed 客户端依赖这条路径,但 Zed 终端卡片是目标客户端的功能特性,而非推测性装饰。 ## 提案 @@ -26,6 +26,6 @@ Status: rejected — Zed 是当前目标客户端,terminal `_meta` 约定是 ## 放弃的内容 -Zed 用户将失去专用终端卡片:没有 cwd 头部、终端展示或 exit pill。他们仍能以纯内容形式看到命令和输出。在 ACP 桥接层尚未发布、`_meta` 键只是约定而非标准的阶段,这是合理的简化。 +如果采用本提案,Zed 用户会失去专用终端卡片:没有 cwd 头部、终端展示或 exit pill。但他们仍会以纯内容形式看到命令和输出。当时 ACP 桥接层尚未发布,且 `_meta` 键只是约定而非标准;在这种情况下,考虑这项简化是合理的。 diff --git a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.i18n.yaml b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.i18n.yaml index da93063670..14c7033185 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.i18n.yaml +++ b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.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 -2026-06-20-generic-tool-rendering.md: 6fc610546da04e7d1e16fc17ada87483a142aa3c -2026-06-20-generic-tool-rendering.zh.md: 11386b87d845129950a8473eb1cf4ea6ce697ac8 +2026-06-20-generic-tool-rendering.md: a9ceb7a0e016b57295e3226e98a7fce51e49c21f +2026-06-20-generic-tool-rendering.zh.md: 553c1caa23ed34eea5f113372d12a7381dc2488a diff --git a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md index 6fc610546d..a9ceb7a0e0 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md +++ b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.md @@ -1,14 +1,16 @@ # Agent Note: Collapse tool-owned UI presentation -Status: rejected — tool-owned presentation should wait for more real tools before being generalized or deleted. Bash and ACP currently need the existing richer presentation path. +Status: rejected — TUI and the Web host/client runtime consume the tagged render-intent union, so tool-owned presentation remains current even though ACP no longer projects it. English | [中文](2026-06-20-generic-tool-rendering.zh.md) ## Problem -Tools can define `presentCall()` and `presentResult()` callbacks that return `ToolCallPresentation`, `ToolResultPresentation`, and optional `ToolTerminal` fields. The code itself flags the design as muddy: title, kind, raw input, content, terminal cwd, terminal output, exit code, and signal grew incrementally into a bag of optional fields. ACP then maintains pending call state to pair a result with the original args, creates replay-only presenters on `session/load`, and maps terminal subfields into Zed-specific `_meta`. `dsh-tool-bash` even parses exit status back out of rendered text because the pure replay-safe presenter no longer has the structured `BashRunResult`. +The optional-field bag and ACP editor mapping below were the proposal-time context for this rejection. The current contracts live in [the tagged render-intent union](../../implemented/architecture/2026-07-02-tool-render-intent-union.md) and [automation-only ACP](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md). -The real first-party use is bash presentation for ACP. That is too little evidence to freeze a cross-package UI presentation API. +Tools could define `presentCall()` and `presentResult()` callbacks that returned `ToolCallPresentation`, `ToolResultPresentation`, and optional `ToolTerminal` fields. The code itself flagged the design as muddy: title, kind, raw input, content, terminal cwd, terminal output, exit code, and signal had grown incrementally into a bag of optional fields. ACP then maintained pending call state to pair a result with the original args, created replay-only presenters on `session/load`, and mapped terminal subfields into Zed-specific `_meta`. `dsh-tool-bash` even parsed exit status back out of rendered text because the pure replay-safe presenter no longer had the structured `BashRunResult`. + +The real first-party use was bash presentation for ACP. That was too little evidence to freeze a cross-package UI presentation API. ## Proposal @@ -28,8 +30,8 @@ As a smaller alternative, replace the current optional-field bag with one explic ## What we give up -Bash loses its custom terminal-looking card and model-written description placement. The fallback remains reasonable: the command appears as tool input, and the output appears as text. Rich rendering should be designed when the product has enough UI/tool variety to justify a stable presentation contract. +Under this proposal, Bash would lose its custom terminal-looking card and model-written description placement. The fallback would remain reasonable: the command would appear as tool input, and the output as text. Rich rendering would be designed when the product had enough UI/tool variety to justify a stable presentation contract. ## Related -This is the broad version of [dropping ACP terminal metadata](2026-06-20-drop-acp-terminal-meta.md). If this Agent Note is accepted, that narrower Agent Note becomes unnecessary. +The later [tagged render-intent union](../../implemented/architecture/2026-07-02-tool-render-intent-union.md) implements the smaller alternative once multiple producer and consumer families provide enough evidence for the vocabulary. [Automation-only ACP](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md) removes ACP's editor projection without removing tool-owned presentation from TUI or the Web host/client runtime. diff --git a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.zh.md b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.zh.md index 11386b87d8..553c1caa23 100644 --- a/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.zh.md +++ b/.agents/notes/rejected/simplification/2026-06-20-generic-tool-rendering.zh.md @@ -1,14 +1,16 @@ # Agent Note: 收拢工具自有的 UI 展示逻辑 -Status: rejected — 工具拥有的呈现机制应等到出现更多真实工具后再进行泛化或删除。Bash 与 ACP(Agent Client Protocol)目前仍需要现有的丰富呈现路径。 +Status: rejected — 尽管 ACP(Agent Client Protocol)已不再投影这套契约,TUI 与 Web 宿主/客户端运行时仍消费带标签 render-intent 联合类型,因此工具自有的展示仍然有效。 [English](2026-06-20-generic-tool-rendering.md) | 中文 ## 问题 -工具可以定义 `presentCall()` 和 `presentResult()` 回调,返回 `ToolCallPresentation`、`ToolResultPresentation` 以及可选的 `ToolTerminal` 字段。代码本身就标记了这个设计的混乱:title、kind、raw input、content、terminal cwd、terminal output、exit code 和 signal 逐步增长为一堆可选字段。ACP 随后维护 pending call 状态以将 result 与原始 args 配对,在 `session/load` 时创建仅用于回放的 presenter,并将 terminal 子字段映射为 Zed 特有的 `_meta`。`dsh-tool-bash` 甚至从渲染后的文本中反向解析退出状态,因为纯回放安全的 presenter 已经拿不到结构化的 `BashRunResult`。 +下文所述的可选字段集合与 ACP 的编辑器映射,是本提案遭否决时的背景。当前契约分别由[带标签 render-intent 联合类型](../../implemented/architecture/2026-07-02-tool-render-intent-union.md)与[ACP 作为仅面向自动化的协议](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md)承载。 -真正的第一方用途是为 ACP 提供 bash 展示。这不足以作为冻结一个跨包(package)UI 展示 API 的依据。 +当时,工具可以定义 `presentCall()` 和 `presentResult()` 回调,返回 `ToolCallPresentation`、`ToolResultPresentation` 以及可选的 `ToolTerminal` 字段。代码本身就标记了这个设计的混乱:title、kind、raw input、content、terminal cwd、terminal output、exit code 和 signal 已经逐步增长为一堆可选字段。ACP 随后维护 pending call 状态以将 result 与原始 args 配对,在 `session/load` 时创建仅用于回放的 presenter,并将 terminal 子字段映射为 Zed 特有的 `_meta`。`dsh-tool-bash` 甚至从渲染后的文本中反向解析退出状态,因为纯回放安全的 presenter 已经拿不到结构化的 `BashRunResult`。 + +当时,真正的第一方用途是为 ACP 提供 bash 展示。这点证据不足以作为冻结一个跨包(package)UI 展示 API 的依据。 ## 提案 @@ -28,8 +30,8 @@ Status: rejected — 工具拥有的呈现机制应等到出现更多真实工 ## 放弃了什么 -Bash 失去其自定义的终端风格卡片和模型生成描述的放置位置。回退方案仍然合理:命令作为工具输入展示,输出作为文本展示。富展示应当在产品拥有足够的 UI/工具多样性、足以支撑一份稳定的展示契约时再行设计。 +如果采用本提案,Bash 会失去其自定义的终端风格卡片和模型生成描述的放置位置。届时,回退方案仍然合理:命令会作为工具输入展示,输出会作为文本展示。只有当产品拥有足够的 UI/工具多样性、足以支撑一份稳定的展示契约时,才会设计富展示。 ## 相关 -这是[移除 ACP terminal 元数据](2026-06-20-drop-acp-terminal-meta.md)的宽泛版本。如果本 Agent Note(agent 决策记录)被接受,那个更窄的 Agent Note 就不再必要。 +后续的[带标签 render-intent 联合类型](../../implemented/architecture/2026-07-02-tool-render-intent-union.md)在多类生产者与消费方为这套词汇提供充分依据后,实现了较小的替代方案。[ACP 作为仅面向自动化的协议](../../implemented/simplification/2026-07-23-acp-automation-only-protocol.md)移除了 ACP 的编辑器投影,但没有从 TUI 或 Web 宿主/客户端运行时中移除工具自有的展示。 From ad419065a0a71a49f801028d66cd0afbdd56df36 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:10:59 +0800 Subject: [PATCH 091/113] test(web): stop pre-clicking the fixture group in the title snapshot The Intent's current-group effect already expands the target workspace; with intent no longer forcing expansion, the header click collapsed it. --- apps/web/tests/session-title.snapshot.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/web/tests/session-title.snapshot.ts b/apps/web/tests/session-title.snapshot.ts index c1616bb724..532c6866da 100644 --- a/apps/web/tests/session-title.snapshot.ts +++ b/apps/web/tests/session-title.snapshot.ts @@ -94,10 +94,10 @@ it('projects initial and revised durable titles through the built nine-plugin fi }) const tree = await screen.findByRole('tree', { name: 'Sessions' }, { timeout: 10_000 }) - const projectCount = await within(tree).findByText('4 sessions') - const projectRow = projectCount.closest('[role="treeitem"]') - if (projectRow === null) throw new Error('fixture project row missing') - fireEvent.click(projectRow) + // The fixture Intent selects the workspace, so the current-group effect + // already expanded it; clicking the header would now collapse (the twist + // stays live since intent stopped forcing expansion). + await within(tree).findByText('4 sessions') const initialLabel = 'Fixture 历史会话' const initialRowLabel = await screen.findByText(initialLabel) From b2d8815a34b584a8704d2285e33ea45b279fc337 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:29:13 +0800 Subject: [PATCH 092/113] test(llm-mock-server): poll for the client-closed outcome The fixed 5ms sleep raced slow CI runners (the server observes the socket close asynchronously); vi.waitFor polls until the outcome lands. --- packages/support/llm-mock-server/tests/server.spec.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/support/llm-mock-server/tests/server.spec.ts b/packages/support/llm-mock-server/tests/server.spec.ts index 1f15ba1a0b..34db57aa82 100644 --- a/packages/support/llm-mock-server/tests/server.spec.ts +++ b/packages/support/llm-mock-server/tests/server.spec.ts @@ -1,5 +1,5 @@ import { request } from 'node:http' -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import type { MockLlmBehavior, MockLlmServer, MockLlmServerEvent } from '../src/index.ts' import { startMockLlmServer } from '../src/index.ts' @@ -179,9 +179,11 @@ describe('mock LLM server wire behaviors', () => { const response = await chat(server, { signal: controller.signal }) controller.abort() await expect(response.text()).rejects.toThrow() - await new Promise((resolve) => { setTimeout(resolve, 5) }) - - expect(server.requests[0]).toMatchObject({ behavior, outcome: 'client_closed' }) + // The server observes the socket close asynchronously; a fixed sleep + // raced slow runners, so poll until the outcome lands. + await vi.waitFor(() => { + expect(server.requests[0]).toMatchObject({ behavior, outcome: 'client_closed' }) + }) expect(events.filter(event => event.type === 'result')).toEqual([ expect.objectContaining({ behavior, outcome: 'client_closed' }), ]) From 30db52fa4bc44f9601207d85f9407bfcd76574d6 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:33:29 +0800 Subject: [PATCH 093/113] docs: translate remaining non-README documentation --- ...-21-bounded-llm-request-recovery.i18n.yaml | 6 + ...2026-06-21-bounded-llm-request-recovery.md | 2 + ...6-06-21-bounded-llm-request-recovery.zh.md | 148 +++++++++++++ ...026-07-05-windows-fs-permissions.i18n.yaml | 6 + .../2026-07-05-windows-fs-permissions.md | 2 + .../2026-07-05-windows-fs-permissions.zh.md | 33 +++ ...05-windows-jsonl-durable-publish.i18n.yaml | 6 + ...026-07-05-windows-jsonl-durable-publish.md | 2 + ...-07-05-windows-jsonl-durable-publish.zh.md | 35 ++++ ...06-tool-result-retention-library.i18n.yaml | 6 + ...026-07-06-tool-result-retention-library.md | 2 + ...-07-06-tool-result-retention-library.zh.md | 157 ++++++++++++++ ...26-07-08-tool-output-spill-files.i18n.yaml | 6 + .../2026-07-08-tool-output-spill-files.md | 2 + .../2026-07-08-tool-output-spill-files.zh.md | 195 +++++++++++++++++ .../2026-06-24-workspace-context.i18n.yaml | 6 + .../feature/2026-06-24-workspace-context.md | 2 + .../2026-06-24-workspace-context.zh.md | 89 ++++++++ .../feature/2026-07-07-plan-mode.i18n.yaml | 6 + .../feature/2026-07-07-plan-mode.md | 2 + .../feature/2026-07-07-plan-mode.zh.md | 196 ++++++++++++++++++ ...-07-08-background-subagent-tasks.i18n.yaml | 6 + .../2026-07-08-background-subagent-tasks.md | 2 + ...2026-07-08-background-subagent-tasks.zh.md | 64 ++++++ ...-bash-backed-grep-glob-discovery.i18n.yaml | 6 + ...6-07-09-bash-backed-grep-glob-discovery.md | 2 + ...7-09-bash-backed-grep-glob-discovery.zh.md | 170 +++++++++++++++ ...ession-identity-and-log-location.i18n.yaml | 6 + ...agent-session-identity-and-log-location.md | 2 + ...nt-session-identity-and-log-location.zh.md | 87 ++++++++ ...-10-parallel-tool-call-execution.i18n.yaml | 6 + ...2026-07-10-parallel-tool-call-execution.md | 2 + ...6-07-10-parallel-tool-call-execution.zh.md | 103 +++++++++ ...2026-07-13-session-query-tracing.i18n.yaml | 6 + .../2026-07-13-session-query-tracing.md | 2 + .../2026-07-13-session-query-tracing.zh.md | 36 ++++ ...13-documentation-site-projection.i18n.yaml | 6 + ...026-07-13-documentation-site-projection.md | 2 + ...-07-13-documentation-site-projection.zh.md | 47 +++++ ...2026-07-06-recallable-compaction.i18n.yaml | 6 + .../2026-07-06-recallable-compaction.md | 2 + .../2026-07-06-recallable-compaction.zh.md | 110 ++++++++++ ...3-human-review-skill-maintenance.i18n.yaml | 6 + ...26-07-13-human-review-skill-maintenance.md | 2 + ...07-13-human-review-skill-maintenance.zh.md | 85 ++++++++ .../maintaining-dsh-code-review.i18n.yaml | 6 + docs/cookbook/maintaining-dsh-code-review.md | 2 + .../maintaining-dsh-code-review.zh.md | 64 ++++++ .../cordis-tutorial/01-first-plugin.i18n.yaml | 6 + docs/cordis-tutorial/01-first-plugin.md | 2 + docs/cordis-tutorial/01-first-plugin.zh.md | 95 +++++++++ .../02-lifecycle-and-effects.i18n.yaml | 6 + .../02-lifecycle-and-effects.md | 2 + .../02-lifecycle-and-effects.zh.md | 98 +++++++++ docs/cordis-tutorial/03-services.i18n.yaml | 6 + docs/cordis-tutorial/03-services.md | 2 + docs/cordis-tutorial/03-services.zh.md | 98 +++++++++ docs/cordis-tutorial/04-events.i18n.yaml | 6 + docs/cordis-tutorial/04-events.md | 2 + docs/cordis-tutorial/04-events.zh.md | 144 +++++++++++++ docs/cordis-tutorial/05-config.i18n.yaml | 6 + docs/cordis-tutorial/05-config.md | 2 + docs/cordis-tutorial/05-config.zh.md | 84 ++++++++ .../06-composition-and-hmr.i18n.yaml | 6 + .../cordis-tutorial/06-composition-and-hmr.md | 2 + .../06-composition-and-hmr.zh.md | 113 ++++++++++ .../07-into-the-harness.i18n.yaml | 6 + docs/cordis-tutorial/07-into-the-harness.md | 2 + .../cordis-tutorial/07-into-the-harness.zh.md | 107 ++++++++++ docs/cordis-tutorial/index.i18n.yaml | 6 + docs/cordis-tutorial/index.md | 4 + docs/cordis-tutorial/index.zh.md | 58 ++++++ docs/core-data-structures/commands.i18n.yaml | 6 + docs/core-data-structures/commands.md | 2 + docs/core-data-structures/commands.zh.md | 86 ++++++++ docs/core-data-structures/goal.i18n.yaml | 6 + docs/core-data-structures/goal.md | 2 + docs/core-data-structures/goal.zh.md | 145 +++++++++++++ docs/core-data-structures/lsp.i18n.yaml | 6 + docs/core-data-structures/lsp.md | 2 + docs/core-data-structures/lsp.zh.md | 165 +++++++++++++++ docs/core-data-structures/pty.i18n.yaml | 6 + docs/core-data-structures/pty.md | 2 + docs/core-data-structures/pty.zh.md | 91 ++++++++ .../session-reference.i18n.yaml | 6 + .../core-data-structures/session-reference.md | 2 + .../session-reference.zh.md | 67 ++++++ .../session-title.i18n.yaml | 6 + docs/core-data-structures/session-title.md | 2 + docs/core-data-structures/session-title.zh.md | 142 +++++++++++++ docs/core-data-structures/spill.i18n.yaml | 6 + docs/core-data-structures/spill.md | 2 + docs/core-data-structures/spill.zh.md | 85 ++++++++ docs/core-data-structures/tasks.i18n.yaml | 6 + docs/core-data-structures/tasks.md | 2 + docs/core-data-structures/tasks.zh.md | 154 ++++++++++++++ .../token-meter.i18n.yaml | 6 + docs/core-data-structures/token-meter.md | 2 + docs/core-data-structures/token-meter.zh.md | 43 ++++ docs/web-styling.i18n.yaml | 6 + docs/web-styling.md | 166 +++++++-------- docs/web-styling.zh.md | 109 ++++++++++ 102 files changed, 3859 insertions(+), 82 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.zh.md create mode 100644 .agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.zh.md create mode 100644 .agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.zh.md create mode 100644 .agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.zh.md create mode 100644 .agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.zh.md create mode 100644 .agents/notes/implemented/feature/2026-06-24-workspace-context.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-06-24-workspace-context.zh.md create mode 100644 .agents/notes/implemented/feature/2026-07-07-plan-mode.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-07-plan-mode.zh.md create mode 100644 .agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md create mode 100644 .agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.zh.md create mode 100644 .agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md create mode 100644 .agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md create mode 100644 .agents/notes/implemented/feature/2026-07-13-session-query-tracing.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-13-session-query-tracing.zh.md create mode 100644 .agents/notes/implemented/process/2026-07-13-documentation-site-projection.i18n.yaml create mode 100644 .agents/notes/implemented/process/2026-07-13-documentation-site-projection.zh.md create mode 100644 .agents/notes/proposed/feature/2026-07-06-recallable-compaction.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-07-06-recallable-compaction.zh.md create mode 100644 .agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.i18n.yaml create mode 100644 .agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.zh.md create mode 100644 docs/cookbook/maintaining-dsh-code-review.i18n.yaml create mode 100644 docs/cookbook/maintaining-dsh-code-review.zh.md create mode 100644 docs/cordis-tutorial/01-first-plugin.i18n.yaml create mode 100644 docs/cordis-tutorial/01-first-plugin.zh.md create mode 100644 docs/cordis-tutorial/02-lifecycle-and-effects.i18n.yaml create mode 100644 docs/cordis-tutorial/02-lifecycle-and-effects.zh.md create mode 100644 docs/cordis-tutorial/03-services.i18n.yaml create mode 100644 docs/cordis-tutorial/03-services.zh.md create mode 100644 docs/cordis-tutorial/04-events.i18n.yaml create mode 100644 docs/cordis-tutorial/04-events.zh.md create mode 100644 docs/cordis-tutorial/05-config.i18n.yaml create mode 100644 docs/cordis-tutorial/05-config.zh.md create mode 100644 docs/cordis-tutorial/06-composition-and-hmr.i18n.yaml create mode 100644 docs/cordis-tutorial/06-composition-and-hmr.zh.md create mode 100644 docs/cordis-tutorial/07-into-the-harness.i18n.yaml create mode 100644 docs/cordis-tutorial/07-into-the-harness.zh.md create mode 100644 docs/cordis-tutorial/index.i18n.yaml create mode 100644 docs/cordis-tutorial/index.zh.md create mode 100644 docs/core-data-structures/commands.i18n.yaml create mode 100644 docs/core-data-structures/commands.zh.md create mode 100644 docs/core-data-structures/goal.i18n.yaml create mode 100644 docs/core-data-structures/goal.zh.md create mode 100644 docs/core-data-structures/lsp.i18n.yaml create mode 100644 docs/core-data-structures/lsp.zh.md create mode 100644 docs/core-data-structures/pty.i18n.yaml create mode 100644 docs/core-data-structures/pty.zh.md create mode 100644 docs/core-data-structures/session-reference.i18n.yaml create mode 100644 docs/core-data-structures/session-reference.zh.md create mode 100644 docs/core-data-structures/session-title.i18n.yaml create mode 100644 docs/core-data-structures/session-title.zh.md create mode 100644 docs/core-data-structures/spill.i18n.yaml create mode 100644 docs/core-data-structures/spill.zh.md create mode 100644 docs/core-data-structures/tasks.i18n.yaml create mode 100644 docs/core-data-structures/tasks.zh.md create mode 100644 docs/core-data-structures/token-meter.i18n.yaml create mode 100644 docs/core-data-structures/token-meter.zh.md create mode 100644 docs/web-styling.i18n.yaml create mode 100644 docs/web-styling.zh.md diff --git a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.i18n.yaml b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.i18n.yaml new file mode 100644 index 0000000000..1c6f4e06ac --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.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 +2026-06-21-bounded-llm-request-recovery.md: 22a56dc6d69340ca1b5f7b77edb4731066c9b2f5 +2026-06-21-bounded-llm-request-recovery.zh.md: 09ebce376a206591ac766067cc41497b74ed1545 diff --git a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md index 932318da4f..22a56dc6d6 100644 --- a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md +++ b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-21-bounded-llm-request-recovery.zh.md) + ## Problem `dsh-llm` can report provider failures either by throwing during adapter dispatch or iteration or by ending with `finish { kind: 'error' | 'aborted' }`. The final adapter boundary tags thrown failures so `dsh-agent-loop` can distinguish them from middleware and result-processing defects, and the loop normalizes both delivery forms into `agent/request-error` after closing the failed step. The default decision is `fail`; `dsh-compact-basic` is the only shipped recovery listener, and it retries a canonical context-window overflow only after compaction proves that the durable surface shrank. diff --git a/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.zh.md b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.zh.md new file mode 100644 index 0000000000..09ebce376a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-06-21-bounded-llm-request-recovery.zh.md @@ -0,0 +1,148 @@ +# Agent Note: LLM(大语言模型)暂时性请求失败的有界恢复 + +Status: implemented + +[English](2026-06-21-bounded-llm-request-recovery.md) | 中文 + +## 问题 + +`dsh-llm` 可能在适配器分发或迭代时抛出异常,也可能以 `finish { kind: 'error' | 'aborted' }` 结束,以这两种形式报告提供方失败。最终适配器边界会标记抛出的失败,使 `dsh-agent-loop` 能将其与中间件和结果处理缺陷区分开。循环关闭失败步骤后,会把两种交付形式统一规范化为 `agent/request-error`。默认决策为 `fail`;`dsh-compact-basic` 是唯一已交付的恢复监听器,它仅在压缩(compaction)证明持久表层已缩减后,才会对规范化的上下文窗口溢出进行重试。 + +该边界已能安全地再次发起请求。原始 `assistant/chunk` 事件携带失败的 `turn` 和 `step`;除非某条成功的 `assistant/message` 引用这些事件,否则消息派生会忽略它们。只有终止性 finish 成功且组装完成后,系统才会分发工具调用;重试则会从持久日志开启新的编号步骤。因此,harness 无需引入第二套响应生命周期或暂定输出协议,即可分隔两次尝试。 + +此前的边界还留有三个较窄的缺口。 + +- 提供方失败只保留消息,通常还会保留一个 code。HTTP 状态、重试延迟和提供方请求 id 会被丢弃,或者只能通过提供方专用错误对象恢复,因此通用恢复机制如果不解析文本,便无法作出决策或解释决策。 +- 重试的归属因适配器而异。手写 DeepSeek 适配器只尝试一次,pi-ai profile 则可以启用库内部的不透明重试。如果把隐藏的传输重试与 `agent/request-error` 监听器结合,尝试次数会成倍增加,中间失败也不会记入会话日志。 +- 恢复后的失败没有持久状态事实。失败的步骤和分片仍可重建,但观察者无法得知 agent(智能体)是否在有意退避、将等待多久,以及等待原因。长时间的静默等待看起来与循环停滞无异。 + +本决策的目标是从同一个显式提供方/模型请求的暂时性失败中进行有界恢复。提供方或模型故障转移、响应拼接和语义输出修复都属于其他问题,目前没有消费方。 + +## 决策 + +### 保留失败事实,不嵌入策略 + +`@deepseek-ai/dsh-llm` 导出唯一的可 JSON 序列化 `LlmFailure` 载荷: + +```ts ignore-check +type ProviderRequestId = Branded<'ProviderRequestId'> + +interface LlmFailure { + message: string + code: string + status?: number + providerRetryAfterMs?: number + requestId?: ProviderRequestId +} +``` + +`code` 仍是 `HarnessError` 建立的提供方无关机器路由分类体系;新字段是在提供方边界观测到的事实。`ProviderRequestId` 由 `dsh-llm` 拥有并构造,序列化后为提供方发放的字符串。该载荷有意不包含 `retryable`、`failover`、`partialOutput`、提供方、模型、阶段或路由 id 字段。是否可重试属于策略,提供方/模型已位于持久请求头中,部分输出则从失败步骤的 `assistant/chunk` 事件派生。 + +`LlmError` 携带 `failure: LlmFailure`,并保持 `failure.code === error.code`。`FinishReasonMap.error` 和 `FinishReasonMap.aborted` 携带同一载荷,而不是并行的失败形状。适配器抛出的 `Error` 保留其精确的对象标识:最终适配器 scope 在调用局部的伴随状态中把规范化事实与该对象关联,然后原样重新抛出;非 `Error` 抛出值则依旧被包装。`llmFailureOf(stream, error)` 会在现有来源检查旁取回这些事实,而没有错误对象的带内 finish 则会成为新的 `LlmError`。这既保留了按错误类型或标识分流的监听器,又使所有最终适配器失败(包括未知 SDK 异常)都获得 `UNKNOWN` 终止载荷。 + +agent loop(智能体循环)会保留 `RequestError` 作为该精确的错误对象,并将 `LlmFailure` 作为独立参数传给 `agent/request-error`;它不会改动可能已冻结的第三方错误。在转换带内 finish 以及记录未恢复的 `turn/end.reason` 时,循环也会使用该载荷。 + +适配器会先提取结构化事实,再回退到消息检查。它们会验证 HTTP 状态,将 `Retry-After` 的秒数或日期解析为正的有限毫秒延迟,在提供方公开请求 id 时将其品牌化,并区分自身超时与调用方中止。提供方专用 code 和消息可以细化映射,但恢复监听器不会解析它们。 + +共享的暂时性 code 集有意保持很小:适配器针对 `RATE_LIMIT` 和 `SERVER` 的映射,远程失败使用的显式 `TIMEOUT` 和 `TRANSPORT` code,以及提供方响应已完成却没有内容块时使用的 `EMPTY_RESPONSE`。两个适配器都会把最后一种情况归类为错误 finish;详见[空模型响应可重试](../bug-fix/2026-07-24-empty-model-response-is-retryable.md)。身份验证、配额、无效请求、上下文溢出、协议、中止和未知失败都保留不同的稳定 code,且默认不属于暂时性失败。新增 code 需要适配器 fixture(测试前置数据)和已记录的策略决策;无需扩展第二个失败类枚举。 + +### 将重试策略放在现有失败步骤 seam 上 + +`@deepseek-ai/dsh-llm-retry` 是监听 `agent/request-error` 的函数插件。它不引入服务或新的循环分支;agent-loop 包仅会更改通过现有失败步骤恢复控制流携带的数据。 + +`agent/request-error` seam 携带当前 `LlmFailure`,以及在这段连续恢复序列中导致再次请求的不可变先前失败列表。`dsh-llm-retry` 只计数 code 位于已配置暂时性集合中的先前失败,`dsh-compact-basic` 则只计数先前的上下文溢出失败。模型请求成功后会清空历史。因此,暂时性失败与上下文溢出交替出现时,两种策略会独立消耗各自预算;最大请求数等于 1 加上已加载恢复策略的有限预算总和。 + +该插件在加载时解析并验证以下部署配置: + +```ts ignore-check +interface Config { + maxTransientRetries?: number + initialDelayMs?: number + maxDelayMs?: number + jitterRatio?: number + retryableCodes?: string[] +} +``` + +默认值为两次暂时性重试、500 毫秒初始延迟、10 秒延迟上限、10% 抖动,以及上述五个暂时性 code(`RATE_LIMIT`、`SERVER`、`TIMEOUT`、`TRANSPORT` 和 `EMPTY_RESPONSE`)。计数与延迟边界参考了所调查实现中较保守的一端:[OpenCode 使用两次请求重试,延迟边界为 500 毫秒/10 秒](https://github.com/anomalyco/opencode/blob/9976269ab1accfc9f9dc98a4a688c516934de422/%70ackages/llm/src/route/executor.ts#L36-L39);[Pi 将三次 agent 级重试与提供方重试分开,且提供方重试默认为零](https://github.com/earendil-works/pi/blob/3da591ab74ab9ab407e72ed882600b2c851fae21/%70ackages/coding-agent/docs/settings.md#L139-L147);[Codex 使用有限请求/流预算以及五分钟空闲超时](https://github.com/openai/codex/blob/0fb559f0f6e231a88ac02ea002d3ecd248e2b515/codex-rs/model-provider-info/src/lib.rs#L25-L33)。10% 抖动参考 [Codex 的有界抖动](https://github.com/openai/codex/blob/0fb559f0f6e231a88ac02ea002d3ecd248e2b515/codex-rs/codex-client/src/retry.rs#L40-L47)。在没有其他恢复策略时,两次重试表示最多发起三次提供方请求。`maxTransientRetries` 是非负整数,延迟是正的有限数且满足 `initialDelayMs <= maxDelayMs`,`jitterRatio` 位于 `[0, 1]`,code 非空且不重复。这些都是 Cordis 配置字段,而不是隐藏常量,使部署能够选择不同的成本与延迟预算。 + +对于预算未耗尽的合格失败,从 1 开始的暂时性重试计数使用有界指数退避。有效的 `providerRetryAfterMs` 只有在不超过 `maxDelayMs` 时才会取代指数退避;提供方延迟更长时,系统会委托给下一监听器,而不会违反提供方指令提前重试。本地退避乘以 `[1 - jitterRatio, 1 + jitterRatio]` 内的注入随机因子,并将最终值限制到 `maxDelayMs`;提供方延迟不加抖动。 + +插件拥有一个全生命期 `AbortController`,并跟踪每个活跃的退避回调。每次等待都会融合 waterfall(瀑布式事件)的轮次信号与该生命期信号。effect 清理会先注销监听器,再中止并等待活跃回调;被捕获回调的生命期信号中止时,回调会返回 `fail`,既不能重试,也不能在插件释放后进入其捕获 waterfall 的剩余部分。尽管 Cordis 已捕获该监听器,此设计仍能使 HMR(热模块替换)释放达到完全停稳。 + +休眠前,`dsh-llm-retry` 会追加一条不进入表层的 `llm/retry` 会话事件,其中包含轮次、失败步骤、从 1 开始的暂时性重试编号、已配置上限、计划延迟和 `LlmFailure`。该插件拥有 `SessionEventMap` 声明合并;`dsh-session` 继续负责通用持久化,不会吸收可选策略的词汇。事件记录已安排的内容,而不是下一个请求已完成;延迟期间取消随后会在 `turn/end` 中可见。因为该事件的目的是表示运行状态,而不是收集跟踪数据,所以它仅与生产渲染器及回放/快照覆盖一起交付。 + +对非暂时性 code、耗尽的策略预算或超出上限的提供方延迟,监听器会调用 `next()`。这保留了与上下文溢出恢复及后续策略插件的组合能力。只有在两个信号下完成延迟后,它才会返回 `{ action: 'retry' }`;轮次取消和插件释放会返回 `fail`,此后仍以循环的取消/释放检查为准。 + +agent-spine 演示组合包加载该插件,因此共享的 stdio/TUI、一次性 CLI(命令行界面)和 ACP(Agent Client Protocol)示例组合使用同一有界策略。库消费方仍需显式组合插件:省略该插件时,`agent/request-error` 保持现有的 fail 默认值。 + +### 由单一层负责可见的尝试 + +适配器每次调用 `stream()` 只执行一次提供方请求。pi-ai 适配器移除公开的 `maxRetries` 和 `maxRetryDelayMs` profile 字段,并禁用库内部重试;手写适配器保持现有的单次尝试行为。这样既避免 SDK 预算成倍放大 agent 预算,又能确保每次暂时性重试都由一个已关闭的失败步骤加 `llm/retry` 表示。 + +`ctx.llm.stream()` 仍是原始的单次尝试 waterfall。压缩摘要等直接调用方会收到结构化失败,但不会自动获得重试,因为它们没有 agent 步骤边界,也没有可供分隔尝试的通用持久位置。未来的直接调用消费方可能会需要一个缓冲辅助函数,仅在尚未发出任何分片时重试;本决策不增加此类辅助函数。 + +### 在能够终止停滞流的位置施加边界 + +每个适配器都公开一个经过验证的 `streamIdleTimeoutMs` 配置字段,默认值采用上文引用的五分钟先例。该间隔不超过 Node 的最大定时器延迟,因此不会被钳制为 1 毫秒。它覆盖每个尚未完成的迭代器 `next()`:从消费方请求下一项开始,到下一条有效 `StreamChunk` 到达为止;消费方在两次 `next()` 调用之间花费的时间不属于提供方空闲时间。 + +`@deepseek-ai/dsh-timeout` 公开一个可重新布防的空闲看门狗原语。一个稳定的局部 `AbortController` 会与调用方信号融合,并在整个适配器调用期间传给传输层;每个尚未完成的 `next()` 都会布防看门狗,该调用完成时解除布防,下一次请求数据时再重新布防。超时会使用能力自身拥有的 `TimeoutReason` 中止这个稳定控制器,`finally` 则会清除定时器。适配器将自身看门狗归类为 `TIMEOUT`,将更早发生的上游中止归类为 `ABORTED`。现有的一次性 `deadline()` 不会被描述为滑动计时器。 + +边界测试证明两个实际传输层都能终止。手写适配器会中止其 fetch/reader,pi-ai 适配器会把稳定信号映射到 SDK,并证明 SDK 会关闭响应。如果定时器只拒绝消费方 promise,却让请求继续运行,就不满足此契约。 + +### 在现有日志中分隔尝试 + +一次失败尝试可以在已关闭的步骤中留下 `assistant/chunk` 事件,但绝不会追加 `assistant/message`,也不会分发工具。重试会开启下一个编号步骤,从持久表层重建请求,并生成自己的分片。步骤仍处于打开状态时,UI 可以渲染实时分片;当 `llm/retry` 标识失败步骤,或 `turn/end` 记录终止失败时,UI 再标记或清除这份暂时视图。消息派生仍会忽略失败分片。 + +如果恢复预算耗尽,最终失败会连同结构化事实在 `turn/end.reason` 中存储一次。如果暂时性恢复继续,`llm/retry` 就是该次尝试的失败与延迟的持久归属位置。本决策不增加独立的最终错误事件或响应 id 词汇。 + +## 不在范围内 + +- 自动提供方或模型故障转移。请求已显式选择一个提供方和模型,提供方注册表也有意规定每个提供方只由一个适配器负责。 +- 在成功的终止性 finish 后重试或继续,或将两次尝试的分片拼接成一条 assistant 消息。 +- 修复格式错误的工具参数、拒答、内容过滤或其他语义模型输出。 +- 无界重试、无人值守地持续重试直至取消、熔断器、共享提供方健康状态或跨 agent 重试预算。 +- 在没有生产消费方的情况下,把 `llm/stream` 改造成响应生命周期或增加便利的生成 API。 + +## 考虑过的替代方案 + +- **在 `llm/stream` 或提供方 SDK 内部重试**:拒绝采用,因为原始流一旦发出分片便没有持久尝试边界,隐藏的 SDK 重试会成倍放大预算,而且两条路径都无法一致地记录每次失败尝试。 +- **向 `dsh-llm` 增加响应开始、中断、丢弃、失败和提交事件**:拒绝采用,因为 agent 日志已经分隔原始分片、成功消息和编号尝试。第二套状态机会重复归属关系,又不能支持有界的同路由重试。 +- **增加逻辑路由、能力矩阵和故障转移选择**:拒绝采用,因为当前请求已经显式指定提供方和模型,每个提供方由一个适配器负责,而且没有当前消费方要求自动回退或能够证明语义兼容性。 +- **把 `retryable` 或 `failover` 放在 `LlmFailure` 上**:拒绝采用,因为适配器报告事实,部署策略决定动作。同一个 429 可以在交互式组合包中重试,也可以在成本受限的批处理中被拒绝。 +- **只要调用方仍处于活跃状态就无限重试**:拒绝采用,因为这会让一次请求产生无界成本和延迟。可见状态能使有界等待易于理解,却不能让无限预算变得安全。 +- **只通过进程 logger 记录重试状态**:拒绝采用,因为进程日志无法重建会话行为,也不能驱动回放后的 UI 状态。 +- **只保留扁平 code**:拒绝采用,因为重试延迟和提供方请求 id 是结构化的提供方事实,而当不同协议失败共用一个稳定 code 时,诊断还需要 HTTP 状态。 + +## 验证 + +- `LlmFailure` 是最终适配器抛出失败、错误 finish 和中止 finish 使用的唯一可序列化载荷;在可用时,规范化保留稳定 code、状态、重试延迟、品牌化的提供方请求 id、错误原因,以及调用方中止与适配器超时之间的分类。 +- 适配器抛出的 `Error` 会以完全相同的对象抵达 `agent/request-error`,其伴随的 `LlmFailure` 则抵达相邻参数;测试保留针对可扩展及冻结第三方错误的现有对象标识断言。 +- DeepSeek 和 pi-ai 适配器测试覆盖具有代表性的 400、401/403、429、5xx、连接、格式错误/截断流、超时、中止、Retry-After 秒数/日期、请求 id 和未知 SDK 错误路径,恢复策略无需解析消息文本。 +- Pi 将 SDK 选项固定为零次重试,并针对可重试的提供方响应执行一次可观测的实际网络请求;独立测试确保移除任一边界都会失败。 +- `agent/request-error` 携带当前失败事实以及不可变的先前已重试失败事实;成功会清除该历史,暂时性失败/上下文溢出交替发生的集成测试证明两种策略只消耗各自的有限预算。 +- `dsh-llm-retry` 在 Loader 启动时验证每个配置字段,使用 `next()` 委托所有不合格路径,而且在没有其他策略时最多发起 `maxTransientRetries + 1` 次提供方请求。 +- 退避期间执行 HMR 的测试证明:释放过程会注销监听器、中止并等待其捕获的回调,释放后不发出重试决策,也不留下存活的定时器或 promise。 +- 纯单元测试覆盖暂时性 code 选择、指数退避和抖动边界、有效及超出上限的 `Retry-After`、耗尽的预算、确定性定时器/随机数 seam,以及退避期间中止。 +- 真实 agent-loop 测试覆盖分片前失败、部分分片后失败、抛出及带内失败、在新步骤中重试至成功、耗尽后写入结构化 `turn/end.reason`,以及与 `dsh-compact-basic` 上下文溢出恢复的组合。 +- 部分分片集成测试证明:失败分片仍归属于失败步骤,该步骤不会提交 assistant 消息或工具副作用,成功的重试具有不同的来源信息。 +- 插件拥有的不进入表层的 `llm/retry` 事件可在 JSONL 和 SQLite 往返后保留,被消息派生忽略,并驱动 TUI 撤回和计划重试渲染。无密钥快照覆盖调度、取消、成功和耗尽;ACP 自动化快照确认,被丢弃的尝试不会通过协议发出,而恢复后的回复会正常发出。 +- 空闲看门狗测试证明:只有 `next()` 尚未完成时才会重新布防稳定信号;在消费方思考期间及 `finally` 中会解除布防;它与总调用 deadline 以及更早发生的调用方中止分开分类。适配器测试证明该信号会终止底层请求,而不只是与其脱离。 +- `ctx.llm.stream()` 的直接调用方仍只尝试一次,并收到相同的结构化失败事实。 + +## 后果 + +- 每次暂时性恢复尝试都以一个已关闭步骤加 `llm/retry` 的形式可见,有界策略还会防止隐藏的 SDK 重试成倍增加成本。即使没有分片到达,重试仍可能造成提供方重复计费;有限的尝试预算只能限制而无法消除此风险。 +- 提供方 SDK 可能隐藏状态或重试标头。适配器会保留 SDK 公开的稳定事实,否则使用粗粒度 code,而不会让恢复策略解析脆弱的文本。 +- 持久重试事件扩展了会话协议和 UI 状态机。事件与其消费方一同交付,可避免产生无人使用的遥测词汇;但以后更改 schema 仍需要同步完成持久化和回放工作。 +- 清除失败步骤的实时分片可能会明显撤回输出。与把丢弃的文本或不完整工具 JSON 呈现为已提交历史相比,这是更好的选择;快照固定这一转换。 +- 适配器局部的空闲强制机制可以终止停滞的传输,而不会计入消费方思考时间。每个传输边界的契约测试会防止 SDK 漂移。 +- 多个恢复插件会叠加各自的有限预算。此处它们的分类器互不重叠;重叠的分类器会形成依赖注册顺序的策略,必须由引入它们的插件记录并测试。 + +## 相关资料 + +- [结构化错误分类体系](../../implemented/architecture/2026-06-11-structured-error-taxonomy.md)负责稳定、可供机器路由的 code 与 cause chaining。 +- [可重建请求](../../implemented/architecture/2026-07-05-reconstructable-requests.md)使提供方/模型和完整请求输入在分发前持久化。 +- [超时 deadline 库](../../implemented/architecture/2026-07-06-timeout-deadline-library.md)将共享的 deadline 分类与能力自身拥有的终止操作分开。 +- [调用后压缩压力与上下文溢出恢复](../../implemented/architecture/2026-07-10-after-call-compaction-pressure-and-overflow-recovery.md)负责当前已关闭步骤的请求恢复 seam 与有界溢出重试。 +- [提供方路由的 LLM 适配器](../../implemented/architecture/2026-07-14-provider-routed-llm-adapters.md)负责显式提供方/模型路由与每个提供方仅有一个适配器的不变量。 diff --git a/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.i18n.yaml new file mode 100644 index 0000000000..108103c370 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.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 +2026-07-05-windows-fs-permissions.md: 243e264bab12e072a7b4ec6beddde1e05546ae7f +2026-07-05-windows-fs-permissions.zh.md: b88244e9f72f743cfd05a758368b40df053ee38d diff --git a/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.md b/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.md index 932b6ddbf4..243e264bab 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.md +++ b/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-windows-fs-permissions.zh.md) + The replacement-file decision in this record is superseded by [Windows DACL preservation](../bug-fix/2026-07-19-windows-atomic-write-dacl-preservation.md). ## Problem diff --git a/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.zh.md b/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.zh.md new file mode 100644 index 0000000000..b88244e9f7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-windows-fs-permissions.zh.md @@ -0,0 +1,33 @@ +# Agent Note: Windows 写入权限语义:继承 DACL,而非权限模式位 + +Status: implemented + +[English](2026-07-05-windows-fs-permissions.md) | 中文 + +本记录中关于替换文件的决策已由 [Windows DACL 保留机制](../bug-fix/2026-07-19-windows-atomic-write-dacl-preservation.md)取代。 + +## 问题 + +`writeFileAtomic` 在 `@deepseek-ai/dsh-fs-local` 中使用 POSIX 权限模式位保护正在写入的内容:以 `0o700` 创建暂存目录,以 `0o600` 打开临时文件,新文件也默认使用 `0o600`。在 POSIX 上,无论父目录的权限如何,这些设置都能保证临时内容仅对所有者可见。 + +Windows 在同一 API 背后没有可用的对等机制。Node 的 `chmod` 在 Windows 上只会驱动只读属性(此包传入的每种模式都包含所有者写权限,因此这些调用是无害的空操作),`stat().mode` 则报告合成的 `0o666`/`0o444` 权限位。真正的安全状态由文件的 DACL 决定:新建文件或目录会从父目录继承,替换操作则需要由取代本文的 Agent Note 所定义的显式处理。 + +## 决策 + +Windows 新建文件使用目录继承,而不使用合成的权限模式位:暂存目录在目标的父目录(`dirname(absolutePath)`)内创建,因此它和临时文件都会继承目标目录的 DACL。替换文件遵循更严格的 [DACL 保留契约](../bug-fix/2026-07-19-windows-atomic-write-dacl-preservation.md)。 + +测试仅在 POSIX 上断言权限模式位。Windows 原生覆盖率锁定由本包(package)负责的替换行为;新文件继承仍属于操作系统契约,而不是针对特定机器的 ACL 允许清单。 + +## 备选方案 + +**为新文件显式设置仅所有者可用的 DACL。** 不予采纳,因为这会破坏继承,也会使特意共享项目目录的用户感到意外。替换写入会复制目标现有的 DACL,而不会自行设计仅所有者可用的策略。 + +**在测试中验证 ACL。** `Get-Acl` SID 允许清单或 `icacls` 验证的是 Windows 继承机制以及当前机器的 `%TEMP%` ACL,而非包的行为;`icacls` 还会对知名账户名进行本地化,导致解析容易受语言区域影响。 + +**在 Windows 上跳过 `chmod`。** 为无害的空操作调用增加平台守卫分支,不会改变任何行为。 + +## 后果 + +无论父目录的权限如何,POSIX 都会继续将临时内容限制为仅所有者可用。Windows 中的新目标如果位于广泛可访问的目录内,将按设计继承这种可访问性;如果替换目标存在更严格的 DACL,则会保留该 DACL。 + +在 Windows 上,替换时的模式保留会退化为空操作:可写文件的探测结果为 `0o666`,通过 `chmod` 重放该模式会使只读属性继续保持清除状态。由于发布操作会在合成模式发挥作用前失败,Windows 上无法替换只读目标。 diff --git a/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.i18n.yaml new file mode 100644 index 0000000000..4322906bb9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.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 +2026-07-05-windows-jsonl-durable-publish.md: 38c4adc7a4f85d45e53e70fcac84073ab4e50775 +2026-07-05-windows-jsonl-durable-publish.zh.md: 8dc77a0ab1b9273cf3f6ecb26916c7861ee81ec4 diff --git a/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.md b/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.md index 23e5f630d3..38c4adc7a4 100644 --- a/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.md +++ b/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-05-windows-jsonl-durable-publish.zh.md) + ## Problem `dsh-session-persistence-jsonl` publishes a session log lazily on the first append. The POSIX protocol writes a temp file, fsyncs it, links it to the final name, fsyncs the parent directory, and then removes the temp link. The parent-directory fsync is part of the durability contract: a crash after the namespace change must not lose the committed final name while leaving callers believing the session log materialized. diff --git a/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.zh.md b/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.zh.md new file mode 100644 index 0000000000..8dc77a0ab1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-05-windows-jsonl-durable-publish.zh.md @@ -0,0 +1,35 @@ +# Agent Note: Windows 原生持久 JSONL 发布 + +Status: implemented + +[English](2026-07-05-windows-jsonl-durable-publish.md) | 中文 + +## 问题 + +`dsh-session-persistence-jsonl` 在首次追加时延迟发布会话日志。POSIX 协议会写入临时文件,对其执行 fsync,将其链接至最终名称,对父目录执行 fsync,然后移除临时链接。对父目录执行 fsync 是持久性契约的一部分:命名空间变更后发生崩溃时,已经提交的最终名称不能丢失,否则调用方会误以为会话日志已经物化。 + +Windows 具备原子命名空间操作,但 Node 没有暴露与 POSIX 等价的父目录 fsync 契约。如果把 Windows 目录同步失败视为成功,就会在无提示的情况下削弱持久化后端。因此,Windows 路径需要采用不同的发布原语,而不是在 POSIX 的 `syncDir` 辅助函数中添加条件分支。 + +## 决策 + +JSONL 后端会在 `materialize()` 内部、任何命名空间变更之前分流。共享代码计算会话目录、最终日志路径,以及编码后的 header 和初始事件批次;随后 POSIX 与 Windows 分别执行各自的发布协议。 + +POSIX 保留现有协议:创建根目录、项目目录与会话目录,并对其父目录执行 fsync;写入临时文件并对其执行 fsync;使用 `link()` 发布,确保绝不覆盖已有的最终日志;对会话目录执行 fsync;最后移除多余的临时硬链接。 + +Windows 通过持久的暂存发布来创建缺失目录:在固定的 `.dsh-mkdir-` 前缀下创建一个随机同级目录,其名称与目标基本名无关;随后使用 `MoveFileExW(..., MOVEFILE_WRITE_THROUGH)` 将其发布为最终目录名称,且不使用 `MOVEFILE_REPLACE_EXISTING` 或 `MOVEFILE_COPY_ALLOWED`。文件物化先写入临时日志并对其执行 fsync,再以同一个启用写穿透的 `MoveFileExW` 调用将临时文件发布到最终路径,并且同样不允许替换。`koffi` 是覆盖这组 API 所需的最小 Win32 桥接层;`pnpm-workspace.yaml` 允许执行它的安装脚本,因为该包(package)会分发原生 loader 和预构建的平台模块。 + +## 考虑过的替代方案 + +**忽略 Windows 目录同步失败。** 不予采纳,因为这会在没有强制将已发布的命名空间条目写入稳定存储时,就把首次追加报告为持久化成功。 + +**使用 `CreateHardLinkW`。** 不予采纳,因为硬链接依赖文件系统、不能发布目录,并且没有提供写穿透选项。 + +**使用替换或事务型 API。** `ReplaceFileW` 的替换语义与拒绝同一 id 冲突的要求相悖,而新应用设计不应使用 Transactional NTFS。 + +## 影响 + +该后端在各平台上维持同一项外部契约:首次追加要么把完整日志发布到最终名称,要么失败且不覆盖已有日志。平台分流只是实现细节;`SessionPersistence` API 和 JSONL 逻辑记录格式均不改变。后续的 [Zstandard 编码决策](2026-07-19-zstandard-jsonl-session-logs.md)会先作用于不透明字节,然后才由任一平台执行发布。 + +Windows 测试会在原生 Windows 上执行真实的 Win32 发布路径。断电行为属于 API 契约属性,单元测试无法证明;可测试的不变量包括:Windows 物化不会调用目录 fsync、最终路径冲突会失败、达到最大长度的目标路径组件仍可物化、临时日志在发布前已经执行 fsync,并且生成的日志可以正常加载。 + +两个平台的追加和修复仍使用普通文件句柄 fsync。追加失败后,系统会关闭仅追加句柄,以读写模式重新打开日志,将文件截断到追加前的大小,并对回滚结果执行 fsync,因为 Windows 不允许在仅追加句柄上调用 `ftruncate`。 diff --git a/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.i18n.yaml new file mode 100644 index 0000000000..6663606c3c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.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 +2026-07-06-tool-result-retention-library.md: 5e42660360e5a23b419c75b9c8006bec459bc322 +2026-07-06-tool-result-retention-library.zh.md: 6e824667f17b361efb57b173c44f489da2cab3b3 diff --git a/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.md b/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.md index 2962f1006e..5e42660360 100644 --- a/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.md +++ b/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-06-tool-result-retention-library.zh.md) + ## Problem Several model-facing tools already bound the amount of context they return, but each one owns a different local mechanism and vocabulary: bash keeps a tail plus spill files, web search caps source lists, web fetch caps body content, and `glob` / `grep` discovery needs an inline first page while keeping exact omission metadata for the full result set. A single `truncate(text)` helper cannot cover those cases: item tools need item counts and grouping outside the primitive, while text tools need byte budgets and UTF-8-safe head/tail cuts. diff --git a/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.zh.md b/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.zh.md new file mode 100644 index 0000000000..6e824667f1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-06-tool-result-retention-library.zh.md @@ -0,0 +1,157 @@ +# Agent Note: 工具结果保留库 + +Status: implemented + +[English](2026-07-06-tool-result-retention-library.md) | 中文 + +## 问题 + +多个面向模型的工具已经限制其返回的上下文量,但每个工具都拥有不同的局部机制和词汇:bash 保留尾部并提供落盘文件;web search 限制来源列表;web fetch 限制正文内容;`glob`/`grep` 发现工具需要在行内提供第一页,同时为完整结果集保留精确的省略元数据。单一的 `truncate(text)` 辅助函数无法覆盖这些情况:条目型工具需要条目计数,并在原语之外分组;文本型工具则需要字节预算和 UTF-8 安全的首尾裁切。 + +这些工具需要共享的抽象是**保留**,而不是通用集合。调用方向一个有界对象输入条目或文本分片,稍后取得保留内容与精确的省略元数据。工具专用代码仍负责业务语义:文件分组、行号、退出码、提供方错误状态、落盘文件和面向模型的说明。公共库只负责一个机械问题:「保留了什么,又省略了什么?」 + +## 决策 + +`@deepseek-ai/dsh-retention` 位于 `packages/util/` 下,与 `dsh-brand` 和 `dsh-timeout` 同级,负责有界的模型可见输出。它是一组纯类与函数构成的库,**不是** Cordis 服务或插件:不接收 `ctx`、不注册任何内容、不持有跨调用状态,也不发出事件。各工具包(package)需要限制输出时直接导入它。 + +该库包含两个相互独立的 retainer: + +- `ItemRetainer` 处理有序逻辑单元,例如路径、grep 匹配项或搜索来源。v1 只支持 `head` 保留,同时维持 retainer 形态,以便未来加入其他保留策略。 +- `TextRetainer` 处理面向字节的文本流,例如 bash stdout/stderr 或 web 响应正文。它支持 `head`、`tail` 和 `headTail` 保留,并在 `finish()` 时维持 UTF-8 边界。 + +两个 retainer 都会返回一个小型 `PushDecision`;每次调用 `push()` 后,调用方都能得知该单元/分片是否完整保留,以及累积结果此时是否已被截断。因为调用方会继续输入每一个已观察到的条目/分片,所以省略计数是精确的。 + +```ts ignore-check +/** + * How much content the retainer omitted. + * + * `unknown` is reserved for callers that omit without a count; the retainers + * themselves return `none` or `exact`. + */ +type Omitted = + | { kind: 'none' } + | { kind: 'exact'; count: number } + | { kind: 'unknown' } + +interface PushDecision { + kept: boolean + truncated: boolean +} + +/** + * Final result for ordered logical units. + */ +interface RetainedItems { + items: T[] + truncated: boolean + seen: number + kept: number + omitted: Omitted +} + +/** + * Final result for text streams. + * + * The returned `text` is safe to send to a formatter; the retainer does not add + * tool-specific headers, exit markers, XML tags, or recovery instructions. + */ +interface RetainedText { + text: string + truncated: boolean + omittedBytes: Omitted +} +``` + +### 策略 + +条目保留支持头部窗口。文本保留支持头部、尾部与首尾字节窗口。 + +```ts ignore-check +type ItemRetentionStrategy = + | { + /** Keep the first `maxItems` units. Use for `glob`, `grep`, and web sources. */ + kind: 'head' + maxItems: number + } + +type TextRetentionStrategy = + | { + /** Keep the first `maxBytes` bytes. */ + kind: 'head' + maxBytes: number + } + | { + /** Keep the final `maxBytes` bytes. Requires reading to the end. */ + kind: 'tail' + maxBytes: number + } + | { + /** Keep a stable prefix and suffix, omitting the middle. Requires reading to the end. */ + kind: 'headTail' + headBytes: number + tailBytes: number + } +``` + +### 工具映射 + +`read` 被有意排除在 v1 保留库之外。它的 `read-render` 辅助函数拥有文件专用的分页契约:`offset`/`limit`、行号、`totalLines`、offset 越界错误、逐行预览截断,以及能够在窗口中途停止扫描的所选输出字节上限。这是行窗口渲染器,不是通用保留原语。它未来可以共享中性的提示辅助函数,但不应把已经选定的窗口再传入 `ItemRetainer`。 + +下文的 `FsGlobEntry` 与 `FlatGrepMatch` 是预期由发现工具使用的条目形态,不是现有保留库的导出。`FsGlobEntry` 是一个由后端派生的路径;`FlatGrepMatch` 是后端将保留匹配项按文件分组之前的一条未分组 grep 匹配。 + +`glob` 收集完整的排序路径列表后,使用 `ItemRetainer`,并将其配置为 `{ kind: 'head', maxItems: globMaxResults }`。工具在行内保留第一页,并可以通过落盘 seam 保存完整列表。路径映射、跳过的候选项与 `incomplete` 均位于 retainer 之外。 + +`grep` 在分组前使用 `ItemRetainer`,并将其配置为 `{ kind: 'head', maxItems: grepMaxMatches }`。执行器解析 ripgrep 输出、映射路径、应用逐行预览截断,并输入扁平匹配项。调用 `finish()` 后,工具按文件对保留的匹配项分组;如果行内结果达到上限,还可以通过落盘 seam 保存完整匹配列表。分组不属于 retainer,因为上限针对匹配总数,而不是文件数;逐匹配项的预览截断和 `incomplete` 也与结果级保留相互独立。 + +`bash` 可以使用 `TextRetainer`,配置为 `tail` 或 `headTail`,并读取至进程结束。bash 执行器仍负责落盘文件、退出状态、信号、超时与后台任务行为;保留辅助函数只在需要该行为时替换临时实现的内存首尾核算。长时间运行任务的所有权与[通用长时间运行工具的运行时](2026-06-20-generic-long-running-tool-runtime.md)相互独立。 + +`web_fetch` 可以使用 `TextRetainer`,配置为 `head` 或 `headTail`;如果提供方必须在内部读取和解码,也可以保留由提供方负责的正文上限。无论采用哪种方式,fetch 结果中的 `truncated` 仍是提供方/工具事实,该库只提供保留文本与省略元数据。 + +`web_search` 可以使用 `ItemRetainer`,配置为 `head`。当前提供方通常返回数组,所以这属于事后处理,但仍能统一提示信息。 + +### 提示 + +该库公开一个中性的提示结构和一个小型格式化钩子,但面向用户的措辞由工具提供。grep 页脚会提示「缩小 pattern、path 或 include」;web fetch 页脚会提示「获取更具体的 URL 或章节」;bash 则可以指向落盘文件。retainer 无法得知这些恢复操作。 + +```ts ignore-check +interface RetentionNotice { + scope: string + strategy: 'head' | 'tail' | 'headTail' + unit: 'items' | 'bytes' | 'chars' | 'lines' + limit: number | { head: number; tail: number } + kept: number + omitted: Omitted +} + +const formatGrepNotice = (notice: RetentionNotice): string => + formatRetentionNotice( + notice, + ({ kept }) => `Results capped at ${kept}. Narrow the pattern, path, or include to see more.`, + ) +``` + +格式化钩子刻意保持精简:工具把 `RetentionNotice` 转换为自己的页脚文本。辅助函数可以统一省略措辞,但不负责恢复指引。 + +`truncated` 表示 retainer 因预算省略了原本可用的内容,不表示上游结果不完整。工具会为权限失败、跳过的二进制文件、提供方局部失败、不可读候选项、无效 UTF-8,以及其他任何「无法检查」状况保留独立字段。 + +## 影响 + +**已交付内容。** `@deepseek-ai/dsh-retention` 导出 `ItemRetainer`、`TextRetainer`、结果类型(`RetainedItems`、`RetainedText`)、策略类型(`ItemRetentionStrategy`、`TextRetentionStrategy`)、`Omitted`、`PushDecision`、`RetentionNotice`,以及中性的提示辅助函数 `describeOmitted`/`formatRetentionNotice`,且不依赖 Cordis 或任何工具包。单元测试覆盖具有精确省略计数的条目头部保留、文本头部保留、文本尾部保留、首尾字节保留、零预算、UTF-8 边界处理(2、3、4 字节码位,以及每个裁切位置上的无效起始字节)和未知省略量的措辞。 + +**已记录但尚未迁移的内容。** `glob`、`grep`、`bash`、`web_fetch` 与 `web_search` 的映射已记录在[包 README](../../../../packages/util/retention/README.md) 中,但本次改动并未把每个工具都迁移到该库;迁移工作刻意留作独立的后续任务。`read` 被明确记录为不在范围内:其 `read-render` 行窗口契约(`offset`/`limit`、`totalLines`、offset 范围错误、逐行预览截断,以及针对所选窗口的字节上限)不属于通用保留,而一个 `Omitted` 计数也无法同时表达行窗口两侧。 + +**该库维持的边界。** `truncated` 表示 retainer 因预算省略了原本可用的内容,绝不表示上游不完整。工具专用状态,包括 `incomplete`、权限失败、提供方局部失败、跳过二进制文件、bash 落盘路径恢复和无效 UTF-8,均留在工具领域字段中、位于 retainer 之外。未来改动迁移某项工具时,该包的 README 与测试必须证明,除了有意改变的提示措辞外,模型可见的结果文本没有变化。 + +**接受的取舍。** v1 接口刻意只支持条目的 `head` 保留,以及文本的 `head`/`tail`/`headTail` 保留;窗口、分组预算、感知排序的上限和上游停止控制,要等第二个消费方证明需求后再引入。文本保留按字节计数,以保障进程/正文安全;字符级和行级预览预算继续由具体工具负责。 + +## 考虑过的替代方案 + +**只进行事后 `truncate(text)`。** 不予采纳:它适合 Codex 的历史/工具输出截断场景,却会丢失条目计数、分组边界、UTF-8 安全的字节窗口与精确省略元数据。 + +**使用一个带可插拔回调的通用 `Collector`。** v1 不予采纳,因为它会掩盖两种重要的资源模式。逻辑条目保留按条目计数;文本保留按字节计数并维持 UTF-8 边界。独立的 `ItemRetainer` 与 `TextRetainer` 名称明确表达这种差异,同时保持 API 精简。 + +**把 `read` 窗口交给 `ItemRetainer`。** v1 不予采纳:`read` 是当前唯一的窗口消费方,其语义属于文件分页,而不是通用保留。一个 `Omitted` 计数无法表示行窗口两侧,而且 `read` 还携带 `totalLines`、offset 范围错误、逐行预览截断和针对所选输出的字节上限。让 `read-render` 由工具所有,可以避免共享库围绕一项特例膨胀。 + +**让截断成为 `ToolExecutionResult` 的一部分。** 不予采纳:工具注册表将不得不理解工具专用的恢复指引、分组、行号、退出状态和提供方语义。保留是由工具的 Native renderer 使用的库;模型可见投影继续由工具所有,而[规范值](2026-07-20-canonical-tool-output-contract.md)可以保留完整的已采集结果。 + +**在每个面向模型的工具 schema 中公开上限。** 不作为默认方案:Claude Code 的 grep 公开 `head_limit`/`offset`,但本 harness 会把常规预算保留为部署配置,除非模型确实需要控制分页。未来可以为具体工具增加类似 read 的续传字段;它不属于共享保留原语。 diff --git a/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.i18n.yaml new file mode 100644 index 0000000000..c241ef4ece --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.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 +2026-07-08-tool-output-spill-files.md: 7c0ca90452645d251559be25108d12883210d00e +2026-07-08-tool-output-spill-files.zh.md: 917d710eb8650e2797287578edd1b0d62813bbd3 diff --git a/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.md b/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.md index e2df9a902b..7c0ca90452 100644 --- a/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.md +++ b/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-08-tool-output-spill-files.zh.md) + ## Problem Tool outputs need bounded model-facing previews, but some oversized results are still useful later. A fetched page body or a verbose tool response should not consume the next model request in full, but the model should be able to inspect the complete formatted result later with existing file-reading tools. diff --git a/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.zh.md b/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.zh.md new file mode 100644 index 0000000000..917d710eb8 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.zh.md @@ -0,0 +1,195 @@ +# Agent Note: 工具输出落盘策略 + +Status: implemented + +[English](2026-07-08-tool-output-spill-files.md) | 中文 + +## 问题 + +工具输出需要有界的模型可见预览,但部分超大结果仍可能在之后有用。抓取的页面正文或冗长的工具响应不应完整占用下一次模型请求,但模型应能使用现有文件读取工具,在之后查看经过格式化的完整结果。 + +这项改动之前的行为并不一致。`dsh-bash-local` 已经会在内存尾部溢出时,把完整 stdout/stderr 流写入私有的临时落盘文件;普通文本工具结果则仍以内联形式返回,除非工具自行临时实现上限。[工具结果保留库](2026-07-06-tool-result-retention-library.md)负责预览机制,但不负责存储,也不负责把这些机制应用于最终工具结果的执行流水线策略。 + +其形态与超时策略设计一致:工具作者声明规范值与 Native renderer,由策略插件在渲染后的内容上执行部署默认的上下文预算。工具仍可在提供方采集上限处提前落盘;由工具负责的展示落盘可以保留已完整采集的规范值,而只替换展示内容。[规范工具输出契约](2026-07-20-canonical-tool-output-contract.md)规定了这项区分。 + +## 决策 + +在新的 `packages/spill/` 分组下增加一层轻量落盘存储 seam 和一个默认落盘策略插件: + +| 包(package) | 角色 | +|---|---| +| `@deepseek-ai/dsh-spill` | 接口:`ctx.spillStore`、词汇类型,不包含存储实现。 | +| `@deepseek-ai/dsh-spill-local` | 本地后端:在宿主文件系统中提供私有、会话作用域的文件存储。 | +| `@deepseek-ai/dsh-spill-policy` | 工具结果策略插件:包装分发后的最终文本结果,并以保留预览和落盘定位符替换超大结果。 | + +系统不增加专用的面向模型消费方包。消费方是现有 `ctx.tools` 执行流水线:`dsh-spill-policy` 通过 `tools/post-execute` waterfall(瀑布式事件)使用最终工具结果,模型则按照后端随定位符返回的检索提示读取内容。 + +### 落盘 seam + +存储 seam 保持最小化:保存文本,并返回定位符与检索提示。 + +```ts ignore-check +interface SpillStore { + saveText(input: SaveTextSpill): Promise +} + +interface SpillSource { + toolName: string + callId: CallId + label: string +} + +interface SaveTextSpill { + owner: { sessionId: SessionId } + source: SpillSource + suggestedName: string + content: string +} + +type SpillLocator = Branded<'SpillLocator'> + +interface SpillRef { + locator: SpillLocator + bytes: number + retrievalHint: string +} +``` + +`SpillLocator` 是一个[品牌化的](../../../../packages/util/brand)模型可见句柄,由后端返回。本地后端将其渲染为文件系统路径;远程或数据库后端可以渲染 URI、键或命令 token。消费方把它视为不透明值,并使用 `retrievalHint` 渲染,而不是假定 `read` 始终是正确的检索机制。`SpillOwner.sessionId` 是保存时的存储命名空间:fork 后的会话会从种子日志继承已有的落盘定位符,无需复制它们或重新取得所有权;fork 后的新落盘使用子会话 id。保留期清理可以连同其他旧会话产物一起使旧定位符失效;落盘 seam 不定义逐会话的清理策略。 + +`dsh-spill-local` 只负责存储细节:选择会话作用域的目录、安全名称、防止路径遍历、执行写入,以及返回 `{ locator, bytes, retrievalHint }`。它不负责保留策略、工具结果替换、搜索或文件检查。文件写入 `/session-/-`:`root` 是配置路径,或延迟创建的私有(0700)进程级临时目录;会话子目录是 `sha256(sessionId)` 的短前缀;叶节点由随机十六进制前缀与调用方的 `suggestedName` 组成,后者会被清理成单一路径段(与 JSONL 后端的 `encodeSegment` 一致)。系统使用 `open(path, 'wx', 0o600)` 写入,确保独占且仅所有者可访问,因此预先植入的符号链接无法重定向写入。定位符就是该路径,检索提示则告知模型可以在该路径上使用 `read` 或 `grep`。 + +### 落盘策略 + +`dsh-spill-policy` 是一个 `tools/post-execute` 结果转换器,只提供一个配置项: + +```ts ignore-check +interface Config { + /** Omitted means no automatic spill policy. Present means apply to oversized plain text tool results. */ + maxInlineBytes?: number +} +``` + +省略 `maxInlineBytes` 时,插件不会注册任何内容,是真正的无操作。设置该值后,它会对最终的纯文本工具结果应用默认策略: + +1. 让工具正常运行,通过 `next()` 委托,使下游监听器先结算结果。 +2. 仅当已接受的最终 `ContentBlock[]` 全部是纯文本时,才将其展平;含任何非文本块的结果保持不变。 +3. 如果 UTF-8 字节大小不超过 `maxInlineBytes`,保持不变。 +4. 如果超出上限,使用完整的最终文本调用 `ctx.spillStore.saveText()`。 +5. 把模型可见结果替换为保留的首尾预览和落盘引用。 + +预览属于策略所有的实现默认值:以 `maxInlineBytes` 为上限,使用保留库的 `TextRetainer` 进行首尾分割。只有第二种部署证明有此需求后,未来配置才会公开预览大小。 + +替换文本刻意保持通用,因为策略只知道最终格式化的工具结果,不了解工具的内部资源: + +```text + + +(Omitted N bytes. Full formatted result stored at: /.../session-.../....txt. Use read with offset/limit, or grep this path to search within it.) +``` + +如果 `ctx.spillStore.saveText()` 失败(权限、ENOSPC、后端不可用),或调用没有会话所有者,或未加载后端,插件会记录原因并原样返回结果。落盘失败绝不会把成功的工具调用变为 `isError` 结果,也不会隐藏内联结果。 + +策略跳过 `read`,以避免形成 `read -> spill file -> read again` 循环。额外的选择退出配置要等确实出现第二个有此需求的工具后再引入。 + +## 示例:web_fetch + +`web_fetch` 是首个示例,因为它天然会返回较大的文本结果,而且无需工具专用的落盘代码。该工具本身无需特殊处理: + +```ts ignore-check +ctx.tools.register(defineTool({ + name: 'web_fetch', + output: { + schema: WEB_FETCH_RESULT_SCHEMA, + render: (_args, value) => [{ type: 'text', text: formatFetchOutput(value) }], + }, + async execute(args, exec) { + const result = await ctx.web.fetch({ url: args.url }, exec.signal ? { signal: exec.signal } : undefined) + return result + }, +})) +``` + +配置 `dsh-spill-policy` 后,格式化后的大型 fetch 结果会自动保留并落盘。部署通过把提供方资源上限设得高于策略上限来展示此行为: + +```yaml +- id: web-fetch-local + name: '@deepseek-ai/dsh-web-fetch-local' + config: + maxBodyChars: 500000 + +- id: spill-local + name: '@deepseek-ai/dsh-spill-local' + +- id: spill-policy + name: '@deepseek-ai/dsh-spill-policy' + config: + maxInlineBytes: 50000 +``` + +这项分离很重要。`web-fetch-local` 仍负责资源上限(`maxResponseBytes`、`maxBodyChars`),用来保护网络、内存和解码工作。`spill-policy` 只负责结果已经存在后针对模型上下文的上限。如果提供方已经返回 `truncated: true`,落盘文件包含的是工具返回的完整格式化结果,而不是原始网页全文;策略不会做出其他承诺。 + +## 与保留和提前落盘的关系 + +保留与落盘存储相互独立: + +- `@deepseek-ai/dsh-retention` 负责预览机制(`TextRetainer`、`ItemRetainer` 和省略元数据)。 +- `@deepseek-ai/dsh-spill` 负责保存最终文本,并返回定位符与检索提示。 +- `@deepseek-ai/dsh-spill-policy` 在工具流水线中应用默认的最终结果策略,将前两者组合起来。 + +最终结果策略不能取代由工具负责的提前落盘。部分有用内容并不存在于最终 `ToolExecutionResult.content` 中: + +- `bash` 的最终输出已经是尾部内容加临时落盘路径;完整的 stdout/stderr 流位于执行器文件中。 +- `subagent` 的最终输出是子 agent(智能体)的最终回答,而不是子 agent 的执行轨迹。 +- 未来的工具可能生成从未出现在最终 `ToolExecutionResult.content` 中的运行时产物。 + +这些场景可以在后续工作中直接使用 `ctx.spillStore`,不属于首个示例的范围。 + +## 非目标 + +- v1 不增加面向模型的 `artifact_read` 或 `artifact_search` 工具。 +- v1 不增加逐工具的保留配置。 +- 不增加面向模型的超时/截断参数。 +- 不把 `read` 输出迁移到落盘文件。 +- 不取代 `web-fetch-local.maxBodyChars` 等提供方/资源上限。 +- 第一版不统一 bash 临时文件,也不采集 subagent 执行轨迹。 + +## 延后事项 + +- 用于现有执行器落盘文件的 `saveFile()`/`linkOrCopy`,这是统一 bash 行为所必需的。 +- 由工具负责的 subagent 执行轨迹落盘(`await run.result`,在 `run.dispose()` 前读取进程内子会话,保存 JSONL)。 +- 如果内置的 `read` 跳过规则不足,再增加逐工具退出或逐工具策略声明。 +- 面向 ACP(Agent Client Protocol)或远程环境的远程/数据库存储后端,因为本地路径在这些环境中没有意义。 +- 旧落盘文件的清理和保留策略,很可能与会话清理绑定。 + +## 测试 + +- `dsh-spill` 单元测试锁定 seam 契约:注册为 `ctx.spillStore`、每个上下文只允许一种实现,并在 dispose(资源释放)时释放。 +- `dsh-spill-local` 单元测试覆盖 `saveText`、`encodeSegment` 清理(分隔符/波浪号/完整路径段的点/空值)、会话哈希目录、仅所有者权限、每次保存生成不同路径、配置根目录/私有根目录,以及存储失败时的拒绝。 +- `dsh-spill-policy` 单元测试通过 `ctx.tools.execute` 驱动真实工具:禁用模式下无操作、替换超大文本、小结果/非文本结果保持不变、跳过 `read`、尽力回退(保存失败/无后端/无所有者),以及下游组合(限制已替换结果、保留 `additionalContexts`)。 +- `dsh-tool-web` 集成测试驱动 `web_fetch`,其实际执行路径经过 `ctx.tools.execute`,并使用真实的 `spill-local` 后端与策略;测试证明只有刻意加入的落盘提示会改变模型可见文本,而落盘文件保存完整的格式化结果。 +- `tui-agent` 示例加载 `spill-local` 与 `spill-policy`,因此其无密钥 Loader/PTY 冒烟测试会执行真实加载路径(namespace-plugin 导出形态与 `inject`)。 + +## 影响 + +默认策略只能看见最终格式化文本。它无法保留已经由提供方限制的内部内容,也无法保留从未成为结果一部分的运行时产物。第一版聚焦最终结果落盘而不是提前落盘,因此可以接受这一限制;由工具负责的提前落盘仍属于后续工作。 + +本地后端返回真实路径,使 v1 保持简单并符合已经验证的 agent 工具行为;seam 本身只承诺一个不透明定位符加检索提示,所以远程后端可以返回非文件定位符。 + +本地后端的价值取决于现有 `read`/`grep` 工具能否检查返回的本地路径,即使落盘目录位于会话 cwd 之外。目前这一条件成立,因为文件系统策略会记录观察结果并设置写保护,但不会把读取限制在工作区内。未来的工作区限制策略必须显式允许本地落盘路径,或改用检索提示指向受支持读取器的非文件落盘后端。 + +**快照缺口。** 目前没有 ACP 快照场景覆盖 transcript(文本记录)可见的 `web_fetch` 落盘提示。ACP 快照 harness 在无密钥环境中回放,无法访问实时 web,而 `web_fetch` 落盘需要一个真实的超上限 HTTP 正文;确定性场景需要一个预置的 loopback fetch 目标,但当前回放树尚未接线(示例根本没有加载 `tool-web`)。该行为改由 `dsh-tool-web` 针对 loopback server 的集成测试覆盖。弥补该缺口属于后续工作:把 `tool-web` 和预置 fetch 目标接入 ACP 示例,然后录制 `web-fetch-spill` 场景。 + +如果策略开始负责工具专用语义,就会膨胀得过大。它必须保持狭窄:只处理纯文本最终结果。由工具负责的提前落盘仍留作未来工作。 + +## 考虑过的替代方案 + +**要求每个工具通过保留声明选择加入。** v1 不予采纳,因为目标是实现类似 Claude Code 通用工具结果持久化的默认行为。只需一个 `maxInlineBytes` 部署配置项即可验证该形态。 + +**把 `tool-results` 建成宽泛的工具结果平台。** 不予采纳:宽泛的包名会诱使系统把保留策略、结果替换、预览措辞、搜索和提前落盘合并进一个 seam。可共享的存储部分更小:保存文本,并返回定位符与检索提示。 + +**使用 `ctx.fs.writeText` 或面向模型的 `write` 工具。** 不予采纳:工作区文件系统写入带有项目文件语义、写入/编辑策略、观察状态和面向用户的副作用。落盘文件是运行时产物,不是由模型编写的工作区改动。现有 `read` 工具之后可以检查它们,但创建操作属于运行时落盘 seam。 + +**让 `web-fetch-local` 不受限地抓取,只依靠 spill-policy。** 不予采纳:spill-policy 在最终工具结果已经存在之后才运行,无法保护网络、内存或解码资源。提供方资源上限仍然必须存在。 + +**把保留合并进落盘机制。** 不予采纳:保留与落盘职责不同。`TextRetainer`/`ItemRetainer` 决定保留哪部分预览、又省略了什么;落盘存储只负责保存策略要求的最终文本。 diff --git a/.agents/notes/implemented/feature/2026-06-24-workspace-context.i18n.yaml b/.agents/notes/implemented/feature/2026-06-24-workspace-context.i18n.yaml new file mode 100644 index 0000000000..e8e4c59638 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-24-workspace-context.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 +2026-06-24-workspace-context.md: 6acdb6241bcc57250e217cfc8856e8b0598d4622 +2026-06-24-workspace-context.zh.md: f165d08108931df21697c7895523f10ef816297f diff --git a/.agents/notes/implemented/feature/2026-06-24-workspace-context.md b/.agents/notes/implemented/feature/2026-06-24-workspace-context.md index 394c0de708..6acdb6241b 100644 --- a/.agents/notes/implemented/feature/2026-06-24-workspace-context.md +++ b/.agents/notes/implemented/feature/2026-06-24-workspace-context.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-06-24-workspace-context.zh.md) + ## Problem Repository guidance such as `AGENTS.md` belongs in a coding session's effective context so project conventions, build commands, and review rules arrive without repeated user pasting. The stdio and ACP products need the same behavior, isolated by session cwd: a global system-prompt section leaks one workspace's files into another live ACP session. diff --git a/.agents/notes/implemented/feature/2026-06-24-workspace-context.zh.md b/.agents/notes/implemented/feature/2026-06-24-workspace-context.zh.md new file mode 100644 index 0000000000..f165d08108 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-06-24-workspace-context.zh.md @@ -0,0 +1,89 @@ +# Agent Note: 工作区上下文指令文件 + +Status: implemented + +[English](2026-06-24-workspace-context.md) | 中文 + +## 问题 + +`AGENTS.md` 等仓库指引应当进入编码会话的有效上下文,使项目约定、构建命令和评审规则无需由用户反复粘贴即可生效。stdio 与 ACP(Agent Client Protocol)产品需要具备相同行为,并按会话 cwd 隔离:全局系统提示词章节会把一个工作区的文件泄漏到另一个仍在运行的 ACP 会话中。 + +相邻产品形成了值得借鉴的约定,但具体做法各不相同。Codex 原生使用 `AGENTS.md`;Claude Code 使用 `CLAUDE.md`,并采用熟悉的 system-reminder 风格用户上下文;opencode 同时支持这两个名称,每个目录只选一个胜出者,并延迟发现嵌套文件。harness 需要跨工具兼容,同时避免从同一作用域加载重复或互相矛盾的文件。 + +生命周期中有两类截然不同的内容。初始适用文件链足够稳定,可以放入请求前缀并受益于提供方前缀缓存。嵌套文件、编辑、候选项切换和移除都发生在会话启动后,应进入持久的仅追加历史,而不是被冻结的前缀。 + +## 决策 + +该实现在 `packages/context/workspace-context` 中,包(package)名为 `@deepseek-ai/dsh-workspace-context`。它是请求上下文扩展,不是核心服务或文件系统后端。共享 demo 主干与 Host Runtime 根据显式的 `{ maxBytes } | false` 部署选择挂载它;`dsh web` 启用 65,536 字节预算,Host Runtime 的 headless 消费方则禁用它。该插件使用 `agent/session-prefix`、`tools/post-execute` 和可选的 `ctx.fs` 功能。 + +插件不会静态注入 `fs`。因此,不带提供方的产品树仍能正常启动;在文件系统提供方出现之前,插件保持无操作。所有生产读取都通过该提供方完成。候选项探测会解析每个路径并对结果执行 stat,因此会跟随最终路径组件的符号链接至其目标:指向普通文件的链接会被加载,缺失路径或非文件目标则确认为不存在。允许仓库拥有的链接跨越信任边界,是对最初不跟随探测方式的刻意反转;[跟随指令符号链接记录](2026-07-21-follow-instruction-symlinks.md)负责说明该决策及其残余风险。会话前缀信号与动态工具执行信号会贯穿解析、元数据探测和流式读取,因此取消不会等待无关的文件系统扫描。解析或 stat 异常归类为不可用:它只跳过该候选项,绝不被解释为已经加载的作用域被删除。 + +### 文件名与优先级 + +默认的逐目录候选列表是 `['AGENTS.md', 'CLAUDE.md']`。该列表可通过 `instructionFileCandidates` 配置;`AGENTS.md` 是普通的第一候选项,而不是隐藏优先级。一个目录中只加载第一个存在的普通文件候选项。使用默认值时,`AGENTS.md` 是原生文件,`CLAUDE.md` 是兼容性回退。第二个列表 `localInstructionFileCandidates`(默认为 `['AGENTS.local.md', 'CLAUDE.local.md']`)会在同一目录的基础文件后加载叠加式本地覆盖层;[默认本地覆盖层记录](2026-07-21-local-instruction-overlay.md)负责说明该决策。 + +候选条目必须是同一目录中的文件名。空条目、`.`/`..`,以及包含 `/` 或 `\` 的条目会被忽略。其他同目录名称可以显式选择加入;规则目录和导入语义不属于本契约。 + +用户全局文件固定为 `$DSH_HOME/AGENTS.md`,不受任一候选列表影响,也没有本地覆盖层。`$DSH_HOME` 默认为 `~/.dsh`,与 `~/.codex` 或 `~/.claude` 在 harness 层的 home 角色一致,而不会引入插件专用 home。波浪号展开与默认值位于 `dsh-paths` 中,以便未来的 harness 功能共享同一约定。 + +### 基线前缀 + +agent loop(智能体循环)实例的第一次请求会让插件通过 `agent/session-prefix` 提供一条 user 角色消息。它先加载用户全局文件,再从 `agent.session.header.cwd` 向上遍历至配置的根标记(默认为 `.git`)以确定项目根目录,随后从根目录至 cwd 的每级目录各加载一个候选项。`.git` 文件与 `.git` 目录都是有效标记,因而能覆盖链接 worktree 和 submodule。找不到标记时,cwd 本身就是根目录。 + +插件会在 `await next()` 返回前前置其贡献,因此会话前缀贡献按插件注册顺序出现。在产品主干中,工作区指令的注册先于 skill 目录,所以它排在前面。循环会深度冻结组合后的前缀,将其记录在 `EpochHeader.messagePrefix` 中,并在该实例内逐字复用。它是请求状态,不是 `Session.deriveMessages()` 历史。 + +恢复 agent 会创建新的循环实例,并使用当前文件重新组合基线;新的前缀由恢复请求 header 锚定。这样,恢复时可以使用当前基线内容,而无需修改先前实例已经使用过的前缀。 + +基线是一条 user 角色的 ``,包含 `Instructions from: ` 章节,以及明确的权威性与优先级说明。这种熟悉的模型可见框架避免引入 harness 专用的 XML 词汇。项目路径相对于根目录;使用默认 home 时,用户全局路径为 `~/.dsh/AGENTS.md`,使用已配置 home 时则为 `$DSH_HOME/AGENTS.md`。文件内容中的字面量 `` 会被转义。包 README 负责规定当前准确的[提示词形态](../../../../packages/context/workspace-context/README.md#prompt-shape)。 + +### 动态发现与刷新 + +第一方 `read`、`write` 或 `edit` 调用成功后,`tools/post-execute` 监听器会协调被触及的后代路径链,以及该会话已经知道的每个作用域。新到达的作用域通过 `additionalContexts` 返回,并在下一次请求中使用 `Additional instructions from: ` system-reminder。在 Code Mode 下,`run_code` 会把子分发上下文延后至其外层结果,因此同一更新只会在父结果之后追加,而不会在调用中途注入。 + +内容编辑会追加 `Updated instructions from: `,说明新内容取代先前内容,并包含当前的完整文件。如果优先级从一个候选项变为另一个,消息还会指出先前路径并说明它不再适用。如果没有候选项保留,插件会追加 `Instructions removed: `,并说明先前加载的指令不再适用。 + +动态消息在 `content` 中携带完整的 system-reminder 框架;每个 `context/message` 都作为 user 角色消息逐字抵达模型,核心层不会再添加可选择退出的包装。`context/message.meta` 携带不透明 JSON 状态,该状态会持久化,但绝不会渲染给模型。 + +shell 命令不会触发发现。本地 bash 调用会启动全新的 shell,而从任意命令字符串推断已到达路径,需要实现提示词插件并不拥有的 shell 语义。 + +### 重复抑制与变更检测 + +每个动态工作区上下文事件都会存储带版本的元数据,其形态为 `{ action, scope, path, digest? }`;`digest` 是对已加载内容计算的 SHA-1。模型可见提示词中没有 HTML 注释、隐藏标记,也没有会被解析回状态的标题。 + +协调时,插件扫描自身拥有的 `context/message` 事件,并派生每个可见作用域的最新状态。一个简短的逐会话待处理映射只会在不可变的顶层 `tools/result` 证明某个 `additionalContexts` 条目经过所有 post-execute 监听器后仍然保留时开始记录;随后,它覆盖循环将该上下文追加到日志之前的间隔。每个条目记录开启状态的 `{ turn, step }`:如果相同的持久 `context/message` 出现在其序列边界或之后,该条目得到确认并被移除;如果匹配的 `step/end` 先到达,则说明循环丢弃了上下文缓冲区,插件会同时移除待处理条目及其版本缓存快速路径。嵌套的 Code Mode 结果会把变更暂存在父级的不透明执行 token 下,确保一次运行中的重复子分发不会产生重复项;父级结果会回滚这份临时状态,并且只提交外层策略保留的上下文。 + +路径和 digest 均未变化时会被抑制。日志中的移除操作是一条墓碑记录,因此重新出现的候选项会成为新的 `set`。恢复操作从持久化元数据继续工作。如果压缩(compaction)从可见表面移除某条指令事件,该状态不再抑制后续加载,这与模型已经无法看见它的事实一致。只有真正纳入字节预算的变更才会进入元数据或待处理状态,因此被省略的文件在之后的触碰中仍有资格加载。 + +被冻结的基线会保留一个内存中的 path/digest map 以供比较。后续成功的文件系统触碰会把基线编辑或移除操作追加为动态消息,绝不重写前缀。恢复时重新组合前缀的过程中,插件还会协调可见的动态作用域,因此 agent 离线期间发生的嵌套变更可以在第一次恢复请求前追加更新。 + +系统刻意不使用文件监视器。检测发生在下一次成功的结构化文件系统触碰或恢复时的前缀组合。提供方失败不会产生移除;只有该作用域中的全部已配置候选项都成功完成探测后,系统才接受「不存在」这一结论。 + +### 字节预算与有界读取 + +`maxBytes` 是必填项,分别作用于渲染后的基线或单个动态协调批次;系统不存在隐式或无界的渲染预算。非正数或非有限值会禁用加载。内容超过预算时,系统会先省略较宽泛的文件,再截断最具体的文件。可见的 `Workspace instruction budget ...` 提示会指出被省略和截断的路径与字节数,并且输出绝不超过配置字节数。 + +`maxSourceBytes` 是正数的逐文件上限,默认为 1 MiB。loader 会在读取前检查报告的大小,同时仍通过 `streamText()` 消费内容并持续统计 UTF-8 字节数,因此缺失/陈旧的元数据无法迫使其进行无界分配。过大的胜出候选项会被视为不可用,而不是改为同目录中的下一个名称。插件刻意不保留进程级缓存,也绝不保留指令正文。它只为每个有效作用域保存 `{ path, version, digest }`,并将这些状态放在 `WeakMap>` 中:提供方 `FsVersion` 与有效提示词状态同时匹配时跳过读取;版本变化则触发有界读取和 SHA-1 确认。SHA-1 仍是持久化在可见结构化元数据中的跨提供方内容标识;提供方版本只作为内存中的失效快速路径。模型可见变更的缓存转换只有在相应上下文通过完整的工具结果策略链后才会提交;如果该已接受上下文随后与中止步骤一起被丢弃、未能进入日志,缓存转换就会失效。 + +## 考虑过的替代方案 + +**使用全局 `ctx.systemPrompt.section()`。** 不予采纳,因为同一个 Cordis 上下文可以承载 cwd 不同的多个会话,而仓库所有的文本属于低权威用户上下文,不是最高权威的提供方系统内容。 + +**在每次 `agent/pre-step` 时注入基线。** 不予采纳,因为重复注入历史会浪费 token、使重复状态复杂化,并妨碍提供方前缀保持结构稳定。前缀组合提供冻结、已记录且逐实例的基线,动态仅追加消息则负责变更。 + +**在一个目录中同时加载 `AGENTS.md` 和 `CLAUDE.md`。** 不予采纳,因为正在迁移的仓库通常会在两个文件中重复指引。按顺序排列的候选项让优先级显式且可配置。 + +**解析渲染后的标题或隐藏注释以恢复已加载状态。** 不予采纳,因为指令正文可能包含相同文本,导致无提示的误报。持久化 JSON 元数据提供明确且对模型不可见的状态通道。 + +**使用模型总结文件。** 不予采纳,因为指令文件本身已经是经过整理的摘要;再执行一次模型调用既不确定,也可能抹掉边界情况要求。使用带字节预算的确定性全文更简单。 + +## 影响 + +工作区指引按会话隔离,并由 demo 前端、Web Host 与每一种工具展示模式共享。初始指令受益于稳定的前缀缓存,嵌套与变更内容则保持持久且可回放。通用的 session/agent 上下文契约通过 prompt-submit 与工具执行后的 `additionalContexts` 数组携带 JSON 元数据,而不会把条目展平。 + +仓库文本仍是不受信任的输入。低权威 user 角色框架、显式优先级说明和分隔符转义可以降低风险,但无法消除提示词注入。跟随候选符号链接到目标,会把该接口扩大至树外内容;因此,把 `ctx.fs` 限制在可信根目录内的权限与沙箱层才是真正的边界,它们让系统把工作区文件当作数据而不是权威([跟随指令符号链接记录](2026-07-21-follow-instruction-symlinks.md)负责说明残余风险)。 + +系统由事件驱动,而不是文件监视器驱动。除非文件系统变更通过结构化工具完成,否则编辑不会在确切的文件系统变更时刻可见;外部文件变更会在下一次成功的结构化触碰或恢复时被发现。这使设计保持确定性并且与提供方无关。 + +## 延后事项 + +从 bash 派生路径报告、递归启动扫描、文件监视器、小写默认名称、`.claude/CLAUDE.md`、`.claude/rules/*.md`、导入指令、ACP `additionalDirectories`、信任确认和模型生成摘要均延后处理。项目目录中的 `.local.` 覆盖层现已默认加载([默认本地覆盖层记录](2026-07-21-local-instruction-overlay.md)负责说明该决策);用户全局覆盖层、目录规则系统和导入仍需要各自的优先级与信任设计。 diff --git a/.agents/notes/implemented/feature/2026-07-07-plan-mode.i18n.yaml b/.agents/notes/implemented/feature/2026-07-07-plan-mode.i18n.yaml new file mode 100644 index 0000000000..4ceac02ce9 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-07-plan-mode.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 +2026-07-07-plan-mode.md: 4265ecdb9fcc022e8b9117ec18f46b9093ce99b8 +2026-07-07-plan-mode.zh.md: f9a734af87e34e946b94da8d7aa656dde78269ec diff --git a/.agents/notes/implemented/feature/2026-07-07-plan-mode.md b/.agents/notes/implemented/feature/2026-07-07-plan-mode.md index f5b76fae5b..4265ecdb9f 100644 --- a/.agents/notes/implemented/feature/2026-07-07-plan-mode.md +++ b/.agents/notes/implemented/feature/2026-07-07-plan-mode.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-07-plan-mode.zh.md) + > **Superseded vocabulary (2026-07-22):** [Collapse named session modes into plan mode](../simplification/2026-07-22-plan-specific-collaboration-state.md) replaces this note's generic `dsh-mode`, `mode/set`, definition map, and `ctx.modes` design with the current plan-specific `dsh-plan-mode`, `plan/mode`, `{ section }`, and `ctx.planMode` contract. The review, boundary, reconstructability, and sandbox-orthogonality decisions below remain in force; generic API examples are retained as the historical design this simplification removed. > **Superseded ACP mapping:** [ACP as an automation-only protocol](../simplification/2026-07-23-acp-automation-only-protocol.md) removes the picker, config-option, and elicitation mappings described below. Plan mode remains available to human-facing interfaces. diff --git a/.agents/notes/implemented/feature/2026-07-07-plan-mode.zh.md b/.agents/notes/implemented/feature/2026-07-07-plan-mode.zh.md new file mode 100644 index 0000000000..f9a734af87 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-07-plan-mode.zh.md @@ -0,0 +1,196 @@ +# Agent Note: plan mode——记录到日志的逐 agent 会话模式 + +Status: implemented + +[English](2026-07-07-plan-mode.md) | 中文 + +> **已取代的词汇(2026-07-22):**[将具名会话模式收敛为 plan mode](../simplification/2026-07-22-plan-specific-collaboration-state.md) 已将本笔记中通用的 `dsh-mode`、`mode/set`、定义 map 与 `ctx.modes` 设计,替换为当前 plan 专用的 `dsh-plan-mode`、`plan/mode`、`{ section }` 和 `ctx.planMode` 契约。下文的评审、边界、可重建性与沙箱正交性决策仍然有效;通用 API 示例则作为此次简化所移除的历史设计保留下来。 + +> **已取代的 ACP(Agent Client Protocol)映射:**[ACP 作为仅面向自动化的协议](../simplification/2026-07-23-acp-automation-only-protocol.md)移除了下文所述的选择器、配置选项和 elicitation 映射。面向人类的接口仍可使用 plan mode。 + +## 问题 + +此次变更之前,harness 无法持久地让某个 agent(智能体)采用独特的工作姿态。Plan mode 要求 agent 在规划指引下探索和设计,产出可供评审的产物,跨过明确的审批边界,并在恢复与 fork 后还原该状态,同时不能让模型可见请求偏离会话日志。 + +既有扩展 seam 已经提供了周边机制:[`system-prompt/assemble`](../../../../packages/core/system-prompt/README.md) 为每个步骤塑造指引,已发送的请求则记录在 `request/header*` 事件中(参见[可重建性](../../implemented/architecture/2026-07-05-reconstructable-requests.md));[`ctx.userInteraction`](../../../../packages/ui/user-interaction/README.md) 承载审批问题与纠正反馈(参见 [ask-user 先例](../../implemented/feature/2026-06-25-ask-user-question.md));`SessionEventMap` 承载逐 agent 的持久事实(参见 [`todo/write` 先例](../../implemented/feature/2026-06-29-todo-write-tool.md))。缺少的是将这些 seam 连在一起的具名会话状态,同时仍让独立的沙箱轴与审批轴负责执行约束。 + +## 决策 + +交付项是 **plan mode**。它作为首个**会话模式**发布,即一个具名、记录到日志且逐 agent 生效的协作状态:模式定义是由部署配置、供模型查看的指引;对某个 agent 生效的模式则是从其日志折叠出的会话状态。模式构成一条轴,强制约束旋钮——沙箱模式与审批策略——构成其他轴;它们从不互相读写,这与 Codex 将 Plan/Default 协作预设同沙箱及审批设置分开的做法一致。新的产品包(package)`@deepseek-ai/dsh-mode` 位于 `packages/mode/mode/`,拥有事件词汇、精简的 `ctx.modes` 服务和全部监听器;循环无需改动。`plan` 是唯一的必需定义;采用模式形状的词汇,是为了以后增加第二种模式时无需重命名持久事件类型,而不是因为当前还会发布其他模式。 + +该状态是 `SessionEventMap` 的一个成员:**`mode/set`** 是只记录日志、不进入 surface 的事件,携带具有整值替换语义的 `{ mode: string }`;另有纯函数 `foldMode(events)` 返回生效模式,即最后一个 `mode/set`,没有该事件时则返回默认模式。由于[日志是事实通道](../../implemented/architecture/2026-06-30-event-domain-semantics.md),恢复、fork 和压缩无需额外机制即可还原模式,UI 则从 `session/event` 读取模式切换。默认模式表示不存在模式指引,即没有段落、过滤或门禁。加载 `dsh-mode` 后,每种模式仍会贡献同一个稳定的 `exit_plan_mode` schema;这项固定成本避免了模式边界处的工具目录抖动。 + +模式的所有外显行为都是软约束:`mode:policy` 提示词段落渲染当前定义的指引,而 `exit_plan_mode` 在每种模式下都留在已注册的工具目录中,仅当折叠模式不是 `plan` 时才在执行阶段拒绝。因此,转换只会在下一步骤改变可归因 `request/header` 中的系统提示词部分,从而在不改变 Native schema 或 Code Mode SDK 的情况下继续满足[可重建性](../../implemented/architecture/2026-07-05-reconstructable-requests.md)。模式有意不强制执行任何约束:没有执行门禁,不过滤工具,也不触及沙箱或审批旋钮。若用户希望规划期间存在硬性的只读下限,可以在模式选择器旁切换沙箱模式选项;二者先后顺序任意,任何一条轴都不会扰动另一条轴。同样也不存在逐模式的工具允许/拒绝清单;模式允许哪些工具属于副作用问题,在工具定义能够声明自身副作用前暂缓处理(见[延期工作](#deferred))。模式只依靠其段落指引与退出评审来约束行为。 + +模型通过 **`exit_plan_mode`** 工具离开 plan mode。其唯一参数是 plan 文本,因此可以从日志重建 plan;该工具自行通过用户交互 seam 完成评审:问题的辅助详情携带确切 plan,并提供选项与自由文本通道,而不是只有一项裸权限。审批通过后,记录到日志的模式切回默认模式;拒绝则成为携带用户逐字反馈的纠正错误,让模型能沿明确方向继续规划。用户可从任意接口通过 `ctx.modes.set()` 切换模式;切换会在下一个轮次边界应用(会话事件都封闭在轮次内),且只有模型可见状态确实变化时才向模型讲述一次。 + +## 高层 API + +### 一次端到端的 plan-mode 会话 + +用户通过 ACP 模式选择器或终端入口中的 `/plan [message]` 将会话切换到 plan mode;从下一步骤开始,每个请求都携带已配置的 plan 指引段落。如果给出可选消息,同一命令还会把它提交到受影响的步骤中。`exit_plan_mode` schema 在默认模式下已经存在,并会保持逐字节不变。 + +模型进行探索与设计;段落中的指引会让它把变更推迟到 plan 中。沙箱与审批旋钮保持用户设置的值不变;希望规划期间由内核强制只读的部署方(或用户),可以把 plan mode 与独立的沙箱模式选项配合使用。 + +准备就绪后,模型调用 `exit_plan_mode`,并把 plan markdown 作为参数;评审问题将这段确切 markdown 作为辅助详情,用户可以批准,也可以要求继续规划并自由填写反馈。Native 调用还会渲染 plan 卡片;Code Mode 嵌套分发没有 Native 卡片,因此评审详情是共用的呈现接口。 + +批准后,工具把记录到日志的模式切回默认模式:下一步骤会移除 plan 段落,但保留同一个工具目录(变化后的 header 已记录到日志),此后的执行跟踪本就由 `todo_write` 负责。要求继续规划时,模型会收到携带用户反馈文本的纠正错误,随后修改并再次呈现。 + +### 部署配置 + +模式定义是经过校验的插件 Config;依照仓库约定,它可以通过 `cordis.yml` 修改,无需编辑代码。部署必须提供完整的 `plan` 段落;该包不内置任何模型指令。其他模式使用同一份配置 map: + +```yaml +- id: mode + name: '@deepseek-ai/dsh-mode' + config: + modes: + plan: + section: | + You are in plan mode: explore and design, then present the + plan for approval through exit_plan_mode. +``` + +定义的精确形状是 `{ section }`;其中有意不提供逐模式工具清单或强制约束字段(见[常见问题](#faq))。定义名称使用小写斜杠命令子集 `/^[a-z][a-z0-9_-]*$/u`;`default` 是保留项(表示没有策略),不能用作键。名称无效或存在未知定义键——包括 `tools` 清单或 `access` 上限——会在加载时校验失败;未知模式名称则会在调用 `set()` 时大声失败。 + +### 在终端中 + +终端入口通过插件自有的命令注册表(`@deepseek-ai/dsh-commands`),为每个已配置定义获得一条进入命令:`dsh-mode` 为必需定义注册 `/plan [message]`,例如还会注册 `/review [message]`(当配置 `review` 时)。每条命令都记录其具名切换;非空的可选消息会去除首尾空白并传给 `agent.steer()`,后者会把消息放入运行中 agent 的下一步骤,或委托给 `send()` 以开启新的空闲轮次。命令名称与结果不会进入模型历史;这条显式消息则会作为所选模式下的普通用户消息记录到日志。合成的 `default` 条目不贡献命令。退出评审无需新机制即可直接在终端中提示:它是普通的用户交互问题,因此会进入组合后的用户交互提供方提示队列,与 `ask_user_question` 使用的队列相同。 + +### 通过 ACP + +模式选择器是该包的对外接口:`session/new`/`session/load` 会通告 `availableModes`/`currentModeId`,其值来自 `ctx.modes`(通过 `ctx.get` 机会式消费,沿用 `tool-bash` 模式);`session/set_mode` 调用 `set()` 并乐观通知 `current_mode_update`(待生效模式就是用户的选择,记录到日志的 `mode/set` 会在边界处跟进);`session/event` 监听器则会在每次已记录切换不同于最近一次已发送值时再次通知。退出工具复用用户交互 ACP 提供方的 elicitation 流程;其 ACP 映射会携带评审 `detail`,因为 Code Mode 嵌套分发没有 Native plan 卡片,而 Native 调用还可以额外流式传输该卡片。沙箱模式、审批策略和模型等单项环境旋钮不是模式,应归入 `session/set_config_option`(见[常见问题](#faq))。 + +### 面向 agent 创建方 + +`ctx.modes` 是完整的程序化接口:`list()` 返回已配置定义和供选择器使用的合成 `default` 条目;`get(agent)` 返回折叠模式与可能存在的待生效意图;`set(agent, mode)` 则根据 `list()` 的词汇校验名称,并记录将在边界应用的意图。`default` 始终是有效目标,因此退出模式与进入模式使用同一次调用。创建时没有模式选项;调用方在首个轮次前通过 `set()` 选择模式,随后以相同方式刷写。系统也不提供可订阅的实时 `agent/*` 镜像:UI 依照[事件领域语义](../../implemented/architecture/2026-06-30-event-domain-semantics.md)读取 `mode/set`,该事件来自 `session/event`。 + +## 详细设计 + +### 词汇 + +```text +'mode/set': { mode: string } // SessionEventMap merge in dsh-mode: log-only, non-surface, + // whole-value replace — the last one in the log wins +DEFAULT_MODE = 'default' // the fold of a log with no mode/set; reserved, not definable +``` + +载荷不携带原因/溯源字段:工具驱动的切换在日志中紧邻其 `tool/call`,用户切换则位于轮次边界,因此原因就在日志相邻位置。这与[可重建性 Agent Note](../architecture/2026-07-05-reconstructable-requests.md)针对请求头事实所作的「叙述字段可以派生」决策相同(进行中的 `env/state` 事件之所以携带 `source`,正是因为其漂移变体在日志相邻位置没有原因;二者形成对照,并不冲突)。模式名称是配置声明的词汇,不是不透明的跨边界 id,因此仍使用裸字符串(不使用 `Branded`)。 + +### 配置与解析步骤 + +```text +interface ModeDefinition { section: string } // prompt text — a mode's whole vocabulary +interface ModeConfig { modes: Record } // plan is required and owns its complete prompt +resolveConfig(config): ResolvedModes // explicit resolve (the dsh-bash template), fail-loud: + // missing plan, 'default', blank sections, and unknown keys rejected +``` + +单字段形状是有意采用的最简设计,并非最终词汇:逐工具策略维度会以工具定义中的副作用元数据形式回归(见[延期工作](#deferred)),在此处读取,而不是由每种模式重新声明;该维度到来时,配置形状不应需要迁移。 + +### 折叠、服务与刷写 + +`foldMode(events)` 是纯函数(导出供重建方与测试使用),直接折叠仅追加的会话日志;`mode/set` 不是 surface 节点,因此压缩无法遮蔽它。`set(agent, mode)` 根据 `list()` 的词汇校验名称,即已配置定义加上保留的 `default`;后者不能用作配置键,却始终可以作为 `set()` 目标。目标与待生效模式相同(没有待生效模式时则与当前模式相同)时,该方法丢弃无操作;其余情况会把 `{ mode, narrate }` 记录到 `WeakMap` 的待生效意图槽中。它不能立即追加,因为[每个会话事件都封闭在轮次内](../../implemented/architecture/2026-06-15-turn-enclosure-invariant.md),而空闲 agent 没有打开的轮次。 + +循环拦截 seam 上经过故障隔离的监听器(参见[防御模式](../../../../docs/defensive-patterns.md):策略插件不得阻塞提示词或轮次)会把待生效意图刷写为一条 `mode/set` 追加:`agent/prompt-submit` 在刚打开的轮次中、首次组装前触发;`agent/turn-continuation` 则在普通步骤关闭后、后续步骤开始前触发。自动请求恢复会绕过 continuation,因此,前置的 `agent/request-error` 包装器会先委托给组合后的策略和异步退避,只在 waterfall 返回循环前刷写 `retry` 决策;effect 作用域的生命周期守卫会抑制在插件资源释放后才恢复的已捕获包装器。三条路径都位于工具执行与日志发布之外(提交后的 `session/event` 观察器只负责观察),因此每个步骤都在其组装所折叠出的模式下运行。刷写模式与最后一个 `request/header` 处的折叠结果不同时,刷写会在同一帧中追加一条合并后的 `context/message` 通知(「用户已将此会话切换到 plan mode。」);面向用户的叙述情形列在[常见问题](#faq)中。 + +### 软层:计算得出的段落与稳定的退出 schema + +已注册的提示词段落从 `AssembleContext.agent` 读取调用 agent 的模式,并解析为当前定义的指引或 `''`。循环逐步骤渲染,并在渲染后的 header 发生变化时记录完整的 `request/header`,因此进入或离开模式均可归因。该段落在每种模式内保持静态,plan 本身则以消息和工具参数留在对话中;无需为了跨压缩保留状态,而在每个请求中重新注入独立的 plan 状态([既有方案](#prior-art)采用的办法),徒增提示词抖动。 + +指引贡献为 `{ name: 'mode:policy', order: 50, text: context => … }`:排在人设(0)之后、工具指引(100–199)之前,并在默认模式或没有 agent 的组装中为空。`exit_plan_mode` 只通过 `ctx.tools` 注册一次且从不过滤,因此模式切换期间 Native schema 与 Code Mode 生成的 SDK 保持逐字节相同;未部署 `dsh-mode` 的环境则没有这项绑定。系统不注册 `tools/pre-execute` 监听器:模式不设置任何门禁,退出工具自身的折叠模式检查会拒绝 plan 之外的调用。退出评审是一个带选项和反馈的问题,不是权限,因此位于工具通过用户交互 seam 执行的过程内。 + +### `exit_plan_mode` + +`defineTool` 有一个必填的 `plan: string` 参数。Native 执行会把它记录在普通 `tool/call` 中;Code Mode 在执行前记录外层 `run_code` 源码,并在分发结算后把规范化的嵌套参数追加到 `tool/code-dispatch`。`execute` 会拒绝没有 agent 的调用(沿用 [`todo_write` 先例](../../implemented/feature/2026-06-29-todo-write-tool.md))和折叠模式不是 `plan` 的调用,并在询问评审人前拒绝空 plan 或不含标题的 plan;随后,它通过 `ctx.userInteraction.ask()` 发起一次单选评审,其 `detail` 是确切 plan,并开放自由文本反馈,供用户批准或要求继续规划。只有恰好选择一个 `Approve` 才表示同意,其他任何形状都按失败关闭处理。批准会记录一项将在边界生效且不叙述的意图,用于切换到 `default`,并返回简短确认。部署指引要求模型把这次调用作为回复中唯一且最后一次工具调用;如果模型违反该规则,运行时仍会让该批次剩余部分保留 plan 指引,下一步骤才记录变化后的 header,其中移除指引而工具 schema 保持不变。所有未获批准的结果都会返回纠正性的 `isError`,并让模式留在 `plan`。 + +其[渲染意图](../../implemented/architecture/2026-07-02-tool-render-intent-union.md)在设计之初就已确定:`presentCall` 是 `generic` 卡片,以 plan 的首个标题命名、以 plan markdown 作为内容,另配一张 `generic` 结果卡片。Native 入口会在问题之前显示该卡片;Code Mode 嵌套分发不会产生 Native 调用卡片事件,因此用户交互 `detail` 会在每个提供方上独立携带同一份 plan。系统机会式消费该 seam(`ctx.get('userInteraction')`),所以 `dsh-mode` 在没有它时仍可组合,并降级为[常见问题](#faq)中确定的手动退出方式。 + +### 依赖与接口 + +`dsh-mode` 是一个产品包,而不是由三个包组成的能力 seam(见[考虑过的替代方案](#alternatives-considered)):它对等依赖 `cordis`、`dsh-session`、`dsh-agent`、`dsh-tools` 与 `dsh-system-prompt`,注入 `['tools', 'systemPrompt']`,并在执行时机会式读取 `ctx.userInteraction`(指向 `dsh-user-interaction` 的仅类型对等依赖边);其仅有的 UI 侧边也是可选的仅类型对等依赖(逐定义进入命令使用 `dsh-commands`)。除 `ctx.modes` 调用接口外,所有内容都通过监听器参与,因此移除该包会平稳移除模式,而不会破坏消费方。终端入口无需模式专用代码:组合命令注册表后,`dsh-mode` 会自行注册每个定义的命令(指向 `dsh-commands` 的可选仅类型对等依赖边),退出评审则使用组合后的用户交互提供方提示队列。[高层 API](#over-acp) 已确定 ACP 协议映射;在包关系上,桥接层对 `dsh-mode` 采用仅类型对等依赖边并机会式读取服务,所以不含该插件的桥接层行为与当前完全相同。 + +### 已记录场景与 harness 操作 + +`input.json` 新增一种步骤操作 `{ "op": "setMode", "modeId": "plan" }`,通过真实的 `session/set_mode` RPC 驱动,并配有脚本化的 `elicitationAnswers` 队列。`plan-mode` 场景在第 1 个轮次前进入 plan,在独立配置的沙箱下运行真实的 `cat`,通过 `exit_plan_mode` 呈现 plan,接收脚本化审批,然后在下一步骤编辑。首个 `request/header` 包含完整、稳定的工具集和已配置模式段落;批准后变化的 header 会保留逐字节相同的工具 schema,只移除该段落。`plan-mode-reject` 固定纠正性的自由文本反馈和未变化的 plan 状态。两份记录都在 Seatbelt 或 bwrap 下回放宿主命令;后端特有的沙箱拒绝仍留在 bash 工具单元层。 + +### 机械收尾 + +系统不声明新的 Cordis 事件(`mode/set` 通过 `session/event` 传递,监听器附着到现有 waterfall),因此事件目录不变。同一变更重新生成以下内容:持久化日志目录(`mode/set`)、服务目录(`ctx.modes`,JSDoc 完整)、配置目录(`ModeConfig`)、工具目录(`exit_plan_mode`)、生产方/消费方 map 与文档图,以及模块图。仓库接线包括:根 tsconfig 的 `paths` 条目、新包组 README 和[包索引](../../../../packages/README.md)中的一行(新增顶层包组正是该表所命名的有意操作)、`architecture.md` 中经过预算检查的 `ctx.modes` 能力服务行,以及实操手册对应行的升级。 + +## 延期工作 + +以下各项都需要独立决策:通过转发的创建时模式选项实现 subagent 模式继承(由于没有消费方而移除,将随首个消费方回归);`plan` 之外的预设模式(只读、接受编辑);若待生效意图丢失被证明是真实问题,则引入空闲记录原语;以及最重要的**在工具定义上自行声明副作用**,即逐工具的只读/变更分类(MCP `ToolAnnotations` 词汇——`readOnlyHint`/`destructiveHint`——是自然模板,其中对不可信提示的警告意味着还需区分信任层级)。通用的逐模式工具策略正在等待这一项:本 Agent Note 最初发布过临时的逐模式名称允许清单,并在发布前移除;手工维护的清单错误地表达了副作用问题,必须跟踪部署所组合的每个工具,且会随工具增加而无声腐化。因此,按模式限制的工具可用性(以及逐工具 `ask` 策略)会作为已声明副作用的消费方回归,而首项消费需求就是其重启触发条件。 + +ACP 自动化组合不挂载 plan mode 或问题工具。面向人类的组合拥有 plan 选择与评审;聚焦的 plan-mode 测试和交互接口快照会固定其已记录状态、指引、评审和稳定工具 schema。 + +## 常见问题 + +以下内容澄清选定设计的行为;遭否决的设计见[考虑过的替代方案](#alternatives-considered),已接受的代价见[后果](#consequences)。 + +**用户切换模式后何时生效?** 在下一个组装前边界生效:`agent/prompt-submit` 覆盖首个步骤,`agent/turn-continuation` 覆盖普通后续步骤,组合策略之后的 `agent/request-error` 重试决策覆盖自动恢复。因此,在请求或重试退避进行期间选择的模式会塑造下一次模型请求。这就是[既有方案](#prior-art)中每项产品都采用的「应用于后续请求」语义。 + +**何时向模型讲述模式变化?** 仅当模型可见状态确实变化时:刷写会把刚刷写的模式与最后一个 `request/header` 处的折叠结果进行比较,并合并讲述一次。净变化为零的切换序列(先进入 plan,再在边界前切回)不会产生叙述;工具驱动的退出只通过自身工具结果叙述;首个轮次前设置的模式也不叙述,因为该段落本身就是状态说明。该原则来自进行中 env-state 提案的边界叙述:如果提示词表层悄然切换,transcript(文本记录)仍会依据 header 已不再具备的状态进行论述。 + +**恢复时,配置已不再定义折叠出的模式会怎样?** 当前配置不再定义的折叠模式名称会在不通知的情况下表现为默认模式,因此会话既不会获得替代约束,也不会变得不可用。`set()` 的大声校验只覆盖写入路径;恢复后的日志以当时找到的配置为准。 + +**如果部署没有组合用户交互提供方,会怎样?** Plan mode 仍然安全,但只能手动退出:`ctx.userInteraction.ask()` 会抛出 `NO_PROVIDER`(seam 不存在时甚至无法解析到该服务),工具返回纠正性的 `isError`,退出方式降级为由用户切换模式,绝不会在未经评审时退出。模式段落会要求模型通过 `exit_plan_mode` 呈现 plan,并在失败时改用普通文本询问用户,因此模型会继续呈现,而不会停滞。 + +**为何没有逐模式工具允许清单?** 因为「哪些工具在规划模式下安全」是每个工具自身的属性(即副作用),不是模式的属性。逐模式名称清单会在错误的归属位置重新声明该事实,必须枚举部署所组合的每个工具(包括 MCP 服务器),且会随工具到来而无声腐化。在工具定义声明其副作用前(见[延期工作](#deferred),其中归档了被移除的临时允许清单及其重启触发条件),模式只通过自身段落和退出评审约束行为;由此产生的暴露面属于已接受代价(见[后果](#consequences))。 + +**subagent 是否继承父级模式?** fork 子级可以直接继承,因为父级的 `mode/set` 位于种子前缀中。spawn 子级从默认模式开始;创建时模式选项与 subagent 提供方的自动转发一并延期(见[延期工作](#deferred))。 + +**plan mode 与沙箱只读模式有何关系?** 二者是互不接触的独立轴:模式是协作姿态(`mode/set` 折叠),沙箱模式是强制约束旋钮(`bash/sandbox-mode` 折叠,参见[沙箱 Agent Note](2026-07-06-sandbox.md))。Plan mode 既不读取也不限制沙箱模式,与 Codex 将 Plan/Default 预设同沙箱及审批设置分开的做法完全一致。希望规划期间由内核强制只读的用户需要同时设置两者:以任意顺序切换模式选择器与沙箱模式选项;每次切换只改变自身折叠结果,因此二者互不干扰,也不存在可能崩溃的还原步骤。日志会把每条轴归因到各自事件:协作姿态对应 `mode/set`,隔离约束对应 `bash/sandbox-mode`。 + +**为何沙箱模式、审批策略或模型本身不属于模式?** 它们是独立于协作状态的单项环境旋钮。已退役的 ACP 映射记录在[仅面向自动化的协议决策](../simplification/2026-07-23-acp-automation-only-protocol.md)中。未来模式定义可以捆绑环境事实(在挂载处通过 `ctx.envState` 应用),让 Codex 风格的预设仍是一种模式;但把审批策略融合进模式概念本身的方案已在[考虑过的替代方案](#alternatives-considered)中遭否决。 + +## 既有方案 + +对已发布 plan mode(Claude Code、Cursor、Copilot、OpenCode、Gemini CLI、Cline、Windsurf、Codex)的调研表明,各产品都包含同样五个部分:低权限工具策略、plan 产物、审批时刻、执行状态切换,以及[问题](#problem)所依赖的持久状态。 + +只要产品公开模式接口,该接口就一定是清单,绝不是布尔值:Claude Code 的选择器提供 `plan`,旁边是 `acceptEdits`(另有自动进入 plan 的模式);Codex 则把 `Plan` 与 `Default` 并列公开为协作模式预设,同时让审批和沙箱设置保持独立。ACP 传输层不公开这项面向人类的控制。 + +由部署拥有的示例提示词借鉴工具性行为,而非产品特有机制。它借鉴 Codex 的以下做法:即使收到祈使式实现语言也留在 plan mode;提问前先探索;区分仓库事实与由用户决定的选择;让 plan 完整覆盖 API、数据流、失败、测试和假设,从而足以作出决策。它还借鉴 Claude Code 的以下做法:禁止变更与提交;优先沿用现有模式;只针对需求或方案选择提问;通过退出工具完成规划,而不在普通文本中请求审批。它有意省略 Codex 协议标签,以及 Claude 的 plan 文件或分阶段 subagent 机制,因为这些属于各自运行时,而非本插件契约。 + +把模式留给约定的生态展示了应避免的失败形态。Pi 风格的模式扩展会争抢一个后写覆盖的全局活跃工具清单,只靠提示词文本强制「只读」(模型幻觉调用一个仍已注册的工具时,该调用会实际执行),并在每个请求中重新注入 plan 状态以跨过压缩。这里通过逐 agent 的折叠状态,以及压缩无法遮蔽的只记录日志、非 surface 事件,从结构上消除了有争议的全局清单和重复注入补丁。相较之下,仅靠提示词的形态被有意保留:Codex 的 Plan 正是如此实现,这也是模式轴可以与强制约束轴自由组合的原因。需要硬性下限的部署会把模式与独立的沙箱旋钮配对,而不是让模式携带自身强制约束(见[常见问题](#faq))。 + +## 考虑过的替代方案 + +**以权限模式作为核心概念(Claude Code 的形态)。** 用一个 `permissionMode` 融合审批策略和工具策略。本设计中,它们是归不同所有者负责的两条轴:审批 seam 拥有「谁回答这个问题」,模式拥有「模型获得什么接口」。ACP 将二者建模为相关但有区别的概念(模式以后可以选择审批策略;届时是模式定义增加字段,而不是合并两者)。 + +**由三个包组成的能力 seam。** 接口/实现/消费方适合可替换后端;模式的可变部分是配置值,而不是实现。拆分会制造一个空实现包,与审批 seam 及 [`todo/`](../../implemented/feature/2026-06-29-todo-write-tool.md) 作出的「不要过早拆分」决策相同。 + +**由循环拥有模式状态。** 依据既有规则(用插件,而不修改循环)予以否决:该功能所需的每个钩子——组装、执行前处理、轮次边界、会话事件——都已经是有文档记录的 seam,修改循环只会增加耦合,别无收益。 + +**带默认拒绝门禁的逐模式工具允许清单(首个发布形态)。** 已在发布前移除。手工维护的名称清单会逐模式重新声明一项逐工具事实(即其副作用):它必须枚举部署所组合的每个工具,包括 MCP 服务器和未来注册项,并会随工具增加而无声腐化(新增只读工具时,在有人编辑每种模式前都会被阻止;编写负担落在了解模式的人身上,而不是了解工具的人身上)。它还过度承诺:该清单看似安全边界,但 shell 之外的任何能力其实都不存在这种真实边界。通用维度已停放到副作用自声明(见[延期工作](#deferred));由此产生的后果——plan mode 只提供指引,也就是该门禁一度弥补的 Pi 缺口——是有意接受的,并计入[后果](#consequences)。 + +**模式上的 `access` 沙箱上限(第二个发布形态)。** 同样已在发布前移除。`ModeDefinition.access` 会把 bash seam 的逐调用沙箱解析限制在模式声明的上限内(一个 `bash/resolve-mode` waterfall 加上取阶梯最小值的监听器;守卫会在执行器无法施加约束时隐藏 bash,并在模式中途拒绝提升权限)。状态仍保持正交,因为上限从不写入沙箱旋钮;但两条轴并不正交:进入 plan 会改变沙箱实际强制执行的内容,把协作姿态与强制约束级别融合起来,违背评审最终达成的 Codex 形态分离方式(Plan/Default 预设从不触及沙箱或审批设置)。这种融合有一项用户可见症状:规划期间把沙箱选项切换为 `workspace-write` 不会产生任何效果。上限、waterfall 和 mode→bash 依赖边随后一并移除;部署可以把模式与独立沙箱模式选项配合使用,从而在规划期间由内核强制只读。以后也可以重新引入模式触发的预设(模式定义捆绑建议的旋钮值,并作为普通旋钮切换加以应用),而无需再次融合两条轴。 + +**仅存在于运行时的模式(只在 UI 或桥接层本地存在,不记录日志)。** 恢复与 fork 会悄然丢失模式,模式引起的 header 增量在日志中也没有可归因原因。记录到日志的状态让模式无需额外机制即可审计和还原。 + +**把模式切换作为 `context/message` 并通过 `agent.inject()` 写入。** 这样可以复用现有的轮次封闭路径,却会把策略状态放入模型 transcript;模型无需被告知两次(段落已经告诉它),而只记录日志的事实不应占用 surface。 + +**plan 文件存储(`.plans/` 目录)。** 这会为日志已经以可回放方式承载的内容创建第二个持久归属位置;需要文件的部署可以添加一个写入文件的工具。同一事实只应有一个归属位置。 + +**用布尔值 `planMode` 取代具名模式。** 对仓库已经跟踪的接口而言过于狭窄:ACP 通告的是模式清单,已发布的选择器也不只填入 plan(见[既有方案](#prior-art));以后再泛化会重命名持久事件词汇。字符串形状的机制现在不产生额外成本;只有 `plan` 作为定义发布。 + +**工具策略栈服务(对 Pi 批评的补救方案)。** 现在就为工具策略建立专用组合服务为时过早:本实现不执行按模式限制的工具过滤,未来的副作用策略可以通过现有带守卫的执行 seam 组合。只有已声明的工具副作用产生具体组合需求后,才应正式建立该服务。 + +**通过审批 seam 执行退出审批(一个 `{ kind: 'ask' }` 门禁决策)。** 最初草案提出该方案;当时审批 seam 是唯一正在落地的询问机制,所以显得自然,但它把评审放进了权限的位置。该 seam 的结果词汇有意封闭且仅供单次使用(`allowed-once`/`rejected`),因此拒绝无法携带反馈,批准也永远无法增加选项(例如「批准并接受编辑」)。退出时刻是一个问题,而非权限;用户交互 seam 为其提供选项与自由文本通道,拒绝反馈也会逐字传给模型。审批 seam 仍适合真正的权限门禁(沙箱提升权限),注册表的 `ask` 词汇也继续供希望在该处设置询问的部署使用。 + +**使用普通文本或 steering(中途引导)退出,而不使用工具。** 这样既没有产物,也没有审批时刻。工具参数本身就是可供评审的 plan,而评审问题会把结构化的是/否选择附着到确切转换上并交给人类。 + +## 后果 + +以下保证现在已经由单元、协议、快照和真实 API 测试层固定: + +- 生效模式是会话日志的纯函数:恢复与 fork 无需额外机制即可还原它;下一变化步骤中,一条 `mode/set` 后会出现匹配的完整 `request/header`。 +- 用户驱动的切换会在下一边界恰好叙述一次,净变化为零的切换序列不会产生叙述;工具驱动的退出只通过自身工具结果叙述。 +- 默认模式下,插件不贡献模式段落,但会贡献稳定的 `exit_plan_mode` schema;未部署 `dsh-mode` 的环境没有这项绑定。 +- 默认、plan 与自定义模式之间转换时,Native 工具 schema 与 Code Mode SDK 保持逐字节相同;只有已配置的指引段落发生变化。 +- Plan mode 不改变强制约束轴上的任何内容:工具集、沙箱模式、权限提升和审批策略在 plan 与默认模式下表现完全相同;部署通过把模式与独立的沙箱/审批旋钮配合使用来强化规划。 +- 模式定义可通过 `cordis.yml` 修改,无需编辑代码;其中必须提供完整 plan 指令。缺失 plan 配置、定义畸形和未知键会在加载时失败,未知模式名称会在 `set()` 时失败。 +- `exit_plan_mode` 始终通告,在 plan 之外会拒绝;批准后只移除 plan 指引,并通过纠正性的 `isError` 携带继续规划反馈;每个面向人类的接口都由其用户交互提供方承载评审。 +- 随功能落地一并交付的文档收尾包括:README、重新生成的目录(持久化日志、配置、Cordis 服务、工具)、包索引与架构行,以及实操手册中的对应行。 + +已接受的代价如下:在 agent 空闲时设置的待生效用户切换,如果进程在下一轮次前退出,就会丢失(UI 会重新应用;若实践中出现问题,空闲记录原语就是逃生口)。模式转换会改变顺序 50 处的系统提示词,因此从该处开始的缓存路径也会变化,但工具 schema 与 Code Mode SDK 不再抖动。**模式只依靠指引约束行为**:忽略该段落的模型可以在 plan 期间执行变更;评审时刻、会话日志以及独立的沙箱、审批和文件系统策略共同构成约束边界。强化规划意味着设置这些旋钮,而不是扩大模式职责;被移除的强制约束形态及其副作用声明重启触发条件仍记录在[考虑过的替代方案](#alternatives-considered)和[延期工作](#deferred)中。面向人类的接口拥有 plan 选择器与评审交互;ACP 自动化传输层两者都不承载。 diff --git a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.i18n.yaml b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.i18n.yaml new file mode 100644 index 0000000000..fb39bd26db --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.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 +2026-07-08-background-subagent-tasks.md: 12b34f2a28cfa311a48904cd5396ec16d9123641 +2026-07-08-background-subagent-tasks.zh.md: 58f035a14d55bc0b4e7f670111909074c3f53b2b diff --git a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md index 83ea99dc75..12b34f2a28 100644 --- a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md +++ b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-08-background-subagent-tasks.zh.md) + ## Problem The [subagent seam](2026-06-21-subagent-capability-seam.md) returns a `SubagentRun`, but the model-facing tool originally collected every run synchronously. Independent, slow delegations therefore held the parent call open or ran serially. diff --git a/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md new file mode 100644 index 0000000000..58f035a14d --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-08-background-subagent-tasks.zh.md @@ -0,0 +1,64 @@ +# Agent Note: 后台 subagent 任务 + +Status: implemented + +[English](2026-07-08-background-subagent-tasks.md) | 中文 + +## 问题 + +[subagent seam](2026-06-21-subagent-capability-seam.md) 会返回 `SubagentRun`,但原先面向模型的工具会同步收集每一次运行。因此,各自独立的慢速委派要么一直占用父调用,要么按串行方式运行。 + +subagent 需要与其他长时间运行的工具相同的启动、收集、列出、停止、归属、通知和清理行为,但不应采用进程流语义。子会话仍是详细记录;父级只需最终答案和任务状态。后台子级的存活时间还会超过启动它的工具调用,因此必须明确其取消和拥有者资源释放契约。 + +## 决策 + +每个 `dsh-tool-subagent` 实例都可以公开 `run_in_background`,由 `enableRunInBackground` 控制,且默认启用。禁用该功能的实例不包含此参数,并会在执行时拒绝强制传入的后台参数。提供方选择仍属于部署配置,因此一个实例仍然只为一个提供方注册一个名称可区分的工具。 + +后台 subagent 使用[通用后台任务运行时](../architecture/2026-06-20-generic-long-running-tool-runtime.md)。`task_output`、`task_list` 和 `task_kill` 负责收集、列出、取消、完成通知和提示词引导;系统不提供 subagent 专用的配套工具。 + +前台调用保留其同步契约:等待提供方启动和 `run.result`;仅当状态为 `completed` 时返回最终文本;将其他终止原因映射为出错的工具结果;并且始终在返回前释放该运行。 + +对于后台调用,工具会验证父级,并在调用 `ctx.tasks.start()` 前拒绝已中止的执行信号。任务运行时会在调用生产者启动器前,预检控制接口和拥有者清理。该启动器创建独立的 `AbortController` 并启动 `ctx.subagents.start()`;返回 id 之后,工具调用的信号不再拥有该子级。 + +任务注册按以下方式映射 subagent seam: + +- `kind` 为 `subagent`,`label` 为模型提供的描述,`owner` 为父 agent(智能体)。 +- `cancel(reason?)` 中止任务自有的控制器。同一个信号同时覆盖尚未完成的提供方启动和已就绪的子级。 +- `done` 等待提供方启动、子级结果和 `run.dispose()`。已完成的运行返回最终文本,已中止的运行变为 `killed`,其他停止原因变为 `failed`。启动、结果和资源释放失败会转换为失败结果,而不是被拒绝的任务 Promise。 +- `readOutput` 不存在。任务存活期间,`task_output` 只返回状态;结算后,它以幂等方式返回最终输出。中间的子级活动仍保留在子会话中。 + +## 生命周期 + +后台 subagent 归属于其父 agent,不会在拥有者关闭后持久存续。任务运行时将清理附加到对应拥有者的确切作用域。agent 资源释放会取消任务,并在 `AgentHandle.dispose()` 完成前等待启动回滚或子级资源释放,避免泄漏子 agent 和会话。 + +完成通知会发送给启动时捕获的确切拥有者。如果拥有者清理过程已经释放了注入目标,该通知将被丢弃;生命周期保证是清理,而不是通知。 + +## 模型引导 + +通用任务提示词教会模型一套共享的做法:保留 id;继续独立工作,而不是忙等轮询;在回答前收集相关任务;终止无关工作。subagent schema 只补充说明:后台模式返回 task id,且 `task_output` 用于收集结果。无论模型是否遵循提示词,授权和拥有者清理都会强制执行运行时边界。 + +## 备选方案 + +### subagent 专用的等待、输出和停止工具 + +能力专用工具会重复任务协议,再教一套收集与停止习惯,并增加多个提供方实例的复杂度。通用运行时在不改变工具「每个实例对应一个提供方」形态的前提下,提供了所需行为。 + +### 在拥有者关闭后存续 + +该方案需要持久化的任务状态、子会话恢复、延迟结果交付通道,以及对被遗弃拥有者的处理策略。以拥有者为作用域的清理为进程内工作界定了明确生命周期。持久作业需要单独设计。 + +### 隔离客户端不做拥有者检查 + +agent 和日志可能以会话为作用域,但任务注册表和可预测 id 属于运行时全局范围。因此,通用拥有者防线同样适用于 subagent 和所有其他生产者。 + +### 增量子 transcript 输出 + +将子级历史以流式方式写入父级,会模糊日志边界,并使提供方行为分化。此接口只公开最终输出;更丰富的观察应由会话或 UI 工具承担。 + +## 测试 + +单元测试覆盖固定了停止原因映射、在报告前释放资源、启动与结果失败、对预中止的拒绝、从启动调用信号分离、在提供方就绪前后取消、通过真实任务工具收集、无控制接口的预检防线、运行时缺失失败,以及每实例 schema 开关。快照覆盖固定了面向模型的 schema。 + +## 影响 + +父级可以并行分派慢速委派任务,并通过与 bash 共用的任务控制来收集结果。子级工作不再占用启动它的工具调用,但在收集、终止或拥有者释放之前可以继续消耗资源。提示词引导鼓励收集;拥有者清理则提供硬性生命周期边界。需要同步委派的部署可以按工具实例禁用后台模式。 diff --git a/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.i18n.yaml b/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.i18n.yaml new file mode 100644 index 0000000000..db23b997c0 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.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 +2026-07-09-bash-backed-grep-glob-discovery.md: 9c25afb44885ca2519c5d74a3d721b34fe3561de +2026-07-09-bash-backed-grep-glob-discovery.zh.md: d0dee8e49e0a500c87afbd59423fb65416c1dcc8 diff --git a/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.md b/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.md index 64fa232831..9c25afb448 100644 --- a/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.md +++ b/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-09-bash-backed-grep-glob-discovery.zh.md) + ## Problem The harness needs model-facing `glob` and `grep` tools, but making them `ctx.fs` provider methods turns a local product convenience into a universal filesystem backend contract. Local workspace discovery is naturally a process-backed `rg` workflow; remote or virtual filesystem backends may expose their own search API, may not share a local `ripgrep` view, or may not support discovery at all. The v1 should not require every filesystem backend to implement search before the file read/write/edit seam has proven that need. diff --git a/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.zh.md b/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.zh.md new file mode 100644 index 0000000000..d0dee8e49e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-09-bash-backed-grep-glob-discovery.zh.md @@ -0,0 +1,170 @@ +# Agent Note: 由 Bash 支持的 grep 与 glob 发现工具 + +Status: implemented + +[English](2026-07-09-bash-backed-grep-glob-discovery.md) | 中文 + +## 问题 + +harness 需要面向模型的 `glob` 和 `grep` 工具,但如果将它们实现为 `ctx.fs` 提供方的方法,就会把本地产品便利功能变成所有文件系统后端都必须实现的契约。本地工作区发现天然适合由进程支持的 `rg` 工作流;远程或虚拟文件系统后端可能公开自己的搜索 API,可能无法共享本地 `ripgrep` 视图,也可能完全不支持发现。文件读取/写入/编辑 seam 尚未证明此需求前,v1 不应要求每个文件系统后端都实现搜索。 + +搜索输出还受到两层不同的预算约束。工具需要足够多的原始 `rg` 输出,才能计算稳定的逻辑结果;模型则只能收到有界预览,并在格式化结果超出内联预算时获得恢复路径。通用落盘策略只能看到最终工具结果,因此无法恢复搜索工具已经省略的匹配项。搜索工具必须自行负责保留,并尽力落盘格式化结果。 + +## 决策 + +`glob` 和 `grep` 是 `@deepseek-ai/dsh-tool-fs-search` 中的条件式面向模型工具,由 bash seam 支持,不会成为新的 `ctx.fs` 提供方方法。加载插件时,该包(package)执行 `command -v rg >/dev/null 2>&1`:先通过 `ctx.bash.resolve(request)` 解析请求,再通过 `ctx.bash.run(spec)` 运行;如果命令以非零状态退出,该包会记录警告,并且既不注册工具,也不注册提示词章节。如果探针无法启动、超时、中止、被终止,或没有产生退出码,插件加载会明确失败,因为这意味着 bash 执行器损坏,而不是可选二进制文件缺失。注册后,执行流程同样依次调用 `ctx.bash.resolve(request)` 与 `ctx.bash.run(spec)`,并使用工具组装的固定 `rg` 命令模板。工具层负责 schema、参数验证、shell 引用、结果解析、结果格式化、保留、格式化结果落盘交接,以及超时声明。bash 执行器负责请求默认值解析与上限控制、子进程执行、进程组终止、环境清理、原始输出捕获,以及在本地、沙箱或远程 bash 实现之间替换后端。 + +这些工具不使用 `ctx.bash.start()`,也不创建模型可见的后台任务。从 agent loop(智能体循环)的视角看,它们是普通前台工具:只有当 `rg` 命令退出、超时、中止或失败后,工具调用才返回。`defineTool({ timeoutMs })` 声明协作式工具调用预算,`@deepseek-ai/dsh-timeout-policy` 通过 `exec.signal` 强制执行;工具会在 `resolve()`/`run()` 前将该信号转发给 bash 请求。bash 后端自身的超时仍作为第二层安全上限;先触发的中止生效。 + +这些工具使 `path` 与 Claude Code 的搜索工具保持一致,但将解析绑定到 bash workdir,而不是 `ctx.fs`。工具从 `exec.agent?.session.header.cwd` 派生 bash 请求 workdir,与 `dsh-tool-bash` 和 `dsh-tool-fs` 一致;如果会话没有 cwd,它会省略 `request.workdir`,由 bash 实现通过 `resolve()` 应用其配置的 cwd 或进程 cwd。对于 `grep`,`path` 是可选的 ripgrep 目标,可以是文件或目录;省略时使用已解析的 bash workdir。对于 `glob`,`path` 是可选的目录搜索根;省略时同样使用已解析的 bash workdir。相对 `path` 值基于该 workdir 解析。只要可行,返回路径就会显示为相对于已解析 bash workdir 的形式;只有在共置部署中,bash workdir 与文件系统 `read` 根指向同一个工作区时,这些路径才保证可以继续读取。v1 会记录这项部署要求,但不执行跨服务运行时验证。在形成共享工作区/根契约或提供方专用搜索后端之前,远程或虚拟文件系统搜索保持暂缓。 + +该包不注入 `fs`,而是注入 `tools`、`systemPrompt` 和 `bash`;它有意读取 `spillStore` 时使用 `ctx.get('spillStore')`,而不使用静态注入,因为格式化结果落盘是可选功能。现有 `@deepseek-ai/dsh-tool-fs` 部署若只需要 `read`/`write`/`edit`,则无需加载 bash。加载搜索功能的部署则必须让 bash 执行器环境可以使用 `rg`,这些工具才会进入模型可见 schema。 + +### 包结构 + +v1 包保持精简。`@deepseek-ai/dsh-tool-fs-search` 内部的源代码布局如下: + +```text +src/index.ts +src/glob.ts +src/grep.ts +src/search-core.ts +src/shell-quote.ts +``` + +`glob.ts` 和 `grep.ts` 各自负责参数验证、命令构造、结果解析、格式化和注册。`shell-quote.ts` 是一个共享辅助模块,因为 shell 引用是两个工具都必须经过的安全边界;`search-core.ts` 是另一个共享模块(实现时对原四文件方案所作的修订):`SEARCH_*` 错误词汇、bash 运行与原始输出获取、格式化结果落盘交接,以及 workdir 相对显示,在两个工具中完全相同。若在每个工具中重复这套精细管道,正是对称性约定所指出的漏提取问题。命令构造器禁止自行拼凑引用,也不能把未经引用、由模型控制的值直接连接到 shell 命令中。 + +### Schema 与配置 + +`glob` 公开精简的发现形状: + +```ts +interface GlobArgs { + pattern: string + path?: string +} +``` + +`grep` 公开 OpenCode 风格的最小形状: + +```ts +interface GrepArgs { + pattern: string + path?: string + include?: string +} +``` + +常规预算不会进入面向模型的 schema。`@deepseek-ai/dsh-tool-fs-search` 拥有以下带默认值并经过验证的配置字段: + +| 字段 | 默认值 | 作用 | +|---|---:|---| +| `globMaxResults` | `100` | 内联保留的最大路径数;与 Claude Code 的默认 `GlobTool` 结果上限一致。 | +| `grepMaxMatches` | `250` | 内联保留的最大扁平匹配数;与 Claude Code 的默认 `GrepTool` `head_limit` 一致。 | +| `grepMaxLineBytes` | `2000` | 每条匹配行预览保留的最大字节数,通过 `TextRetainer({ kind: 'head', maxBytes: grepMaxLineBytes })` 应用。 | +| `rawOutputMaxBytes` | `20000000` | 工具会解析的完整原始 `rg` stdout 最大字节数;与 Claude Code 的 ripgrep 原始缓冲区一致。 | +| `timeoutMs` | `30000` | 附加到两个工具定义并由 `@deepseek-ai/dsh-timeout-policy` 强制执行的工具调用超时。 | + +`globMaxResults` 和 `grepMaxMatches` 使用 `ItemRetainer({ kind: 'head' })`。`grepMaxLineBytes` 针对每条匹配行使用 `TextRetainer({ kind: 'head', maxBytes: grepMaxLineBytes })`,使预览截断保留 UTF-8 边界。这遵循[工具结果保留库](../architecture/2026-07-06-tool-result-retention-library.md)对发现条目的映射:收集完整结果,在内联结果中保留头部条目,并将路径映射、分组和逐行预览放在保留器外部。v1 的 `grep` 不公开 `case_insensitive`、`head_limit`、`offset`、`count`、多行、上下文行、输出模式或文件类型过滤器。模型如需周边上下文,可使用 `read` 读取匹配文件;如需后续结果,则遵循返回的落盘定位符所给出的检索提示。 + +Claude Code 的数值只是两层预算的参考点,并非面向模型 schema 的先例。其专用搜索工具会缓冲最多 20 MB 的原始 ripgrep 输出用于内部处理;在非 WSL 平台上使用 20 秒 ripgrep 超时,在 WSL 上使用 60 秒,之后才在模型看到结果前应用搜索专用上限:`GrepTool` 默认 `head_limit = 250`,并持久化超过 20,000 个字符的格式化结果;`GlobTool` 默认最多 100 条路径,并持久化超过 100,000 个字符的格式化结果。此 Agent Note 采用同样的原始缓冲区和内联数量默认值,将默认搜索超时设为 30 秒,并通过本 harness 的 `ctx.spillStore.saveText()` 路径恢复格式化结果。 + +`path` 字段沿用与 Claude Code 相同的区分方式:`grep.path` 是文件或目录形式的 ripgrep 目标,`glob.path` 则是目录搜索根。v1 不为这些工具公开单独的 cwd/workdir 参数。 + +`include` 是一个正向 glob 过滤器,不是列表,也不是排除语法。系统会预先拒绝逗号分隔或取反的 include 模式,并返回结构化参数错误。shell 命令中使用的每个模型控制值,包括 `pattern`、`path` 和 `include`,都必须经过包私有的 shell 引用辅助模块。 + +### 执行 + +`glob` 构建固定的 `rg --files` 命令,并以解析后的目录搜索根为根(提供 `path` 时使用该值,否则使用 bash workdir):`rg --files --glob --sort=modified --no-ignore --hidden`,另加针对 `.git`、`.svn`、`.hg`、`.bzr`、`.jj` 和 `.sl` 的 VCS 元数据排除项。这样既与 Claude Code 的隐藏/忽略文件发现和修改时间排序保持一致,也避免宽泛搜索包含 VCS 内部文件。工具逐行解析路径,只要可行就将结果映射为相对于 bash workdir 的路径,将每条路径推入 `ItemRetainer({ kind: 'head', maxItems: globMaxResults })`;当保留结果达到上限时,它会格式化完整的已排序路径列表,作为落盘产物。 + +`grep` 构建固定的逐行 `rg --json` 命令,作用于所提供的文件/目录目标(提供 `path` 时使用该值,否则使用 bash workdir),从而无需按冒号拆分,就能解析文件路径、行号和行文本。它消费 `match` 记录,将格式错误的 JSON 或匹配记录视为 `SEARCH_FAILED`;只要可行,就将结果路径映射为相对于 bash workdir 的路径;通过 `grepMaxLineBytes` 应用逐行预览保留,将每个匹配推入 `ItemRetainer({ kind: 'head', maxItems: grepMaxMatches })`,然后只按文件分组内联输出中保留的预览匹配。落盘产物保存完整的格式化匹配列表,而不是只保存省略的尾部,因此检索提示指向模型已经看到的同一逻辑结果。 + +原始 `rg` stdout 是内部传输细节。工具请求 `stdoutMaxBytes: rawOutputMaxBytes`,并通过 `ctx.bash.resolve()` 解析;只有当执行器在该上限内返回未截断的 stdout 时,工具才解析 `stdout.text`。如果 stdout 超过 `rawOutputMaxBytes`,或者执行器仍返回 `stdout.truncated`,工具会以明确的搜索错误失败,要求模型缩小 `pattern`、`path` 或 `include`。工具绝不向模型公开原始 `rg` 输出或 bash 原始落盘路径。 + +只有 stdout 是解析源。对于无效模式、注册后运行时 `rg` 消失,以及搜索失败,stderr 作为诊断文本;如果 bash 截断 stderr,工具会使用保留的 stderr 尾部并附加截断说明,不会读取 `stderr.spillPath`。 + +如果 `ctx.bash.run()` 因工具超时或调用方取消触发而报告 `aborted`,工具会返回结构化失败,而不是假装没有匹配项。如果 bash 自身的超时先触发,工具同样会以明确的超时消息失败。非零 ripgrep 退出语义由工具负责:退出码 0 表示存在匹配并成功;退出码 1 表示没有匹配但成功;无效模式、运行时 `rg` 消失或无法访问搜索 workdir 则表示失败。 + +搜索失败使用包自有的 `HarnessError` 子类与 `SEARCH_*` 代码,而不使用 `FsErrorCode`,因为这些工具不是 `ctx.fs` 提供方操作。v1 的词汇包括 `SEARCH_INVALID_PATTERN`、`SEARCH_FAILED`、`SEARCH_RAW_OUTPUT_OVERFLOW` 和 `SEARCH_ABORTED`。缺少必填字段、空字符串或不支持的取反/列表式 `include` 值等模型参数验证失败,仍作为普通工具参数错误处理。 + +### 格式化结果落盘 + +`ctx.spillStore` 是可选服务,仅用于面向模型的格式化结果。这是代码库中首个工具自有落盘调用模式;此设计有意为之,因为搜索保留属于条目级策略:`globMaxResults` 限制路径数,`grepMaxMatches` 限制匹配数,而工具此时仍持有完整逻辑结果。通用 `dsh-spill-policy` 会在 `tools/post-execute` 阶段限制最终文本字节数;到那时搜索工具已经省略后续路径或匹配,策略无法恢复它们。 + +当搜索产生的逻辑结果数超过内联上限,且 `ctx.spillStore` 存在时,工具会通过 `saveText()` 保存完整的格式化结果。落盘所有者是调用 agent 的会话头 id(`exec.agent?.session.header.id`);缺少该所有者时,搜索会保留内联结果,并报告完整结果无法保存。落盘来源是工具执行身份:`{ toolName: exec.name, callId: exec.callId, label: 'result' }`。建议文件名为 `grep-results.txt` 和 `glob-results.txt`;落盘后端仍将它们视为提示,而不是路径。 + +如果落盘存储不存在、调用没有会话所有者,或保存失败,工具仍返回内联页和页脚,说明完整结果无法保存。格式化结果落盘存储不可用本身绝不能把搜索成功变为 `isError` 结果。 + +bash 原始输出流与格式化搜索落盘产物是两个不同的产物。原始 `rg` stdout 只会在所请求的 bash stdout 上限内于内存中解析;格式化落盘产物则是 `ctx.spillStore.saveText()` 生成的稳定、面向模型的恢复定位符。 + +### 结果形状 + +带有成功格式化落盘的受限 `glob` 结果会返回内联页与落盘通知: + +```text + + +(Showing N of M paths. Full sorted result stored at: /.../session-abc123/9f8e7d-glob-results.txt. Use read with offset/limit, or grep this path to search within it.) +``` + +带有成功格式化落盘的受限 `grep` 结果会返回分组后的预览匹配与落盘通知: + +```text +Found N of M matches + + +Line 12: ... + +(Full grep result stored at: /.../session-abc123/9f8e7d-grep-results.txt. Use read with offset/limit, or grep this path to search within it.) +``` + +如果完整逻辑结果未超过内联上限,系统不会创建格式化落盘产物。如果完整逻辑结果过大但无法格式化落盘,页脚会说明结果已受限,完整结果无法保存。`truncated`/省略计数是预算事实,并不表示搜索不完整;超时、无效正则表达式、运行时 `rg` 消失、无法访问 workdir、原始输出溢出、跳过二进制文件和解析失败,仍属于工具领域的错误或不完整字段。 + +## 考虑过的替代方案 + +**将 `glob`/`grep` 放在 `ctx.fs` 上。** v1 不采用:这会迫使每个文件系统后端增加搜索 API,并使本地 ripgrep 行为成为提供方 seam 的一部分。搜索是有用的产品行为,但不像 `readText` 或 `writeText` 那样属于通用文本存储原语。 + +**直接从 `dsh-fs-local` spawn ripgrep。** 此 Agent Note 的 v1 不采用:直接 spawn 提供最简洁的 argv 边界、stdout/stderr 控制与提前停止控制,但会重复 bash seam 已负责的进程执行事项,包括环境清理、进程组终止、超时传播、沙箱/远程执行器替换,以及有界输出捕获。如果 bash 支持的搜索被证明过于依赖 shell 字符串,或必须支持前台流式输出,该方案仍是合理优化。 + +**通过 `ctx.bash.start()` 实现流式提前停止。** 不采用:`start()` 会创建模型可见的后台任务语义,包括 task id、所有者 token、`bash_output`、`bash_kill`、完成通知,并且没有内置超时。`grep` 需要前台工具结果,而不是后台 bash 工作流。如果将来必须流式搜索,正确的抽象是在 bash/进程 seam 上增加前台流式进程句柄,而不是借用公开后台任务 API。 + +**向模型公开 bash 原始落盘路径。** 不采用:bash 原始落盘路径包含原始 `rg` stdout(对于 grep 即 `rg --json` 记录),并非稳定的格式化搜索结果。搜索只把原始 stdout 当作内部传输;模型恢复使用通过 `ctx.spillStore.saveText()` 保存的格式化结果。 + +**先为 bash 输出规范化增加 `spillStore.saveFile()`。** 此 Agent Note 的 v1 不采用:未来规范化 bash 时,`saveFile()` 可以帮助将现有执行器落盘文件移动到会话范围的落盘存储,但搜索只需在生成面向模型的产物前,在内存中获取有界的原始 `rg` stdout。`saveText()` 足以保存格式化搜索结果。 + +**依赖通用 `dsh-spill-policy`。** 不采用:通用 post-execute 落盘只能看到最终工具结果。如果 `grep`/`glob` 内联返回第一页,通用策略无法恢复省略的结果。搜索工具必须在返回有界的面向模型文本前,自行保存完整的格式化结果。 + +**公开 Claude Code 的完整 `GrepTool` schema。** v1 不采用:`output_mode`、上下文标志、多行、`head_limit`、`offset`、`case_insensitive` 和类型过滤器会使面向模型的接口变成 ripgrep 包装层。本 harness 将常规预算与续传机制保留在部署策略和落盘产物中。 + +**保留提前停止搜索,并省略格式化落盘产物。** 此提案不采用:提前停止效率更高,却不给模型检查后续结果的路径。所选 v1 优先保证结果可恢复性与实现简洁性,并以 `timeoutMs`、`rawOutputMaxBytes`、bash 后端上限和格式化落盘产物作为安全后备。 + +**先扩展 bash seam,增加原始输出读取器。** 不采用:可移植的 `readRawOutput(ref, maxBytes)` API 会增加引用生命周期、权限和后端存储语义。逐次运行的 `stdoutMaxBytes` 请求是更窄的 seam:搜索要么在 `rawOutputMaxBytes` 内收到完整 stdout,要么明确失败。 + +**始终注册,只有执行时才报告缺少 `rg`。** 不采用:模型可见工具 schema 是部署能够尝试该能力的承诺。如果 bash 执行器在加载时找不到 ripgrep,更安全的接口是完全没有 `glob`/`grep` 工具或提示词指引。对于注册后发生环境变化的情况,执行时的 `rg` 缺失分类仍作为防御性回退。 + +## 测试 + +- 测试覆盖注册时 `rg` 探测(探测成功会注册两个工具和提示词章节;非零探测会跳过工具与提示词章节并发出警告;基础设施探测失败会拒绝插件加载),证明中止的 `exec.signal` 会到达 bash 后端(通过同一引用的 spec 断言和 `SEARCH_ABORTED` 结果),并覆盖命令构造/引用(恶意模式、带空格路径、以短横线开头的值、引号、换行、glob 元字符:既有单元断言,也针对每个恶意值执行真实 `bash -c` 往返)、将 `grep.path` 用作文件与目录目标、将 `glob.path` 用作目录搜索根、无效模式处理、无匹配、格式错误的 `rg --json` 输出、匹配行预览截断、原始输出溢出、超时/中止、格式化落盘成功/失败、包自有 `SEARCH_*` 错误代码,以及无后台任务不变量。 +- 直接覆盖第一方工具自有落盘先例:落盘后端存在、落盘后端缺失、`saveText()` 失败,以及缺少落盘所有者。 +- 该包通过真实 Loader 路径覆盖命名空间插件的导出形状(`name`、`inject`、`Config` 和 `apply`,且没有默认导出)。 +- 真实执行器集成测试(`dsh-bash-local` + 真实 `rg`)验证外部世界:恶意模式保持惰性、逐会话 cwd 解析、VCS 元数据排除、按修改时间排序,以及真实 ripgrep stderr 分类。如果测试进程的 PATH 中没有 `rg`,该测试会自行跳过(这是与无密钥 e2e 跳过相似的 CI 兼容措施);伪执行器测试覆盖注册和执行时缺少 `rg`,并由逐文件 100% 覆盖率门禁兜底。 +- transcript 可见落盘通知仍有快照缺口:此功能合入时记录了缺口说明,没有快照。快照层会回放 acp-agent 树;在其中加入搜索插件会改变组装的系统提示词,必须使用真实密钥重新录制每一份预期输出,而实现环境没有密钥。落盘通知的确切 transcript 文本由单元测试固定(`formatGlobOutput`/`formatGrepOutput` 以及通过注册表执行的落盘测试);下一次拥有密钥的会话应把插件接入 acp-agent 树,并运行一次 `test:snapshot:record`。 + +## 后果 + +- `glob` 和 `grep` 是 `@deepseek-ai/dsh-tool-fs-search` 中的条件式面向模型工具,不是 `ctx.fs` 提供方方法,也不属于现有 `@deepseek-ai/dsh-tool-fs` 根插件。只有 bash 执行器能找到 `rg` 时才会注册;该包注入 `tools`、`systemPrompt` 和 `bash`,不注入 `fs`,并使 `ctx.spillStore` 保持可选,读取时使用 `ctx.get('spillStore')`。 +- Schema 严格为 `glob(pattern, path?)` 和 `grep(pattern, path?, include?)`;搜索上限与超时是带默认值并经过验证的 Config 字段(`globMaxResults`、`grepMaxMatches`、`grepMaxLineBytes`、`rawOutputMaxBytes`、`timeoutMs`)。 +- 工具通过 `ctx.bash.resolve(request)` → `ctx.bash.run(spec)` 执行,转发 `exec.signal`,绝不调用 `ctx.bash.start()`,也绝不公开 bash task id。如果存在 `exec.agent?.session.header.cwd`,bash 请求 workdir 来自该值;解析后的 `spec.workdir` 决定执行与相对路径显示。 +- 工具向 bash seam 请求 `stdoutMaxBytes: rawOutputMaxBytes`,只解析上限内未截断的 stdout,并将超限或仍被截断的原始输出视为明确的搜索失败;绝不向模型公开原始 `rg` 输出。 +- 只要可用,过大的完整格式化结果会通过 `ctx.spillStore.saveText()` 保存,而内联结果保持有界;落盘失败、后端缺失或所有者缺失时,系统保留内联结果并报告未保存的剩余内容,绝不会返回 `isError`。 +- 包 README、生成的配置目录与导出 JSDoc 会记录 Config 字段和 `SEARCH_*` 代码;tui-agent 示例会提供条件式工具插件(acp-agent 树等待完成上述快照重新录制);fs 组 README 会记录 `rg` 可用性以及 bash/文件系统共置部署要求。 + +## 风险 + +在宽泛模式下,完整运行的 `grep` 可能比提前停止搜索更慢。v1 为了简化实现并恢复完整结果而接受这项成本,同时通过工具超时、bash 超时、`rawOutputMaxBytes` 和输出上限加以约束。如果实际运行过慢,仍可采用直接 ripgrep 或前台流式替代方案。 + +Shell 命令构造是最尖锐的安全边界。`ctx.bash` 接受命令字符串而不是 argv 向量,因此实现必须集中处理 shell 引用,并测试恶意模式、带空格路径、以短横线开头的模式、引号、换行和 glob 元字符。 + +v1 假设 bash 与文件系统共置部署。如果 bash 搜索一个工作区,而 `read` 工具基于另一个根解析路径,返回路径可能无法继续读取。该包会记录这项要求,但不在运行时验证。 + +落盘定位符由后端负责。当前本地后端返回本地文件系统路径,适用于 `read`/`grep` 能打开这些文件的部署;远程或工作区受限部署可以使用另一种后端,让其定位符和检索提示指向受支持的检索机制。 diff --git a/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.i18n.yaml new file mode 100644 index 0000000000..2e7b5b1d58 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.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 +2026-07-10-agent-session-identity-and-log-location.md: a55bf276bff998a94f84ec1af078022e4881903c +2026-07-10-agent-session-identity-and-log-location.zh.md: 84b8b22187ccd1078ff13e39f4a345efbecfaeac diff --git a/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md b/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md index d4c5154ed2..a55bf276bf 100644 --- a/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md +++ b/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-10-agent-session-identity-and-log-location.zh.md) + ## Problem An agent can identify its workspace through `session.header.cwd`, but a model using bash cannot reliably identify the session that owns the call or the durable transcript that records it. Searching `./.sessions` guesses deployment config and JSONL layout; custom roots, alternate persistence backends, resume, forks, and concurrent parent/child agents make that guess unreliable. Hooks have the same need for transcript location, while future plugins may need to expose other harness-owned environment facts to shell commands. diff --git a/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md b/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md new file mode 100644 index 0000000000..84b8b22187 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.zh.md @@ -0,0 +1,87 @@ +# Agent Note: 向工具与钩子公开 agent(智能体)会话标识和 JSONL 位置 + +Status: implemented + +[English](2026-07-10-agent-session-identity-and-log-location.md) | 中文 + +## 问题 + +agent 可以通过 `session.header.cwd` 识别其工作区,但使用 bash 的模型无法可靠识别当前调用所属的会话,也无法找到记录该调用的持久 transcript(文本记录)。搜索 `./.sessions` 等同于猜测部署配置和 JSONL 布局;自定义根目录、替代持久化后端、恢复、fork,以及并发运行的父子 agent,都会让这种猜测失效。钩子同样需要 transcript 位置,而未来的插件也可能需要向 shell 命令公开其他由 harness 所有的环境事实。 + +这项边界必须维持两个属性:事实的所有者决定如何解析该事实;每个子进程接收每次执行的快照,而不是进程级可变全局状态。尤其是嵌套 harness 不能把环境中的 `DSH_*` 值泄漏给当前 agent、持久化后端或配置均可能不同的子进程。 + +## 决策 + +在 [`SessionPersistence`](../architecture/2026-06-14-session-persistence.md) seam 上增加同步、无副作用的位置查询: + +```ts +import type { SessionHeader } from '@deepseek-ai/dsh-session' + +interface SessionLocation { + readonly kind: string + readonly path: string +} + +interface SessionPersistence { + locate(meta: SessionHeader): SessionLocation | undefined +} +``` + +`path` 是指向该后端为 `meta` 保留的专用日志的绝对本地路径;`kind` 标识其表示形式。JSONL 使用解析后的根目录和路径辅助函数返回 `{ kind: 'jsonl', path }`。SQLite 以及任何无法诚实提供逐会话本地产物的后端均返回 `undefined`。该查询不会创建或刷写任何内容,因此即使文件尚不存在,也可以报告延迟创建的目标路径。 + +面向模型的 bash 包(package)拥有一个 `ctx.bashEnv` 注册表。贡献方声明稳定名称、它可能返回的每个 `DSH_*` 键、每个键的说明,以及 `resolve(execution: ToolExecution)`。贡献方名称重复、键所有权重复、使用保留键、声明格式错误、运行时输出未声明或输出不是字符串时,系统都会明确失败。注册属于 Cordis effect,并随贡献插件的 fiber 一同移除。`list()` 无需运行解析器即可公开声明,从而让环境接口可供诊断工具和未来的提示词/UI 消费方枚举。 + +注册表会为每次前台和后台 bash `ToolExecution` 重新构建受信任的覆盖层: + +- `DSH_HOME` 始终是配置的 Harness home 绝对路径。独立的 [`@deepseek-ai/dsh-paths`](../../../../packages/util/paths/README.md) 工具库规定其优先级:显式 `dshHome`,其次是环境中的 `$DSH_HOME`,最后是 `~/.dsh`。 +- `DSH_SHELL=1` 始终存在,用于标识由 DeepSeek Harness 管理、面向模型的 bash 子进程。 +- 执行具有关联 agent 时,`DSH_SESSION_ID` 存在并等于 `agent.session.header.id`。 +- 内置的持久化转换层提供 `DSH_SESSION_JSONL` 的条件是 `ctx.sessionPersistence.locate(header)` 返回 `kind: 'jsonl'`。 + +会话持久化仍然是事实所有者:JSONL 不依赖 tool-bash,也不会自行注册 shell 变量;钩子继续直接使用 `locate()`。tool-bash 是把持久化事实转换为 shell 约定的转换层。其他需要向 shell 公开事实的插件依赖该注册表,并注册各自的键;它们不修改 `process.env`。 + +bash seam 导出 `DSH_ENV_PREFIX` 作为唯一的命名空间来源,并派生 `DshEnvironmentKey`,其来源是该常量的 `typeof`。tool-bash 从该常量派生内置名称与模型指引,执行器则使用该常量进行过滤和通道校验。seam 通过 `BashExecRequest.dshEnv`/`BashExecSpec.dshEnv` 单独传递受管理的覆盖层。普通 `env` 仍是钩子所用的通用进程内插件接口,但不能包含受管理的键;对称地,`dshEnv` 不能包含普通键。本地执行器会在 spawn 前拒绝任一错误通道,移除环境中继承的全部受管理键,依次应用普通清理、终端环境和显式 `env`,最后合并受信任的 `dshEnv` 快照。这保证了值缺失表示它当前确实不存在,而不是从外层或先前的 harness 继承而来。面向模型的工具仍忽略模型提供的 `env`/`stdin` 参数。 + +bash 工具说明只讲解持久约定:当前 harness 环境事实通过受管理的 `$DSH_*` 变量提供,可以在需要时查看。它不会枚举持久化专用键,也不会添加永久的系统提示词章节。工具 schema 已记录在请求 header 中,工具输出则记录为 `tool/result`,因此无需新增会话事件。 + +[Claude Code 和 Codex 钩子桥接层](2026-06-30-hook-bridges.md)在构造 payload 时,从同一持久化 seam 解析 transcript 位置。Codex 使用 `transcript_path: string | null`;Claude Code 保留其字符串字段,并回退为 `''`。钩子查询不会物化或刷写会话。 + +## 同类产品调研 + +同类产品把稳定标识与物理存储分开处理。Codex 向 spawn 的 shell 注入稳定的 `CODEX_THREAD_ID`,而 recorder 和钩子接口负责提供 transcript 路径。Claude Code 通过结构化的钩子/状态输入提供 `session_id` 和 `transcript_path`。OpenCode 在结构化工具上下文中携带标识;Kimi Code 展开会话占位符;Reasonix 则把活动会话路径保存在控制器上。可移植的规则是:在调用边界注入标识,由存储层解析位置,绝不在并发 harness 中使用进程级的当前会话全局变量。 + +## 生命周期与持久化语义 + +新会话在第一个轮次之前获得 id,因此它的首次 bash 调用即可读取 `DSH_SESSION_ID` 和 JSONL 目标。JSONL 文件可能要等到第一次成功的轮次结束检查点后才存在,而且在一个轮次仍未结束时,它只包含上次刷写的前缀。`DSH_SESSION_JSONL` 是位置提示,不是授权凭据或新鲜度保证。 + +恢复操作复用已加载的 header,因此 id 和位置不变。fork 和 spawn 会创建新的会话 id 与位置。父子调用分别从自己的 `ToolExecution.agent` 解析事实;即使调用重叠,每条命令也会收到不可变快照。替换持久化服务会影响后续收集,因为转换层在执行时查询 `ctx.get('sessionPersistence')`;注册表本身受 effect 作用域约束,并且可安全用于 HMR(热模块替换)。 + +`dshHome` 是与会话无关的部署上下文。agent-core 通过 `@deepseek-ai/dsh-paths` 解析出一个值,并将其同时传给 tool-bash 和本地 skill(技能)发现;独立消费方调用同一解析器。如果顶层 `dshHome` 与 `skills.local.dshHome` 均已提供但解析结果不同,组合会失败,而不会公开互相矛盾的 home。持久化可以独立变更,无需把其事实冻结到会话前缀中。 + +## 测试 + +单元测试覆盖注册表声明校验、effect 释放、逐次执行收集、`dshHome` 优先级,以及本地执行器清理并重建 `DSH_*` 的顺序。请求录制测试覆盖前台/后台快照、无 agent 调用、持久化不存在或为 JSONL、忽略模型 `env`,以及父子隔离。JSONL/SQLite 定位器契约测试与两套钩子桥接测试均锁定 transcript 可用和不可用两种方言。 + +一项无密钥的完整循环集成测试会在第一个轮次驱动真实的 agent loop、JSONL 持久化、tool-bash 与 bash-local。子进程打印 `DSH_HOME`、`DSH_SHELL`、会话 id、JSONL 目标和继承的陈旧哨兵值;测试校验当前值、陈旧变量不存在、刷写前文件不存在,并最终检查持久化 header。快照覆盖会锁定录制请求 header 中的通用 bash 说明。该契约属于确定性的本地执行,不涉及模型选择,因此无需带密钥测试。 + +## 考虑过的替代方案 + +**只提供 id,再用 `find`。** 搜索无法得知自定义根目录或后端布局,并且在多会话环境下存在竞态。 + +**只提供绝对路径。** 路径可能不可用、延迟创建或取决于表示形式,不能作为稳定的会话标识。 + +**使用全局 `process.env`。** 并发 agent 会互相覆盖,嵌套 harness 也会继承陈旧的当前会话值。 + +**把持久化说明放入会话前缀。** 活动服务可以在 HMR 或未来的后端切换中改变,而会话前缀保持冻结;持久化专用指引会因此变得陈旧。 + +**使用类型化 waterfall 事件。** 监听器不运行就无法声明所有权,而后续监听器可以无提示地覆盖键。注册表能在注册时检测键冲突,并且保持可枚举。 + +**让每个持久化后端直接注册 bash 环境。** 这会反转依赖方向,让存储层依赖某一个消费方,并迫使未使用 bash 的部署也引入它。钩子仍然需要 `locate()`。 + +**增加面向模型的 `session_info` 工具。** bash 已经提供查询接口,新增工具只会多出 schema 和一次调用;注册表可以扩展至未来的环境事实,无需为每项事实增加一个工具。 + +## 影响 + +每个面向模型的 bash 子进程都会收到当前 Harness home 和 shell 标识,关联 agent 的调用还会收到稳定的会话标识。使用 JSONL 后端的调用可以获得可选的目标路径;非文件持久化会如实省略该值。这些子进程中的完整 `DSH_*` 命名空间由 harness 管理:系统移除环境中已有的受管理值、重新加入当前受信任的值,并禁止普通调用方通过 `env` 绕过所有权检查。 + +该命名空间可被发现,但并非秘密。路径可能泄露配置的根目录,延迟创建的目标也可能不存在或处于陈旧状态,而且命令可以在自己的 shell 语法中覆盖变量。消费方应把这些值视为关联信息和环境事实,在归属关系重要时校验 transcript 元数据,并依靠沙箱/文件系统策略而不是变量保密性来完成授权。 diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.i18n.yaml new file mode 100644 index 0000000000..0c7363827e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.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 +2026-07-10-parallel-tool-call-execution.md: c67ae61939a3e7974f9bf729058a57f5576308a1 +2026-07-10-parallel-tool-call-execution.zh.md: a80317aa951cbf3a9cae0651348c99712a4193d5 diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md index 4904da5bd5..c67ae61939 100644 --- a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-10-parallel-tool-call-execution.zh.md) + ## Problem An assistant message may contain several sibling `tool-call` blocks. Running them serially adds the latency of independent reads and web requests even though the model has already requested them together. diff --git a/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md new file mode 100644 index 0000000000..a80317aa95 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-10-parallel-tool-call-execution.zh.md @@ -0,0 +1,103 @@ +# Agent Note: 按单次调用安全性并行执行工具调用 + +Status: implemented + +[English](2026-07-10-parallel-tool-call-execution.md) | 中文 + +## 问题 + +一条 assistant 消息可以包含多个并列的 `tool-call` 块。尽管模型已经同时请求了这些调用,串行执行仍会叠加各个独立读取和 Web 请求的延迟。 + +并发属于宿主调度范畴,不是面向模型的工具元数据。循环需要在不硬编码工具名称、不向 JSON Schema 暴露调度策略的前提下,判断哪些调用可以重叠执行。 + +会话日志仍是权威记录:每个已启动的调用都有审计事件,都会获得结果;无论完成顺序如何,模型历史都按原始调用顺序观察结果。 + +## 决策 + +每个工具都可以提供可选的 `isConcurrencySafe(args)` 分类器。该分类器必须是同步纯函数:它只检查当前调用已解析的参数,不执行 I/O 或任何变更。只有显式返回 `true` 才表示选择并行;分类器缺失、参数无效、分类器抛错或返回任何其他值,都会使该调用按独占方式执行。规范类型契约见[工具数据结构](../../../../docs/core-data-structures/tools.md)。 + +分类器有意设计为一元函数。返回 `true` 表示工具承诺:此调用可以与任何同样返回 `true` 的并列调用重叠执行。调度器不会比较调用,也不会证明它们的资源访问相容。 + +这个一元分类器仍然可以感知输入。工具可以将只读操作分类为并行,将变更操作分类为独占。该接口无法表达「仅当路径不同时,这些写入才安全」之类的关系规则,因此,安全性依赖并列调用的调用仍按独占方式执行。 + +`defineTool()` 先验证参数,再调用类型化分类器。无效参数会被归为独占,且只有该调用真正执行时才会产生常规参数错误。`ctx.tools.executionMode(exec)` 会解析当前有效的工具定义,并返回带标签的 `parallel` 或 `exclusive` 模式;未知工具将以安全方式退化为独占。 + +使用带标签的模式,而不是公开布尔型调度器 API,使得以后可以表达感知资源的变体,无需改变分类器契约。 + +## 调度与顺序 + +循环会等待完整的 assistant 消息,对每个调用只解析一次,为每个调用创建独立的 `ToolExecution`,再按模型顺序扫描。连续的并行调用组成一组;每个独占调用单独组成一组,并构成顺序屏障。各组按顺序执行。分类采用惰性方式:每经过一个屏障,调度器都会解析下一个调用;补充并行池之前,还会重新分类每个后续调用。如果注册表变更使该调用变为独占,当前池会先完全排空,然后该调用才作为下一个屏障启动。 + +例如: + +```text +[parallel read(A), parallel read(B), exclusive write(A), parallel read(C)] + +→ [read(A), read(B)] +→ [write(A)] +→ [read(C)] +``` + +`read(A)` 和 `read(B)` 可以重叠执行。`write(A)` 要等两者都完成后才启动,`read(C)` 则要等写入完成后才启动。 + +每组都使用一个由 `maxParallelToolCalls` 限制上限的滚动池:循环先按模型顺序启动调用,直到达到上限;每有一个调用结算,就再启动一个。独占组是容量为 1 的池。将上限设为 `1` 可保持串行执行。 + +只有派发和工具主体会重叠执行。`tools/pre-execute` 和 `tools/post-execute` 按模型顺序运行,因为中间件可能维护对顺序敏感的状态。`tools/execute` 包装层会环绕并发派发运行,因此必须能在不同执行之间重入。 + +每个已启动的调用都会在进入 pre-execute 门禁之前立即追加 `tool/call`。已完成的派发占据模型顺序的槽位;提交游标只有在下一个槽位就绪时,才会追加 `tool/result` 并收集 `additionalContexts`。实时界面可以显示多个待处理调用,但结果和工具执行后的上下文仍按模型顺序排列。 + +如果在一组启动前中止,系统不会记录该组的任何调用。如果在一组执行期间中止,系统会停止补充池,等待已启动的调用,按顺序提交其结果,在这些结果之后排空已接受的批次上下文,然后通过现有中止路径结束该步骤。从未启动的调用没有审计事件。 + +Code Mode 仍不使用此调度器,因为模型只会发出一个原生 `run_code` 调用。`run_code` 及其内部派发队列仍按串行方式执行;`mode: 'both'` 中的原生并列调用使用常规调度器。 + +## 安全契约 + +工具返回 `true` 即承诺:其主体可以与其他并行调用同时运行。它不得直接变更父会话或其他由父级拥有的状态;它将输出返回给循环,由循环按模型顺序提交。 + +执行期间触及的任何共享状态都必须支持并发。这也包括工具包装层和提供方:它们可以在内部串行化,也可以实施自身容量限制,但必须在并发派发时不破坏状态。 + +## 配置与声明 + +`maxParallelToolCalls` 是 AgentLoop 的正整数部署上限,由工厂创建的所有 agent(智能体)共享。默认值为 `10`;`1` 保持串行执行。字段和默认值的精确定义见生成的[配置目录](../../../../docs/config-catalog.md)。 + +当前实现中的声明保持保守。Web 搜索、Web 获取和文件系统读取选择并行。文件系统写入与编辑、bash 工具、subagent 委派、工作流、用户交互、todo 变更、Code Mode 以及 Cordis 变更工具仍按独占方式执行。subagent 可能共享父级的工作区或外部资源,而一元分类器无法证明并列委派的作用互不重叠。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。 + +文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。 + +## 验证 + +单元测试覆盖固定了安全退化的分类、类型化参数验证、分组、屏障、替换注册表后的实时重新分类、滚动上限、独立执行对象、中间件顺序、有序结果与上下文,以及中止排空。第一方测试固定每项并行声明。 + +快照覆盖固定了可见的多调用 transcript(文本记录):待处理调用可以重叠执行,已完成结果仍按模型顺序排列。Code Mode 覆盖固定其串行边界。此调度属于确定性循环行为,因此无需依赖提供方的 e2e 测试。 + +## 备选方案 + +**保持串行执行。** 这可以避免新的顺序和中止情形,但会保留独立并列调用所产生的不必要延迟。 + +**使用一个工具级布尔值。** 固定的 `supportsParallelToolCalls` 标志更小,但无法区分同一工具的只读操作和变更操作。感知参数的分类器保留了这项区分。 + +**使用有状态的分类。** 向分类器提供实时 agent、注册表或 I/O 访问,会使决策依赖分类器的运行时机,并在分类与派发之间留下缺口。可变授权和陈旧状态检查仍属于执行时职责。 + +**使用感知并列调用或感知资源的分类。** 调度器可以成对比较调用,或让每个调用声明资源读写要求。这样可以并行化不冲突的写入,却要求不相关工具共享资源标识和冲突语义。一元契约选择放弃这部分并发性,并在安全性取决于关系时安全退化。 + +**并行执行完整的工具流水线。** 这样可以让循环继续使用公开的单调用 API,但会并发运行 pre-execute 和 post-execute 中间件。现有防护和钩子桥可能承载有序状态,因此只允许派发重叠。 + +**公开分阶段方法或调度 waterfall。** 公开的 `prepare` / `dispatch` / `finalize` 方法或 `tools/execution-mode` 事件,会在出现另一个消费方之前扩大扩展接口。循环使用内部调度器视图,而 `executionMode(exec)` 为策略 seam 保留了插入点。 + +**在模型流式输出时启动调用。** 这可能进一步降低延迟,但会改变 assistant 消息的权威性、回放以及调用/结果配对。调度器只在 assistant 消息完成后才启动。 + +**使用固定大小的窗口。** 如果在启动下一个窗口前等待当前窗口的每个调用,一个缓慢调用就会使容量闲置。滚动池在保持上限的同时避免了这项延迟。 + +**向模型暴露并发元数据。** 模型已可以发出并列调用。宿主调度元数据会扩大请求,却无助于工具选择。 + +## 影响 + +该设计以安全退化为原则,对工具作者而言也很简单,但无法利用必须通过比较并列调用才能确认安全的并发性。工具过于宽泛地选择并行,可能暴露潜在的共享状态竞态。 + +在某些情形下,并行调用会先行启动,而串行执行原本会在轮到这些调用之前中止。因此,调度器只记录已启动的调用,在中止时将其排空,且取消后绝不启动替换调用。 + +有序提交可能会让快速结果等待较慢的早期并列调用。这保留了回放和模型历史顺序,同时实时界面仍可显示待处理进度。 + +并发外部调用可能会争用配额或进程容量。提供方负责自身容量控制;循环上限只限制一个 agent 步骤中的调用数量。 + +工具注册是调度边界。调度器会在每个屏障之后以及每次补充池之前重新分类,因此注册表变更会影响尚未启动的调用。已启动的调用保留它们进入池时所依据的调度决策。 diff --git a/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.i18n.yaml b/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.i18n.yaml new file mode 100644 index 0000000000..ca8877d5a7 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.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 +2026-07-13-session-query-tracing.md: 47c12824a331546676d3bc79920f861afe648431 +2026-07-13-session-query-tracing.zh.md: 485060f9e57b5644f7b364e2120bfe30607b1945 diff --git a/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.md b/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.md index 08f856863e..47c12824a3 100644 --- a/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.md +++ b/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-13-session-query-tracing.zh.md) + ## Problem Session relationships are encoded across immutable headers, positional surface operations, and logged provenance arrays. A consumer reconstructing those relationships directly would need to duplicate corpus precedence, surface folding, malformed-log handling, deterministic lineage ordering, and cloning. Positional replacement and provenance are different graphs, so collapsing them into one generic edge type would also lose meaning. diff --git a/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.zh.md b/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.zh.md new file mode 100644 index 0000000000..485060f9e5 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-13-session-query-tracing.zh.md @@ -0,0 +1,36 @@ +# Agent Note: 会话查询关系追踪 + +Status: implemented + +[English](2026-07-13-session-query-tracing.md) | 中文 + +## 问题 + +会话关系分散编码在不可变 header、位置式表面操作和已记录的来源数组中。消费方如果直接重建这些关系,就必须重复实现语料优先级、表面折叠、格式错误日志的处理、确定性的谱系顺序和克隆。位置替换与来源属于不同的图,因此把两者合并为一种通用边类型也会丢失含义。 + +## 决策 + +`ctx.sessionQuery` 除精确读取外,还公开 `traceSession(sessionId)` 和 `traceEvent({ sessionId, seq })`。两者都是基于现有「实时数据优先」语料的一次性视图:会话追踪读取一次完整语料列表,事件追踪读取一份逻辑日志并执行一次规范表面折叠。服务在调用结束后不会保留谱系、反向索引或替换状态。 + +`SessionLineageTrace` 返回目标、按从直接父级到外层父级排序的已知父级,以及递归的后代树;同级节点先按创建时间排序,再按 session id 排序。`complete: true` 会携带已知根节点;`complete: false` 会携带第一个无法解析的父级 id。与目标相连的循环会以 `SESSION_QUERY_INVALID_LINEAGE` 失败。 + +`SessionEventTrace` 将位置关系与来源关系分开保留。`replacedBy` 是直接的位置替换者,`replacementChain` 沿替换者追踪至最终节点,`replacedEventSeqs` 则列出目标直接移除的真实表面节点。`sourceEventSeqs` 保留日志中直接来源的顺序,而 `derivedEventSeqs` 按日志顺序列出后续的直接反向引用。来源关系不会传递展开。 + +## 校验边界 + +事件追踪会在分析表面之前检查目标是否存在。随后,事件列表与追踪都会使用 `dsh-session` 的单遍表面折叠,对加载的日志整体进行接受或拒绝:事件 seq 从零开始且连续;表面标记符合事件类型的适用范围;只有表面事件类型可以携带来源;存在的数组必须非空且没有重复项;每个来源必须是更早的 seq;每次位置替换必须指明并引用它所移除的全部表面节点。任何契约违例都使用 `SESSION_QUERY_INVALID_SURFACE`;系统不存在只用于分类、要求更弱的表面标准。 + +所有返回的记录与数组都与内部状态分离。已知的实时事件追踪绝不查询持久化;持久化事件追踪保留精确读取所要求的列表/加载一致性检查。会话谱系必然属于跨语料操作,因此也保留跨语料的持久化失败语义。 + +## 考虑过的替代方案 + +- **公开独立的追踪辅助函数**:不予采纳,因为源优先级与状态分离边界属于 `ctx.sessionQuery`;公开辅助函数会诱使调用方绕过该边界。 +- **合并替换边与来源边**:不予采纳,因为位置替换可以遮蔽表面节点,同时引用不在表面上的构造输入,而消费方需要区分这两种含义。 +- **返回传递来源闭包**:不予采纳,因为这会掩盖日志中直接记录的证据、增大结果,并让一条遥远的格式错误边改变原本局部的输出。 +- **在格式错误的来源关系上返回尽力而为的追踪结果**:不予采纳,因为结构上看似合理的局部图会显得具有权威性。当规范的关系契约损坏时,精确检查必须快速失败。 + +## 影响 + +消费方无需缓存或引入第二份语料,即可获得确定性的关系视图。事件追踪每次调用都会执行全日志校验和分配,而谱系追踪每次调用都会列出完整的逻辑语料。这些成本让真源保持明确,并且与承载内容的全文搜索及过滤 API 相互独立。 + +该功能具备单元测试和服务层覆盖率,但没有快照或端到端 fixture(测试前置数据),因为它没有引入面向模型的消费方、transcript(文本记录)变更或跨进程协议。 diff --git a/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.i18n.yaml b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.i18n.yaml new file mode 100644 index 0000000000..9a0f4cfbda --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.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 +2026-07-13-documentation-site-projection.md: 2452c9dfa53e05061446df2fe650f3b4d6428c01 +2026-07-13-documentation-site-projection.zh.md: 9df230ea8adeb8744387a5f7efdf288d6a1f6eaa diff --git a/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md index a5c15686ae..2452c9dfa5 100644 --- a/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md +++ b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.md @@ -2,6 +2,8 @@ Status: implemented +English | [中文](2026-07-13-documentation-site-projection.zh.md) + ## Problem The repository needs a navigable documentation website without turning the website directory into a second documentation source. Copying package guides, architecture pages, or generated catalogs into a site-specific tree allows the two copies to drift, while pointing VitePress directly at the repository root couples public URLs and navigation to the internal file layout. Repository-relative links also need different destinations on the website: published pages stay inside the site, but source files and unpublished contributor documents belong on GitHub. diff --git a/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.zh.md b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.zh.md new file mode 100644 index 0000000000..9df230ea8a --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-13-documentation-site-projection.zh.md @@ -0,0 +1,47 @@ +# Agent Note: 将规范文档投影到网站 + +Status: implemented + +[English](2026-07-13-documentation-site-projection.md) | 中文 + +## 问题 + +仓库需要一个可导航的文档网站,但不能让网站目录成为第二个文档源。把包(package)指南、架构页面或生成目录复制到网站专用目录树,会使两份副本发生漂移;让 VitePress 直接指向仓库根目录,又会把公开 URL 和导航与内部文件布局耦合。仓库相对链接在网站上也需要指向不同位置:已发布页面应留在站内,源文件和未发布的贡献者文档则应指向 GitHub。 + +## 决策 + +规范 Markdown 保留在拥有它的仓库层级中。面向产品的指南位于 `docs/user/`,生成的参考资料保留在现有生成目录中,架构页面和实操手册(cookbook)页面也保留在现有的 `docs/` 路径。 + +`website/docs.ts` 是一份显式的发布 manifest(元数据清单)。每个条目将一个规范源文件映射到稳定的公开路由、侧边栏、分区和顺序。因此,新增或移除已发布页面是一项可评审的 manifest 变更,而不是隐式目录扫描的结果。 + +在 VitePress 启动或构建之前,`scripts/project-doc-site.ts` 会把 manifest 投影到被忽略的 `website/.generated/` 目录。生成目录树遵循公开路由,使 VitePress 导航、locale 检测和本地搜索使用同一套路由词汇。每个页面都会获得一个指向其规范仓库文件的 `editSource` frontmatter 字段;编辑链接回调只读取该页面的数据,因此公开 URL 与源文件布局彼此独立。 + +各 locale 的首页投影只保留规范 YAML frontmatter。面向仓库的正文可以保留其 H1 和双语源文件链接,而 VitePress 首页主题负责渲染 hero 与功能区,网站导航负责切换 locale。 + +投影器解析 Markdown 链接,但不会重新序列化文档。指向另一个已发布源文件的链接会变成站内相对路由;指向未发布仓库文件的链接会变成 GitHub 源文件链接;仓库图片会变成 GitHub raw URL。相对目标不存在时,投影快速失败。单元测试固定这些转换,`docs:check` 则运行投影器测试和 VitePress 生产构建,并将二者纳入 `doc-sync` 和并行文档门禁。 + +`website/AGENTS.md` 是网站子树中唯一维护的 Markdown 文件。投影器测试会枚举已跟踪且未被忽略的文件,并拒绝网站中的任何其他 Markdown,因此网站专用的 locale、路由、API 或生成源文件副本无法绕过发布 manifest。 + +Mermaid 渲染规范图表。网站工作区显式声明 `vitepress-plugin-mermaid` 要求 Vite 预打包的 5 个包,因为 pnpm 的严格依赖隔离会使本地开发服务器无法使用这些传递依赖;Knip 将这种仅运行时使用记录为有意的依赖例外。 + +网站发布与网站构建保持分离。专用 GitHub Actions 工作流运行现有文档门禁,将 `website/.dist` 作为 Pages 产物上传,并只在构建成功后部署。`actions/configure-pages` 在构建时向 VitePress 提供目标位置的 base path,因此私有 Pages 源站、未来的公开项目路径和自定义域名不需要各自的检入配置。Pages 可见性仍是仓库托管设置,而不是工作流权限。 + +## 考虑过的替代方案 + +**在 `website/` 下提交复制的 Markdown。** 这种方式让 VitePress 设置更直接,但每份复制的指南或 API 表格都会多出一个所有者,并且需要一套无法识别权威副本的同步约定。 + +**让 `website/` 成为每个已发布页面的规范归属。** 这种方式仍只有一份副本,却只是为了满足渲染器,就把架构、生成的参考资料和面向贡献者的材料移出了各自的仓库归属层级。 + +**自动发现所有 Markdown 文件。** 这种方式最大限度减少 manifest 维护,却会意外发布内部文档、把源文件移动暴露为 URL 变更,并根据偶然的目录顺序生成导航。 + +**使用文件系统符号链接。** 符号链接保留单一来源,却无法解决公开路由或仓库相对链接问题,而且在本地开发、包工具和托管 CI 环境中的行为不够可预测。 + +**只在部署工作流中构建。** 部署作业可以在合并后发现渲染故障。把生产构建纳入 `doc-sync`,则无论是否存在公开部署,同一个故障都能在本地和常规 CI 中暴露。 + +**硬编码公开项目路径。** 固定的 `/deepseek-harness/` base 适用于公开项目 URL,却不适用于私有 Pages 站点分配的唯一源站,也不适用于未来的自定义域名。使用 Pages 元数据可让这些目标位置共享同一份构建契约。 + +## 后果 + +文档事实只有一个可编辑归属,公开路由在源文件移动后仍保持稳定,网站也能纳入生成的参考资料而无需提交另一份生成副本。本地开发会监视规范输入并重新生成一次性投影。布局门禁会把陈旧的网站专用 Markdown 目录树变成合并失败,而不是被忽略的构建输入。影响文档网站的合并会把检查过的结果部署到 Pages,手动触发则提供恢复与验证入口。 + +发布 manifest 是一份需要维护的 allowlist,链接投影也引入了一层仓库专用的构建适配器。新增一种 Markdown 链接行为时,需要增加投影器测试。Mermaid 支持也会增大客户端 bundle,但能保留规范文档中已经使用的图表。 diff --git a/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.i18n.yaml b/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.i18n.yaml new file mode 100644 index 0000000000..7dcdab8078 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.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 +2026-07-06-recallable-compaction.md: ed5491e642ea7ac99fd9f4ba071a61e655f968d3 +2026-07-06-recallable-compaction.zh.md: 4060df2c2550f9ea3287adfb51d097c1a60baf71 diff --git a/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.md b/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.md index 3f54030f9d..ed5491e642 100644 --- a/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.md +++ b/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-07-06-recallable-compaction.zh.md) + ## Problem Compaction is a one-way door. The summary the model sees carries no reference to what it shadows — the `shadowedRange` provenance lives only on the log-only `compact/summary` event — and no tool lets the model read a shadowed span back. Whatever the summarizer drops is gone from the model's reachable world, even though the append-only log holds every byte. Repeated compaction compounds this: the head checkpoint is rewritten every pass, so the request prefix takes a full prompt-cache miss each time, and earlier summaries are re-summarized generation after generation. diff --git a/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.zh.md b/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.zh.md new file mode 100644 index 0000000000..4060df2c25 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-07-06-recallable-compaction.zh.md @@ -0,0 +1,110 @@ +# Agent Note: 可回溯压缩(compaction):索引检查点、状态检查点与会话内历史回溯 + +Status: proposed + +[English](2026-07-06-recallable-compaction.md) | 中文 + +## 问题 + +压缩是一扇单向门。模型看到的摘要没有指向被其遮蔽内容的引用,因为 `shadowedRange` 来源只存在于仅写入日志、模型不可见的 `compact/summary` 事件上,也没有工具能让模型重新读取被遮蔽的区段。即使仅追加日志仍保存每一个字节,摘要器丢弃的内容也会离开模型可触达的世界。重复压缩会进一步放大问题:每一轮都会重写头部检查点,因此请求前缀每次都会完全失去提示词缓存命中,而更早的摘要也会一代又一代地被重新摘要。 + +根本原因是一个产物承担了两个互相冲突的角色。**索引** 需要冻结、按时间排序且成本低廉;模型的**工作记忆** 则需要全局视图、重新确定优先级并且可变。单一摘要无法同时胜任两者。 + +主流编码 harness 都没有让模型在循环内回溯,而且调研过的实现均未让压缩感知前缀缓存。事件溯源会话具备持久原文、可按 seq 寻址和精确回放的特征,是支持这两项功能的天然底座。 + +## 提案 + +把检查点拆为两类,并让被遮蔽的历史重新可达。 + +### 冻结的索引检查点 + +新近变为陈旧的历史按确定性策略拆分为分片:向 `chunkTokens` 累积;使用 `toolPairingBalancedBefore`/`toolPairingBalancedAfter` 对齐边缘;优先选择轮次边界;在平衡允许的范围内,把最终边界放在尽量接近保留边界的位置,使尾随切片缩小到大约一个轮次。每个分片通过一次 `compactRegion` 调用压缩为一个**索引存根**(`stubTokens`,约 100–200 个 token): + +- 用两三行说明发生了什么; +- 用一行关键词记录低频字面锚点,例如确切的错误字符串、值和配置键,并按类别分组; +- 由代码组装页脚:`[checkpoint c: shadows conversation span #–#; originals retrievable via history_read]`。指针根据来源组装,绝不由模型编写。 + +已经提交的存根永不重写,也绝不再次进入之后的压缩区域。存根调用采用分层输入:固定前导内容与逐字节相同的本轮开始状态检查点(该阶段所有调用共享的前缀);随后是先前所有已提交存根的关键词行,使新条目索引其分片的独特内容,而不是重复整个目录;再加最近一两个已提交存根以维持时间连续性;最后是切片本身。同一轮中的同级存根不作为输入,因为并发阶段禁止这种依赖,而与轮次对齐的边界已经维持局部连续性。状态检查点只作为背景,绝不能成为存根需要总结的材料。完全由回溯内容构成的切片只通过代码生成存根,即只写一行指针,不调用 LLM(大语言模型)。存根调用失败时采用相同降级方式:其切片获得一个仅包含代码指针的存根,本轮继续执行,使状态重写成为一轮中唯一的强制 LLM 依赖。 + +### 状态检查点 + +系统维护一份可变的工作记忆文档(最多一份;第一次压缩前为零份),位于所有存根之后、保留尾部之前。每一轮根据先前状态与本轮变为陈旧的内容重写它,成本为 O(previous + new);过程遵守摘要提示词中已有的「合并而不重复陈述」规则,并覆盖决策、当前状态、约束和后续步骤。它带有自己的页脚,其大小上限与当前摘要处于同一量级。 + +膨胀保护会约束整轮操作:如果压缩后大小没有严格小于压缩前大小,就不提交任何内容,并继续当前轮次;本次尝试延后至积累更多陈旧历史后再进行。保护逻辑在两侧比较同一项度量:优先使用请求路径上提供方报告的用量;如果不可用,则两侧都回退为字符估算器。 + +### 一轮的执行过程 + +- 分片切片由表面位置范围表示。一轮分两个阶段运行:所有摘要调用先并发执行并在表面之外缓冲;随后严格从左到右提交区域,先提交各分片,最后提交尾随切片,使状态检查点通过连续的单节点替换落在所有存根之后。墙钟时间维持在接近一次摘要调用的水平。 +- 被取代的状态检查点会作为普通历史折入下一轮的第一个分片,不需要墓碑或新原语。其存根省略该状态,`history_read` 会把它渲染为 `[prior state checkpoint]`,并让页脚随渲染文本一同传递,使每个尾随切片都可通过两跳链路触达。 +- 范围选择会感知冻结边界:可压缩区段从最后一个已提交索引检查点之后开始;只有在不存在索引检查点时,才从表面头部开始。旧会话现有的头部检查点会被视为状态类检查点:其文本作为合并基线,其节点则像其他被取代状态一样折入历史。 +- 摘要阶段发生崩溃时不会提交任何内容;提交中途崩溃会留下一个从左到右的已提交前缀,恢复后的一轮从日志中最新的状态类 `compact/summary` 事件读取合并基线,并无条件提交剩余区域。恢复 `[stubs…][state][tail]` 的优先级高于缩减大小。 + +### 回溯工具 + +新增包(package)`@deepseek-ai/dsh-tool-recall`,它只是 `dsh-session` 与 `dsh-compact` 词汇之上的消费方,注册两个面向模型的工具: + +- `history_read(checkpoint, offset?)`:把日志中任意检查点(包括已被取代的检查点)遮蔽的区段渲染为 `User:`/`Assistant:`/`Tool result:` transcript(文本记录),并按配置预算分页,提供续传游标。 +- `history_search(query, checkpoint?, limit?)`:对每个被遮蔽区段进行不区分大小写的字面量扫描;返回带检查点 id 的片段与覆盖元数据(`scanned`/`matched`/`truncated`)。零匹配提示会说明扫描按字面量执行,并建议对可能的检查点直接使用 `history_read`。 + +两个工具都读取 `exec.agent.session.events`(沿用 tool-todo 访问模式;拒绝非 agent(智能体)调用方),只渲染表面类型的消息事件,并返回普通 `tool/result`:回溯字节会进入上下文尾部并记录到日志,因此无需特殊处理即可满足可重建性。系统不增加新存储或伴随索引:会话日志是归档,`compact/summary` 来源是索引元数据,而这些工具是两者之上的读取路径。工具 schema 与该包唯一的系统提示词章节都是静态字符串;检查点 id 只会通过页脚抵达模型。transcript 渲染器从 `compact-basic` 移入 `dsh-session`,供摘要器与工具共享。 + +### 缓存与成本 + +一轮后的请求前缀为 `[system][stubs…][state][tail]`。冻结存根在各轮之间逐字节稳定,因此缓存缺失从替换先前状态检查点的 token 才开始,规模保持 O(new chunks + state + tail),而当前实现会从位置零开始缺失。回溯输出落在尾部,不会改变前缀。每轮摘要输入大约是当前实现的两倍,另加一个 m·S 背景项;该成本受到 `chunkTokens` 下限(状态上限的小倍数)以及经过校验的 `stubTokens`/`chunkTokens` 比例上限约束。共享前缀输入布局依次为前导内容、逐字节相同的本轮开始状态、位于尾部的切片内容,使同级调用可以按缓存费率重复读取。 + +### 打包方式 + +该设计以新的后端 `dsh-compact-recallable` 交付,挂在现有 `ctx.compact` seam 上,并在已交付的示例配置中默认启用。`compact-basic` 保留为参考实现和该 seam 的设计对照,与成对 LLM 适配器的模式一致。seam JSDoc 中「最多一个自动生成的检查点,始终位于头部」这一条会放宽,改为说明两个后端各自的行为。 + +### 与进行中工作的关系 + +- **工具结果裁剪**(进行中的裁剪服务):其替换节点携带 `sourceEventSeqs`;同一注册表折叠会把经过裁剪的结果列为可回溯。它属于后续范围,两项工作互不阻塞。 +- **提供方 token 用量核算**(正在把压缩压力迁移至提供方报告用量的工作):为保护逻辑提供核算基础;本实现堆叠在它之后。 +- **「查询会话」backlog(待翻清单)条目**:它是跨会话的泛化方案;本 Agent Note(agent 决策记录)把范围限定在实时会话内,并选择工具名称与渲染方式,使该工作能够扩展本设计而不产生冲突。 +- **训练**:何时回溯属于学习到的行为。确定性页脚与关键词锚点为训练提供稳定目标,而回溯使用情况在会话日志中完全可见,可供轨迹导出;基准测试与 RL 设计由后训练侧推进。 + +### 后续事项 + +以下项目在评审期间已经明确,但会延后至观察结果证明需要时再实现: + +- 保护逻辑降级阶梯(通过代码汇总最早的存根前缀,保留页脚,已汇总 id 仍可作为回溯目标;随后在冻结边界后生成一份摘要):触发条件是观察到保护逻辑活锁或存根区域压力。 +- 存根输出回声检测(句子级 n-gram,豁免短字面量;先重试,再剥离):触发条件是观察到职责分工泄漏。 +- 定期使用分片原文刷新状态:触发条件是交接探针观察到漂移。 +- `stateFallbackThreshold`(存根数量低于阈值时使用完整细节的状态提示词):触发条件是短会话回归。 +- 延迟注册回溯工具:触发条件是在从不进行压缩的会话中测得上下文开销。 +- 在 pre-step 分摊存根起草工作:一旦已经陈旧但尚未压缩的内容积累超过 `chunkTokens`,就在下一个 pre-step 起草该分片的存根(一个仅写入日志的草稿事件,在分片周围的上下文仍然存活时写入),让压缩轮提交草稿,而不是集中执行摘要。这是后台压缩的确定性、精确回放等价形式(Claude Code 会话记忆采用这种模式;OpenClaw 证明同步语义完全相同)。触发条件是观察到一轮延迟,或近实时起草带来的存根质量收益得到验证。 +- 拆分摘要模型;由模型选择分片边界;跨会话回溯;语义搜索回退:每项都必须由各自证据支持。 +- 更丰富的 `history_search` 查询形式:正则表达式,以及对日志 JSON 工具结果执行的结构化查询(sql/jq 风格,或由 agent 针对索引存储编写查询)。触发条件是观察到搜索漏检;首版先交付字面量匹配,使回溯路径保持为日志的纯函数。 + +## 考虑过的替代方案 + +- **分阶段交付**(先在当前后端之上单独交付回溯工具;观察到回溯使用后,再决定是否拆分检查点):不予采纳。未经训练的模型会低频使用任何新工具,因此该条件测量的是训练缺失,而不是设计价值;训练侧需要完整机制来构建环境;预发布阶段修改持久化格式的成本最低;缓存经济性则属于第一方已经掌握的知识,不是等待遥测验证的假设。实现仍以堆叠 PR 方式落地,并先交付回溯工具,但这只是构建顺序,不是决策门槛。 +- **只保留冻结的全尺寸摘要,不设状态检查点**:不予采纳,因为永久前缀会无界增长、自我加速并最终发生颠簸,而且没有任何内容可以重新确定优先级。 +- **只保留纯存根,不设状态检查点**:不予采纳,因为这假定模型知道自己缺少什么,在面对未知的未知时会失败。 +- **由 LLM 老化/整合冻结分片**:不作为常规机制,因为摘要的摘要会丢失信息,并使冻结前缀频繁变化;其保留下来的形式是由代码汇总,且延后实现。 +- **把完整前缀作为分片摘要器输入**:不予采纳,因为成本为 O(N²);状态文档以 O(state) 提供相同背景。 +- **一次摘要调用输出全部结果**:不予采纳,因为摘要路径没有结构化输出约束;解析一份自由文本响应并将其拆开,正是保守失败设计要避免的脆弱 seam。 +- **由模型选择分片边界**:延后实现,因为相对于未经证明的收益,解析与校验成本过高;分片策略位于配置之后。 +- **由模型编写指针**:不予采纳,因为指针必须精确,应由确定性代码组装。 +- **FTS/向量索引伴随存储**:在会话内不予采纳,因为实时日志已在内存中且大小有界,在预算内进行字面量扫描已经足够;只有跨会话范围才能证明索引的价值。 +- **回溯路径中的语义搜索回退/次级模型提取**:不予采纳,因为其中的 LLM 或嵌入调用会破坏无密钥回放的确定性;回溯必须保持为日志的纯函数。 +- **使用原始事件而不是渲染后的 transcript**:不予采纳,因为这会泄漏仅日志可见的词汇与分片噪声;模型应读取模型曾经看到的内容。 +- **什么都不做(用 resume/fork 恢复)**:不予采纳,因为这会把恢复变成人工操作。 + +## 验收标准 + +- 长会话自动压缩后,每一轮完成时都会得到 `[stubs…][state][tail]`;先前存根在各轮之间保持逐字节相同;已提交存根绝不落入后续区域;被取代的状态检查点无需墓碑即可折入历史,渲染时带有标签,并可通过两跳链路触达和搜索。 +- 每个检查点的表面文本都以确定性页脚结束;页脚通过回放逐字节往返;状态检查点的来源记录其更宽的输入范围。 +- 在全部摘要就绪且保护逻辑通过同类核算前,不提交任何内容;保护失败不会提交任何内容,也不会让轮次失败;提交中途被终止后,下一次 pre-step 会恢复处理,从日志读取合并基线,并无条件提交状态区域以完成本轮;旧版头部检查点会被视为状态类。 +- `history_read` 在预算内渲染任意已记录检查点的区段,并提供可用游标;`history_search` 覆盖每个被遮蔽区段,返回带检查点 id 的片段与覆盖元数据,测试尤其要能找到只存在于被已取代状态检查点遮蔽区段中的内容,这是锁定尾随切片可达性的回归用例;两个工具都会拒绝非 agent 调用方,并对从未存在的 id 或遗留 `compact/start` 返回类型化错误;回溯内容作为普通 `tool/result` 出现;请求重建不变量会在同时包含压缩与回溯的会话上通过;一项无密钥快照场景端到端覆盖先压缩再回溯;工具 schema 与提示词章节在各轮之间逐字节相同。 +- 在长时间跨度 bench 套件中:任务成功率在预算相同的条件下不低于 `compact-basic`;交接保真探针(在一轮后重新陈述 K 项已知决策和约束)的得分不降低;每次运行都通过 dsh bench 报告流水线汇报回溯使用频率和命中有效性,并同时报告存根目录注意力度量与缓存命中遥测。 +- seam JSDoc、压缩能力 seam Agent Note、`architecture.md`,以及生成的工具、配置、持久化与模块图目录都在同一改动中更新;全部预算位于配置中;新源码目录具备逐文件 100% 覆盖率与 HMR(热模块替换)释放测试。 + +## 风险 + +- **回溯属于学习到的行为**:未经训练的模型会低频使用它,bench 报告会持续追踪这项差距,直至训练弥合问题。在此之前,状态检查点会让质量下限保持在当前摘要水平。 +- **未知的未知仍然存在**:如果某项细节既未出现在摘要中,也未出现在关键词中,就不会触发回溯。回溯把「即使已经怀疑也无法触达」变成「怀疑时可以触达」。 +- **存根目录会占用注意力**:每次请求中包含数十张稳定的索引卡,可能稀释模型关注点;验收标准中的 bench 度量会将其与 `compact-basic` 对比。 +- **成本**:每轮摘要输入大约是当前实现的两倍;短会话的成本和质量接近当前水平,而设计收益随会话长度增长。 +- **状态漂移与职责分工泄漏** 可以通过交接探针和存根评审观察;对应措施已列为后续事项。 +- **两个后端** 会增加维护接口;seam 契约和共享回溯消费方会约束该成本,bench 对比则用于逐步决定默认实现。 diff --git a/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.i18n.yaml b/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.i18n.yaml new file mode 100644 index 0000000000..d392c8cf22 --- /dev/null +++ b/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.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 +2026-07-13-human-review-skill-maintenance.md: 76391bd110b7a86b194a9340ffcf7cc4602d1d2e +2026-07-13-human-review-skill-maintenance.zh.md: 67d68d07cc7f467a310b64d833a28da6f04bcc8e diff --git a/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.md b/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.md index 6d4de215c9..76391bd110 100644 --- a/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.md +++ b/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.md @@ -2,6 +2,8 @@ Status: proposed +English | [中文](2026-07-13-human-review-skill-maintenance.zh.md) + ## Problem The `dsh-code-review` skill records failure modes that require reviewer judgment, but one-off audits are expensive to repeat and easy to scope inconsistently. Treating every comment as a lesson produces checklist bloat; treating merge, thread resolution, or an author's “fixed” reply as proof of adoption promotes feedback that the final code may not implement. The maintenance process needs enough evidence and independent review to fail closed without requiring a webhook service, durable event state, or automatic repository promotion before the workflow has proven useful. diff --git a/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.zh.md b/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.zh.md new file mode 100644 index 0000000000..67d68d07cc --- /dev/null +++ b/.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.zh.md @@ -0,0 +1,85 @@ +# Agent Note: dsh-code-review 的定期人工评审维护 + +Status: proposed + +[English](2026-07-13-human-review-skill-maintenance.md) | 中文 + +## 问题 + +`dsh-code-review` skill(技能)记录需要评审人判断的失败模式,但一次性审计既难以重复,作用域也容易不一致。把每条评论都当作教训会让检查清单不断膨胀;把合并、讨论串已解决或作者回复「已修复」视为采纳证据,则会把最终代码可能并未落实的反馈提升为规则。维护流程需要足够的证据和独立评审,以便在证据不足时按不采纳处理,同时无需在工作流证明有用之前引入 webhook 服务、持久事件状态或自动仓库推广。 + +## 提案 + +在仓库外定期维护。一项保存在 skill 维护者机器上、而不提交到本仓库的私有工具,会针对刷新至 `origin/master` 的干净完整历史 checkout 运行。预期的调度器每天运行,并使用两天的 UTC 重叠窗口;手动运行可以通过另一个 `--since` 时长或重复的 `--pr` 参数指定显式集合。扫描相对于当前 skill 是幂等的,不存储仓库游标。推广时唯一会变更的仓库文件是 [.agents/skills/dsh-code-review/SKILL.md](../../../skills/dsh-code-review/SKILL.md);draft PR(Pull Request)携带来源概述,因此评审人无需私有适配器日志,也能审计源反馈与采纳证据。 + +```mermaid +flowchart TD + A["Maintainer or scheduler runs the tool on origin/master"] --> B["List PRs merged in the overlap window"] + B --> C["Collect pre-merge User feedback and final PR evidence"] + C --> D["Two reviewers verify provenance and adoption"] + D --> E{"Both confirm human-authored and adopted?"} + E -- "No" --> F["Exclude or retain as unresolved"] + E -- "Yes" --> G["Two reviewers classify against the current skill"] + G --> H["Draft a complete candidate from agreed guidance"] + H --> I["Two reviewers inspect the same skill diff"] + I -- "Blocking finding" --> J["Bounded revision loop"] + J --> I + I -- "Both approve" --> K["Run documentation and lint checks"] + K --> L["Leave a reviewed local working-tree diff"] +``` + +### 采集契约 + +每个选定的 PR 都会在获取任何反馈前接受过滤:其 merge commit 必须是 `origin/master` 的祖先。merge commit 可达性是唯一的资格检查:直接 base 为功能分支的堆叠 PR,只要该 base 随后已经进入 master,就会被纳入,因为无论中间 stack 如何,评审人评论的代码此时已经在 master 上。工具还会解析落地 merge 的目标父级;无法重建的落地形态会记录到 `skipped-pulls.json` 并跳过。单个 PR 在预检、采集或证据收集时失败,只会被跳过,不会中止整次运行。如果时间窗口会超过 GitHub 搜索的 1,000 条结果上限,搜索阶段会明确失败,避免无提示地遗漏已合并 PR。采集阶段会完整读取内联评审评论、评审提交和 PR commit 的分页连接。不采集 PR 对话评论,因为强制推送后,GitHub 当前状态无法证明哪个仍然存在的 commit 位于评论之前,采纳契约因此必然会无条件排除这些评论。只有当 GitHub 报告 actor `type` 为 `User`,并且创建时间与最后编辑时间都严格早于 PR 合并时,工作流才接受已采集反馈;与合并同一时间戳的编辑视为合并后操作。评审提交使用 GraphQL 的 `lastEditedAt`,因为 REST 表示不含编辑时间。 + +### 采纳证据 + +每条反馈都携带稳定的来源 ID 和有界的变更证据。评审人的 `commit_id` 仍属于该 PR 时(强制推送场景无法确认即排除),工具会选择 committer 时间戳严格早于反馈的最新 PR commit 作为基线,而不是采用评审人点击的 commit,因为后者可能更旧。工具绝不会直接比较该基线与落地 merge:这种 diff 会混入不断前移的目标分支中的无关变更。相反,它会向采纳评审人提供两份 PR 专用 patch 快照。令 `B` 为反馈基线,`T` 为落地 merge 的目标父级,`M` 为落地 merge。反馈时快照是从 `merge-base(B, T)` 至 `B` 的树 diff;最终快照是从 `T` 至 `M` 的树 diff。因此,目标分支专有变更不会出现在任一 PR patch 中,而反馈后加入 PR 的变更只会出现在最终快照中。遭到强制推送的评审、早于全部现存 PR commit 的反馈,以及无法重建目标父级的落地形态,会在任何评审人看到之前确定性地归类为 `unclear`。合并状态、已解决讨论串、作者回复「已修复」或同文件编辑只是上下文,不是采纳证明;PR 作者自己的评论绝不会进入适配器,因为它们不可能构成对作者自身意见的采纳。 + +### 双评审人分类与起草 + +两个独立配置的评审适配器,会从来源(`human-authored`、`forwarded-automation` 或 `unclear`)和采纳情况(`adopted`、`rejected` 或 `unclear`)两个维度,对每个符合条件的条目进行分类。只有两个适配器都判定为 `human-authored` 加 `adopted` 的条目才会继续。采纳集合随后会针对当前 skill 接受第二次独立分类:候选项、已经覆盖、实现专用或并非反馈。单个条目即可符合要求,不要求重复出现。意见分歧会得到一次有界的重新评估;如果仍未解决,则继续保留在运行产物中。单个批次的适配器输出如果未通过 schema 或 id 校验,系统会在批次层按不采纳处理:其中的每条反馈都标记为 unclear 并路由到 `excluded`,而不是中止整次运行;有问题的原始输出会保存在该次运行的私有产物中,供调试使用。如果任一适配器在某项操作的任何非空批次中都没有返回有效结果,运行会以非零状态退出并发出失败记录,而不会报告「没有候选项」。 + +主适配器只根据结构化的共同指引起草,绝不接收原始评审文本。根据适配器作者的契约,它保持无工具且只读:返回完整的候选文件内容,由工具校验后写入唯一目标。两个适配器随后评审同一份完整 skill diff;阻塞性问题会进入有界修订循环,而且两者必须批准同一版修订。工具会在运行文档和 lint 检查前,以及报告成功前,再次拒绝暂存改动和目标 skill 之外的编辑,因此检查或并发进程无法通过添加其他路径混入。失败时,工具使用尽力而为的比较并交换恢复自身写入,避免覆盖维护者的并发编辑。成功时,它保存一份候选资料包,其中包含源 `origin/master` commit、源 skill blob ID、已评审 diff、完整候选文件、源反馈 ID 与 URL、落地证据范围、适配器判定和检查结果;它绝不提交、推送、打开或合并 PR。 + +### 评审适配器协议 + +每个私有可执行文件从 stdin 接收有字节上限、带版本的 JSON 请求,并在 stdout 返回有字节上限且符合 schema 的 JSON。两个评审命令解析为逐字节相同的可执行文件时,工具拒绝运行;这是机械性的最低标准,保证主适配器与次适配器由独立提供方或模型驱动,仍是部署运维方的责任。`access` 与 `tools` 字段是适配器作者承担的契约标记,不是 OS 沙箱:评审子进程在清理后的环境中 spawn,其 `cwd` 指向私有运行目录而非仓库根目录;反馈包装在带随机数的 `` 块中,每个提示词都会要求模型把它视为数据;128 位随机数防止不受信任的正文伪造结束标签。每个子进程都采用有界、感知中止的进程树清理。适配器作者把每项操作实现为纯只读推理(inference);即使 `edit` 操作也只会在 JSON 中返回完整候选内容,由工具校验后写入唯一目标。每个生产 `git`/`gh`/检查命令同样在清理后的环境中 spawn,避免 pre-push 钩子的路由变量无提示地重定向维护工具。候选写入与失败回滚会针对最近一次写入内容使用尽力而为的比较并交换;回滚还会取消暂存目标,避免由适配器或检查暂存的候选项在失败运行后遗留并进入之后的 commit。 + +### 推广契约 + +推广辅助工具从刷新至 `origin/master` 的干净 checkout 开始;当前 skill blob 与资料包中记录的源 blob 不同时,它拒绝应用候选项。运维方随后重新运行维护分析,或手动把 diff 变基后重新评审候选项;辅助工具绝不会用陈旧的完整文件输出替换较新的 `SKILL.md`。应用仍然有效的候选项后,它会打开 draft PR,其正文列出源反馈 URL 或 ID、用作采纳证据的落地 commit 范围、来源运行、检查结果和任何运维方编辑。原始适配器提示词与响应保持私有,但仓库评审人会获得足够的来源信息,以判断每条提议规则是否确实来自已采纳的人类反馈。 + +### 机制所在位置 + +工具源码、适配器二进制文件、提供方凭据和预期的每日调度器保存在维护者机器上,不会提交到本仓库。本文规定协议,参考实现属于私有基础设施。该机制只服务于由单个运维方维护的一项 skill,因此,让机制编辑持续接受仓库评审的成本高于来源可追溯性的收益。如果该机制将来移交给第二位维护者,移交工作需要一篇后续 Agent Note(agent 决策记录)来修订本决策;任何接手者都应从运维文档 [docs/cookbook/maintaining-dsh-code-review.md](../../../../docs/cookbook/maintaining-dsh-code-review.md) 入手。 + +## 考虑过的替代方案 + +- **把工具放入本仓库。** 对单维护者作用域不予采纳:仓库维护开销(类型检查、lint、覆盖率与横切重构)会超过已提交来源信息的价值。未来移交时仍可重新考虑。 +- **记录每条反馈产生时的 PR head**:不予采纳,因为这需要持续运行的观察器、持久事件状态、重试和强制推送协调。定期维护会在可用时使用经过评审的 commit 证据,并在整 PR 证据范围过宽、无法确认时直接排除。 +- **持久化已处理 PR 游标**:不予采纳,因为带重叠的时间窗口扫描成本低廉,并且相对于当前 skill 天然幂等;游标状态反而带来恢复和漏事件问题。 +- **每次新评论都运行**:不予采纳,因为一轮评审会产生许多相关评论,并且缺少判断采纳情况所需的最终产物。 +- **把合并或讨论串解决视为采纳**:不予采纳,因为 PR 可能在反馈被拒绝、被取代或刻意不解决的情况下合并。 +- **自动创建或合并仓库改动**:不予采纳,因为工具首先需要通过有用的定期输出积累可信记录。维护者检查并通过普通仓库评审推广本地 diff。 +- **从已经修复的 bot 问题中学习**:不予采纳,因为来源契约限定为人类评审反馈。系统会在分析前按 actor 类型过滤,并通过来源评审排除转发自动化问题的人类账号。 +- **让同一个评审人既当作者又作最终裁决**:不予采纳,因为独立判定能在不受支持的概括进入 skill 之前暴露问题。 + +## 验收标准 + +从 `proposed/` 推广到 `implemented/`,需要在针对本仓库的真实端到端运行中观察到以下全部事实: + +- 私有工具从刷新至 `origin/master` 的干净 detached checkout 运行,并且要么报告「没有候选项」,要么只生成 `.agents/skills/dsh-code-review/SKILL.md` 的 working-tree diff。**2026-07-15 已观察:** 扫描 62 个已合并 PR,跳过 5 个(merge commit 不可达或采集超过 250 个 commit 的上限),考虑 426 条人类反馈,发现 0 个候选项。 +- 两个评审适配器独立配置(不同的提供方或模型),无需用户干预即可完成 analyze/adopt/review 流程。**2026-07-15 已观察:** 不同的主/次适配器约用 8 分钟完成采纳与分析;一次适配器 id 幻觉由批次级保守失败机制处理,没有中止整次运行。 +- 调度器在没有交互式终端的情况下触发工具,并通过持久通知通道把候选 diff(或「没有候选项」记录)送达运维方。 +- 一个受控采集场景会在反馈基线之后,向目标分支加入与反馈匹配的变更;评审证据排除该目标分支专有变更,同时保留后续由 PR 自身加入的变更。 +- 源 skill 改变后,推广辅助工具会拒绝候选项;仍然有效的候选项会按照上文定义的来源概述打开 draft PR。 +- 该工作流生成的至少一个候选 diff 会由运维方检查,并通过普通仓库 PR 评审推广到 `master`。该 PR 用以证明工作流能够把已采纳反馈转化为已交付的 skill 指引。 + +## 风险 + +- **根据 committer 时间戳推断因果关系。** 反馈 commit 基线通过比较 GitHub commit 时间戳与反馈创建时间戳选出;committer 时钟偏差与重写仍会留下误判采纳的残余窗口。与 GitHub 的 PR 事件流交叉比对可以进一步收紧,但需要采集定期工具作用域以外的事件。 +- **两个「非候选项」分类结果会直接路由到 `excluded`,不进入争议轮次。** 两个分类器都判断「不是候选项」,但对非候选原因意见不一时(例如 `covered` 与 `specific`),该条目会被排除而不是重新评估。两个分类器都同意它不会形成新的评审行为,所以争议轮次不会改变结果。 +- **超出字节哈希差异的双评审人独立性属于部署契约。** 两个命令解析为逐字节相同的可执行文件时,工具拒绝运行,但它无法验证两个不同包装层是否由不同提供方或模型驱动。运维方必须配置相互独立的主适配器与次适配器。 +- **候选写入与回滚使用尽力而为的比较并交换。** POSIX 上基于文件的比较并交换并不真正原子;窗口持续一个事件循环周期。该工具面向单用户定期维护,不考虑真正并发的编辑器。 +- **单维护者风险。** 由于机制位于单台机器,服务中断后,skill 维护会完全停止,直到运维方恢复服务,或通过一篇后续 Agent Note 把机制移交给新维护者。 diff --git a/docs/cookbook/maintaining-dsh-code-review.i18n.yaml b/docs/cookbook/maintaining-dsh-code-review.i18n.yaml new file mode 100644 index 0000000000..b983ffd591 --- /dev/null +++ b/docs/cookbook/maintaining-dsh-code-review.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 +maintaining-dsh-code-review.md: 2b5d0d926ae922f2650daac33cf35991cb71c5e5 +maintaining-dsh-code-review.zh.md: c0e8b64fde3a67174878b4b0665712c9ba2e67c0 diff --git a/docs/cookbook/maintaining-dsh-code-review.md b/docs/cookbook/maintaining-dsh-code-review.md index 8af449b749..2b5d0d926a 100644 --- a/docs/cookbook/maintaining-dsh-code-review.md +++ b/docs/cookbook/maintaining-dsh-code-review.md @@ -1,5 +1,7 @@ # Maintaining the dsh-code-review skill +English | [中文](maintaining-dsh-code-review.zh.md) + The [`dsh-code-review`](../../.agents/skills/dsh-code-review/SKILL.md) skill is kept current by a single designated operator running a private periodic maintenance tool. This cookbook is the entry point for that operator — and for anyone taking over the role — and for repo contributors who want to understand why skill updates arrive as small periodic PRs rather than one-off audits. The workflow itself is specified in the [human-review skill-maintenance Agent Note](../../.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.md). ## What the maintainer receives diff --git a/docs/cookbook/maintaining-dsh-code-review.zh.md b/docs/cookbook/maintaining-dsh-code-review.zh.md new file mode 100644 index 0000000000..c0e8b64fde --- /dev/null +++ b/docs/cookbook/maintaining-dsh-code-review.zh.md @@ -0,0 +1,64 @@ +# 维护 dsh-code-review skill + +[English](maintaining-dsh-code-review.md) | 中文 + +[`dsh-code-review`](../../.agents/skills/dsh-code-review/SKILL.md) skill(技能)由一名指定操作员通过私有的周期维护工具持续更新。本实操手册(cookbook)既是该操作员和接任者的入口,也帮助仓库贡献者理解为何 skill 更新会以小型周期 PR(Pull Request)的形式出现,而不是一次性审计。工作流本身由[人工评审 skill 维护 Agent Note(agent 决策记录)](../../.agents/notes/proposed/process/2026-07-13-human-review-skill-maintenance.md)规定。 + +## 维护者会收到什么 + +每天运行私有工具,并使用 2 个 UTC 日的重叠窗口;在拟议的调度器完成验收运行之前,操作员按相同频率手动调用包装脚本。每周手动恢复运行使用 7 日窗口。工作流会: + +1. 选择指定窗口内合并、且合并 commit 可从 `origin/master` 到达的 PR(每天运行默认选择 2 个 UTC 日,每周运行选择 7 日)。合并 commit 无法到达的 PR(例如父分支被 squash 的堆叠分支),或超出 250 个 commit 获取上限的 PR,会记录到 `skipped-pulls.json` 并跳过,不会中止本次运行。 +2. 收集合并前带 commit 锚点的人工评审反馈(行内评论和评审提交),然后比较反馈时与最终落地的 PR patch。它不获取 PR 会话评论,因为 GitHub 当前状态无法为这些评论提供可抵抗 force-push 的反馈时基线;它也不会把只存在于目标分支的变更作为采纳证据。 +3. 两个独立配置的评审适配器先对来源和采纳情况分类,再根据当前 skill 对双方一致认定已采纳的条目分类。 +4. 主适配器起草完整修订版 `SKILL.md`;两个适配器评审同一份 diff;只要仍有阻塞发现,循环就会继续,直到双方批准。 +5. 工具声明成功前,会针对候选版本运行 `pnpm run doc-sync` 和 `pnpm run lint`。 + +每次运行都把产物保存在操作员的机器上。保存的 diff、候选 `SKILL.md` 和提升 manifest(元数据清单)按时间戳命名,存放在 `~/dsh-code-review-outputs/` 下。manifest 记录源 master commit 与 skill blob、源反馈 ID 和 URL、已落地证据范围、适配器裁决和门禁结果;每个适配器的原始 I/O 留在私有临时目录中,该目录路径会写入通知和 `~/Library/Logs/dsh-code-review-maintainer/` 下的每日日志。维护 worktree 在每次运行后都会恢复为干净状态,避免操作员直接在维护副本中编辑。 + +## 操作员如何处理候选 diff + +某次运行产出候选版本时,macOS 会发出一条带 `dsh-code-review-promote ` 提示的通知。 + +1. **根据 diff 本身作出判断。** 不要因为「评审者已经批准」就直接接受:维护者契约规定最终判断由操作员作出。检查清单是否膨胀、是否有历史叙述、是否根据单次事件作出无依据的外推,以及是否与现有 skill 或权威文档重复。 + + ```sh + ls ~/dsh-code-review-outputs/ # every candidate ever produced + less ~/dsh-code-review-outputs/2026-07-16T02-00-00Z.diff + less ~/dsh-code-review-outputs/2026-07-16T02-00-00Z.SKILL.md + less ~/dsh-code-review-outputs/2026-07-16T02-00-00Z.manifest.json + ``` + +2. **与运行产物交叉核验。** 提升 manifest 会把每条拟议规则映射到源反馈和已落地证据;每个适配器的详细 I/O、共识和采纳证据位于本次运行的私有临时目录中(路径见日志)。至少抽查一个候选项:链接的人工评论是否确实支持新增规则?链接的 PR 是否确实采纳了它? + +3. **从三种处理方式中选择一种:** + - **丢弃。** 删除保存的候选版本。下一次运行会依据届时的当前 skill,重新考虑同一份反馈。 + + ```sh + rm ~/dsh-code-review-outputs/2026-07-16T02-00-00Z.{diff,SKILL.md,manifest.json} + ``` + - **暂存成批。** 如果更新很小,可以把候选版本留待与后续版本合并。源 skill 检查仍然适用;如果 `master` 先发生变化,请重新运行分析,或手动 rebase 并重新评审 diff。 + - **提升。** 在仓库的干净 `master` checkout 中运行提升辅助工具。它会刷新 `master`、验证当前 skill 与记录的源 blob 一致、应用保存的 diff,并创建一份 draft PR,其正文包含 manifest 的来源摘要。如果 skill 已发生漂移,它会停止而不是覆盖更新后的指导;操作员仍需在 GitHub 上评审 PR,并选择合并或关闭。 + + ```sh + cd ~/path/to/deepseek-harness # clean master + dsh-code-review-promote 2026-07-16T02-00-00Z + ``` + +4. **不要逐字提交适配器输出。** 提升过程中可以进行小幅编辑,例如收紧措辞、移除只有结合源 PR 上下文才有意义的示例、把规则并入现有规则。这些编辑是预期行为,也保留了工作流所依赖的「评审者判断」。合并前应在该分支上修订这些改动。 + +## 运行未产出候选版本时 + +只要每个非空分类阶段都至少产生一个有效的适配器结果,这就是常见情况。工具会在每日日志中记录「无候选版本」,不发送通知(避免提醒疲劳),然后继续。某天没有 skill 更新,说明工作流运行正常,而不是停滞。 + +## 中断与交接 + +该机制运行在一台机器上。操作员应随时处理以下中断: + +- **错过每日运行。** 2 日重叠窗口会自动覆盖一次漏跑;更长的间隔可通过设置 `DSH_CODE_REVIEW_SINCE=` 手动运行包装脚本来恢复。重叠窗口具有幂等性:当前 skill 已包含的指导会被归类为 `covered`,不会再次成为候选项。 +- **适配器提供方中断。** 当两个评审命令解析为逐字节相同的可执行文件时,工具会拒绝运行。某个批次的适配器响应未通过 schema 或 ID 校验时,该批次会整体 fail-closed(其中每个条目都标记为不明确),运行则继续;原始输出会保留以便调试。如果任一适配器在某项操作的所有非空批次中都未产生有效结果,本次运行就会失败、写入失败记录并通知操作员;它绝不会把提供方完全中断折叠成「无候选版本」。 +- **交接给另一名维护者。** 新建一篇取代当前记录的后续 Agent Note:要么把机制移入仓库,要么记录新操作员的私有设置。不要暗中转交工具;Agent Note 的风险章节已把「单维护者关键人风险」列为交接必须记录决策的原因。 + +## 操作员的私有设置位于何处 + +工具源代码、评审适配器、提供方凭据和调度器属于操作员的私有基础设施,按设计位于本仓库之外(参见 Agent Note 的「机制位于何处」章节)。本实操手册和 Agent Note 描述的是**工作流保证什么**;这些保证**如何**实现则属于私有基础设施问题。如果你是新操作员,应以 Agent Note 的 `## Proposal` 各节作为实现依据。 diff --git a/docs/cordis-tutorial/01-first-plugin.i18n.yaml b/docs/cordis-tutorial/01-first-plugin.i18n.yaml new file mode 100644 index 0000000000..6ab341e8f5 --- /dev/null +++ b/docs/cordis-tutorial/01-first-plugin.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 +01-first-plugin.md: b730b7ad7dc9ebd2e5dc8af4f7a83bd58ac7d4d8 +01-first-plugin.zh.md: 1e6901c048f5268ddead0faca85eaf5eef9c7533 diff --git a/docs/cordis-tutorial/01-first-plugin.md b/docs/cordis-tutorial/01-first-plugin.md index 084f9964e1..b730b7ad7d 100644 --- a/docs/cordis-tutorial/01-first-plugin.md +++ b/docs/cordis-tutorial/01-first-plugin.md @@ -1,5 +1,7 @@ # 1. Your first plugin +English | [中文](01-first-plugin.zh.md) + In the loader configuration used here, a Cordis plugin module named-exports an `apply` function. When Cordis loads it, it calls `apply` with a **context** — the `ctx` object through which the plugin registers everything it contributes. ## Write the plugin diff --git a/docs/cordis-tutorial/01-first-plugin.zh.md b/docs/cordis-tutorial/01-first-plugin.zh.md new file mode 100644 index 0000000000..1e6901c048 --- /dev/null +++ b/docs/cordis-tutorial/01-first-plugin.zh.md @@ -0,0 +1,95 @@ +# 1. 编写第一个插件 + +[English](01-first-plugin.md) | 中文 + +在本教程使用的 loader 配置中,Cordis 插件模块通过命名导出提供 `apply` 函数。Cordis 加载模块时,会用一个 **上下文** 调用 `apply`;该上下文就是 `ctx` 对象,插件通过它注册自己贡献的所有内容。 + +## 编写插件 + +在 `tmp/cordis-tutorial` 目录中(参见[环境设置](index.md#setup))创建 `hello.ts`: + +```ts +import type { Context } from 'cordis' + +export const name = 'hello' + +export function apply(ctx: Context) { + console.log('hello from my first plugin') +} +``` + +`name` 导出项是可选的显示元数据;它用于在诊断信息中标识插件。 + +## 组合应用 + +本教程的启动器通过配置组装应用。创建 `cordis.yml`: + +```yaml +- name: './hello.ts' +``` + +该文件是一组 Cordis 配置项的列表。`name` 是模块指定符,可以是相对路径或 NPM 包(package)名;loader 会挂载每个配置项。各项会并发启动,因此它们在列表中的位置不保证插件的加载先后;顺序由服务依赖(`inject`,参见[第 3 章](03-services.md))决定,而非文件中的位置。 + +## 运行 + +```sh +node --import tsx ../../vendor/cordis/bin.js +``` + +预期输出: + +``` +hello from my first plugin +``` + +当没有任何内容继续运行时,进程会自行退出。具体过程如下: + +1. 启动器创建根 `Context`,并挂载 **Loader** 插件。 +2. Loader 读取 `cordis.yml`,解析 `./hello.ts`,然后将其作为子插件挂载。 +3. Cordis 调用你的 `apply(ctx)`。 + +你的文件中没有框架启动代码:插件描述自己的贡献,`cordis.yml` 则组合应用。例如,[TUI agent(智能体)](../../examples/tui-agent/cordis.yml) 就是一个更长的插件组合。 + +## 其他两种插件形态 + +函数是最常见的形态,但 Cordis 接受三种形态: + +```ts +import { Service, type Context } from 'cordis' + +// 1. Function plugin (what you just wrote). +export function apply(ctx: Context) {} + +// 2. Object plugin: an object with an `apply` method. +export const objectPlugin = { + name: 'object-plugin', + apply(ctx: Context) {}, +} + +// 3. Class plugin: a Service subclass (covered in chapter 3). +export class MyService extends Service { + constructor(ctx: Context) { + super(ctx, 'myTutorialService') + } +} +``` + +在你需要公开服务之前,请一直使用函数形态;[第 3 章](03-services.md)介绍了何时应当使用类形态。 + +## 尝试制造错误 + +让 `apply` 抛出异常: + +```ts ignore-check +export function apply(ctx: Context) { + throw new Error('apply exploded') +} +``` + +再次运行:进程会因该错误而终止。插件加载失败必须明确报错,不会仅跳过该配置项。 + +还需要尽早了解一个例外:如果某个配置项的模块无法被 **解析**,例如路径或包名拼写错误,Cordis 会通过 logger 服务报告错误,而不会使进程崩溃。在启动阶段,这条报告可能在 console 导出器开始观察之前丢失。如果新增配置项似乎没有任何效果,请先检查拼写。 + +下一章:[生命周期与 effect](02-lifecycle-and-effects.md):插件卸载时会发生什么。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/cordis-tutorial/02-lifecycle-and-effects.i18n.yaml b/docs/cordis-tutorial/02-lifecycle-and-effects.i18n.yaml new file mode 100644 index 0000000000..6d9e4bb6fd --- /dev/null +++ b/docs/cordis-tutorial/02-lifecycle-and-effects.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 +02-lifecycle-and-effects.md: f1b39e06e9d25c51ab2d76503025e2b6ffe90c73 +02-lifecycle-and-effects.zh.md: a6021ed7475a0045d480810747244274eb5b4198 diff --git a/docs/cordis-tutorial/02-lifecycle-and-effects.md b/docs/cordis-tutorial/02-lifecycle-and-effects.md index 68a0f12ec8..f1b39e06e9 100644 --- a/docs/cordis-tutorial/02-lifecycle-and-effects.md +++ b/docs/cordis-tutorial/02-lifecycle-and-effects.md @@ -1,5 +1,7 @@ # 2. Lifecycle and effects +English | [中文](02-lifecycle-and-effects.zh.md) + A Cordis plugin can be unloaded by a config edit, hot reload, explicit disposal, or loss of a required service. Registrations made through Cordis APIs are effects and are undone when their owning plugin unloads; resources managed outside those APIs must be wrapped in `ctx.effect()`. ## Effects diff --git a/docs/cordis-tutorial/02-lifecycle-and-effects.zh.md b/docs/cordis-tutorial/02-lifecycle-and-effects.zh.md new file mode 100644 index 0000000000..a6021ed747 --- /dev/null +++ b/docs/cordis-tutorial/02-lifecycle-and-effects.zh.md @@ -0,0 +1,98 @@ +# 2. 生命周期与 effect + +[English](02-lifecycle-and-effects.md) | 中文 + +Cordis 插件可能因配置编辑、热重载、显式资源释放或所需服务消失而卸载。通过 Cordis API 建立的注册属于 effect,会在所属插件卸载时撤销;在这些 API 之外管理的资源必须包装在 `ctx.effect()` 中。 + +## Effect + +对于 Cordis 尚未管理的资源,例如定时器、连接或 watcher,应将其包装在 `ctx.effect()` 中并返回 disposer(dispose(资源释放)函数): + +创建 `lifecycle.ts`,将它放在 `tmp/cordis-tutorial` 中: + +```ts +import type { Context } from 'cordis' + +export const name = 'lifecycle-demo' + +function heartbeat(ctx: Context) { + console.log('heartbeat plugin loading') + ctx.effect(() => { + const timer = setInterval(() => console.log('tick'), 200) + return () => { + clearInterval(timer) + console.log('heartbeat cleaned up') + } + }) +} + +export function apply(ctx: Context) { + // Mount a child plugin and keep its fiber to dispose it later. + const fiber = ctx.plugin(heartbeat) + // The demo timer is itself an effect: if THIS plugin is unloaded first, + // the pending callback is cancelled instead of firing on a dead app. + ctx.effect(() => { + const timer = setTimeout(async () => { + await fiber.dispose() + console.log('disposed') + process.exit(0) + }, 700) + return () => clearTimeout(timer) + }) +} +``` + +让 `cordis.yml` 指向该文件: + +```yaml +- name: './lifecycle.ts' +``` + +运行(`node --import tsx ../../vendor/cordis/bin.js`)后会得到: + +``` +heartbeat plugin loading +tick +tick +tick +heartbeat cleaned up +disposed +``` + +请留意三点: + +- `ctx.plugin(heartbeat)` 会把一个**来自代码**的函数挂载为插件,这与 YAML loader 为每个配置项执行的操作相同。函数插件不需要 `apply` 方法:Cordis 会直接调用该函数,其名称只用于诊断。只有对象形态才要求 `apply` 方法,例如 `ctx.plugin({ apply(ctx) { /* ... */ } })`。调用会返回一个 **fiber**,即一个已加载插件实例的运行时句柄。 +- effect 主体在加载期间运行;它返回的 disposer 在卸载期间运行。对于生命周期与插件一致的资源,你绝不需要自行调用 disposer。 +- `fiber.dispose()` 会等该插件的所有清理工作(包括异步 disposer)完成后才结束,并递归卸载它挂载的所有子插件。 + +## Fiber 状态机 + +每个已加载插件实例都拥有一个 fiber,并依次经过以下状态: + +``` +PENDING → LOADING → ACTIVE → UNLOADING → DISPOSED + ↘ FAILED +``` + +- **PENDING**:已经声明,但所需服务(第 3 章)尚不可用。 +- **LOADING / ACTIVE**:`apply` 正在运行/已经完成。 +- **FAILED**:`apply` 或配置校验抛出异常。 +- **UNLOADING / DISPOSED**:disposer 正在运行/一切均已拆除。 + +你会在[第 6 章](06-composition-and-hmr.md)再次遇到 PENDING,它通常就是「为什么我的插件没有输出」的答案。 + +## 已经属于 effect 的操作 + +你很少需要亲自编写 `ctx.effect()`,因为内置注册 API 本身已经是 effect: + +- `ctx.on(event, listener)`:监听器会在卸载时移除([第 4 章](04-events.md))。 +- `ctx.plugin(child)`:子插件会随父插件一同 dispose。 +- 服务注册属于 effect。`ctx.tools.register(...)` 等 harness 注册表也会把返回的 disposer 附着到调用插件上,因此会自动回卷([第 7 章](07-into-the-harness.md))。 + +对于 Cordis 不管理的资源,应在 `ctx.effect()` 内获取它,并返回用于释放资源的 disposer。此后 Cordis 会在卸载期间调用该释放逻辑,热重载时也不例外。 + +有一项顺序注意事项:disposer 会按注册顺序的逆序启动,但多个**异步** disposer 会并发运行。如果拆除步骤必须按顺序执行,请把它们放在同一个 disposer 中,并在其中依次等待每步完成。 + +下一章:[服务](03-services.md):插件如何共享功能。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/cordis-tutorial/03-services.i18n.yaml b/docs/cordis-tutorial/03-services.i18n.yaml new file mode 100644 index 0000000000..d42d5eb250 --- /dev/null +++ b/docs/cordis-tutorial/03-services.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 +03-services.md: 5848132c6ad18338fa893954d45fc20005db6199 +03-services.zh.md: 3c77d0451df9062f1a344e7474e6be141b709197 diff --git a/docs/cordis-tutorial/03-services.md b/docs/cordis-tutorial/03-services.md index 9f62003e99..5848132c6a 100644 --- a/docs/cordis-tutorial/03-services.md +++ b/docs/cordis-tutorial/03-services.md @@ -1,5 +1,7 @@ # 3. Services +English | [中文](03-services.zh.md) + A **service** is a named capability one plugin provides and other plugins consume through `ctx`. In the harness, `ctx.tools`, `ctx.llm`, and `ctx.agents` are services. A consumer names the capability, such as `'tools'`, rather than importing its provider, so configuration can select a provider without changing the consumer. ## Provide a service diff --git a/docs/cordis-tutorial/03-services.zh.md b/docs/cordis-tutorial/03-services.zh.md new file mode 100644 index 0000000000..3c77d0451d --- /dev/null +++ b/docs/cordis-tutorial/03-services.zh.md @@ -0,0 +1,98 @@ +# 3. 服务 + +[English](03-services.md) | 中文 + +**服务**是一个插件提供、其他插件通过 `ctx` 消费的命名功能。在 harness 中,`ctx.tools`、`ctx.llm` 和 `ctx.agents` 都是服务。消费方只命名 `'tools'` 之类的功能,而不导入其提供方,因此配置可以选择提供方,无需修改消费方。 + +## 提供服务 + +创建 `greeter.ts`,将它放在 `tmp/cordis-tutorial` 中: + +```ts +import { Service, type Context } from 'cordis' + +declare module 'cordis' { + interface Context { + greeter: GreeterService + } +} + +export class GreeterService extends Service { + constructor(ctx: Context) { + super(ctx, 'greeter') + } + + greet(who: string) { + return `Hello, ${who}!` + } +} + +export const name = 'greeter' + +export function apply(ctx: Context) { + ctx.plugin(GreeterService) +} +``` + +两部分协同工作: + +- **运行时**:`super(ctx, 'greeter')` 以名称 `greeter` 注册该实例。此后,任何插件都可以通过 `ctx.greeter` 访问它。注册属于 effect,卸载提供方时会移除该服务。 +- **编译时**:`declare module 'cordis'` 块使用 TypeScript 声明合并,把 `greeter` 加入 `Context` 接口,使 `ctx.greeter` 在各处都能通过类型检查。它不会生成代码;没有该声明时,服务在运行时仍能工作,但消费方会失去类型安全。 + +`Service` 子类本身就是插件(第 1 章介绍的类形态),因此 `ctx.plugin(GreeterService)` 会像挂载其他插件一样挂载它。 + +## 使用 `inject` 消费服务 + +创建 `consumer.ts`: + +```ts +import type { Context } from 'cordis' + +export const name = 'consumer' +export const inject = ['greeter'] + +export function apply(ctx: Context) { + console.log(ctx.greeter.greet('world')) +} +``` + +`inject` 列出该插件需要的服务。Cordis 会让插件保持 PENDING,直到列出的每项服务都存在,因此在 `apply` 内可以保证 `ctx.greeter` 已经就绪。`cordis.yml` 中的加载顺序无关紧要:决定插件何时启动的是依赖关系,而不是文件顺序。 + +组合并运行: + +```yaml +- name: './greeter.ts' +- name: './consumer.ts' +``` + +``` +Hello, world! +``` + +交换 `cordis.yml` 中两行的顺序后重新运行,输出仍然相同。尝试彻底移除 `./greeter.ts`:消费方会保持 PENDING,不输出任何内容,既不崩溃,也不会只运行一部分。处于 PENDING 的 fiber 也不会让 Node 的事件循环保持活跃,因此如果组合中没有其他运行项,进程会静默地以状态码 0 退出。[第 6 章](06-composition-and-hmr.md)介绍如何诊断这种状态。 + +## 加载后仍会跟踪依赖关系 + +`inject` 并非一次性的启动检查。如果应用运行期间所需服务消失,例如提供方被卸载或热替换,每个依赖插件也会随之卸载,并在服务恢复后再次加载。结合 effect([第 2 章](02-lifecycle-and-effects.md)),这能防止运行中的消费方保留对不可用服务的引用:依赖消失时,它自己的注册也会回卷。 + +这也是配置中可以替换服务的原因:卸载 `dsh-bash-local` 配置项,挂载另一个 `bash` 提供方,所有注入 `'bash'` 的插件都会干净地重启并使用新实现。 + +## 可选依赖 + +`inject` 用于硬性依赖。如果某项功能缺失时插件仍可运行,请跳过 `inject`,并在使用处探测: + +```ts ignore-check +export function apply(ctx: Context) { + // undefined when no provider is loaded; the plugin still runs. + const greeter = ctx.get('greeter') + console.log(greeter?.greet('maybe') ?? 'no greeter available') +} +``` + +## 命名 + +每个应用中的服务名称共用一个扁平命名空间。请为自有服务添加有辨识度的前缀或命名空间(harness 已占用 `tools` 和 `llm` 等普通名称);生成的[服务目录](../cordis-catalog/services.md)列出 harness 注册的每个名称。 + +下一章:[事件](04-events.md):无需共享服务即可通信。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/cordis-tutorial/04-events.i18n.yaml b/docs/cordis-tutorial/04-events.i18n.yaml new file mode 100644 index 0000000000..cd1fc962a7 --- /dev/null +++ b/docs/cordis-tutorial/04-events.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 +04-events.md: 18f39dc1b693e5fb7e1793ec4b7dcac9cf24db95 +04-events.zh.md: f55a61ff2f43ea42968893d07eb92ea0613b921a diff --git a/docs/cordis-tutorial/04-events.md b/docs/cordis-tutorial/04-events.md index 4c14ba5313..18f39dc1b6 100644 --- a/docs/cordis-tutorial/04-events.md +++ b/docs/cordis-tutorial/04-events.md @@ -1,5 +1,7 @@ # 4. Events +English | [中文](04-events.zh.md) + Services support direct calls; **events** let a plugin announce something without knowing which plugins listen. The harness uses events for interactions such as tool results, model requests, and approval decisions. ## Declare, emit, listen diff --git a/docs/cordis-tutorial/04-events.zh.md b/docs/cordis-tutorial/04-events.zh.md new file mode 100644 index 0000000000..f55a61ff2f --- /dev/null +++ b/docs/cordis-tutorial/04-events.zh.md @@ -0,0 +1,144 @@ +# 4. 事件 + +[English](04-events.md) | 中文 + +服务支持直接调用;**事件**让插件无需知道有哪些插件正在监听,就能发出通知。harness 使用事件处理工具结果、模型请求和审批决定等交互。 + +## 声明、发出与监听 + +创建 `stats.ts`,将它放在 `tmp/cordis-tutorial` 中。它是一项负责计数并在每次变化时发出通知的服务: + +```ts +import { Service, type Context } from 'cordis' + +declare module 'cordis' { + interface Context { + stats: StatsService + } + interface Events { + 'stats/report'(name: string, count: number): void + } +} + +export class StatsService extends Service { + private counts = new Map() + + constructor(ctx: Context) { + super(ctx, 'stats') + } + + bump(name: string) { + const next = (this.counts.get(name) ?? 0) + 1 + this.counts.set(name, next) + this.ctx.emit('stats/report', name, next) + } +} + +export const name = 'stats' + +export function apply(ctx: Context) { + ctx.plugin(StatsService) +} +``` + +`interface Events` 合并与第 3 章的 `interface Context` 合并在事件系统中相互对应:它声明事件名称及其监听器签名,因此 `ctx.emit` 和 `ctx.on` 都具有完整类型。`namespace/action` 命名约定让扁平的事件命名空间保持易读。 + +创建 `reporter.ts`: + +```ts ignore-check +import type { Context } from 'cordis' +import type {} from './stats.ts' + +export const name = 'reporter' +export const inject = ['stats'] + +export function apply(ctx: Context) { + ctx.on('stats/report', (name, count) => { + console.log(`[stats] ${name} -> ${count}`) + }) + ctx.stats.bump('tool_call') + ctx.stats.bump('tool_call') + ctx.stats.bump('prompt') +} +``` + +`import type {} from './stats.ts'` 行不会在运行时导入任何内容;它的作用是让 TypeScript 看到声明合并。组合并运行: + +```yaml +- name: './stats.ts' +- name: './reporter.ts' +``` + +``` +[stats] tool_call -> 1 +[stats] tool_call -> 2 +[stats] prompt -> 1 +``` + +因为 `ctx.on()` 属于 effect,监听器会随插件一同消失,绝不需要手动维护 `removeListener`。 + +## 分发模式 + +`emit` 是 5 种分发模式之一。事件采用哪种模式是其契约的一部分,决定了监听器能否返回值、能否并发运行,以及能否彼此短路: + +| 模式 | 调用 | 语义 | +|---|---|---| +| emit | `ctx.emit(name, ...args)` | 同步广播;不会等待或收集返回的 promise 与值。 | +| parallel | `await ctx.parallel(name, ...args)` | 所有监听器并发运行,并一同等待。 | +| serial | `await ctx.serial(name, ...args)` | 监听器按顺序运行并等待;第一个非 `null`/`false`/`undefined` 返回值胜出,并停止后续监听器。 | +| bail | `ctx.bail(name, ...args)` | serial 的同步版本。 | +| waterfall(瀑布式事件) | `ctx.waterfall(name, ...args, next)` | 环绕中间件,见下文。 | + +每个 harness 事件都会在生成的[事件目录](../cordis-catalog/events.md)中记录其模式。 + +## Waterfall:转换或短路 + +waterfall 是实现拦截的模式。每个监听器都会收到参数和一个 `next()` continuation;它可以转换 `next()` 的返回值,也可以不调用 `next()` 就直接返回,从而短路链条的其余部分。Cordis 文档把后一种行为称为否决。创建 `waterfall-demo.ts`: + +```ts +import type { Context } from 'cordis' + +declare module 'cordis' { + interface Events { + 'demo/transform'(input: string, next: () => Promise): Promise + } +} + +export const name = 'waterfall-demo' + +export function apply(ctx: Context) { + // Listener 1: wrap the downstream result. + ctx.on('demo/transform', async (input, next) => { + const downstream = await next() + return downstream.toUpperCase() + }) + + // Listener 2: short-circuit when it owns the decision. + ctx.on('demo/transform', async (input, next) => { + if (input.includes('blocked')) return '** blocked **' + return next() + }) + + void (async () => { + console.log(await ctx.waterfall('demo/transform', 'hello', async () => 'hello')) + console.log(await ctx.waterfall('demo/transform', 'blocked words', async () => 'blocked words')) + })() +} +``` + +让 `cordis.yml` 只指向该文件并运行: + +``` +HELLO +** BLOCKED ** +``` + +按顺序看第二行如何产生:监听器 1 先运行并调用 `next()`,从而调用监听器 2;监听器 2 看到 `blocked` 后直接返回而不调用 `next()`,因此最内层默认逻辑(传给 `ctx.waterfall` 的函数)从未运行;返回途中,监听器 1 再把替换消息转换为大写。 + +由此得到一项纪律:**只负责观察或标注的 waterfall 监听器必须调用 `next()`**;不调用就直接返回代表有意短路。如果日志监听器忘记调用 `next()`,会悄无声息地吞掉所有下游的默认行为。这一点极其重要,已成为本仓库的常设规则([waterfall 语义](../cordis-primer.md#cordis-waterfall-semantics))。 + +harness 使用 waterfall 处理协作插件可以包装或回答的决策:[`agent/request`](../cordis-catalog/events.md#agentrequest--waterfall) 允许插件替换模型调用配置,[`approval/request`](../cordis-catalog/events.md#approvalrequest--waterfall) 允许策略代替用户作答。 + +下一章:[配置](05-config.md):来自 `cordis.yml` 的插件选项。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/cordis-tutorial/05-config.i18n.yaml b/docs/cordis-tutorial/05-config.i18n.yaml new file mode 100644 index 0000000000..deb6f119c2 --- /dev/null +++ b/docs/cordis-tutorial/05-config.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 +05-config.md: fc19add239636fa9e7071d9c77e48595caec1f08 +05-config.zh.md: 52a75e40672c9a08d285677dd14dcd404b925e5a diff --git a/docs/cordis-tutorial/05-config.md b/docs/cordis-tutorial/05-config.md index 09aaf8971d..fc19add239 100644 --- a/docs/cordis-tutorial/05-config.md +++ b/docs/cordis-tutorial/05-config.md @@ -1,5 +1,7 @@ # 5. Configuration +English | [中文](05-config.zh.md) + Each `cordis.yml` entry can carry a `config` block, and the plugin declares a schema that validates it before `apply` runs. Bad config fails the load with a precise error — the plugin never starts half-configured. ## A configurable plugin diff --git a/docs/cordis-tutorial/05-config.zh.md b/docs/cordis-tutorial/05-config.zh.md new file mode 100644 index 0000000000..52a75e4067 --- /dev/null +++ b/docs/cordis-tutorial/05-config.zh.md @@ -0,0 +1,84 @@ +# 5. 配置 + +[English](05-config.md) | 中文 + +每个 `cordis.yml` 配置项都可以携带 `config` 块,插件则声明一个 schema,在运行 `apply` 前验证该块。错误配置会导致加载失败,并给出准确的错误:插件绝不会在配置不完整时启动。 + +## 可配置插件 + +创建 `config-demo.ts`,并将其放在 `tmp/cordis-tutorial` 中: + +```ts +import type { Context } from 'cordis' +import Schema from 'schemastery' + +export const name = 'config-demo' + +export interface Config { + greeting: string + targets: string[] +} + +export const Config: Schema = Schema.object({ + greeting: Schema.string().default('Hello'), + targets: Schema.array(String).default(['world']), +}) + +export function apply(ctx: Context, config: Config) { + for (const target of config.targets) { + console.log(`${config.greeting}, ${target}!`) + } +} +``` + +导出的 `Config` 既是 TypeScript 接口,也是同名的运行时 schema:消费方获得类型,Cordis 获得验证器。本仓库使用 [Schemastery](https://github.com/shigma/schemastery) 定义 schema;Cordis 本身接受任意 [Standard Schema](https://standardschema.dev/) 验证器,因此将普通对象导出为 `Config` 无法工作。 + +对其进行配置: + +```yaml +- name: './config-demo.ts' + config: + targets: ['alpha', 'beta'] +``` + +运行: + +``` +Hello, alpha! +Hello, beta! +``` + +未提供 `greeting`,因此 schema 默认值会将其补齐:`apply` 始终会收到完整且经过验证的配置。 + +## 明确报错 + +现在向它传入无效内容: + +```yaml +- name: './config-demo.ts' + config: + targets: 'not-an-array' +``` + +``` +ValidationError: invalid config: + - $.targets expected array but got not-an-array (at targets) +``` + +插件的 fiber 进入 FAILED 状态,本教程的启动器打印错误后以状态码 1 退出。如果某个插件的 schema 有效配置命名了不可用的资源或提供方,该插件也应当在能解析该引用时立即拒绝。 + +## 计算得到的配置值 + +本仓库使用的 loader 支持 `!!js` 标签,用于必须在加载时计算的配置值,例如从环境中读取 API key: + +```yaml +- name: '@deepseek-ai/dsh-llm-deepseek' + config: + apiKey: !!js process.env.DEEPSEEK_API_KEY +``` + +`!!js` **仅在 `config` 内有效**。配置项元数据(`name`、`id`、`disabled`、`inject` 等)是静态的;`disabled: !!js ...` 会生成一个真值表达式对象,始终禁用该配置项。详见 [loader 配置](../cordis-primer.md#loader-configuration)。 + +下一章:[组合与 HMR](06-composition-and-hmr.md):将 `cordis.yml` 视为应用。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/cordis-tutorial/06-composition-and-hmr.i18n.yaml b/docs/cordis-tutorial/06-composition-and-hmr.i18n.yaml new file mode 100644 index 0000000000..01f9345de3 --- /dev/null +++ b/docs/cordis-tutorial/06-composition-and-hmr.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 +06-composition-and-hmr.md: 66d6a9d93fe39baa881940ba32388979e2678505 +06-composition-and-hmr.zh.md: ebe63fc26607ae6d9344c4795a7975496ed901b5 diff --git a/docs/cordis-tutorial/06-composition-and-hmr.md b/docs/cordis-tutorial/06-composition-and-hmr.md index bb236cc169..66d6a9d93f 100644 --- a/docs/cordis-tutorial/06-composition-and-hmr.md +++ b/docs/cordis-tutorial/06-composition-and-hmr.md @@ -1,5 +1,7 @@ # 6. Composition and HMR +English | [中文](06-composition-and-hmr.zh.md) + Every capability built so far is a plugin, and `cordis.yml` selects the application's plugin tree. This chapter changes that composition, hot-reloads a plugin, and diagnoses a plugin that never loads. ## Entries are more than a name diff --git a/docs/cordis-tutorial/06-composition-and-hmr.zh.md b/docs/cordis-tutorial/06-composition-and-hmr.zh.md new file mode 100644 index 0000000000..ebe63fc266 --- /dev/null +++ b/docs/cordis-tutorial/06-composition-and-hmr.zh.md @@ -0,0 +1,113 @@ +# 6. 组合与 HMR(热模块替换) + +[English](06-composition-and-hmr.md) | 中文 + +到目前为止构建的每项功能都是插件,`cordis.yml` 则选择应用的插件树。本章会改变这种组合、热重载一个插件,并诊断始终无法加载的插件。 + +## 配置项不只有名称 + +配置项除了 `name` 和 `config`,还接受其他元数据: + +```yaml +- id: greeter # stable identity for this entry + name: './greeter.ts' +- id: consumer + name: './consumer.ts' + disabled: true # keep the entry, skip mounting it +``` + +`id` 为配置项提供稳定标识,使 loader 能区分修改现有配置项与先删除再添加。`disabled: true` 会卸载插件而不删除其配置项;改回原值后,插件以及所有因依赖其服务而处于 PENDING 的插件都会再次加载。 + +组可以嵌套一份配置项子列表,并将其作为一个单元加载和卸载;`isolate` 则为一个组提供某项服务名称的独立实例,因此两个组可以各自看到配置不同的 `bash`,互不影响。这些概念值得在用到之前先了解;[Cordis 入门](../cordis-primer.md)和[服务隔离示例](../user/develop/framework/service.md#service-isolation)介绍了详细内容。 + +## 热模块替换 + +卸载会释放 effect([第 2 章](02-lifecycle-and-effects.md)),加载则遵循依赖关系([第 3 章](03-services.md)),因此 HMR 可以先卸载、再加载,以替换正在运行的插件。`@cordisjs/plugin-hmr` 插件会监视文件,并在保存时执行这一过程。 + +在 `tmp/cordis-tutorial` 中编写 `cordis.yml`: + +```yaml +- id: logger + name: '@cordisjs/plugin-logger-console' +- id: timer + name: '@cordisjs/plugin-timer' +- id: hmr + name: '@cordisjs/plugin-hmr' + config: + root: ['.'] +- id: hello + name: './hello.ts' +``` + +列表中增加了两个支持插件:HMR 通过 Cordis logger 服务记录日志,因此没有 console exporter 时看不到其消息;它还会 `inject` `timer` 服务来实现去抖,如果没有 `@cordisjs/plugin-timer`,它就会永远停在 PENDING,而且不发出任何提示。下一节就讨论这种静默状态。 + +HMR 通过 Loader 的原生辅助工具读取 Node 的 loader 内部结构。请在 tsx 下运行 Cordis: + +```sh +node --import tsx ../../vendor/cordis/bin.js +``` + +现在编辑 `hello.ts`,修改日志消息并保存: + +``` +hello from my first plugin +2026-07-22 15:44:36 [I] hmr watching [ '.' ] +2026-07-22 15:44:39 [I] hmr reload plugin at hello.ts +hello from my EDITED plugin +``` + +旧实例先卸载(其所有 effect 都会回卷),新代码随后加载,`apply` 再次运行。按 Ctrl-C 停止进程。编辑 `cordis.yml` 本身也会触发更新:loader 按 `id` 比较配置项,只挂载、卸载或重新配置发生变化的部分。这就是上述配置项显式携带 `id` 的原因:不带该字段的配置项在每次读取时都会获得一个新生成的 id,所以只要配置文件发生任何编辑,即使自身文本未变,它也会被视为先删除再添加并重新挂载。 + +## 诊断始终无法加载的插件 + +依赖驱动加载也有另一面:如果插件的 `inject` 指定了无人提供的服务,它就会一直等待,不输出任何内容。这不是错误,因为 PENDING 是合法状态,提供方可能稍后才挂载。 + +你可以直接查看这些状态。每个上下文都能枚举插件注册表;创建 `diagnose.ts`: + +```ts +import { FiberState, type Context } from 'cordis' + +export const name = 'diagnose' + +export function apply(ctx: Context) { + setTimeout(() => { + for (const runtime of ctx.registry.values()) { + for (const fiber of runtime.fibers) { + if (fiber.state === FiberState.PENDING) { + console.log(`${fiber.name} is PENDING — a required service is missing`) + } + } + } + }, 500) +} +``` + +再创建一个依赖无法满足的插件 `needs-timer.ts`: + +```ts +import type { Context } from 'cordis' + +export const name = 'needs-timer' +export const inject = ['timer'] + +export function apply(ctx: Context) { + console.log('needs-timer loaded') +} +``` + +```yaml +- name: './needs-timer.ts' +- name: './diagnose.ts' +``` + +运行它(直接执行 `node --import tsx ../../vendor/cordis/bin.js`,按 Ctrl-C 停止): + +``` +needs-timer is PENDING — a required service is missing +``` + +`inject: ['timer']` 没有提供方。向列表添加 `- name: '@cordisjs/plugin-timer'` 后,插件就会加载。如果插件既不执行任何操作,也不报告任何内容,请检查其 fiber 状态。不加 PENDING 过滤条件进行迭代时,还会看到 loader 自身的插件(Loader、Include)处于 ACTIVE,因为配置文件本身也是通过插件挂载的。 + +下一章:[进入 harness](07-into-the-harness.md):把相同模式用于真实的 harness 服务。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/cordis-tutorial/07-into-the-harness.i18n.yaml b/docs/cordis-tutorial/07-into-the-harness.i18n.yaml new file mode 100644 index 0000000000..c85bcad755 --- /dev/null +++ b/docs/cordis-tutorial/07-into-the-harness.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 +07-into-the-harness.md: 6ec42c50fe5059955734fe7bc46117538dafaffc +07-into-the-harness.zh.md: 32b21b008837e2972a53db9d893788dc6a7de9a9 diff --git a/docs/cordis-tutorial/07-into-the-harness.md b/docs/cordis-tutorial/07-into-the-harness.md index a86c538d48..6ec42c50fe 100644 --- a/docs/cordis-tutorial/07-into-the-harness.md +++ b/docs/cordis-tutorial/07-into-the-harness.md @@ -1,5 +1,7 @@ # 7. Into the harness +English | [中文](07-into-the-harness.zh.md) + This chapter registers a model-callable tool with the harness's `tools` service, executes it through the harness tool pipeline, and observes the result event. It remains keyless and does not call a model. ## A tool plugin diff --git a/docs/cordis-tutorial/07-into-the-harness.zh.md b/docs/cordis-tutorial/07-into-the-harness.zh.md new file mode 100644 index 0000000000..32b21b0088 --- /dev/null +++ b/docs/cordis-tutorial/07-into-the-harness.zh.md @@ -0,0 +1,107 @@ +# 7. 进入 harness + +[English](07-into-the-harness.md) | 中文 + +本章会向 harness 的 `tools` 服务注册一个可由模型调用的工具,通过 harness 工具流水线执行它,并观察结果事件。整个示例无需密钥,也不会调用模型。 + +## 工具插件 + +创建 `greet-tool.ts`,将它放在 `tmp/cordis-tutorial` 中: + +```ts +import type { Context } from 'cordis' +import { defineTool } from '@deepseek-ai/dsh-tools' +import { CallId } from '@deepseek-ai/dsh-llm' + +export const name = 'greet-tool' +export const inject = ['tools'] + +export function apply(ctx: Context) { + ctx.tools.register(defineTool({ + name: 'greet', + description: 'Greet the named person.', + parameters: { + name: { type: 'string', required: true, description: 'Who to greet' }, + }, + output: { + schema: { type: 'string' }, + render: (_args, value) => [{ type: 'text', text: value }], + }, + async execute(args) { + return `Hello, ${args.name}!` + }, + })) + + // Drive one call through the real execution pipeline, standing in for + // the model. CallId brands the correlation id a provider would issue. + void (async () => { + const result = await ctx.tools.execute({ + callId: CallId('demo-1'), + name: 'greet', + arguments: { name: 'Cordis' }, + signal: new AbortController().signal, + }) + console.log('tool replied:', JSON.stringify(result.content)) + })() +} +``` + +这里的每个模式都来自前几章:`inject: ['tools']`([第 3 章](03-services.md))会让插件等待工具注册表就绪;`ctx.tools.register(...)` 会把注册 disposer 附着到插件([第 2 章](02-lifecycle-and-effects.md)),因此卸载时会注销工具。`defineTool` 将 `parameters` 规约转换为向模型展示的 JSON Schema,推导 `args` 的类型,并在 `execute` 运行前校验模型提供的参数。工具返回由 `output.schema` 声明的规范值;`output.render` 则另行生成原生且持久的结果内容。 + +## 观察插件 + +创建 `tool-logger.ts`。这是一个独立插件,通过 harness 的 `tools/result` 事件观察应用中的每次工具调用: + +```ts +import type { Context } from 'cordis' +import type {} from '@deepseek-ai/dsh-tools' + +export const name = 'tool-logger' +export const inject = ['tools'] + +export function apply(ctx: Context) { + ctx.on('tools/result', (exec, result) => { + const text = result.content + .map(block => (block.type === 'text' ? block.text : '')) + .join('') + console.log(`[tool-logger] ${exec.name} -> ${text}`) + }) +} +``` + +`import type {} from '@deepseek-ai/dsh-tools'` 行会引入该包的声明合并,使 `'tools/result'` 及其 payload 具有类型。这与第 4 章导入 `stats.ts` 的做法相同,只是扩展到了包级别。 + +## 组合并运行 + +```yaml +- name: '@deepseek-ai/dsh-system-prompt' +- name: '@deepseek-ai/dsh-tools' +- name: './tool-logger.ts' +- name: './greet-tool.ts' +``` + +`@deepseek-ai/dsh-tools` 会注入 `systemPrompt` 服务,因为工具需要向系统提示词贡献 schema,所以组合中也要列出该服务的提供方。缺少提供方时,工具插件会像[第 6 章](06-composition-and-hmr.md)所述那样保持 PENDING。 + +```sh +node --import tsx ../../vendor/cordis/bin.js +``` + +``` +[tool-logger] greet -> Hello, Cordis! +tool replied: [{"type":"text","text":"Hello, Cordis!"}] +``` + +logger 会先触发:`tools/result` 在结果物化过程中发出,早于 `execute` 的 promise 向调用方返回结果。两个插件都不知道另一个插件存在,它们由注册表服务和事件连接。 + +## 从这里走向完整 agent(智能体) + +真实 agent 就是这套组合再加上更多插件:LLM(大语言模型)适配器、agent loop(智能体循环)、持久化和前端。对照 [examples/headless-agent/cordis.yml](../../examples/headless-agent/cordis.yml),你现在已经可以读懂其中每个配置项。将 `greet-tool.ts` 加入该文件的副本即可。 + +后续可以阅读: + +- [构建工具](../user/develop/basic/tool.md):深入了解 `defineTool`,包括呈现和更丰富的 schema。 +- [三层功能设计](../user/develop/practice/index.md):harness 如何组织可替换功能。 +- 生成的[服务](../cordis-catalog/services.md)与[事件](../cordis-catalog/events.md)目录:可以注入和监听的所有内容。 +- [架构](../architecture.md):这些插件所处的系统地图。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/cordis-tutorial/index.i18n.yaml b/docs/cordis-tutorial/index.i18n.yaml new file mode 100644 index 0000000000..275c700851 --- /dev/null +++ b/docs/cordis-tutorial/index.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 +index.md: af622ad4e35829c6283c40f1b0019d7959dac973 +index.zh.md: 35bad552ecce9c0496b0ed88b041a8109c81945b diff --git a/docs/cordis-tutorial/index.md b/docs/cordis-tutorial/index.md index 9cf3966117..af622ad4e3 100644 --- a/docs/cordis-tutorial/index.md +++ b/docs/cordis-tutorial/index.md @@ -1,5 +1,7 @@ # Cordis tutorial +English | [中文](index.zh.md) + Cordis is the plugin framework underneath the DeepSeek Harness SDK: a small runtime where every capability — tools, LLM adapters, file access, the agent loop itself — is a plugin mounted into a shared context. This tutorial teaches Cordis hands-on: each chapter is a runnable example you build in a scratch directory inside this repository, ending with a plugin wired into real harness services. The audience is agent developers. You do not need deep TypeScript experience; the [TypeScript notes](#typescript-notes) below explain the syntax that may be unfamiliar, and every chapter shows the exact commands and expected output. @@ -41,6 +43,8 @@ That one-file launcher (see [vendor/cordis/bin.js](../../vendor/cordis/bin.js)) 6. [Composition and HMR](06-composition-and-hmr.md) — the config file as a plugin tree, hot reload, and diagnosing a plugin that never loads. 7. [Into the harness](07-into-the-harness.md) — register a model-callable tool against real harness services. + + ## TypeScript notes The examples use three TypeScript features beyond ordinary modern JavaScript: diff --git a/docs/cordis-tutorial/index.zh.md b/docs/cordis-tutorial/index.zh.md new file mode 100644 index 0000000000..35bad552ec --- /dev/null +++ b/docs/cordis-tutorial/index.zh.md @@ -0,0 +1,58 @@ +# Cordis 教程 + +[English](index.md) | 中文 + +Cordis 是 DeepSeek Harness SDK 底层的插件框架:它是一个小型运行时,其中的每项能力,包括工具、LLM(大语言模型)适配器、文件访问乃至 agent loop(智能体循环)本身,都是挂载到共享上下文中的插件。本教程通过动手实践讲解 Cordis:每一章都是一个可以运行的示例,你将在本仓库内的临时目录中逐步构建它,最后把一个插件接入真实的 harness 服务。 + +本教程面向 agent 开发者。你不需要深入掌握 TypeScript;下文的 [TypeScript 说明](#typescript-notes)会解释可能陌生的语法,并且每一章都会给出确切命令和预期输出。 + +如果你想阅读精简的概念参考,而不是逐步实践,请参阅 [Cordis 入门](../cordis-primer.md)。详尽的 API 参考见生成的[事件](../cordis-catalog/events.md)与[服务](../cordis-catalog/services.md)目录,以及 [Cordis 核心 API](../cordis-catalog/core/context.md)页面。 + +## 准备工作 + +你需要克隆本仓库并安装依赖,具体前置条件见[快速入门](../user/guide/quickstart.md)。本教程不需要 API 密钥;所有示例均可在无密钥环境中运行。 + +```sh +git clone https://github.com/deepseek-harness/deepseek-harness.git +cd deepseek-harness +pnpm install +``` + +创建各章使用的临时目录。`tmp/` 已被 git 忽略,因此你在其中写入的任何内容都不会进入版本控制: + +```sh +mkdir -p tmp/cordis-tutorial +cd tmp/cordis-tutorial +``` + +每一章都从该目录运行同一条命令: + +```sh +node --import tsx ../../vendor/cordis/bin.js +``` + +这个单文件启动器(见 [vendor/cordis/bin.js](../../vendor/cordis/bin.js))会创建根 `Context`、挂载 Loader 插件,并让它从当前目录加载 `./cordis.yml`。其余所有内容,包括有哪些插件以及如何配置它们,都来自你稍后将编写的 YAML 文件。`--import tsx` 标志让 Node 无需构建步骤即可运行配置所指向的 TypeScript 文件。 + +## 章节 + +1. [你的第一个插件](01-first-plugin.md):插件是函数,由 loader 挂载。 +2. [生命周期与 effect](02-lifecycle-and-effects.md):由 Cordis 管理的注册会在所属插件卸载时撤销。 +3. [服务](03-services.md):在 `ctx` 上公开一项能力,并通过 `inject` 依赖它。 +4. [事件](04-events.md):类型化事件、广播分发和 waterfall(瀑布式事件)的短路行为。 +5. [配置](05-config.md):读取 `cordis.yml` 中经过校验的配置,并在输入错误时快速失败。 +6. [组合与 HMR(热模块替换)](06-composition-and-hmr.md):把配置文件作为插件树,使用热重载,并诊断始终无法加载的插件。 +7. [进入 harness](07-into-the-harness.md):基于真实的 harness 服务注册一个可由模型调用的工具。 + + + +## TypeScript 说明 + +这些示例使用了普通现代 JavaScript 之外的三项 TypeScript 功能: + +- **类型注解** 描述值,但不会改变运行时行为:`ctx: Context` 表示 `ctx` 具备 Cordis 上下文 API,`who: string` 接受文本,而 `string[]` 表示字符串数组。 +- **`import type { Context } from 'cordis'`** 只导入类型信息。它在运行时会消失,因此仅为类型注解使用 `Context` 的插件文件不会增加运行时依赖。 +- **声明合并**(`declare module 'cordis' { ... }`)会为 Cordis 已经声明的接口添加你的条目,例如新 `ctx.greeter` 属性的类型或事件名称。它不会生成任何运行时接线;插件必须另行提供服务或发出事件。第 3 章会完整展示该模式。 + +第 5 章还会使用 `interface` 描述配置对象的字段,并使用 `Schema` 这类泛型表示 schema 所校验的对象形状。你可以直接照写这些声明;周围的正文会解释每项声明连接了什么。 + +[![](https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white)](https://github.com/deepseek-harness/deepseek-harness) diff --git a/docs/core-data-structures/commands.i18n.yaml b/docs/core-data-structures/commands.i18n.yaml new file mode 100644 index 0000000000..ba55abec39 --- /dev/null +++ b/docs/core-data-structures/commands.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 +commands.md: 056c775f4c2e1586447db11821e5c7d56be01881 +commands.zh.md: 1a51305df356d8becf8c5517704dc375cdb8b585 diff --git a/docs/core-data-structures/commands.md b/docs/core-data-structures/commands.md index c36942cf18..056c775f4c 100644 --- a/docs/core-data-structures/commands.md +++ b/docs/core-data-structures/commands.md @@ -1,5 +1,7 @@ # Human Commands +English | [中文](commands.zh.md) + The human-command seam of [`dsh-commands`](../../packages/ui/commands). Interactive adapters use it to discover and directly execute plugin-owned commands for an exact agent without creating a model message. The [command Agent Note](../../.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md) owns dispatch and lifecycle rationale; the [package README](../../packages/ui/commands/README.md) owns composition and limitations. Source: [`packages/ui/commands/src/index.ts`](../../packages/ui/commands/src/index.ts) diff --git a/docs/core-data-structures/commands.zh.md b/docs/core-data-structures/commands.zh.md new file mode 100644 index 0000000000..1a51305df3 --- /dev/null +++ b/docs/core-data-structures/commands.zh.md @@ -0,0 +1,86 @@ +# 用户命令 + +[English](commands.md) | 中文 + +[`dsh-commands`](../../packages/ui/commands) 的用户命令 seam。交互式适配器用它发现插件拥有的命令,并针对确切的 agent(智能体)直接执行这些命令,而不创建模型消息。[命令 Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-07-19-plugin-command-registration.md) 负责分发与生命周期的决策依据;[包(package)README](../../packages/ui/commands/README.md) 负责组合方式与限制。 + +来源:[`packages/ui/commands/src/index.ts`](../../packages/ui/commands/src/index.ts) + +## 输入元数据 + +该 seam 公开一个可选的非结构化输入提示。命令的可用性由插件组合决定:每个消费注册表的适配器都会看到全部生效定义。 + +```ts type-equiv +/** Immutable metadata for a command's optional unstructured input. */ +interface CommandInputDescriptor { + /** Placeholder shown before the user supplies free-form input. */ + readonly hint: string +} +``` + +## 定义 + +`CommandDefinition` 是由插件编写的注册定义。注册表会验证并冻结一份与原始注册对象脱离的生效定义。 + +```ts type-equiv +/** Plugin-owned command registration. */ +interface CommandDefinition { + /** Lowercase command name without the leading slash. */ + readonly name: string + /** Human-readable summary used in discovery UI. */ + readonly description: string + /** Optional free-form input hint advertised to capable clients. */ + readonly input?: CommandInputDescriptor + /** Execute against the receiving agent without sending the command to the model. */ + readonly handler: (invocation: CommandInvocation) => CommandResult | Promise +} +``` + +## 调用与结果 + +适配器拥有取消操作,并传入确切的目标 agent。`rawInput` 紧接在解析后的名称之后,并保留适配器传入的分隔符与后缀。结果会直接呈现给 UI,而不是工具结果或会话事件。 + +```ts type-equiv +/** Invocation passed to one registered command handler. */ +interface CommandInvocation { + /** Exact agent whose human-facing surface received the command. */ + readonly agent: Agent + /** Exact text following the registered command name, including separator whitespace. */ + readonly rawInput: string + /** Cancellation signal owned by the dispatching UI request. */ + readonly signal: AbortSignal +} +``` + +```ts type-equiv +/** Expected command outcome rendered directly by the dispatching UI. */ +type CommandResult = + | { readonly kind: 'success'; readonly text?: string } + | { readonly kind: 'error'; readonly text: string } +``` + +## 发现与解析视图 + +作用域解析后,适配器会获得不含处理器的不可变描述符。`parseCommand()` 在注册表解析前返回 `ParsedCommand`;语法有效的输入仍可能指向不可用的命令。 + +```ts type-equiv +/** Handler-free immutable command view returned to UI adapters. */ +interface CommandDescriptor { + /** Lowercase command name without the leading slash. */ + readonly name: string + /** Human-readable summary used in discovery UI. */ + readonly description: string + /** Optional free-form input hint advertised to capable clients. */ + readonly input?: CommandInputDescriptor +} +``` + +```ts type-equiv +/** Syntactically valid slash command before registry resolution. */ +interface ParsedCommand { + /** Lowercase command name without the leading slash. */ + readonly name: string + /** Exact text following the command name. */ + readonly rawInput: string +} +``` diff --git a/docs/core-data-structures/goal.i18n.yaml b/docs/core-data-structures/goal.i18n.yaml new file mode 100644 index 0000000000..47dc0c1b1c --- /dev/null +++ b/docs/core-data-structures/goal.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 +goal.md: 2e8d296eeda6e5f69c0f92829e347b7f55f41fa9 +goal.zh.md: a9c946e7cd37cf948c7ac0f3e4d0ea35ac80d614 diff --git a/docs/core-data-structures/goal.md b/docs/core-data-structures/goal.md index c0351f2f77..2e8d296eed 100644 --- a/docs/core-data-structures/goal.md +++ b/docs/core-data-structures/goal.md @@ -1,5 +1,7 @@ # Same-session goals +English | [中文](goal.zh.md) + Types shared by the event-sourced goal domain and its policy consumers. The [goal-domain Agent Note](../../.agents/notes/implemented/feature/2026-07-19-persisted-same-session-goal-domain.md) owns the persistence and activation decisions; this page records the literal shapes from [`packages/goal/goal/src/types.ts`](../../packages/goal/goal/src/types.ts). ## Identity and lifecycle diff --git a/docs/core-data-structures/goal.zh.md b/docs/core-data-structures/goal.zh.md new file mode 100644 index 0000000000..a9c946e7cd --- /dev/null +++ b/docs/core-data-structures/goal.zh.md @@ -0,0 +1,145 @@ +# 同会话目标 + +[English](goal.md) | 中文 + +事件溯源目标领域及其策略消费方共享的类型。[目标领域 Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-07-19-persisted-same-session-goal-domain.md)负责记录持久化与激活决策;本页记录 [`packages/goal/goal/src/types.ts`](../../packages/goal/goal/src/types.ts) 中的字面形态。 + +## 标识与生命周期 + +`GoalId` 是[品牌化 id](core.md#branded-ids)。调用方通过 `GoalRef` 修改一个确切修订版本;每次获准的持久变更都会递增修订号。 + +```ts type-equiv +/** Compare-and-set identity for one exact goal revision. */ +interface GoalRef { + /** Stable goal identity. */ + readonly id: GoalId + /** Positive revision; every durable mutation increments it. */ + readonly revision: number +} +``` + +持久阶段回答目标发生了什么。进程本地激活状态则另行回答续跑消费方能否开始另一个 Round。 + +```ts type-equiv +/** Durable continuation phase. Activation is process-local and separate. */ +type GoalPhase = + | 'active' + | 'paused' + | 'blocked' + | 'complete' +``` + +阻塞是唯一表示「因问题而停止」的持久状态。由策略负责的阻塞原因会携带一个用于路由、稳定且采用 lower-kebab-case 的代码,以及一段供人和模型阅读的自由文本说明。 + +```ts type-equiv +/** Machine-routable and human-readable explanation for a blocked goal. */ +interface GoalBlockReason { + /** Stable lower-kebab-case classification chosen by the blocking policy. */ + readonly code: string + /** Non-empty explanation shown to humans and models. */ + readonly message: string +} +``` + +```ts type-equiv +/** Full durable state written by every non-clear goal mutation. */ +interface GoalSnapshot extends GoalRef { + /** Human-requested completion objective. */ + readonly objective: string + /** Durable lifecycle phase. */ + readonly phase: GoalPhase + /** Present exactly while `phase` is `blocked`. */ + readonly blockedReason?: GoalBlockReason + /** Total admitted goal-round cap. */ + readonly maxGoalRounds: number +} +``` + +```ts type-equiv +/** Current goal projection, including values derived from the session log. */ +interface GoalView extends GoalSnapshot { + /** Highest admitted round number for this goal. */ + readonly roundsStarted: number + /** Epoch milliseconds of the create mutation. */ + readonly createdAt: number + /** Epoch milliseconds of the latest mutation. */ + readonly updatedAt: number + /** Process-local continuation eligibility; never persisted. */ + readonly activation: GoalActivation +} +``` + +## 持久变更 + +每次变更都是 Round 编号为 0、来源为目标的 `user/message`,其元数据要么是完整快照,要么是清除墓碑。版本、元数据、目标来源和逐字渲染内容共同构成一项回放不变量。 + +```ts type-equiv +/** Full-snapshot goal mutation retained in a model-visible context event. */ +interface GoalSnapshotChangeMeta { + readonly kind: 'goal/change' + readonly version: 1 + readonly operation: Exclude + readonly goal: GoalSnapshot + readonly roundsStarted: number + readonly createdAt: number + readonly updatedAt: number +} +``` + +```ts type-equiv +/** Tombstone retained when the current goal is cleared. */ +interface GoalClearChangeMeta { + readonly kind: 'goal/change' + readonly version: 1 + readonly operation: 'clear' + readonly cleared: GoalRef + readonly clearedAt: number +} +``` + +目标状态变更使用 Round `0`。续跑消费方会为每个获准的用户消息轮次标注正数且连续的 Round 编号和当前修订号;回放会拒绝编号缺口、陈旧修订号、已停止阶段和超出上限。 + +```ts type-equiv +/** Message attribution for durable goal state and continuation rounds. */ +interface GoalMessageSource { + readonly kind: 'goal' + readonly goalId: GoalId + readonly revision: number + /** Zero for state changes; positive for admitted continuation rounds. */ + readonly round: number +} +``` + +## 请求与通知 + +创建操作会区分调用方省略的值与部署选择,`create()` 会在内部解析后者。编辑是局部替换,其运行时校验器要求至少提供一个字段。每条变更通知都会携带获准的操作和确切修订号;清除操作不带 `goal`。 + +```ts type-equiv +/** Input whose omitted round cap is resolved by the service configuration. */ +interface CreateGoalRequest { + readonly objective: string + readonly maxGoalRounds?: number +} +``` + +```ts type-equiv +/** Fields changed by an edit; at least one must be present. */ +interface EditGoalRequest { + readonly objective?: string + readonly maxGoalRounds?: number +} +``` + +```ts type-equiv +/** Live notification after one goal mutation has been accepted for logging. */ +interface GoalChanged { + readonly operation: GoalOperation + readonly ref: GoalRef + /** Absent for a clear tombstone. */ + readonly goal?: GoalView +} +``` + +## 服务行为 + +[`GoalService`](../../packages/goal/goal/src/index.ts) 解析创建默认值、执行严格回放折叠、校验确切的活跃 agent 身份、以比较并设置方式执行变更、叠加延迟注入,并发出 `goal/changed` 通知;监听器故障会被隔离。包 [README](../../packages/goal/goal/README.md) 负责记录可调用契约和面向模型的契约。 diff --git a/docs/core-data-structures/lsp.i18n.yaml b/docs/core-data-structures/lsp.i18n.yaml new file mode 100644 index 0000000000..5ab99680eb --- /dev/null +++ b/docs/core-data-structures/lsp.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 +lsp.md: 62b133cbfdf521e067c56355664d7514a613397f +lsp.zh.md: d7000970ec9114bcdad40a39d2712d48b9865529 diff --git a/docs/core-data-structures/lsp.md b/docs/core-data-structures/lsp.md index eb370f6e38..62b133cbfd 100644 --- a/docs/core-data-structures/lsp.md +++ b/docs/core-data-structures/lsp.md @@ -1,5 +1,7 @@ # LSP navigation +English | [中文](lsp.zh.md) + The LSP seam — a [capability seam](../../.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.md) exposing semantic code navigation on one `ctx.lsp` service, split across packages: interface ([dsh-lsp](../../packages/lsp/lsp), `ctx.lsp` + the provider registry), a generic implementation ([dsh-lsp-local](../../packages/lsp/lsp-local), a configured stdio language-server host), and consumer ([dsh-tool-lsp](../../packages/lsp/tool-lsp), the `lsp` tool schema). LSP is **one optional capability**, not part of the agent-loop spine — so its vocabulary lives here, not in [core.md](core.md). A provider swap does not change how the model asks for navigation. Source: [`packages/lsp/lsp/src/types.ts`](../../packages/lsp/lsp/src/types.ts) diff --git a/docs/core-data-structures/lsp.zh.md b/docs/core-data-structures/lsp.zh.md new file mode 100644 index 0000000000..d7000970ec --- /dev/null +++ b/docs/core-data-structures/lsp.zh.md @@ -0,0 +1,165 @@ +# LSP 导航 + +[English](lsp.md) | 中文 + +LSP seam 是一个[能力 seam](../../.agents/notes/implemented/architecture/2026-07-15-lsp-capability-seam.md):它在单一 `ctx.lsp` 服务上公开语义代码导航,并拆分到多个包(package):接口([dsh-lsp](../../packages/lsp/lsp),`ctx.lsp` + 提供方注册表)、通用实现([dsh-lsp-local](../../packages/lsp/lsp-local),经过配置的 stdio 语言服务器宿主)和消费方([dsh-tool-lsp](../../packages/lsp/tool-lsp),即 `lsp` 工具 schema)。LSP 是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇定义在此而非 [core.md](core.md) 中。更换提供方不会改变模型请求导航的方式。 + +源文件:[`packages/lsp/lsp/src/types.ts`](../../packages/lsp/lsp/src/types.ts) + +## 操作与坐标 + +seam 与模型恰好公开 4 项语义查询;该联合是闭合的,因此新增一项查询会通过编译强制要求同步修改 seam、提供方和工具。位置与范围采用从零开始的 UTF-16 坐标,与协议一致;面向模型的工具采用从 1 开始的光标约定,并在输入和输出时进行转换。 + +```ts type-equiv +/** + * The four semantic queries the seam and model expose. A closed union: adding an operation is a + * compile-enforced change across the seam, providers, and the tool. Symbols and call hierarchy are + * deliberately deferred (they need different schemas). + */ +type LspOperation = 'goToDefinition' | 'findReferences' | 'goToImplementation' | 'hover' +``` + +```ts type-equiv +/** A zero-based UTF-16 cursor coordinate, matching the LSP wire convention. */ +interface LspPosition { + /** Zero-based line. */ + readonly line: number + /** Zero-based UTF-16 code-unit offset within the line. */ + readonly character: number +} +``` + +```ts type-equiv +/** A zero-based UTF-16 half-open range `[start, end)`. */ +interface LspRange { + readonly start: LspPosition + readonly end: LspPosition +} +``` + +## 请求 + +每个字段都是必填项:`workspaceRoot` 由调用方提供,`languageId` 来自提供方注册而非请求,超时与结果上限由消费方决定。因此没有字段需要由实现提供默认值,也不存在 `resolve()` 步骤。提供方收到调用方请求和派生的 `languageId`;后者只用于同步瞬态文档,从不参与选择。 + +```ts type-equiv +/** + * A caller's normalized query. Every field is required: `workspaceRoot` is caller-supplied, + * `languageId` comes from the provider registration (not here), and consumers own timeouts and + * result limits — so no field needs implementation defaulting and there is no `resolve()` step. + */ +interface LspQueryRequest { + /** Which semantic query to run. */ + readonly operation: LspOperation + /** The source file to query (relative to `workspaceRoot` or absolute; the provider canonicalizes). */ + readonly filePath: string + /** The zero-based UTF-16 cursor position to query at. */ + readonly position: LspPosition + /** The workspace root the provider resolves against and indexes; required, never defaulted. */ + readonly workspaceRoot: string +} +``` + +```ts type-equiv +/** + * A request as a provider receives it: the caller's {@link LspQueryRequest} plus the `languageId` + * the seam derived from the provider's extension mapping. The language id only synchronizes the + * transient document; it does not participate in selection. + */ +interface LspProviderQuery extends LspQueryRequest { + /** The LSP language id for `filePath`, from this provider's extension mapping. */ + readonly languageId: string +} +``` + +## 结果 + +这是一个闭合的可辨识联合:导航操作规范化为 `locations`,`hover` 规范化为内容或 `null`。消费方使用 `switch` 对 `kind` 做穷尽处理,因此新增分支会使编译失败,直到完成处理。`findReferences` 始终包含声明;提供方在内部强制保证这一点,因此调用方没有对应 flag。`locations` 变体携带 `resolvedWorkspaceRoot`,即提供方对请求中 `workspaceRoot` 的规范形式,也是其 `file:` URI 所相对的根目录;调用方在相对化显示路径时应使用它,而不是可能经过符号链接的请求根目录。 + +```ts type-equiv +/** One resolved location: a document URI and the range within it. */ +interface LspLocation { + /** The target document URI (`file:` or otherwise), verbatim from the server. */ + readonly uri: string + /** The range within the target document. */ + readonly range: LspRange +} +``` + +```ts type-equiv +/** Normalized hover content, or `null` for no hover at the position. */ +interface LspHover { + /** The normalized hover text (markdown or plaintext, provider-joined). */ + readonly contents: string + /** The range the hover applies to, when the server supplied one. */ + readonly range?: LspRange +} +``` + +```ts type-equiv +/** + * The closed result union. Navigation operations (`goToDefinition`, `findReferences`, + * `goToImplementation`) normalize to `locations`; `hover` normalizes to content or `null`. + * Consumers `switch` on `kind` to exhaustiveness so a new arm breaks compilation until handled. + * + * The `locations` variant carries `resolvedWorkspaceRoot`: the provider's canonical form of the + * request's `workspaceRoot`, and the root its `file:` location URIs are relative to. A caller that + * relativizes display paths MUST use this, not the request's (possibly symlinked) `workspaceRoot`; + * otherwise a symlinked workspace misclassifies in-workspace results as external. + */ +type LspQueryResult = + | { readonly kind: 'locations'; readonly locations: readonly LspLocation[]; readonly resolvedWorkspaceRoot: string } + | { readonly kind: 'hover'; readonly hover: LspHover | null } +``` + +## 提供方与服务 + +每个提供方拥有一个稳定的品牌化 `id`,以及一份互斥的、小写且以点开头的扩展名映射。`registerProvider` 会原子保留 id 和每个扩展名:注册无效或冲突时不发布任何内容;其 disposer 会释放所有保留项。每次查询独立选择提供方,且选择与顺序无关;没有匹配项时抛出 `LspError` `LSP_UNAVAILABLE`。该 seam 不公开协议类型、进程或文档控制,也不提供通用 JSON-RPC 逃生口。 + +```ts type-equiv +/** + * A language-server backend registered on `ctx.lsp`. Each provider owns a stable {@link + * LspProviderId} and an extension-to-language-id map (lowercase, leading-dot keys). + * `findReferences` always includes declarations — the provider enforces this internally; callers + * get no flag. + */ +interface LspProvider { + /** Stable provider identity, reserved atomically with the extension mappings. */ + readonly id: LspProviderId + /** Lowercase leading-dot extension → LSP language id (e.g. `{ '.ts': 'typescript' }`). */ + readonly extensionToLanguage: Readonly> + /** + * Run one query. The seam has already selected this provider and derived `languageId`. + * @param request - the resolved provider query (caller request + derived language id). + * @param signal - optional cancellation; the provider stops its own work when it aborts. + * @returns the normalized, closed-union result. + */ + query(request: LspProviderQuery, signal?: AbortSignal): Promise +} +``` + +```ts type-equiv +/** + * The LSP capability seam (`ctx.lsp`). Owns provider registration/selection and normalized query + * execution; exposes exactly the four operations and no protocol escape hatch. + */ +interface LspService { + /** + * Register a provider, atomically reserving its id and every normalized extension. Any conflict + * or invalid input publishes nothing and throws `LspError`; the returned disposer releases all + * reservations. Disposed with the calling fiber. + * @param provider - the backend to register. + * @returns a synchronous disposer releasing the id and all extension reservations. + */ + registerProvider(provider: LspProvider): () => void + /** + * Select a provider by the file's extension and run one query. Selection is per-query and + * order-independent; no match throws `LspError` `LSP_UNAVAILABLE`. + * @param request - the normalized query. + * @param signal - optional cancellation forwarded to the selected provider. + * @returns the normalized, closed-union result. + */ + query(request: LspQueryRequest, signal?: AbortSignal): Promise +} +``` + +`LspProviderId` 是该 seam 的品牌化 id(来自 [dsh-brand](../../packages/util/brand) 的 `Branded<'LspProviderId'>`);`LspError` 扩展 `HarnessError`,提供 `LSP_INVALID_PROVIDER`、`LSP_CONFLICT`、`LSP_UNAVAILABLE`、`LSP_DISPOSED`、`LSP_UNSUPPORTED_OPERATION` 和 `LSP_MALFORMED_RESPONSE` 等稳定错误码,调用方应按错误码路由,而不是解析 `message`。 diff --git a/docs/core-data-structures/pty.i18n.yaml b/docs/core-data-structures/pty.i18n.yaml new file mode 100644 index 0000000000..6fa7d71d13 --- /dev/null +++ b/docs/core-data-structures/pty.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 +pty.md: 97e1e662d1128ab0555e34f8284cf69d7d9d0d1a +pty.zh.md: b17bc0d2c7bdb2a980df36824bd360ea975967f5 diff --git a/docs/core-data-structures/pty.md b/docs/core-data-structures/pty.md index b205ec64c9..97e1e662d1 100644 --- a/docs/core-data-structures/pty.md +++ b/docs/core-data-structures/pty.md @@ -1,5 +1,7 @@ # Persistent PTY Sessions +English | [中文](pty.zh.md) + Types shared by PTY backends, `ctx.pty`, and the model-facing consumer. The [persistent PTY Agent Note](../../.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md) owns the rationale; this page records the cross-package vocabulary from [`packages/pty/pty/src/types.ts`](../../packages/pty/pty/src/types.ts). ## Identity and readiness diff --git a/docs/core-data-structures/pty.zh.md b/docs/core-data-structures/pty.zh.md new file mode 100644 index 0000000000..b17bc0d2c7 --- /dev/null +++ b/docs/core-data-structures/pty.zh.md @@ -0,0 +1,91 @@ +# 持久 PTY 会话 + +[English](pty.md) | 中文 + +PTY 后端、`ctx.pty` 与面向模型的消费方共享的类型。[持久 PTY Agent Note(agent 决策记录)](../../.agents/notes/implemented/feature/2026-07-16-persistent-pty-sessions.md) 负责记录决策依据;本页记录来自 [`packages/pty/pty/src/types.ts`](../../packages/pty/pty/src/types.ts) 的跨包(package)词汇。 + +## 标识与就绪 + +`PtySessionId` 是由服务铸造的品牌化 id。可选名称是拥有者本地的显示元数据;授权比较的是确切的所属 `Agent`,而不是名称或猜测的 id。 + +`PtyWaitReason` 说明一次发送为何返回。它与 `PtySessionStatus` 无关:一次发送可能因静默或超时而返回,但顶层 shell 仍然存活;`session_exit` 表示该 shell 已退出,而不是某个任意的前台子进程已退出。 + +```ts type-equiv +/** Why one interactive send returned control to its caller. */ +type PtyWaitReason = 'stdin_read' | 'inferred_idle' | 'timeout' | 'session_exit' +``` + +```ts type-equiv +/** Top-level PTY process status, independent of a send's wait reason. */ +type PtySessionStatus = + | { kind: 'running' } + | { kind: 'exited'; exitCode: number | null; signal: NodeJS.Signals | null } +``` + +## 后端与活跃会话 + +后端负责某个已注册类型的启动方式和就绪检测。`PtyService` 只在初始化成功后才发布返回的会话,随后负责 id 授权与清理。无法清理部分启动资源的后端会以 `PtyBackendCleanupError` 拒绝,从而让资源释放流程保留该清理失败,同时不替换调用方的取消原因。后端会话拥有终端状态,并负责使已捕获资源完全停稳。 + +```ts type-equiv +/** Replaceable provider for one PTY session type. */ +interface PtyBackend { + /** Stable type selected by {@link PtySpawnRequest.type}. */ + readonly type: string + /** Create an unpublished session or reject after cleaning partial resources; cleanup failure uses {@link PtyBackendCleanupError}. */ + spawn(spec: PtyBackendSpawnSpec): Promise +} +``` + +```ts type-equiv +/** Backend-owned live session retained by {@link PtyService}. */ +interface PtyBackendSession { + /** Initial bounded terminal output returned from `terminal_open`. */ + readonly motd: string + /** Top-level process id when one exists. */ + readonly pid?: number + /** Start one exclusive send operation. */ + startSend(request: PtySendRequest): PtySendOperation + /** Read one bounded page from retained scrollback. */ + read(request: PtyReadRequest): PtyReadResult + /** Signal the verified foreground process group. */ + signal(signal: PtySignal): Promise + /** Observe top-level process status. */ + status(): PtySessionStatus + /** Idempotently close the captured owned process tree and await quiescence. */ + close(reason: string): Promise +} +``` + +## 发送与保留输出 + +一个活跃会话同时只接受一个活动发送。该操作向通用后台任务公开一个消费式输出游标,并向前台调用方公开一个最终结果。`PtyReadResult` 则为有界的会话 scrollback 单独分页。 + +```ts type-equiv +/** Live backend-owned send; exactly one may be active per PTY session. */ +interface PtySendOperation { + /** Resolves after readiness, timeout, cancellation, or top-level process exit. */ + done: Promise + /** Consume output produced since the prior call. */ + readOutput(): PtySendRead + /** Request `SIGINT`; returns false after the operation settled. */ + cancel(): boolean +} +``` + +```ts type-equiv +/** Settled result for one foreground or background send. */ +interface PtySendResult { + /** Bounded rendered terminal delta remaining at settlement. */ + viewport: string + /** Why the wait returned; this does not imply arbitrary child-process exit. */ + waitReason: PtyWaitReason + /** Top-level session status observed at settlement. */ + sessionStatus: PtySessionStatus + /** Whether output was dropped from the operation or retained scrollback. */ + truncated: boolean +} +``` + +## 归属与持久性 + +`PtyService` 会将一项等待完成的清理附加到确切的拥有者作用域,拒绝其他拥有者的操作,并让会话在后端或工具插件重载期间保持存活。PTY 状态与原始字节仍局限在进程内。模型输入与有界的返回输出通过现有 `tool/call`、`tool/result` 和任务结果路径持久保存,而不是重复记录 PTY 会话事件。 diff --git a/docs/core-data-structures/session-reference.i18n.yaml b/docs/core-data-structures/session-reference.i18n.yaml new file mode 100644 index 0000000000..2fd211e4e2 --- /dev/null +++ b/docs/core-data-structures/session-reference.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 +session-reference.md: 4898cdd641427a023dde63bfc9759300964c7fac +session-reference.zh.md: 8e36d70241f2565a587bd3c1ee270d99dba47d71 diff --git a/docs/core-data-structures/session-reference.md b/docs/core-data-structures/session-reference.md index d9a73c08c6..4898cdd641 100644 --- a/docs/core-data-structures/session-reference.md +++ b/docs/core-data-structures/session-reference.md @@ -1,5 +1,7 @@ # Session References +English | [中文](session-reference.zh.md) + Structured cross-session reference requests and prepared message contexts. The [package contract](../../packages/context/session-reference) owns canonical URIs, current-surface projection, tag-safe JSON and byte retention, stable errors, and the untrusted model prompt. Host adapters use these types instead of passing their UI mention syntax into the agent core. Source: [`packages/context/session-reference/src/types.ts`](../../packages/context/session-reference/src/types.ts) diff --git a/docs/core-data-structures/session-reference.zh.md b/docs/core-data-structures/session-reference.zh.md new file mode 100644 index 0000000000..8e36d70241 --- /dev/null +++ b/docs/core-data-structures/session-reference.zh.md @@ -0,0 +1,67 @@ +# 会话引用 + +[English](session-reference.md) | 中文 + +结构化的跨会话引用请求与预备消息上下文。[包(package)契约](../../packages/context/session-reference) 负责规范 URI、当前表层投影、标签安全的 JSON 与字节保留、稳定错误和不可信的模型提示词。宿主适配器使用这些类型,而不会把各自 UI 的提及语法传入 agent(智能体)核心。 + +来源:[`packages/context/session-reference/src/types.ts`](../../packages/context/session-reference/src/types.ts) + +## 输入与候选项 + +`SessionReferenceInput` 是与宿主无关的选择。id 具有权威性;label 是随快照携带的显示元数据。 + +```ts type-equiv +/** One source session selected by a host. */ +interface SessionReferenceInput { + /** Opaque source session identity. */ + sessionId: SessionId + /** Optional user-facing mention label. */ + label?: string +} +``` + +`SessionReferenceCandidate` 是面向宿主的发现输出。存在最新会话标题时,它的 label 使用该标题;筛选仍只搜索 session id 和 cwd,绝不搜索 transcript(文本记录)。 + +```ts type-equiv +/** One host-facing candidate from exact session metadata. */ +interface SessionReferenceCandidate { + /** Opaque source session identity. */ + sessionId: SessionId + /** Latest log-backed title, falling back to the opaque session id. */ + label: string + /** Source session working directory, when recorded. */ + cwd?: string + /** Source session creation time in Unix epoch milliseconds. */ + createdAt: number +} +``` + +## 预备消息 + +预备过程保留可读的当前消息内容,并最多返回一个聚合上下文。宿主会把 `contexts` 绑定到该次确切的 `followup()` 或 `steer()` 调用。 + +```ts type-equiv +/** Message payload and the zero-or-one durable snapshot contexts bound to it. */ +interface PreparedReferencedMessage { + /** Readable message content after host mention tokens are removed. */ + content: ContentBlock[] + /** Empty without references; otherwise one aggregated untrusted context. */ + contexts: HookContext[] +} +``` + +## 错误 + +`SessionReferenceError.code` 区分无效配置或输入、自引用、数量限制、源读取失败、预算失败和取消。宿主协议会把这些 code 映射到各自的错误信封,无需检查提示词字节。 + +```ts type-equiv +/** Stable failure codes exposed to host adapters. */ +type SessionReferenceErrorCode = + | 'SESSION_REFERENCE_INVALID_CONFIG' + | 'SESSION_REFERENCE_INVALID_REFERENCE' + | 'SESSION_REFERENCE_SELF_REFERENCE' + | 'SESSION_REFERENCE_TOO_MANY' + | 'SESSION_REFERENCE_READ_FAILED' + | 'SESSION_REFERENCE_BUDGET_EXCEEDED' + | 'SESSION_REFERENCE_CANCELLED' +``` diff --git a/docs/core-data-structures/session-title.i18n.yaml b/docs/core-data-structures/session-title.i18n.yaml new file mode 100644 index 0000000000..f31d9016ac --- /dev/null +++ b/docs/core-data-structures/session-title.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 +session-title.md: 6575bda5fdecf2be15ed7c3288efb0efa759ac8a +session-title.zh.md: 66ec567ac6cef32acef9c50ae3e67155097a76b6 diff --git a/docs/core-data-structures/session-title.md b/docs/core-data-structures/session-title.md index 39e2b00ae5..6575bda5fd 100644 --- a/docs/core-data-structures/session-title.md +++ b/docs/core-data-structures/session-title.md @@ -1,5 +1,7 @@ # Session Titles +English | [中文](session-title.zh.md) + Durable latest-wins title state and the optional asynchronous provider vocabulary owned by [`@deepseek-ai/dsh-session-title`](../../packages/session-title/session-title). The shared LLM helper owns the exact auxiliary request record. Package READMEs own timing, fallback, failure, and fork behavior; the generated [persistence catalog](../persistence-catalog.md) owns the complete event declarations. Sources: [`packages/session-title/session-title/src/index.ts`](../../packages/session-title/session-title/src/index.ts), [`packages/session-title/session-title-llm/src/index.ts`](../../packages/session-title/session-title-llm/src/index.ts) diff --git a/docs/core-data-structures/session-title.zh.md b/docs/core-data-structures/session-title.zh.md new file mode 100644 index 0000000000..66ec567ac6 --- /dev/null +++ b/docs/core-data-structures/session-title.zh.md @@ -0,0 +1,142 @@ +# 会话标题 + +[English](session-title.md) | 中文 + +[`@deepseek-ai/dsh-session-title`](../../packages/session-title/session-title) 所拥有的持久化后写覆盖标题状态与可选异步提供方词汇。共享 LLM(大语言模型)辅助组件负责精确的辅助请求记录。各包(package)README 负责时序、回退、失败与 fork 行为;生成的[持久化日志事件目录](../persistence-catalog.md)负责完整的事件声明。 + +源码:[`packages/session-title/session-title/src/index.ts`](../../packages/session-title/session-title/src/index.ts)、[`packages/session-title/session-title-llm/src/index.ts`](../../packages/session-title/session-title-llm/src/index.ts) + +## 持久标题状态 + +提供方生成修订时会记录 `SessionTitleProviderId`。`SessionTitleEventData` 携带精确的人类消息来源信息,`SessionTitleSnapshot` 则加入 `foldSessionTitle()` 选出的持久事件信封事实。 + +```ts type-equiv +/** Identifies one session-title provider registration. */ +type SessionTitleProviderId = Branded<'SessionTitleProviderId'> +``` + +```ts type-equiv +/** Exact auxiliary model route that produced a title. */ +interface SessionTitleModelProvenance { + /** Registered LLM provider route. */ + readonly provider: string + /** Provider model id. */ + readonly model: string +} +``` + +```ts type-equiv +/** Durable ownership record for an accepted session title. */ +type SessionTitleSource = + | { readonly kind: 'fallback' } + | { + readonly kind: 'provider' + readonly provider: SessionTitleProviderId + readonly model?: SessionTitleModelProvenance + } +``` + +```ts type-equiv +/** Payload of the log-only `session/title` event. */ +interface SessionTitleEventData { + /** Normalized non-empty title text. */ + readonly title: string + /** Exact human `user/message` seqs used to derive this title. */ + readonly messageSeqs: number[] + /** Built-in fallback or registered-provider provenance. */ + readonly source: SessionTitleSource +} +``` + +```ts type-equiv +/** Latest folded title plus the title event's durable envelope facts. */ +interface SessionTitleSnapshot extends SessionTitleEventData { + /** Seq of the latest `session/title` event. */ + readonly eventSeq: number + /** Timestamp of the latest `session/title` event. */ + readonly updatedAt: number +} +``` + +## 辅助请求记录 + +共享 LLM 辅助组件会在调用模型前,记录每一项已经过验证且可分发的标题请求。即使后续生成失败,载荷仍会复现模型可见的系统输入与消息输入、路由、输出上限、提供方归属和源消息归因。 + +```ts type-equiv +/** Exact model-visible request recorded before one auxiliary title dispatch. */ +interface SessionTitleLlmRequestEventData { + /** Registered title-provider identity responsible for the request. */ + readonly titleProvider: SessionTitleProviderId + /** Exact human `user/message` seqs represented in `messages`. */ + readonly messageSeqs: number[] + /** Exact auxiliary LLM route. */ + readonly route: SessionTitleModelProvenance + /** Exact auxiliary system prompt. */ + readonly system: string + /** Exact auxiliary message list. */ + readonly messages: Message[] + /** Exact auxiliary output-token cap. */ + readonly maxTokens: number +} +``` + +## 提供方输入与输出 + +服务会对截至某一修订的合格消息创建快照。提供方返回的 seq 仅可来自该请求;由服务负责的接受过程会验证顺序、规范化标题、强制执行字节上限并追加来源信息。 + +```ts type-equiv +/** One eligible human text message exposed to title providers. */ +interface SessionTitleUserMessage { + /** Source `user/message` event seq. */ + readonly seq: number + /** Exact concatenated text-block content. */ + readonly text: string +} +``` + +```ts type-equiv +/** Automatic generation cadence owned by a registered provider. */ +type SessionTitleAutomaticMode = 'first-message' | 'all-user-messages' +``` + +```ts type-equiv +/** Immutable input supplied to one title-provider call. */ +interface SessionTitleProviderRequest { + /** Live session being titled. */ + readonly session: Session + /** All eligible human messages through this generation revision. */ + readonly messages: readonly SessionTitleUserMessage[] + /** Exact current logged main-request route, when one has been recorded. */ + readonly route?: SessionTitleModelProvenance + /** Cancellation for supersession, disposal, timeout composition, or the explicit caller. */ + readonly signal: AbortSignal +} +``` + +```ts type-equiv +/** Provider output before service-owned normalization and durable acceptance. */ +interface SessionTitleProviderResult { + /** Proposed title text. */ + readonly title: string + /** Exact seqs from `request.messages` used by this result. */ + readonly messageSeqs: readonly number[] + /** Auxiliary LLM route, when generation used a model. */ + readonly model?: SessionTitleModelProvenance +} +``` + +```ts type-equiv +/** One optional asynchronous title implementation registered with the service. */ +interface SessionTitleProvider { + /** Stable provider identity recorded in title provenance. */ + readonly id: SessionTitleProviderId + /** When new human prompts start automatic generation. */ + readonly automatic: SessionTitleAutomaticMode + /** + * Produce one title revision. + * @param request - message snapshot, current route, session, and cancellation. + * @returns proposed title plus exact input seqs and optional model provenance. + */ + generate(request: SessionTitleProviderRequest): Promise +} +``` diff --git a/docs/core-data-structures/spill.i18n.yaml b/docs/core-data-structures/spill.i18n.yaml new file mode 100644 index 0000000000..4cd4cc5e1e --- /dev/null +++ b/docs/core-data-structures/spill.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 +spill.md: a798d8143b2849dc0cf49d04e7019ce796cdee45 +spill.zh.md: 1af6939d1d8fd37958cae4f9cf2cbf706b17acd0 diff --git a/docs/core-data-structures/spill.md b/docs/core-data-structures/spill.md index a964064912..a798d8143b 100644 --- a/docs/core-data-structures/spill.md +++ b/docs/core-data-structures/spill.md @@ -1,5 +1,7 @@ # Spill Storage +English | [中文](spill.zh.md) + The spill storage seam — a [capability seam](../../.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.md) that persists a tool's oversized text and returns a model-facing locator plus retrieval guidance, split across packages: interface ([dsh-spill](../../packages/spill/spill), `ctx.spillStore`), implementation ([dsh-spill-local](../../packages/spill/spill-local), private session-scoped files on the host filesystem), and consumer ([dsh-spill-policy](../../packages/spill/spill-policy), the `tools/post-execute` policy). Spill is **one optional capability**, not part of the agent-loop spine — so its vocabulary lives here, not in [core.md](core.md). Preview mechanics stay in [dsh-retention](../../packages/util/retention); this seam only saves the final text the policy hands it. Source: [`packages/spill/spill/src/types.ts`](../../packages/spill/spill/src/types.ts) diff --git a/docs/core-data-structures/spill.zh.md b/docs/core-data-structures/spill.zh.md new file mode 100644 index 0000000000..1af6939d1d --- /dev/null +++ b/docs/core-data-structures/spill.zh.md @@ -0,0 +1,85 @@ +# 落盘存储 + +[English](spill.md) | 中文 + +落盘存储 seam 是一项[能力 seam](../../.agents/notes/implemented/architecture/2026-07-08-tool-output-spill-files.md),它持久保存工具的超大文本,并返回面向模型的定位符与检索指引;该能力拆分到三个包(package):接口([dsh-spill](../../packages/spill/spill),`ctx.spillStore`)、实现([dsh-spill-local](../../packages/spill/spill-local),宿主文件系统中会话作用域的私有文件)和消费方([dsh-spill-policy](../../packages/spill/spill-policy),`tools/post-execute` 策略)。落盘是**一项可选能力**,不属于 agent loop(智能体循环)主干,因此其词汇记录在此处,而不在 [core.md](core.md) 中。预览机制仍归 [dsh-retention](../../packages/util/retention) 所有;该 seam 只保存策略交给它的最终文本。 + +源码:[`packages/spill/spill/src/types.ts`](../../packages/spill/spill/src/types.ts) + +## 保存请求 + +`saveText` 是整个 seam:原样持久保存 `content`,并返回不透明的定位符、后端提供的检索提示和准确字节数。请求携带保存时的存储命名空间(`owner`)、内容来源(`source`,用于命名和检查的描述性来源信息,而非访问控制)以及后端可用作命名提示的 `suggestedName`(它不是路径)。 + +```ts type-equiv +/** One request to persist text to a spill artifact. */ +interface SaveTextSpill { + owner: SpillOwner + source: SpillSource + /** + * A caller-suggested base name (e.g. `web_fetch.txt`). The backend sanitizes + * it to a single safe path segment before use — it is a hint, never a path. + */ + suggestedName: string + /** The full text to persist (UTF-8). */ + content: string +} +``` + +```ts type-equiv +/** + * Save-time storage namespace for a spilled artifact. The session id lets a + * backend group storage under the producing session, but the returned + * {@link SpillLocator} is the model-facing handle. Forked sessions inherit + * locators already present in the seeded log; those artifacts are not copied or + * re-owned, and spills produced after the fork use the child session id. + */ +interface SpillOwner { + sessionId: SessionId +} +``` + +`SpillOwner.sessionId` 是保存时的存储命名空间。fork 后的会话会从种子日志继承已有的落盘定位符;这些产物不会被复制或重新取得所有权,fork 后产生的落盘则使用子会话 id。保留期清理可以连同其他旧会话产物一起使旧定位符失效;落盘 seam 不定义逐会话的清理策略。 + +```ts type-equiv +/** + * Provenance of one spilled artifact — recorded by the backend for a readable + * filename and inspection. Not interpreted for access control; purely + * descriptive. + */ +interface SpillSource { + /** The tool whose result was spilled (e.g. `web_fetch`). */ + toolName: string + /** The model-issued call id the result belongs to. */ + callId: CallId + /** A short human label for the artifact (e.g. `result`). */ + label: string +} +``` + +## 结果 + +```ts type-equiv +/** A saved spill artifact: its locator, byte length, and backend-specific retrieval guidance. */ +interface SpillRef { + locator: SpillLocator + bytes: number + retrievalHint: string +} +``` + +`SpillLocator` 是后端返回的[品牌化](core.md#branded-ids)面向模型句柄。本地后端将它渲染为文件系统路径;远程或数据库后端可以渲染 URI、键或命令 token。消费方将它视为不透明值,并使用 `retrievalHint` 渲染,而不是假定 `read` 始终是正确的检索机制。 + +```ts type-equiv +/** + * Opaque model-facing handle for one spilled artifact. A local backend may use a + * filesystem path; a remote or database backend may use a URI or key. Consumers + * render it with {@link SpillRef.retrievalHint}, but do not parse it. + */ +type SpillLocator = Branded<'SpillLocator'> +``` + +## 服务 + +`SpillStore`(`ctx.spillStore`,定义于 [`packages/spill/spill/src/index.ts`](../../packages/spill/spill/src/index.ts))是只有一个方法的抽象服务:`saveText(input) → Promise`。它持久保存完整的 `content`,并在实际存储失败(权限、ENOSPC、后端不可用)时拒绝。该 seam 只负责存储:不负责保留策略、工具结果替换或检索/搜索 API。 + +本地后端([dsh-spill-local](../../packages/spill/spill-local))写入 `/session-/-`:根目录是已配置或延迟创建的私有(0700)目录,会话子目录采用 `sha256(sessionId)`,并通过排他的仅所有者可访问写入(`open(path, 'wx', 0o600)`)防止预先植入的符号链接重定向写入。其 `locator` 是本地路径,`retrievalHint` 则告知模型在该路径上使用 `read` 或 `grep`。策略消费方([dsh-spill-policy](../../packages/spill/spill-policy))会把超过 `maxInlineBytes` 的纯文本最终结果替换为保留库生成的首尾预览和落盘引用;该过程尽力而为:保存失败时保留原始内联结果,而不会把成功的调用变成 `isError`。 diff --git a/docs/core-data-structures/tasks.i18n.yaml b/docs/core-data-structures/tasks.i18n.yaml new file mode 100644 index 0000000000..f9d14f2163 --- /dev/null +++ b/docs/core-data-structures/tasks.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 +tasks.md: d1f5a6d7b369e6113132f60e493cf87757e20599 +tasks.zh.md: 1562d9401f0f55ac6d6260902b8b1c71d9664d48 diff --git a/docs/core-data-structures/tasks.md b/docs/core-data-structures/tasks.md index 2c7555b84d..d1f5a6d7b3 100644 --- a/docs/core-data-structures/tasks.md +++ b/docs/core-data-structures/tasks.md @@ -1,5 +1,7 @@ # Background Task Runtime +English | [中文](tasks.zh.md) + Types shared by long-running producers, `ctx.tasks`, and task control surfaces. The [runtime Agent Note](../../.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md) owns the design; this page records the literal shapes from [`packages/tasks/tasks/src/types.ts`](../../packages/tasks/tasks/src/types.ts). ## Ids and status diff --git a/docs/core-data-structures/tasks.zh.md b/docs/core-data-structures/tasks.zh.md new file mode 100644 index 0000000000..1562d9401f --- /dev/null +++ b/docs/core-data-structures/tasks.zh.md @@ -0,0 +1,154 @@ +# 后台任务运行时 + +[English](tasks.md) | 中文 + +长时间运行的生产方、`ctx.tasks` 与任务控制接口共用的类型。[运行时 Agent Note(agent 决策记录)](../../.agents/notes/implemented/architecture/2026-06-20-generic-long-running-tool-runtime.md)负责设计;本页记录 [`packages/tasks/tasks/src/types.ts`](../../packages/tasks/tasks/src/types.ts) 中的字面形状。 + +## ID 与状态 + +`TaskId` 是按 `-N` 生成的[品牌化 id](core.md#branded-ids)。访问控制依赖拥有者授权,而非 id 的保密性。`TaskKind` 派生自可合并扩展的 map;注册表将各个 kind 视为不透明的 id 命名空间。 + +```ts type-equiv +/** + * Producer-defined task kinds. Plugins extend this map by declaration merging; + * the registry treats every value as an opaque id namespace. + */ +interface TaskKindMap { + bash: 'bash' + subagent: 'subagent' +} +``` + +`TaskStatus` 为 `'running' | 'stopping' | 'completed' | 'killed' | 'failed'`;生产方特有的事实归入 `TaskSnapshot.detail`。 + +## 生产方契约 + +`TaskStart` 声明身份和启动器。运行时会在调用 `run()` 前完成预检,随后提交注册,不再执行可能失败的步骤。生产方拥有执行资源;运行时拥有身份、访问权限和生命周期状态。 + +```ts type-equiv +/** + * Producer declaration passed to {@link TaskService.start}. The runtime + * preflights access and cleanup before invoking {@link run}; the producer owns + * execution resources while the runtime owns identity and lifecycle state. + */ +interface TaskStart { + /** Producer kind — also the id prefix (`bash`, `subagent`, …). */ + kind: TaskKind + /** One-line model-facing label (the command; the delegation description). */ + label: string + /** + * Optional UTF-8 byte cap for each complete model-facing completion notice or + * output read, including control-surface status metadata. + */ + outputLimitBytes?: number + /** + * Owning live agent. Access is fenced by its session id, and agent disposal + * cancels and awaits the task. The instance must be the one currently + * registered under its agent id. Omitting the owner creates an unowned task, + * open to any caller until service disposal. + */ + owner?: Agent + /** + * Start the work after preflight and synchronously return its hooks. Called + * once; a throw leaves nothing registered, and the producer must clean up any + * partially started resources. + */ + run(): TaskHooks +} +``` + +`TaskHooks.done` 是完全停稳边界。可选的 `readOutput` 用来区分会消费输出的流式任务和仅有最终输出的任务。 + +```ts type-equiv +/** Hooks through which the runtime controls and observes producer work. */ +interface TaskHooks { + /** + * Request termination. Must be synchronous, idempotent, and eventually settle + * {@link done}; throws propagate. The optional reason is forwarded verbatim. + */ + cancel(reason?: string): void + /** + * Resolves after the producer releases its resources, not merely when work + * finishes. Must not reject; the runtime converts a rejection to `failed`. + * If teardown cancellation throws, the runtime may force-fail only the + * registry record without claiming that the work stopped. + */ + done: Promise + /** + * Consume output produced since the previous call. The producer formats + * truncation and spill notices. Absence marks a final-output-only task; each + * task has one consuming cursor. + */ + readOutput?(): string +} +``` + +```ts type-equiv +/** Terminal result supplied by a producer through {@link TaskHooks.done}. */ +interface TaskOutcome { + /** How the task ended: finished (`completed`), cancelled (`killed`), or broke (`failed`). */ + status: 'completed' | 'killed' | 'failed' + /** Kind-specific detail rendered into status lines ('exit code: 3', 'max-tokens'). */ + detail?: string + /** Final output for tasks without `readOutput`; stream tasks leave it unset. */ + output?: string +} +``` + +## 消费方视图 + +快照是每次新建的只读投影。`ownerSession` 携带用于授权的共享 `SessionId`;完成监听器则会另行收到用于生命周期清理的确切拥有者对象。另一个接口已经交付终止状态或承诺交付时,`reported` 会抑制完成通知。 + +```ts type-equiv +/** + * A read-only projection of one task, safe to hand to listeners and tools — + * a fresh object per call, never live registry state. + */ +interface TaskSnapshot { + /** The registry-issued id (`-N`). */ + id: TaskId + /** The producer kind the task was registered with. */ + kind: TaskKind + /** The producer-supplied one-line label. */ + label: string + /** Producer-owned cap for complete model-facing notices and output reads. */ + outputLimitBytes?: number + /** + * Owner session id used for authorization and correlation; absent for + * unowned tasks. Completion listeners receive the exact {@link Agent} + * separately through {@link TaskDoneListener}. + */ + ownerSession?: SessionId + /** Current lifecycle state. */ + status: TaskStatus + /** Kind-specific status detail, present once the producer supplied one (usually terminal). */ + detail?: string + /** Epoch ms when the task was registered. */ + startedAt: number + /** Epoch ms when the task settled; absent while `running`/`stopping`. */ + finishedAt?: number + /** + * True when a kill, read, or wait has reported or committed to report the + * terminal state. Completion surfaces suppress redundant notices when set. + */ + reported: boolean +} +``` + +```ts type-equiv +/** Output and post-read state returned by {@link TaskService.read}. */ +interface TaskRead { + /** + * Stream kinds: the consuming delta since the previous read. Final-output + * kinds: empty while live, the terminal {@link TaskOutcome.output} (or + * empty) once settled — idempotent, never consumed. + */ + text: string + /** The task's state at read time. */ + snapshot: TaskSnapshot +} +``` + +## 服务行为 + +[`TaskService`](../../packages/tasks/tasks/src/index.ts) 提供原子 `start`、限定调用方作用域的 `get` 和 `list`、`read`、`kill`、有界 `wait`、故障隔离的 `onTaskDone` 监听器,以及 `attachSurface` 可用性防线。授权会比较拥有者会话;拥有者清理会选择确切的已注册 `Agent` 实例。包(package)契约见 [`dsh-tasks`](../../packages/tasks/tasks/README.md),面向模型的接口见 [`dsh-tool-tasks`](../../packages/tasks/tool-tasks/README.md)。 diff --git a/docs/core-data-structures/token-meter.i18n.yaml b/docs/core-data-structures/token-meter.i18n.yaml new file mode 100644 index 0000000000..ed05739725 --- /dev/null +++ b/docs/core-data-structures/token-meter.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 +token-meter.md: 05784e294485a11acf0e4c8972e4083b1786c943 +token-meter.zh.md: c0dc55274acf21186f7baa00c377f9135792f888 diff --git a/docs/core-data-structures/token-meter.md b/docs/core-data-structures/token-meter.md index 880ec79d7d..05784e2944 100644 --- a/docs/core-data-structures/token-meter.md +++ b/docs/core-data-structures/token-meter.md @@ -1,5 +1,7 @@ # Token Meter +English | [中文](token-meter.zh.md) + `@deepseek-ai/dsh-token-meter` exposes one detached replay snapshot for request pressure and positional surface pricing. `logRevision` is the number of durable events consumed for every field in the measurement. Source: [`packages/llm/token-meter/src/types.ts`](../../packages/llm/token-meter/src/types.ts) diff --git a/docs/core-data-structures/token-meter.zh.md b/docs/core-data-structures/token-meter.zh.md new file mode 100644 index 0000000000..c0dc55274a --- /dev/null +++ b/docs/core-data-structures/token-meter.zh.md @@ -0,0 +1,43 @@ +# Token 计量 + +[English](token-meter.md) | 中文 + +`@deepseek-ai/dsh-token-meter` 公开一个独立的回放快照,用于表示请求压力与按位置计算的 surface 定价。`logRevision` 表示生成该计量中每个字段时所消费的持久事件数量。 + +来源:[`packages/llm/token-meter/src/types.ts`](../../packages/llm/token-meter/src/types.ts) + +## `TokenMeasurement` + +```ts type-equiv +/** Detached immutable request-pressure and surface snapshot at one consumed log revision. */ +interface TokenMeasurement { + /** Number of durable events consumed; equal to the next unread event seq. */ + readonly logRevision: number + /** Provider or heuristic anchor used for this measurement. */ + readonly baseline: TokenMeasurementBaseline + /** Signed repricing of current surface content relative to the baseline anchor. */ + readonly surfaceDeltaTokens: number + /** Non-negative current request-and-response pressure. */ + readonly totalTokens: number + /** Total heuristic tokens across the current surface. */ + readonly surfaceTokens: number + /** Current surface nodes in positional head-to-tail order. */ + readonly nodes: readonly TokenSurfaceNode[] +} +``` + +`baseline.kind === 'usage'` 表示最近一次成功的提供方调用具有相同的规范请求信封,且当前总量不低于该调用的完整启发式锚点。`estimated` 表示不存在可复用的保守 usage 锚点,因此服务使用固定启发式规则对完整信封和 surface 定价。后续成功请求会替换早先的锚点;有符号的 `surfaceDeltaTokens` 会保留相对于匹配锚点的增长与缩减。`totalTokens` 仍表示请求与响应压力,`surfaceTokens` 则是仅针对 surface 的启发式总量,等于所有节点价格之和。 + +## `TokenSurfaceNode` + +```ts type-equiv +/** One token-priced node in the current ordered session surface. */ +interface TokenSurfaceNode { + /** Durable sequence number of the surface event. */ + readonly seq: number + /** Heuristic tokens for the exact message projected by this node. */ + readonly tokens: number +} +``` + +surface 顺序具有权威性;替换节点的持久 seq 可能高于位置排在其后的节点。该快照不可变,不会随底层回放折叠推进而增长。 diff --git a/docs/web-styling.i18n.yaml b/docs/web-styling.i18n.yaml new file mode 100644 index 0000000000..5509012e3e --- /dev/null +++ b/docs/web-styling.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 +web-styling.md: af05faca30fc968828f5a850f59d9d48ae382b05 +web-styling.zh.md: d0838cd8a6ee4290cdddff16b979950bec396314 diff --git a/docs/web-styling.md b/docs/web-styling.md index 0b6aeb55d5..af05faca30 100644 --- a/docs/web-styling.md +++ b/docs/web-styling.md @@ -1,107 +1,109 @@ -# Web GUI 样式规范 +# Web GUI Style Guide -> **【token 体系已换代——§1 表格仅历史参考】** 本文的 `--bg-*`/`--text-*`/`--accent` token 族与其宿主包 `packages/client/web-ui` 已随插件化重构退役。现行 token 唯一来源=`packages/client/ui-theme/src/styles/` 的 `--dsw-*` 体系(static 色阶+alias 语义层,暗色=`body[data-ds-dark-theme]` 覆写),sheet 即权威、组件对账以它为准。**仍然有效**:工程约束(CSS Modules + clsx、无组件库、无 tailwind、组件禁 hardcode 色值)、字号成对写行高、间距 4 倍数、代码字体栈末位不放 monospace。 +English | [中文](web-styling.zh.md) -> 状态:原「活文档」(随 `packages/client/web-ui` 演进)。视觉基线源自对 deepseekchat 前端仓的实测调研。框架决策与工程约束由 [web-styling-system RFC](../.agents/notes/implemented/process/2026-07-19-web-styling-system.md) 拍板,本文不重复论证。 +> **[The token system has been replaced—the table in § 1 is retained only for historical reference]** The `--bg-*`/`--text-*`/`--accent` token families documented here and their host package, `packages/client/web-ui`, were retired during the plugin refactor. The sole current token source is `packages/client/ui-theme/src/styles/`, which defines the `--dsw-*` system (a static color scale plus a semantic alias layer, with dark-mode overrides under `body[data-ds-dark-theme]`). The sheet is authoritative and component audits use it as the baseline. **The following rules remain in force**: CSS Modules + clsx, no component library, no Tailwind, no hard-coded color values in components, pair every font size with a line height, use spacing in multiples of 4, and do not put monospace last in the code font stack. -## 1. 设计 token 表(权威定义) +> Status: formerly a “living document” that evolved with `packages/client/web-ui`. The visual baseline came from empirical study of the deepseekchat frontend repository. The [web-styling-system RFC](../.agents/notes/implemented/process/2026-07-19-web-styling-system.md) owns the framework decisions and engineering constraints; this document does not repeat their rationale. -所有 token 住 `packages/client/web-ui/src/style/global.css`:`:root` 亮色实值,`[data-theme='dark']` 块覆盖同名变量(未补全前列为占位)。组件 CSS 只引 token,不出现字面量色值。 +## 1. Design token table (authoritative definitions) -### 1.1 颜色(两层:注释里是 base 色板出处,变量名即语义别名) +All tokens live in `packages/client/web-ui/src/style/global.css`: `:root` contains the light-theme values, and the `[data-theme='dark']` block overrides the same variables (columns that were not complete are marked as placeholders). Component CSS references tokens only and contains no literal color values. -| token | 亮色实值 | 暗色(占位) | 用途 | +### 1.1 Colors (two layers: comments identify the base-palette source, while variable names are semantic aliases) + +| token | Light value | Dark value (placeholder) | Purpose | | --- | --- | --- | --- | -| `--bg-base` | `#ffffff` | `#151517` | 页面底 | -| `--bg-layer` | `#ffffff` | `#232324` | 浮层/面板 | -| `--bg-sidebar` | `#f9fafb` | `#1b1b1c` | 侧边栏底 | -| `--text-primary` | `#0f1115` | `#f9fafb` | 正文 | -| `--text-secondary` | `#61666b` | `#cfd3d6` | 次要文字 | -| `--text-tertiary` | `#81858c` | `#adb2b8` | 辅助/说明 | -| `--border-l1` | `rgba(0,0,0,.04)` | `rgba(255,255,255,.06)` | 弱分隔(侧边栏右缘) | -| `--border-l2` | `rgba(0,0,0,.1)` | `rgba(255,255,255,.12)` | 常规边框 | -| `--hover-bg` | `rgba(38,49,72,.06)` | `rgba(255,255,255,.08)` | hover 态底 | -| `--active-bg` | `rgba(38,49,72,.1)` | `rgba(255,255,255,.14)` | 按压/激活态底 | -| `--accent` | `#3964fe` | `#5686fe` | 品牌蓝(deepseek-500;暗提亮一档) | -| `--accent-soft` | `#edf3fe` | `#28313f` | 淡品牌底(强调块) | -| `--accent-item` | `#e4edfd` | `#35363a` | 侧边栏选中条目底 | -| `--bubble-bg` | `#edf3fe` | `#2c2c2e` | 用户消息气泡底 | -| `--ok` / `--error` / `--warn` | `#22c55e` / `#ec1313` / `#f59e0b` | 同值 | 语义状态色 | -| `--text-on-solid` | `#ffffff` | 同值 | 实色底(accent/error 徽标等)上的文字 | -| `--ok-soft` / `--error-soft` | `#e6faed` / `#fee2e2` | `#233c2c` / `#570c0c` | 语义状态软底(徽章);green-100/red-100,暗为 900 档 | -| `--color-frame-mux` / `--color-frame-host` | `#8250df` / `#0969da` | 同值 | RPC 调试面板方向色(自有,非基线) | -| `--frame-mux-soft` / `--frame-host-soft` | `rgba(130,80,223,.1)` / `rgba(9,105,218,.1)` | 同色 `.24` | 方向色软底(徽章) | -| `--scroll-color` / `--scroll-color-hover` | `rgba(0,0,0,.08)` / `.15` | `rgba(255,255,255,.15)` / `.24` | 滚动条(`.scrollable` 专用) | +| `--bg-base` | `#ffffff` | `#151517` | Page background | +| `--bg-layer` | `#ffffff` | `#232324` | Floating layer/panel | +| `--bg-sidebar` | `#f9fafb` | `#1b1b1c` | Sidebar background | +| `--text-primary` | `#0f1115` | `#f9fafb` | Body text | +| `--text-secondary` | `#61666b` | `#cfd3d6` | Secondary text | +| `--text-tertiary` | `#81858c` | `#adb2b8` | Supporting/descriptive text | +| `--border-l1` | `rgba(0,0,0,.04)` | `rgba(255,255,255,.06)` | Subtle separator (sidebar right edge) | +| `--border-l2` | `rgba(0,0,0,.1)` | `rgba(255,255,255,.12)` | Standard border | +| `--hover-bg` | `rgba(38,49,72,.06)` | `rgba(255,255,255,.08)` | Hover-state background | +| `--active-bg` | `rgba(38,49,72,.1)` | `rgba(255,255,255,.14)` | Pressed/active-state background | +| `--accent` | `#3964fe` | `#5686fe` | Brand blue (deepseek-500; one step lighter in dark mode) | +| `--accent-soft` | `#edf3fe` | `#28313f` | Soft brand background (emphasis blocks) | +| `--accent-item` | `#e4edfd` | `#35363a` | Selected sidebar-item background | +| `--bubble-bg` | `#edf3fe` | `#2c2c2e` | User-message bubble background | +| `--ok` / `--error` / `--warn` | `#22c55e` / `#ec1313` / `#f59e0b` | Same values | Semantic status colors | +| `--text-on-solid` | `#ffffff` | Same value | Text on solid backgrounds (accent/error badges, etc.) | +| `--ok-soft` / `--error-soft` | `#e6faed` / `#fee2e2` | `#233c2c` / `#570c0c` | Soft semantic status backgrounds (badges); green-100/red-100, with the 900 shades in dark mode | +| `--color-frame-mux` / `--color-frame-host` | `#8250df` / `#0969da` | Same values | RPC debugger direction colors (project-specific, not part of the baseline) | +| `--frame-mux-soft` / `--frame-host-soft` | `rgba(130,80,223,.1)` / `rgba(9,105,218,.1)` | Same colors at `.24` | Soft direction-color backgrounds (badges) | +| `--scroll-color` / `--scroll-color-hover` | `rgba(0,0,0,.08)` / `.15` | `rgba(255,255,255,.15)` / `.24` | Scrollbar colors (for `.scrollable` only) | -### 1.2 非颜色 +### 1.2 Non-color tokens -| token | 值 | 说明 | +| token | Value | Description | | --- | --- | --- | -| `--font-ui` | `Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif` | 正文栈 | -| `--font-mono` | `Menlo, Monaco, Consolas, 'JetBrains Mono', 'Courier New', sans-serif` | 代码栈;**末位不放 monospace**(防 Windows 中文回退宋体) | -| `--fw-strong` | `600` | 粗体统一权重 | -| `--ease` | `cubic-bezier(.4,0,.2,1)` | 唯一缓动曲线 | -| `--dur` / `--dur-fast` / `--dur-slow` | `.2s` / `.1s` / `.3s` | 过渡三档 | -| `--radius-s` / `--radius-m` / `--radius-l` / `--radius-bubble` / `--radius-xl` | `8px` / `12px` / `16px` / `22px` / `24px` | 圆角语义档:小控件 / 列表条目与面板内块 / 浮层 / 气泡 / 输入卡片(基线 inputWrapper 同值);胶囊直接写 `999px` | -| `--shadow-panel` | `0 0 1px rgba(0,0,0,.2), 0 0 4px rgba(0,0,0,.02), 0 12px 32px rgba(0,0,0,.08)` | 浮层阴影(基线 lv3) | -| `--shadow-float` | `0 0 1px rgba(0,0,0,.24), 0 4px 12px rgba(0,0,0,.06), 0 16px 48px rgba(0,0,0,.16)` | 强浮动面板(lv3 加强档,如 RPC 调试浮层) | -| `--shadow-card` | `0 4px 10px rgba(0,0,0,.02), 0 2px 4px rgba(0,0,0,.04)`;暗色 `none` | 输入卡片微阴影(基线:亮色同底靠边框+微影区分,暗色靠提亮底、阴影关闭) | +| `--font-ui` | `Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif` | Body-text stack | +| `--font-mono` | `Menlo, Monaco, Consolas, 'JetBrains Mono', 'Courier New', sans-serif` | Code stack; **do not put monospace last** (prevents SimSun fallback for Chinese on Windows) | +| `--fw-strong` | `600` | Unified bold weight | +| `--ease` | `cubic-bezier(.4,0,.2,1)` | Sole easing curve | +| `--dur` / `--dur-fast` / `--dur-slow` | `.2s` / `.1s` / `.3s` | Three transition durations | +| `--radius-s` / `--radius-m` / `--radius-l` / `--radius-bubble` / `--radius-xl` | `8px` / `12px` / `16px` / `22px` / `24px` | Semantic radius steps: small controls / list items and blocks inside panels / floating layers / bubbles / input cards (same as the baseline inputWrapper); use `999px` directly for pills | +| `--shadow-panel` | `0 0 1px rgba(0,0,0,.2), 0 0 4px rgba(0,0,0,.02), 0 12px 32px rgba(0,0,0,.08)` | Floating-layer shadow (baseline lv3) | +| `--shadow-float` | `0 0 1px rgba(0,0,0,.24), 0 4px 12px rgba(0,0,0,.06), 0 16px 48px rgba(0,0,0,.16)` | Strong floating panel (enhanced lv3, such as the RPC debugger overlay) | +| `--shadow-card` | `0 4px 10px rgba(0,0,0,.02), 0 2px 4px rgba(0,0,0,.04)`; dark value `none` | Subtle input-card shadow (baseline: borders plus a subtle shadow distinguish same-color light surfaces; a lighter background distinguishes dark surfaces, with the shadow disabled) | -字号与间距**不 token 化**(基线仓同款决策):字号在组件里写 px 且**成对写行高**,常用对 16/24(气泡)、14/22(UI 默认)、12/18(辅助);间距用 4 的倍数。 +Font sizes and spacing are **not tokenized** (matching the baseline repository's decision): components specify font sizes in px and **always pair them with line heights**. Common pairs are 16/24 (bubbles), 14/22 (UI default), and 12/18 (supporting text); spacing uses multiples of 4. -## 2. 视觉基线(源自 deepseekchat) +## 2. Visual baseline (from deepseekchat) -- 侧边栏:宽 `260px + 1px` 右边框(`--border-l1`);底色 `--bg-sidebar`。 -- 侧边栏条目:高 `40px`、圆角 `--radius-m`、字号 14px;hover 底 `--hover-bg` 或 sidebar 专属灰、**选中底 `--accent-item` 且不改文字色**。 -- 侧边栏分组标题:12px / weight 500 / `--text-tertiary` / sticky 顶部(底色同侧边栏遮滚动内容)。 -- 会话列:`max-width: 840px` 居中,<1024px 降 712px。 -- 消息流:**仅用户侧有气泡**——`--bubble-bg` 底、圆角 `--radius-bubble`、padding `10px 16px`、字号 16px/24px、`max-width: calc(100% - 88px)`;**助手侧纯文档流无底色**。 -- 消息操作条:默认 `opacity: 0`,父块 hover/focus-within 淡入(`--dur` + `--ease`)。 -- 输入卡片:与会话列同宽(840px,<1024px 降 712px)居中悬浮(距底留白带);圆角 `--radius-xl`、边框 `--border-l2`、底 `--bg-base`、阴影 `--shadow-card`;内部上下两段=textarea(16px/24px,min 2 行 max 14 行=336px,镜像 div 自增高)+ 操作行(右下嵌 34px 主圆钮);focus 无边框/阴影变化(基线同款)。 -- 输入主按钮(拍板 2026-07-20 三连,视觉参照 Codex App):32px 实心正圆图标钮(内联 SVG)——空闲=`--accent` 底白↑箭头「发送」,运行中原地变 `--accent-soft` 底 accent ■「停止」(同色系不告警、不用红)。**运行中锁输入**(拍板 3,取代早先 hover 菜单方案):textarea disabled(灰、草稿内容保留可见)、无任何排队/插话菜单,停止是唯一动作;turn 结束解禁并 refocus。键盘 Enter=发送、Ctrl/Meta+Enter=换行(运行中键盘路径随锁失效)。 -- 滚动条:近隐形、hover 加深、`scrollbar-gutter: stable` 不占布局(统一走 `.scrollable`,见 §3-9)。 -- RPC 四象限方向符(官方视觉词汇,空间隐喻:上=去 server、下=来自 server;单线=unary、双线=SSE): +- Sidebar: width `260px + 1px` right border (`--border-l1`); background `--bg-sidebar`. +- Sidebar items: height `40px`, radius `--radius-m`, font size 14px; hover background `--hover-bg` or a sidebar-specific gray; **selected items use `--accent-item` without changing text color**. +- Sidebar group headings: 12px / weight 500 / `--text-tertiary` / sticky at the top (using the sidebar background to cover scrolling content). +- Conversation column: centered at `max-width: 840px`, reduced to 712px below 1024px. +- Message stream: **only user messages have bubbles**: background `--bubble-bg`, radius `--radius-bubble`, padding `10px 16px`, font size 16px/24px, and `max-width: calc(100% - 88px)`; **assistant messages are a plain document flow without a background**. +- Message action bar: `opacity: 0` by default; fades in when its parent is hovered or contains focus (`--dur` + `--ease`). +- Input card: floats centered at the same width as the conversation column (840px, reduced to 712px below 1024px) with bottom spacing; radius `--radius-xl`, border `--border-l2`, background `--bg-base`, shadow `--shadow-card`; two internal vertical sections = textarea (16px/24px, minimum 2 lines, maximum 14 lines = 336px, auto-growing through a mirror div) + action row (a 34px primary round button nested at bottom right); focus does not change the border or shadow (matching the baseline). +- Primary input button (the three decisions made on 2026-07-20, visually based on the Codex App): a 32px solid circular icon button (inline SVG). Idle = `--accent` background with a white ↑ “Send” arrow; while running it changes in place to an accent ■ “Stop” icon on `--accent-soft` (the same color family, not a warning, and not red). **Input is locked while running** (decision 3, replacing the earlier hover-menu design): the textarea is disabled (gray, with draft content still visible), there is no queue/interjection menu, and Stop is the only action. When the turn ends, input unlocks and regains focus. Enter sends; Ctrl/Meta+Enter inserts a newline (the keyboard path is disabled with the locked input while running). +- Scrollbars: nearly invisible, darkening on hover, with `scrollbar-gutter: stable` so they do not consume layout space (always use `.scrollable`; see § 3.9). +- Four-quadrant RPC direction symbols (the official visual vocabulary, using the spatial metaphor that up goes to the server, down comes from the server; single line = unary, double line = SSE): -| 符号 | 象限 | 徽章配色 | +| Symbol | Quadrant | Badge colors | | --- | --- | --- | -| `↑` | client-request(unary 出站) | `--accent` / `--accent-soft` | -| `↓` | server-response(unary 回包) | ok `--ok`/`--ok-soft`,error `--error`/`--error-soft` | -| `⇟` | server-request(SSE 帧推送) | mux `--color-frame-mux`/`--frame-mux-soft`,host `--color-frame-host`/`--frame-host-soft` | -| `⇞` | client-response(SSE 侧回应) | `--accent`/`--accent-soft` 降透明度 | +| `↑` | client-request (unary outbound) | `--accent` / `--accent-soft` | +| `↓` | server-response (unary response) | ok `--ok`/`--ok-soft`, error `--error`/`--error-soft` | +| `⇟` | server-request (SSE frame push) | mux `--color-frame-mux`/`--frame-mux-soft`, host `--color-frame-host`/`--frame-host-soft` | +| `⇞` | client-response (SSE-side response) | `--accent`/`--accent-soft` at reduced opacity | -## 3. 样式编码规范(review 对照打勾) +## 3. Style implementation rules (review checklist) -1. 颜色/圆角/动效/字体栈只引 §1 token;组件 CSS 出现字面量色值即打回(渐变遮罩等特效除外,须注释说明)。 -2. 组件 CSS 禁止出现 `[data-theme]` 选择器;暗色差异只在 global.css token 表做。确需按主题换非 token 值(渐变端点等),组件定义局部 CSS 变量、主题块只覆写变量(变量桥)。 -3. 类名 camelCase;状态类用单形容词(`.active` `.show`),由 clsx 挂载:`clsx(styles.x, cond && styles.active, className)`。 -4. 对外组件必须透传 `className` 并合入根元素。 -5. 禁用 `composes`;复用靠 token 与组件抽取。 -6. `:global` 仅用于穿透第三方/跨包类名;禁止用它定义新全局类。 -7. 交互过渡一律 `var(--dur*) var(--ease)`,只过渡 opacity / transform / 背景色 / 阴影;纯 hover 展示型元素包 `@media (hover: hover)`。 -8. hover/active 底色优先用透明度制 token(叠任意海拔底色都成立),不新造实色灰。 -9. 滚动容器统一挂 global.css 的 `.scrollable` 工具类;组件内禁写 `::-webkit-scrollbar`。 -10. 媒体查询写在组件 css 尾部、贴着被覆盖规则;断点当前仅 1024px 一档(会话列降档),加第二档需先记入本文档。 -11. 动态样式 JS 侧只写 CSS 变量(`style={{'--x': v}}`),规则留在 CSS;禁止在 TSX 里拼接样式对象做主题/状态分支。 -12. 文字灰阶只用 `--text-primary/secondary/tertiary` 三级,不新造灰色。 +1. Colors, radii, motion, and font stacks reference only the § 1 tokens. Reject literal color values in component CSS (except for special effects such as gradient masks, which require an explanatory comment). +2. Component CSS must not contain `[data-theme]` selectors; dark-mode differences belong only in the global.css token table. If a theme must change a non-token value such as a gradient endpoint, define a local CSS variable in the component and have the theme block override only that variable (a variable bridge). +3. Use camelCase class names; use a single adjective for state classes (`.active` `.show`) and attach them with clsx: `clsx(styles.x, cond && styles.active, className)`. +4. Public components must accept `className` and merge it into the root element. +5. Do not use `composes`; share through tokens and extracted components. +6. Use `:global` only to pierce third-party or cross-package class names; do not use it to define new global classes. +7. All interaction transitions use `var(--dur*) var(--ease)` and transition only opacity / transform / background color / shadow. Wrap hover-only reveal elements in `@media (hover: hover)`. +8. Prefer opacity-based tokens for hover/active backgrounds because they compose over any elevation background; do not add new solid grays. +9. Apply the `.scrollable` utility class from global.css to every scroll container; do not write `::-webkit-scrollbar` inside components. +10. Put media queries at the end of the component CSS, next to the rules they override. The only current breakpoint is 1024px (where the conversation column steps down); record a second breakpoint in this document before adding it. +11. Dynamic styles in JS set only CSS variables (`style={{'--x': v}}`), while rules remain in CSS; do not assemble style objects in TSX to branch by theme or state. +12. Use only the three `--text-primary/secondary/tertiary` levels for gray text; do not add another gray. -## 4. 文件组织 +## 4. File organization -- `src/style/global.css` 固定分区顺序:① token 表(`:root` + `[data-theme='dark']`)② 全局基础(box-sizing、body、button reset)③ 全局工具类(`.scrollable` 等,总数保持个位数)。 -- `*.module.css` 与组件同目录同名;一个组件一个 module 文件。 -- 类型声明用现有 `css-modules.d.ts` 通配;组件数超 20 再评估引入 tcm 生成精确 `.css.d.ts`。 -- PostCSS 特性白名单:当前**零插件**(平铺 CSS + 原生嵌套按需);引入 nested/custom-media 需先记入本文档。 +- `src/style/global.css` always uses this section order: ① token table (`:root` + `[data-theme='dark']`), ② global foundations (box-sizing, body, button reset), ③ global utility classes (`.scrollable`, etc.; keep the total in single digits). +- Place each `*.module.css` beside the component with the same name; use one module file per component. +- Use the existing `css-modules.d.ts` wildcard declaration. Reassess introducing tcm to generate exact `.css.d.ts` files only after the component count exceeds 20. +- PostCSS feature allowlist: currently **no plugins** (flat CSS plus native nesting when needed). Record nested/custom-media in this document before introducing either. -## 5. 演进规则与偏离记录 +## 5. Evolution rules and deviation log -- **加新 token**:先进 §1 表(含暗色占位列)再在组件使用;review 见到未入表的 `--` 新变量即打回(组件局部变量桥除外)。 -- **偏离基线**:与 §2 任一常数不一致的实现,须在下方偏离表记一行(日期/项/理由)。 -- **暗色表补全验收**:`[data-theme='dark']` 覆盖 §1 全部占位列后,用 RPC 面板 + 侧边栏 + 会话流三个界面人工/截图核对一遍,无组件级主题选择器即达标。 +- **Adding a token**: add it to the § 1 table first (including the dark-placeholder column), then use it in the component. Reject any new `--` variable that has not been added to the table (except for component-local variable bridges). +- **Deviating from the baseline**: if an implementation differs from any constant in § 2, add one row to the deviation table below (date / item / rationale). +- **Dark-table completion acceptance**: after `[data-theme='dark']` overrides every placeholder column in § 1, compare the RPC panel, sidebar, and conversation stream manually or with screenshots. Acceptance requires all three to match and no component-level theme selector to remain. -| 日期 | 偏离项 | 理由 | +| Date | Deviation | Rationale | | --- | --- | --- | -| (空) | | | +| (none) | | | -## 6. 相关文档 +## 6. Related documentation -- [web-styling-system RFC](../.agents/notes/implemented/process/2026-07-19-web-styling-system.md)(框架五条与工程约束的裁决记录) -- 客户端消费架构与分层协议:[Web 客户端架构 RFC](../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md)、[GUI 分层与 RPC 协议 RFC](../.agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md) +- [web-styling-system RFC](../.agents/notes/implemented/process/2026-07-19-web-styling-system.md) (decision record for the five framework rules and engineering constraints) +- Client consumption architecture and layered protocols: [Web client architecture RFC](../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md), [GUI layering and RPC protocol RFC](../.agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md) diff --git a/docs/web-styling.zh.md b/docs/web-styling.zh.md new file mode 100644 index 0000000000..d0838cd8a6 --- /dev/null +++ b/docs/web-styling.zh.md @@ -0,0 +1,109 @@ +# Web GUI 样式规范 + +[English](web-styling.md) | 中文 + +> **【token 体系已换代——§1 表格仅历史参考】** 本文的 `--bg-*`/`--text-*`/`--accent` token 族与其宿主包 `packages/client/web-ui` 已随插件化重构退役。现行 token 唯一来源=`packages/client/ui-theme/src/styles/` 的 `--dsw-*` 体系(static 色阶+alias 语义层,暗色=`body[data-ds-dark-theme]` 覆写),sheet 即权威、组件对账以它为准。**仍然有效**:工程约束(CSS Modules + clsx、无组件库、无 tailwind、组件禁 hardcode 色值)、字号成对写行高、间距 4 倍数、代码字体栈末位不放 monospace。 + +> 状态:原「活文档」(随 `packages/client/web-ui` 演进)。视觉基线源自对 deepseekchat 前端仓的实测调研。框架决策与工程约束由 [web-styling-system RFC](../.agents/notes/implemented/process/2026-07-19-web-styling-system.md) 拍板,本文不重复论证。 + +## 1. 设计 token 表(权威定义) + +所有 token 住 `packages/client/web-ui/src/style/global.css`:`:root` 亮色实值,`[data-theme='dark']` 块覆盖同名变量(未补全前列为占位)。组件 CSS 只引 token,不出现字面量色值。 + +### 1.1 颜色(两层:注释里是 base 色板出处,变量名即语义别名) + +| token | 亮色实值 | 暗色(占位) | 用途 | +| --- | --- | --- | --- | +| `--bg-base` | `#ffffff` | `#151517` | 页面底 | +| `--bg-layer` | `#ffffff` | `#232324` | 浮层/面板 | +| `--bg-sidebar` | `#f9fafb` | `#1b1b1c` | 侧边栏底 | +| `--text-primary` | `#0f1115` | `#f9fafb` | 正文 | +| `--text-secondary` | `#61666b` | `#cfd3d6` | 次要文字 | +| `--text-tertiary` | `#81858c` | `#adb2b8` | 辅助/说明 | +| `--border-l1` | `rgba(0,0,0,.04)` | `rgba(255,255,255,.06)` | 弱分隔(侧边栏右缘) | +| `--border-l2` | `rgba(0,0,0,.1)` | `rgba(255,255,255,.12)` | 常规边框 | +| `--hover-bg` | `rgba(38,49,72,.06)` | `rgba(255,255,255,.08)` | hover 态底 | +| `--active-bg` | `rgba(38,49,72,.1)` | `rgba(255,255,255,.14)` | 按压/激活态底 | +| `--accent` | `#3964fe` | `#5686fe` | 品牌蓝(deepseek-500;暗提亮一档) | +| `--accent-soft` | `#edf3fe` | `#28313f` | 淡品牌底(强调块) | +| `--accent-item` | `#e4edfd` | `#35363a` | 侧边栏选中条目底 | +| `--bubble-bg` | `#edf3fe` | `#2c2c2e` | 用户消息气泡底 | +| `--ok` / `--error` / `--warn` | `#22c55e` / `#ec1313` / `#f59e0b` | 同值 | 语义状态色 | +| `--text-on-solid` | `#ffffff` | 同值 | 实色底(accent/error 徽标等)上的文字 | +| `--ok-soft` / `--error-soft` | `#e6faed` / `#fee2e2` | `#233c2c` / `#570c0c` | 语义状态软底(徽章);green-100/red-100,暗为 900 档 | +| `--color-frame-mux` / `--color-frame-host` | `#8250df` / `#0969da` | 同值 | RPC 调试面板方向色(自有,非基线) | +| `--frame-mux-soft` / `--frame-host-soft` | `rgba(130,80,223,.1)` / `rgba(9,105,218,.1)` | 同色 `.24` | 方向色软底(徽章) | +| `--scroll-color` / `--scroll-color-hover` | `rgba(0,0,0,.08)` / `.15` | `rgba(255,255,255,.15)` / `.24` | 滚动条(`.scrollable` 专用) | + +### 1.2 非颜色 + +| token | 值 | 说明 | +| --- | --- | --- | +| `--font-ui` | `Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif` | 正文栈 | +| `--font-mono` | `Menlo, Monaco, Consolas, 'JetBrains Mono', 'Courier New', sans-serif` | 代码栈;**末位不放 monospace**(防 Windows 中文回退宋体) | +| `--fw-strong` | `600` | 粗体统一权重 | +| `--ease` | `cubic-bezier(.4,0,.2,1)` | 唯一缓动曲线 | +| `--dur` / `--dur-fast` / `--dur-slow` | `.2s` / `.1s` / `.3s` | 过渡三档 | +| `--radius-s` / `--radius-m` / `--radius-l` / `--radius-bubble` / `--radius-xl` | `8px` / `12px` / `16px` / `22px` / `24px` | 圆角语义档:小控件 / 列表条目与面板内块 / 浮层 / 气泡 / 输入卡片(基线 inputWrapper 同值);胶囊直接写 `999px` | +| `--shadow-panel` | `0 0 1px rgba(0,0,0,.2), 0 0 4px rgba(0,0,0,.02), 0 12px 32px rgba(0,0,0,.08)` | 浮层阴影(基线 lv3) | +| `--shadow-float` | `0 0 1px rgba(0,0,0,.24), 0 4px 12px rgba(0,0,0,.06), 0 16px 48px rgba(0,0,0,.16)` | 强浮动面板(lv3 加强档,如 RPC 调试浮层) | +| `--shadow-card` | `0 4px 10px rgba(0,0,0,.02), 0 2px 4px rgba(0,0,0,.04)`;暗色 `none` | 输入卡片微阴影(基线:亮色同底靠边框+微影区分,暗色靠提亮底、阴影关闭) | + +字号与间距**不 token 化**(基线仓同款决策):字号在组件里写 px 且**成对写行高**,常用对 16/24(气泡)、14/22(UI 默认)、12/18(辅助);间距用 4 的倍数。 + +## 2. 视觉基线(源自 deepseekchat) + +- 侧边栏:宽 `260px + 1px` 右边框(`--border-l1`);底色 `--bg-sidebar`。 +- 侧边栏条目:高 `40px`、圆角 `--radius-m`、字号 14px;hover 底 `--hover-bg` 或 sidebar 专属灰、**选中底 `--accent-item` 且不改文字色**。 +- 侧边栏分组标题:12px / weight 500 / `--text-tertiary` / sticky 顶部(底色同侧边栏遮滚动内容)。 +- 会话列:`max-width: 840px` 居中,<1024px 降 712px。 +- 消息流:**仅用户侧有气泡**——`--bubble-bg` 底、圆角 `--radius-bubble`、padding `10px 16px`、字号 16px/24px、`max-width: calc(100% - 88px)`;**助手侧纯文档流无底色**。 +- 消息操作条:默认 `opacity: 0`,父块 hover/focus-within 淡入(`--dur` + `--ease`)。 +- 输入卡片:与会话列同宽(840px,<1024px 降 712px)居中悬浮(距底留白带);圆角 `--radius-xl`、边框 `--border-l2`、底 `--bg-base`、阴影 `--shadow-card`;内部上下两段=textarea(16px/24px,min 2 行 max 14 行=336px,镜像 div 自增高)+ 操作行(右下嵌 34px 主圆钮);focus 无边框/阴影变化(基线同款)。 +- 输入主按钮(拍板 2026-07-20 三连,视觉参照 Codex App):32px 实心正圆图标钮(内联 SVG)——空闲=`--accent` 底白↑箭头「发送」,运行中原地变 `--accent-soft` 底 accent ■「停止」(同色系不告警、不用红)。**运行中锁输入**(拍板 3,取代早先 hover 菜单方案):textarea disabled(灰、草稿内容保留可见)、无任何排队/插话菜单,停止是唯一动作;turn 结束解禁并 refocus。键盘 Enter=发送、Ctrl/Meta+Enter=换行(运行中键盘路径随锁失效)。 +- 滚动条:近隐形、hover 加深、`scrollbar-gutter: stable` 不占布局(统一走 `.scrollable`,见 §3-9)。 +- RPC 四象限方向符(官方视觉词汇,空间隐喻:上=去 server、下=来自 server;单线=unary、双线=SSE): + +| 符号 | 象限 | 徽章配色 | +| --- | --- | --- | +| `↑` | client-request(unary 出站) | `--accent` / `--accent-soft` | +| `↓` | server-response(unary 回包) | ok `--ok`/`--ok-soft`,error `--error`/`--error-soft` | +| `⇟` | server-request(SSE 帧推送) | mux `--color-frame-mux`/`--frame-mux-soft`,host `--color-frame-host`/`--frame-host-soft` | +| `⇞` | client-response(SSE 侧回应) | `--accent`/`--accent-soft` 降透明度 | + +## 3. 样式编码规范(review 对照打勾) + +1. 颜色/圆角/动效/字体栈只引 §1 token;组件 CSS 出现字面量色值即打回(渐变遮罩等特效除外,须注释说明)。 +2. 组件 CSS 禁止出现 `[data-theme]` 选择器;暗色差异只在 global.css token 表做。确需按主题换非 token 值(渐变端点等),组件定义局部 CSS 变量、主题块只覆写变量(变量桥)。 +3. 类名 camelCase;状态类用单形容词(`.active` `.show`),由 clsx 挂载:`clsx(styles.x, cond && styles.active, className)`。 +4. 对外组件必须透传 `className` 并合入根元素。 +5. 禁用 `composes`;复用靠 token 与组件抽取。 +6. `:global` 仅用于穿透第三方/跨包类名;禁止用它定义新全局类。 +7. 交互过渡一律 `var(--dur*) var(--ease)`,只过渡 opacity / transform / 背景色 / 阴影;纯 hover 展示型元素包 `@media (hover: hover)`。 +8. hover/active 底色优先用透明度制 token(叠任意海拔底色都成立),不新造实色灰。 +9. 滚动容器统一挂 global.css 的 `.scrollable` 工具类;组件内禁写 `::-webkit-scrollbar`。 +10. 媒体查询写在组件 css 尾部、贴着被覆盖规则;断点当前仅 1024px 一档(会话列降档),加第二档需先记入本文档。 +11. 动态样式 JS 侧只写 CSS 变量(`style={{'--x': v}}`),规则留在 CSS;禁止在 TSX 里拼接样式对象做主题/状态分支。 +12. 文字灰阶只用 `--text-primary/secondary/tertiary` 三级,不新造灰色。 + +## 4. 文件组织 + +- `src/style/global.css` 固定分区顺序:① token 表(`:root` + `[data-theme='dark']`)② 全局基础(box-sizing、body、button reset)③ 全局工具类(`.scrollable` 等,总数保持个位数)。 +- `*.module.css` 与组件同目录同名;一个组件一个 module 文件。 +- 类型声明用现有 `css-modules.d.ts` 通配;组件数超 20 再评估引入 tcm 生成精确 `.css.d.ts`。 +- PostCSS 特性白名单:当前**零插件**(平铺 CSS + 原生嵌套按需);引入 nested/custom-media 需先记入本文档。 + +## 5. 演进规则与偏离记录 + +- **加新 token**:先进 §1 表(含暗色占位列)再在组件使用;review 见到未入表的 `--` 新变量即打回(组件局部变量桥除外)。 +- **偏离基线**:与 §2 任一常数不一致的实现,须在下方偏离表记一行(日期/项/理由)。 +- **暗色表补全验收**:`[data-theme='dark']` 覆盖 §1 全部占位列后,用 RPC 面板 + 侧边栏 + 会话流三个界面人工/截图核对一遍,无组件级主题选择器即达标。 + +| 日期 | 偏离项 | 理由 | +| --- | --- | --- | +| (空) | | | + +## 6. 相关文档 + +- [web-styling-system RFC](../.agents/notes/implemented/process/2026-07-19-web-styling-system.md)(框架五条与工程约束的裁决记录) +- 客户端消费架构与分层协议:[Web 客户端架构 RFC](../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md)、[GUI 分层与 RPC 协议 RFC](../.agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md) From f32d3f207f84cb3e915fb9b2bfd3d2a74aba047d Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:33:53 +0800 Subject: [PATCH 094/113] docs: require bilingual non-README documentation --- ...-bilingual-docs-and-pairing-gate.i18n.yaml | 4 +- ...6-07-02-bilingual-docs-and-pairing-gate.md | 6 +-- ...7-02-bilingual-docs-and-pairing-gate.zh.md | 6 +-- docs/i18n/README.i18n.yaml | 4 +- docs/i18n/README.md | 6 +-- docs/i18n/README.zh.md | 6 +-- docs/i18n/style-samples.md | 4 +- .../request-response.expected.json | 8 ++-- scripts/translation-pairing.manifest.json | 4 ++ scripts/translation-pairing.spec.ts | 38 +++++++++++++++++++ scripts/translation-pairing.ts | 33 ++++++++++++++++ scripts/verify-translation-pairing.ts | 35 +++++++---------- 12 files changed, 111 insertions(+), 43 deletions(-) diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml index 3bfc8414e7..c3430eb57d 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.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 -2026-07-02-bilingual-docs-and-pairing-gate.md: 4bc02878a0ea3f998e411ecc2b064c1626eacf3c -2026-07-02-bilingual-docs-and-pairing-gate.zh.md: 90a0c2f07f68b0fb4e26cd1c4b537a30a829b10f +2026-07-02-bilingual-docs-and-pairing-gate.md: 08e149ccc2342695d6dae4f1845896def6bf4388 +2026-07-02-bilingual-docs-and-pairing-gate.zh.md: 91f25f33c20337ea688257829552795085e0a8c0 diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md index 4bc02878a0..08e149ccc2 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md @@ -12,8 +12,8 @@ This repo's README and docs tree are read by people and agents inside and outsid - **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md). - **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR. -- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: required pairs exist, every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical), excluded (generated or bilingual-by-construction) files stay unpaired, and date-named documents on or after the manifest's `requiredSince` cutoff have complete pairs. The `required` list in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) is a ratchet: each merged translation batch adds its files, so coverage only grows. -- **The enforcement frontier advances in coherent review batches.** A related set enters `required` only when reviewers can evaluate it as a unit. The core frontier groups [architecture](../../../../docs/architecture.md), the [Cordis primer](../../../../docs/cordis-primer.md), [defensive patterns](../../../../docs/defensive-patterns.md), the [glossary](../../../../docs/glossary.md), and [testing](../../../../docs/testing.md) because their terminology, links, and contributor contracts inform one another; admitting only part would leave the enforced corpus internally inconsistent. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it. +- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot. +- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it. - **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration. - **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent. @@ -40,5 +40,5 @@ Paired sibling files with locale suffixes are the dominant Chinese big-tech conv - Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, "who confirmed these consistent, and when" is answerable from git blame on the yaml. - When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring. - Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list. -- Rollout is incremental by design: documents outside `required` are visible backlog (`--list`), not red CI, so pairs land in reviewable batches without a big-bang PR. A date-named document dated on or after the manifest's `requiredSince` cutoff merges bilingual or not at all, so new date-named Agent Notes do not enlarge that backlog. +- Rollout remains incremental until a document class is complete: explicit `required` entries and the date cutoff prevent regression during review batches, while a closed class makes every current and future member mandatory. The non-README class is closed, so only the README class can still appear as backlog. - The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism. diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md index 90a0c2f07f..91f25f33c2 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md @@ -12,8 +12,8 @@ Status: implemented - **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。 - **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。 -- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:required 的配对必须存在;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的文件(生成物或本身即双语的)不得配对;凡文件名以日期开头且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,也必须有完整配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `required` 清单只进不退:每个合并的翻译批次将自己的文件加入其中,覆盖面只增不减。 -- **执行红线按连贯的评审批次推进。** 一组相关文档只有在评审者能够将其作为整体评估时,才进入 `required`。核心红线将[架构](../../../../docs/architecture.md)、[Cordis 入门](../../../../docs/cordis-primer.md)、[防御性模式](../../../../docs/defensive-patterns.md)、[术语表](../../../../docs/glossary.md)和[测试](../../../../docs/testing.md)归为一组,因为它们的术语、链接和贡献者契约相互关联;只纳入其中一部分会使受门禁约束的文档集合内部不一致。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。 +- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。 +- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。 - **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。 - **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。 @@ -40,5 +40,5 @@ Status: implemented - 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。 - 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。 - 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。 -- 推进天然是渐进的:`required` 之外的文档是可见的 backlog(待翻清单,`--list`),而非红色的 CI;因此配对按可评审的批次落地,无需一个巨型 PR。凡文件名以日期开头且日期不早于 manifest 中 `requiredSince` 分界日期的文档,都必须配齐双语文件,因此新建的日期命名 Agent Note 不会增加这份 backlog。 +- 在文档类别全部完成之前,推进仍然是渐进的:显式 `required` 条目与日期分界可在评审批次期间防止回退,已纳入强制范围的类别则将其当前及今后的每个成员都列为必选项。非 README 类别已纳入强制范围,因此只有 README 类别仍可能出现 backlog(待翻清单)。 - 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。 diff --git a/docs/i18n/README.i18n.yaml b/docs/i18n/README.i18n.yaml index 602699a178..02f6151e29 100644 --- a/docs/i18n/README.i18n.yaml +++ b/docs/i18n/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 -README.md: 77d7b3210216c7c12d7d06b1ed16396d02ef1d16 -README.zh.md: de15fc3b5f30c1280ce6b38c1afd2475be7f9671 +README.md: a60572b0691702c949b44b82a7b1d732a888ed93 +README.zh.md: 04ae032233dfa01c145b5d6bdbe7353a366e11f1 diff --git a/docs/i18n/README.md b/docs/i18n/README.md index 77d7b32102..a60572b069 100644 --- a/docs/i18n/README.md +++ b/docs/i18n/README.md @@ -23,7 +23,7 @@ This repo's documentation is read by people and agents both inside and outside t `pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically: -1. Every file listed as `required` in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair. +1. Every file listed as `required`, and every document whose class appears in `requiredClasses`, in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair. The classes are `non-readme` and `readme`; class matching is case-insensitive on the basename, so `missions/readme.md` is a README. 2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher. 3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all. 4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth. @@ -41,11 +41,11 @@ The gate's limit, stated plainly: **a green gate means the pair was confirmed co **Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them): - `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list. -- `docs/AGENTS.md` and `.agents/notes/**/AGENTS.md` — agent instructions, maintained in English only like the root `AGENTS.md`. +- `docs/AGENTS.md`, `.agents/notes/**/AGENTS.md`, and their `CLAUDE.md` instruction symlinks — agent instructions, maintained in English only like the root `AGENTS.md`. - `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction. - [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior. -**Rollout**: a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after the manifest's `requiredSince` cutoff must merge with its pair. Earlier dates are backlog, including files created on the cutoff's eve. An Agent Note filename records its first-proposed date, so backdating past the cutoff is a review-visible violation. The manifest's `required` list is the current enforcement frontier, not the goal of full coverage. Translation batches add paths to `required`, ratcheting the gate forward. Unlisted documents remain visible in `--list`, while every existing pair is governed by the full contract. Because later edits must update both sides, expand `required` only as fast as translation review can support. +**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. `non-readme` is closed: every current or future in-scope non-README document must merge bilingual. README coverage remains an explicit-file rollout until `readme` joins the closed set. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract. ## Division of labor diff --git a/docs/i18n/README.zh.md b/docs/i18n/README.zh.md index de15fc3b5f..04ae032233 100644 --- a/docs/i18n/README.zh.md +++ b/docs/i18n/README.zh.md @@ -23,7 +23,7 @@ `pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约: -1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件都有完整配对。 +1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件,以及所属文档类别出现在 `requiredClasses` 中的每篇文档,都有完整配对。类别分为 `non-readme` 和 `readme`;判断类别时,basename 不区分大小写,因此 `missions/readme.md` 也属于 README。 2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。 3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。 4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。 @@ -41,11 +41,11 @@ **排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`): - `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。 -- `docs/AGENTS.md` 与 `.agents/notes/**/AGENTS.md`:agent 指令,与根 `AGENTS.md` 一样只以英文维护。 +- `docs/AGENTS.md`、`.agents/notes/**/AGENTS.md` 以及指向它们的 `CLAUDE.md` 指令符号链接:agent 指令,与根 `AGENTS.md` 一样只以英文维护。 - `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。 - [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。 -**推进**:以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note),只要标注日期等于或晚于 manifest 的 `requiredSince` 分界日期,合并时就必须配齐双语文件。更早日期的文件属于 backlog(待翻清单),包括分界前夜创建的文件。Agent Note 文件名记录首次提出日期,因此倒填日期绕过分界属于评审可见的违规。manifest 中的 `required` 列表是当前执行红线,并非全量覆盖这一最终目标。翻译批次将路径加入 `required`,使门禁只向前收紧。未列入的文档仍可通过 `--list` 查看,而任何已存在的配对都受完整契约约束。后续修改必须同步更新两侧,因此 `required` 的扩展速度不能超过翻译评审的承载能力。 +**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 已纳入强制范围:当前及今后所有纳入范围的非 README 文档,合并时都必须配齐双语文件。README 覆盖仍按显式文件逐步推进,直到 `readme` 加入这一强制范围。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。 ## 分工 diff --git a/docs/i18n/style-samples.md b/docs/i18n/style-samples.md index b20b2a4c90..c62ae259d0 100644 --- a/docs/i18n/style-samples.md +++ b/docs/i18n/style-samples.md @@ -70,9 +70,9 @@ ## ⑦ 推进策略(长段拆分示范) -> **Rollout**: date-named Agent Notes don't wait for a batch — one dated on or after the manifest's `requiredSince` cutoff must merge with its pair, so each new date-named Agent Note is bilingual from birth. For the back-catalog, the `required` list in the manifest is the enforcement frontier, not the goal. […] Pairing a document is a commitment: every later edit to either side must carry the counterpart along, so grow the frontier at the pace translation review is actually resourced, not ahead of it. +> **Enforcement frontier**: a document class enters the manifest's `requiredClasses` set only after its back-catalog has been translated and reviewed. The `non-readme` class is closed, so every current or future in-scope non-README document must merge bilingual; README coverage remains an explicit-file rollout until that class is ready to close. […] Pairing a document is a commitment: every later edit to either side must carry the counterpart along, so close a class only when translation review can sustain it. -**推进**:日期命名的 Agent Note 无需等待批量翻译。只要文件名中的日期不早于 manifest(元数据清单)的 `requiredSince` 分界日期,合入时就必须配齐中英文,因此此类 Agent Note 从创建起就要求双语齐备。对于存量文档,manifest 中的 `required` 列表只是当前的执行红线,并非最终目标。(……)一旦文档完成配对,后续修改任一侧都必须同步更新另一侧。因此,应根据实际可投入的翻译评审能力逐步扩展执行红线,不能超前。 +**执行红线**:只有在某个文档类别的存量文档全部完成翻译和评审后,该类别才会进入 manifest(元数据清单)的 `requiredClasses` 集合。`non-readme` 类别已纳入强制范围,因此当前及今后所有纳入范围的非 README 文档,合入时都必须配齐双语文件;README 覆盖仍按显式文件逐步推进,直到该类别具备整体纳入强制范围的条件。(……)一旦文档完成配对,后续修改任一侧都必须同步更新另一侧。因此,只有在翻译评审能力足以持续支撑时,才应将整个类别纳入强制范围。 ## 从样例提炼的要点 diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index fd9e0bec36..bc5355b931 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -24,11 +24,11 @@ }, { "role": "user", - "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p `), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required` in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md` and `.agents/notes/**/AGENTS.md` — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Rollout**: a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after the manifest's `requiredSince` cutoff must merge with its pair. Earlier dates are backlog, including files created on the cutoff's eve. An Agent Note filename records its first-proposed date, so backdating past the cutoff is a review-visible violation. The manifest's `required` list is the current enforcement frontier, not the goal of full coverage. Translation batches add paths to `required`, ratcheting the gate forward. Unlisted documents remain visible in `--list`, while every existing pair is governed by the full contract. Because later edits must update both sides, expand `required` only as fast as translation review can support.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" + "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p `), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required`, and every document whose class appears in `requiredClasses`, in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair. The classes are `non-readme` and `readme`; class matching is case-insensitive on the basename, so `missions/readme.md` is a README.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md`, `.agents/notes/**/AGENTS.md`, and their `CLAUDE.md` instruction symlinks — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. `non-readme` is closed: every current or future in-scope non-README document must merge bilingual. README coverage remains an explicit-file rollout until `readme` joins the closed set. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" }, { "role": "assistant", - "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p `),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件都有完整配对。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md` 与 `.agents/notes/**/AGENTS.md`:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**推进**:以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note),只要标注日期等于或晚于 manifest 的 `requiredSince` 分界日期,合并时就必须配齐双语文件。更早日期的文件属于 backlog(待翻清单),包括分界前夜创建的文件。Agent Note 文件名记录首次提出日期,因此倒填日期绕过分界属于评审可见的违规。manifest 中的 `required` 列表是当前执行红线,并非全量覆盖这一最终目标。翻译批次将路径加入 `required`,使门禁只向前收紧。未列入的文档仍可通过 `--list` 查看,而任何已存在的配对都受完整契约约束。后续修改必须同步更新两侧,因此 `required` 的扩展速度不能超过翻译评审的承载能力。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" + "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p `),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件,以及所属文档类别出现在 `requiredClasses` 中的每篇文档,都有完整配对。类别分为 `non-readme` 和 `readme`;判断类别时,basename 不区分大小写,因此 `missions/readme.md` 也属于 README。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md`、`.agents/notes/**/AGENTS.md` 以及指向它们的 `CLAUDE.md` 指令符号链接:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 已纳入强制范围:当前及今后所有纳入范围的非 README 文档,合并时都必须配齐双语文件。README 覆盖仍按显式文件逐步推进,直到 `readme` 加入这一强制范围。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" }, { "role": "user", @@ -40,11 +40,11 @@ }, { "role": "user", - "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: required pairs exist, every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical), excluded (generated or bilingual-by-construction) files stay unpaired, and date-named documents on or after the manifest's `requiredSince` cutoff have complete pairs. The `required` list in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) is a ratchet: each merged translation batch adds its files, so coverage only grows.\n- **The enforcement frontier advances in coherent review batches.** A related set enters `required` only when reviewers can evaluate it as a unit. The core frontier groups [architecture](../../../../docs/architecture.md), the [Cordis primer](../../../../docs/cordis-primer.md), [defensive patterns](../../../../docs/defensive-patterns.md), the [glossary](../../../../docs/glossary.md), and [testing](../../../../docs/testing.md) because their terminology, links, and contributor contracts inform one another; admitting only part would leave the enforced corpus internally inconsistent. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it.\n- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Verification\n\nThe verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Rollout is incremental by design: documents outside `required` are visible backlog (`--list`), not red CI, so pairs land in reviewable batches without a big-bang PR. A date-named document dated on or after the manifest's `requiredSince` cutoff merges bilingual or not at all, so new date-named Agent Notes do not enlarge that backlog.\n- The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" + "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot.\n- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it.\n- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Verification\n\nThe verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Rollout remains incremental until a document class is complete: explicit `required` entries and the date cutoff prevent regression during review batches, while a closed class makes every current and future member mandatory. The non-README class is closed, so only the README class can still appear as backlog.\n- The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" }, { "role": "assistant", - "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:required 的配对必须存在;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的文件(生成物或本身即双语的)不得配对;凡文件名以日期开头且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,也必须有完整配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `required` 清单只进不退:每个合并的翻译批次将自己的文件加入其中,覆盖面只增不减。\n- **执行红线按连贯的评审批次推进。** 一组相关文档只有在评审者能够将其作为整体评估时,才进入 `required`。核心红线将[架构](../../../../docs/architecture.md)、[Cordis 入门](../../../../docs/cordis-primer.md)、[防御性模式](../../../../docs/defensive-patterns.md)、[术语表](../../../../docs/glossary.md)和[测试](../../../../docs/testing.md)归为一组,因为它们的术语、链接和贡献者契约相互关联;只纳入其中一部分会使受门禁约束的文档集合内部不一致。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。\n- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 验证\n\n验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 推进天然是渐进的:`required` 之外的文档是可见的 backlog(待翻清单,`--list`),而非红色的 CI;因此配对按可评审的批次落地,无需一个巨型 PR。凡文件名以日期开头且日期不早于 manifest 中 `requiredSince` 分界日期的文档,都必须配齐双语文件,因此新建的日期命名 Agent Note 不会增加这份 backlog。\n- 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" + "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。\n- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。\n- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 验证\n\n验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 在文档类别全部完成之前,推进仍然是渐进的:显式 `required` 条目与日期分界可在评审批次期间防止回退,已纳入强制范围的类别则将其当前及今后的每个成员都列为必选项。非 README 类别已纳入强制范围,因此只有 README 类别仍可能出现 backlog(待翻清单)。\n- 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" }, { "role": "user", diff --git a/scripts/translation-pairing.manifest.json b/scripts/translation-pairing.manifest.json index 4e08844dc9..ebed3a6851 100644 --- a/scripts/translation-pairing.manifest.json +++ b/scripts/translation-pairing.manifest.json @@ -1,4 +1,7 @@ { + "requiredClasses": [ + "non-readme" + ], "requiredSince": "2026-07-14", "required": [ ".agents/notes/README.md", @@ -215,6 +218,7 @@ "excluded": [ ".agents/notes/AGENTS.md", ".agents/notes/implemented/AGENTS.md", + ".agents/notes/implemented/CLAUDE.md", "docs/AGENTS.md", "docs/agent-lifecycle.md", "docs/capability-seams.md", diff --git a/scripts/translation-pairing.spec.ts b/scripts/translation-pairing.spec.ts index 2bdc4f4e15..b8b880565a 100644 --- a/scripts/translation-pairing.spec.ts +++ b/scripts/translation-pairing.spec.ts @@ -7,6 +7,8 @@ import { parseTranslationMarkdown, parseTranslationPairingManifest, requiresPairByDate, + requiresTranslationPair, + translationDocumentClass, translationStructureDiff, translationStructureSignature, } from './translation-pairing.ts' @@ -20,10 +22,12 @@ describe('translation pairing manifest', () => { expect(parseTranslationPairingManifest(JSON.stringify({ requiredSince: '2026-07-14', required: ['README.md'], + requiredClasses: ['non-readme'], excluded: ['docs/generated/'], }))).toEqual({ requiredSince: '2026-07-14', required: ['README.md'], + requiredClasses: ['non-readme'], excluded: ['docs/generated/'], }) }) @@ -33,6 +37,7 @@ describe('translation pairing manifest', () => { expect(() => parseTranslationPairingManifest(JSON.stringify({ requiredSince: cutoff, required: [], + requiredClasses: [], excluded: [], }))).toThrow('requiredSince must be a valid YYYY-MM-DD date') }) @@ -41,9 +46,42 @@ describe('translation pairing manifest', () => { expect(() => parseTranslationPairingManifest(JSON.stringify({ requiredSince: '2026-07-14', required: [42], + requiredClasses: [], excluded: [], }))).toThrow('required must be an array of strings') }) + + it('rejects unknown and duplicate document classes', () => { + const manifest = (requiredClasses: string[]) => JSON.stringify({ + requiredSince: '2026-07-14', + required: [], + requiredClasses, + excluded: [], + }) + expect(() => parseTranslationPairingManifest(manifest(['guide']))).toThrow('requiredClasses must contain only') + expect(() => parseTranslationPairingManifest(manifest(['readme', 'readme']))).toThrow('requiredClasses must not contain duplicates') + }) +}) + +describe('document-class pairing frontier', () => { + const manifest = parseTranslationPairingManifest(JSON.stringify({ + requiredSince: '2026-07-14', + required: ['docs/legacy/README.md'], + requiredClasses: ['non-readme'], + excluded: [], + })) + + it('classifies README basenames case-insensitively', () => { + expect(translationDocumentClass('packages/core/README.md')).toBe('readme') + expect(translationDocumentClass('missions/readme.md')).toBe('readme') + expect(translationDocumentClass('docs/readme-guide.md')).toBe('non-readme') + }) + + it('requires every non-README while retaining explicit README entries', () => { + expect(requiresTranslationPair('docs/guide.md', manifest)).toBe(true) + expect(requiresTranslationPair('docs/legacy/README.md', manifest)).toBe(true) + expect(requiresTranslationPair('docs/new/README.md', manifest)).toBe(false) + }) }) describe('date-based pairing frontier', () => { diff --git a/scripts/translation-pairing.ts b/scripts/translation-pairing.ts index b7238fa3aa..92c38e8896 100644 --- a/scripts/translation-pairing.ts +++ b/scripts/translation-pairing.ts @@ -12,11 +12,18 @@ import type { Nodes } from 'mdast' /** Validated shape of `scripts/translation-pairing.manifest.json`. */ export interface TranslationPairingManifest { required: string[] + /** Document classes whose complete in-scope population must be paired. */ + requiredClasses: TranslationDocumentClass[] excluded: string[] /** Date-named documents on or after this day must merge bilingual. */ requiredSince: string } +/** Stable classes used to close one translation rollout without enumerating files. */ +export type TranslationDocumentClass = 'readme' | 'non-readme' + +const TRANSLATION_DOCUMENT_CLASSES: TranslationDocumentClass[] = ['readme', 'non-readme'] + const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/ const DATED_DOCUMENT = /(?:^|\/)(\d{4}-\d{2}-\d{2})-[^/]*\.md$/ @@ -40,6 +47,19 @@ function stringArrayField(record: Record, field: 'required' | ' return entries } +/** Read and validate the manifest's closed document-class set. */ +function requiredClassesField(record: Record): TranslationDocumentClass[] { + const value = record.requiredClasses + if (!Array.isArray(value) || !value.every((entry): entry is TranslationDocumentClass => + typeof entry === 'string' && TRANSLATION_DOCUMENT_CLASSES.includes(entry as TranslationDocumentClass))) { + throw new Error('translation-pairing.manifest.json: requiredClasses must contain only "readme" and "non-readme"') + } + if (new Set(value).size !== value.length) { + throw new Error('translation-pairing.manifest.json: requiredClasses must not contain duplicates') + } + return value +} + /** Parse and validate the checked-in bilingual manifest. */ export function parseTranslationPairingManifest(content: string): TranslationPairingManifest { const value: unknown = JSON.parse(content) @@ -53,11 +73,24 @@ export function parseTranslationPairingManifest(content: string): TranslationPai } return { required: stringArrayField(record, 'required'), + requiredClasses: requiredClassesField(record), excluded: stringArrayField(record, 'excluded'), requiredSince, } } +/** Classify a Markdown source by whether its basename is README, case-insensitively. */ +export function translationDocumentClass(file: string): TranslationDocumentClass { + return /(?:^|\/)readme\.md$/i.test(file) ? 'readme' : 'non-readme' +} + +/** Whether the manifest requires this in-scope source to have a complete pair. */ +export function requiresTranslationPair(file: string, manifest: TranslationPairingManifest): boolean { + return manifest.required.includes(file) + || manifest.requiredClasses.includes(translationDocumentClass(file)) + || requiresPairByDate(file, manifest.requiredSince) +} + /** Return the leading date of a `yyyy-mm-dd-*.md` basename, if present. */ export function datedDocumentDate(file: string): string | undefined { return DATED_DOCUMENT.exec(file)?.[1] diff --git a/scripts/verify-translation-pairing.ts b/scripts/verify-translation-pairing.ts index 860e193b4f..9372064707 100644 --- a/scripts/verify-translation-pairing.ts +++ b/scripts/verify-translation-pairing.ts @@ -1,9 +1,10 @@ /** * Enforce complete English/Chinese pairs, matching structure, and recorded git * blob hashes under the bilingual manifest. Required files and date-named docs - * at or after `requiredSince` must be paired; excluded docs may have neither a - * counterpart nor sidecar. `--list` reports state and `--write` records both - * sides after human review. Translation quality remains a review responsibility. + * at or after `requiredSince`, plus every source in a required document class, + * must be paired; excluded docs may have neither a counterpart nor sidecar. + * `--list` reports state and `--write` records both sides after human review. + * Translation quality remains a review responsibility. * See `docs/i18n/README.md` for the owning contract. */ @@ -11,11 +12,11 @@ import { createHash } from 'node:crypto' import { existsSync, globSync, readFileSync, writeFileSync } from 'node:fs' import { basename, join, resolve, sep } from 'node:path' import { - datedDocumentDate, linksTo, parseTranslationMarkdown, parseTranslationPairingManifest, - requiresPairByDate, + requiresTranslationPair, + translationDocumentClass, translationStructureDiff, translationStructureSignature, } from './translation-pairing.ts' @@ -118,29 +119,21 @@ if (writeMode) { const errors: string[] = [] const state = new Map() -// 1. Required pairs exist. +// 1. Explicit manifest entries name existing source documents. for (const req of manifest.required) { if (!existsSync(join(root, req))) { errors.push(`${req}: listed in translation-pairing.manifest.json \`required\` but the file does not exist`) - continue - } - const { zh } = pairPaths(req) - if (!existsSync(join(root, zh))) { - errors.push(`${req}: required to have a translation, but ${zh} does not exist`) - state.set(req, 'missing') } } -// 2. Date-named documents (Agent Notes) dated on/after the requiredSince cutoff merge -// bilingual: a new Agent Note lands with its pair or not at all. Deterministic from -// the filename alone — no git history, so it holds on shallow CI checkouts. +// 2. Every source selected explicitly, by document class, or by the dated-document +// cutoff merges bilingual. Class enforcement closes a rollout for future files too. for (const source of sources) { if (isExcluded(source)) continue - const date = datedDocumentDate(source) - if (!requiresPairByDate(source, manifest.requiredSince) || date === undefined) continue + if (!requiresTranslationPair(source, manifest)) continue const { zh } = pairPaths(source) if (!existsSync(join(root, zh))) { - errors.push(`${source}: dated ${date} — documents dated on/after ${manifest.requiredSince} merge bilingual (docs/i18n/README.md); add the counterpart and record the pair`) + errors.push(`${source}: required to merge bilingual as a ${translationDocumentClass(source)} document (docs/i18n/README.md); add the counterpart and record the pair`) state.set(source, 'missing') } } @@ -214,8 +207,8 @@ if (listMode) { const order = { 'out-of-sync': 0, missing: 1, ok: 2 } as const const rows = [...state.entries()].sort((a, b) => order[a[1]] - order[b[1]] || a[0].localeCompare(b[0])) for (const [file, status] of rows) { - const required = manifest.required.includes(file) - const tag = required ? ' (required)' : requiresPairByDate(file, manifest.requiredSince) ? ' (required by date)' : ' (backlog)' + const required = requiresTranslationPair(file, manifest) + const tag = required ? ` (required ${translationDocumentClass(file)})` : ' (backlog)' console.log(`${status.padEnd(11)} ${file}${status === 'missing' ? tag : ''}`) } const counts = { 'ok': 0, 'out-of-sync': 0, 'missing': 0 } @@ -225,7 +218,7 @@ if (listMode) { } if (errors.length === 0) { - console.log(`verify-translation-pairing: ${pairAnchors.size} pair(s) checked against ${manifest.required.length} required, all consistent.`) + console.log(`verify-translation-pairing: ${pairAnchors.size} pair(s) checked against ${manifest.required.length} explicit requirements and required classes [${manifest.requiredClasses.join(', ')}], all consistent.`) process.exit(0) } From 7953759aa2cda3062d6a2211e35948976ca80a22 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:33:58 +0800 Subject: [PATCH 095/113] docs: remove missions folder --- missions/readme.md | 36 ------------------------------------ 1 file changed, 36 deletions(-) delete mode 100644 missions/readme.md diff --git a/missions/readme.md b/missions/readme.md deleted file mode 100644 index 66167719ad..0000000000 --- a/missions/readme.md +++ /dev/null @@ -1,36 +0,0 @@ -# Workspace GUI 收尾备忘 - -## 产品改动 - -- 用户要求“去掉功能”时,先拆开视觉入口、可访问性语义和响应行为分别确认。本次 composer 加号保留原样和 `Add attachment` 标签,只在组合层停止传入 Workspace 回调;不要删除按钮、改样式或把它禁用。 -- 临时交互不应上浮到 React 呈现层。Session/Workspace Intent、首次消息保留和 materialize 重试归 runtime 对象与 service;组件只接收标准 action、hooks 和纯呈现状态。 -- RFC、测试名称和 PR 描述只写最终产品语义,不保留 `reconcilePublishedDraft`、`pendingCwd` 等已经撤销的中间方案。 - -## Snapshot 与测试定位 - -- `apps/web/tests/**/*.snapshot.ts` 验证 built application,需用 `DSH_EXAMPLE_MODE=lib`,并确认相关 `lib/` 已由当前源码构建;普通 source-mode Vitest 通过不能替代它。 -- 对 runtime 管理的受控输入执行 `fireEvent.change` 后,必须 `waitFor` 输入值回显再点击发送,否则发送可能读取旧的空 prompt。 -- 页面中 Workspace 与 Session 可以同名,禁止用无作用域的 `findByText` 定位。先用 `within` 锁定 Sessions tree、计数或对应 group,再找目标行。 -- 新 push 后先看 assembled snapshot 是否真正跑过;本地 focused snapshot 通过后仍以 `gh pr checks` 的 artifact job 为准。 - -## Coverage 收口 - -- 测试筛选和 coverage 筛选是两件事。用 owning tests 配合逐个 `--coverage.include=''`,先拿到真实未覆盖行和分支,不要直接反复跑全仓 coverage。 -- 多个 coverage 进程并发时必须给不同的 `--coverage.reportsDirectory`,否则报告目录互相覆盖。各 worker 完成后再跑一次合并后的精确 coverage,确认共享 worktree 的改动组合起来仍为 100%。 -- 全仓 coverage 若先被无关测试超时打断,不能把它当作目标文件的结论;先用精确 include 修本分支缺口,再让 CI exhaustive coverage 验证整体。 -- Coverage 测试仍要描述行为,不写“为了覆盖某分支”的注释。不可达分支才使用已有规范允许的 `v8 ignore`,可达分支补真实行为测试。 - -## 并发与提交 - -- Coverage 适合按不相交写区并发:例如 Sidebar tests、Workspace picker tests、connection/storage tests。派工时明确“只改 tests、不改 src、不 commit、不得回滚他人改动”。 -- 不直接信任各 worker 的单独结果;主会话审查 diff、运行合并后的 focused coverage、清理生成报告,再统一 commit。 -- 推送前按 `dsh-pre-push-checks` 选择最小充分验证,不重复已经通过的检查;正常 push 让 pre-push typecheck 运行,并核对本地 HEAD 与远端 ref 一致。 -- 生成的 `.coverage/` 只属于本地诊断。环境拒绝 `rm -rf` 时,依次使用 `find .coverage -type f -delete` 和 `find .coverage -depth -type d -empty -delete`;不要让报告进入 commit。 - -## GitHub 与 CI - -- GitHub 操作统一走 `gh`,并从 git 配置注入代理:`proxy="$(git config --get http.https://github.com.proxy)"; https_proxy="$proxy" http_proxy="$proxy" GH_PAGER=cat ~/.local/bin/gh ...`。不要改用网页。 -- 每次 push 都会产生一轮新 checks;旧轮次的失败不能代表当前 HEAD。先确认 run 对应当前提交,再拉失败日志。 -- `gh run watch` 只监视一个 workflow。最终必须用 `gh pr checks` 汇总 CI、e2e、sandbox 和 Windows 等独立 workflow;偶发平台失败先等当前 HEAD 重跑结果,不预先修改无关代码。 -- PR base 和 description 在最终 push 后再次用 `gh pr edit --base ... --body-file ...` 同步。PR 描述应包含最终产品动线、架构边界和实际运行过的验证,不写仍待执行的承诺。 -- Review thread 用 GraphQL/`gh api` 检查 `isResolved` 和已有回复,避免对已经解决的旧实现评论重复修复。 From 5fad2fc93445ae2875048b7009ab2deef6161f9d Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:45:56 +0800 Subject: [PATCH 096/113] docs: define extensible PR labels --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index eae3007c86..e68ef8086a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,7 +111,7 @@ Real-API tests and demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, - **A tool's UI render intent is part of its design**, decided up front (`generic`/`terminal`/`diff`, `locations`); presentation methods are pure functions of `args` ([cookbook](docs/cookbook/adding-a-tool.md)). - **Plan unit, e2e, and snapshot coverage** for new seams, lifecycle shapes, and transcript surfaces; missing snapshot-harness support is part of the implementation, not deferred follow-up. - **Keep PRs coherent and merge with merge commits.** Split an independently meaningful feature or design decision into a separate or stacked PR when combining it obscures ownership, intent, or verification. Never squash/rebase or rewrite pushed branches; put a review fix on its introducing PR, then merge down the stack ([guide](docs/cookbook/responding-to-pr-review-on-a-stack.md)). -- Pick matching existing GitHub labels such as `documentation`, `web`, `tui`, or `core`; never create new labels. +- **Label PRs:** exactly one kind (`feature`/`bug-fix`/`doc`/`testing`/`cleanup`), all matching areas; the taxonomy remains extensible for recurring distinctions. - TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)). - Files end with exactly one trailing newline; `git diff --cached --check` (pre-commit) gates it. From 23a60ade67215b2ad6da00e24921fba8dafda4b9 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:51:36 +0800 Subject: [PATCH 097/113] refactor(gui): features register their own settings surfaces MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings collaboration direction (recorded in the note): the shell only provides composition faces — feature plugins register themselves. The General section moves into the ui-settings shell (order 0, skeleton rows) and declares the settings.general.item list slot; locale registers the Language row and ui-theme the Appearance row (each with its own store mirror, dictionaries, and ledger-judged deferral); the ui-settings-general package is gone. ui-settings-models becomes ui-models — a feature package that contributes its Settings section rather than a settings-owned satellite. The item-slot SlotMap entry is authored in the ui-settings contract and repeated verbatim in locale/ui-theme (reference-cycle avoidance; declaration merging keeps the copies identical). --- ...2026-07-25-client-settings-locale-theme.md | 42 ++++-- ...6-07-25-client-settings-locale-theme.zh.md | 44 +++--- apps/cli/cordis.yml | 7 +- apps/cli/package.json | 3 +- apps/cli/tsconfig.json | 5 +- apps/web/tests/session-title.snapshot.ts | 3 +- apps/web/tests/workspace-flow.snapshot.ts | 3 +- packages/client/locale/package.json | 22 ++- .../locale/src/client/LanguageRow.module.css | 47 ++++++ .../client/locale/src/client/LanguageRow.tsx | 68 +++++++++ packages/client/locale/src/client/index.ts | 72 ++++++++- .../locale/src/client/settings-contract.ts | 18 +++ .../locale/src/client/settings-store.ts | 47 ++++++ .../src/css-modules.d.ts | 0 .../client/locale/tests/invariant.spec.ts | 6 +- packages/client/locale/tsconfig.json | 9 ++ .../README.md | 2 +- .../package.json | 4 +- .../src/client/ModelsSection.tsx | 0 .../src/client/index.ts | 4 +- .../src/css-modules.d.ts | 0 .../src/index.ts | 0 .../src/invariant.ts | 8 +- .../tests/apply.spec.ts | 4 +- .../tests/invariant.spec.ts | 4 +- .../tsconfig.json | 0 packages/client/ui-models/tsdown.config.ts | 3 + packages/client/ui-settings-general/README.md | 15 -- .../client/ui-settings-general/package.json | 70 --------- .../src/client/GeneralSection.tsx | 118 --------------- .../src/client/contract.ts | 66 -------- .../ui-settings-general/src/client/index.ts | 117 --------------- .../ui-settings-general/src/client/store.ts | 43 ------ .../client/ui-settings-general/src/index.ts | 4 - .../ui-settings-general/src/invariant.ts | 32 ---- .../ui-settings-general/tests/apply.spec.ts | 139 ----------------- .../tests/general-section.spec.tsx | 112 -------------- .../tests/invariant.spec.ts | 18 --- .../ui-settings-general/tests/store.spec.ts | 56 ------- .../client/ui-settings-general/tsconfig.json | 36 ----- .../ui-settings-general/tsdown.config.ts | 3 - .../ui-settings-models/tsdown.config.ts | 3 - .../src/client/GeneralSection.module.css | 38 ++--- .../ui-settings/src/client/GeneralSection.tsx | 51 +++++++ .../ui-settings/src/client/contract/slots.ts | 38 ++++- .../client/ui-settings/src/client/index.ts | 59 +++++++- .../src/client/locales.ts | 26 ++-- .../client/ui-settings/tests/apply.spec.ts | 81 +++++++++- .../tests/general-section.spec.tsx | 47 ++++++ packages/client/ui-theme/package.json | 25 +++- .../src/client/AppearanceRow.module.css | 51 +++++++ .../ui-theme/src/client/AppearanceRow.tsx | 63 ++++++++ packages/client/ui-theme/src/client/index.ts | 89 ++++++++++- .../ui-theme/src/client/settings-contract.ts | 17 +++ .../ui-theme/src/client/settings-store.ts | 37 +++++ packages/client/ui-theme/src/css-modules.d.ts | 6 + .../client/ui-theme/tests/invariant.spec.ts | 10 +- packages/client/ui-theme/tsconfig.json | 12 ++ pnpm-lock.yaml | 141 +++++++++--------- .../verify-package-readme-model-experience.ts | 3 +- tsconfig.base.json | 3 +- tsconfig.client.json | 3 +- 62 files changed, 1008 insertions(+), 1049 deletions(-) create mode 100644 packages/client/locale/src/client/LanguageRow.module.css create mode 100644 packages/client/locale/src/client/LanguageRow.tsx create mode 100644 packages/client/locale/src/client/settings-contract.ts create mode 100644 packages/client/locale/src/client/settings-store.ts rename packages/client/{ui-settings-general => locale}/src/css-modules.d.ts (100%) rename packages/client/{ui-settings-models => ui-models}/README.md (92%) rename packages/client/{ui-settings-models => ui-models}/package.json (89%) rename packages/client/{ui-settings-models => ui-models}/src/client/ModelsSection.tsx (100%) rename packages/client/{ui-settings-models => ui-models}/src/client/index.ts (96%) rename packages/client/{ui-settings-models => ui-models}/src/css-modules.d.ts (100%) rename packages/client/{ui-settings-models => ui-models}/src/index.ts (100%) rename packages/client/{ui-settings-models => ui-models}/src/invariant.ts (81%) rename packages/client/{ui-settings-models => ui-models}/tests/apply.spec.ts (96%) rename packages/client/{ui-settings-models => ui-models}/tests/invariant.spec.ts (82%) rename packages/client/{ui-settings-models => ui-models}/tsconfig.json (100%) create mode 100644 packages/client/ui-models/tsdown.config.ts delete mode 100644 packages/client/ui-settings-general/README.md delete mode 100644 packages/client/ui-settings-general/package.json delete mode 100644 packages/client/ui-settings-general/src/client/GeneralSection.tsx delete mode 100644 packages/client/ui-settings-general/src/client/contract.ts delete mode 100644 packages/client/ui-settings-general/src/client/index.ts delete mode 100644 packages/client/ui-settings-general/src/client/store.ts delete mode 100644 packages/client/ui-settings-general/src/index.ts delete mode 100644 packages/client/ui-settings-general/src/invariant.ts delete mode 100644 packages/client/ui-settings-general/tests/apply.spec.ts delete mode 100644 packages/client/ui-settings-general/tests/general-section.spec.tsx delete mode 100644 packages/client/ui-settings-general/tests/invariant.spec.ts delete mode 100644 packages/client/ui-settings-general/tests/store.spec.ts delete mode 100644 packages/client/ui-settings-general/tsconfig.json delete mode 100644 packages/client/ui-settings-general/tsdown.config.ts delete mode 100644 packages/client/ui-settings-models/tsdown.config.ts rename packages/client/{ui-settings-general => ui-settings}/src/client/GeneralSection.module.css (75%) create mode 100644 packages/client/ui-settings/src/client/GeneralSection.tsx rename packages/client/{ui-settings-general => ui-settings}/src/client/locales.ts (64%) create mode 100644 packages/client/ui-settings/tests/general-section.spec.tsx create mode 100644 packages/client/ui-theme/src/client/AppearanceRow.module.css create mode 100644 packages/client/ui-theme/src/client/AppearanceRow.tsx create mode 100644 packages/client/ui-theme/src/client/settings-contract.ts create mode 100644 packages/client/ui-theme/src/client/settings-store.ts create mode 100644 packages/client/ui-theme/src/css-modules.d.ts diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md index e1245a9e1f..0dfcb4ea90 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md @@ -10,41 +10,48 @@ The browser client's existing Settings is written directly inside the Sidebar, a ## Proposal -The Sidebar declares the `sidebar.settings` single slot; `ui-settings` occupies it and declares the `settings.section` list slot. Each section is contributed by an independent plugin; the Settings shell only reads entry metadata from the slot ledger to build the navigation, rendering the current section via `only`. +**Collaboration doctrine (how every later module joins Settings): feature owners self-register.** The Settings shell provides only the composition surface (the top-level section list plus the item list inside General) and neither imports nor enumerates any feature; for a feature to appear in Settings, its own plugin registers into the corresponding slot — locale registers the Language row, ui-theme registers the Appearance row, ui-models registers the Models top-level panel. No separate `ui-settings-*` package is created for "a feature's settings page": the settings surface belongs to the feature package itself (shipping the Theme feature means Theme's settings choices ship with ui-theme). The only content the shell carries itself is the first top-level directory, General (skeleton rows plus the item slot declaration), because it belongs to no single feature. + +The Sidebar declares the `sidebar.settings` single slot; `ui-settings` occupies it and declares the `settings.section` list slot. Each section is contributed by a feature plugin; the Settings shell only reads entry metadata from the slot ledger to build the navigation, rendering the current section via `only`. General is registered by the shell itself (order 0) and declares the `settings.general.item` list slot, into which the feature plugins' preference rows slot by order. The Settings entry is the Settings row in the sidebar Foot; clicking it directly opens a 1080×700 centered overlay (black 24% mask); the close button, a mask click, and ESC all close it. There is no intermediate menu form of any kind. `@deepseek-ai/dsh-client-locale` provides `ctx.locale`; `ui-theme` provides `ctx.theme`. Both services read through a getter, write through a setter, and publish immutable snapshots via typed Cordis change events; each service persists its own preference (storing only the id, with bad values falling back to the default). -General's apply layer subscribes to `locale/change` and `theme/change` and projects the snapshots into the Zustand store declared by that section. React components only read `useStore` and write through the injected setter callbacks, never reading ctx or the services. +Each feature row's apply layer subscribes to its own change event (locale to `locale/change`, ui-theme to `theme/change`) and projects the snapshot into the slot store declared when that row registered. React components only read `useStore` and write through the injected setter callbacks, never reading ctx or the services. The theme preference has three states — `light`, `dark`, `system` — defaulting to `system` (when no persisted preference exists or the value is bad). Resolving system belongs to the theme domain: ThemeService holds the `prefers-color-scheme` matchMedia listener (environment sensing, not DOM presentation) and re-emits the snapshot when the preference is system and the system color scheme changes; the snapshot carries both `preference` and the resolved `active` definition. The theme service never touches the DOM. `ui-layout` reads the Theme getter initially and then subscribes to `theme/change`; the presenter owned by Layout updates `body[data-ds-dark-theme]` and the theme tokens according to `active`. The presenter has no notion of system — it consumes only resolved results. -### First-phase section scope +### First-phase registration surfaces -| section | Plugin | First-phase content | +| Registration surface | Owning plugin | First-phase content | |---|---|---| -| General | `ui-settings-general` | Language (Selector dropdown) and Appearance (Light/Dark/System three cubes) genuinely switch; Permission and Tool Call are visual skeletons only, with no write operations | -| Models | `ui-settings-models` | Navigation item only; the content area is empty | -| Plugin | no package | Not built this phase, and the navigation does not show the item (an external-link entry with no target never renders; once a later plugin registers the section it appears automatically) | +| General section (order 0) | built into the `ui-settings` shell | Permission and Tool Call visual skeletons (no write operations) plus the `settings.general.item` slot declaration | +| Language row (item order 0) | `locale` | Selector dropdown; 中文/English genuinely switch | +| Appearance row (item order 10) | `ui-theme` | Light/Dark/System three cubes genuinely switch (the selected state reflects preference) | +| Models section (order 10) | `ui-models` | Navigation item only, with an empty content area; later model-management features land in that package | +| Plugin | none | Not built this phase, and the navigation does not show the item (once a later plugin feature package registers the section it appears automatically) | -The first phase localizes only the copy inside the Settings overlay (the General rows plus the navigation); copy on other pages is untouched. +The first phase localizes only the copy inside the Settings overlay; dictionaries stay close to their owners — shell copy (the chrome plus the General skeletons) lives in the `settings` namespace, and feature-row copy lives in each feature package (`settings.locale`, `settings.theme`, `settings.models`). ### Slot topology ```text root └─ sidebar - └─ sidebar.settings single/root - └─ ui-settings - └─ settings.section list/root - ├─ general ui-settings-general - └─ models ui-settings-models + └─ sidebar.settings single/root + └─ ui-settings(壳) + └─ settings.section list/root + ├─ general (order 0) ui-settings 壳自带 + │ └─ settings.general.item list/root + │ ├─ language (0) locale 注册 + │ └─ appearance (10) ui-theme 注册 + └─ models (order 10) ui-models 注册 ``` -Section contributions use declaration-aware deferral and do not depend on the client manifest's apply order. +Section and item contributions both use declaration-aware deferral and do not depend on the client manifest's apply order. The `settings.general.item` SlotMap entry's canonical home is the ui-settings contract; locale/ui-theme, because of the reference cycle (the shell consumes ctx.locale), consume that entry as verbatim duplicated merges, with declaration merging guaranteeing the copies agree. ### Service contracts @@ -95,13 +102,16 @@ Locale ships with 中文 and English built in; `setLocale`/`setTheme` are the on **Settings importing and enumerating the sections.** Adding a page would require modifying the shell plugin, breaking the composition model where each feature occupies a slot from its own plugin. +**One `ui-settings-*` package per section (the first-cut implementation).** It divorces the settings surface from the feature itself: changing Theme behavior touches two packages, the package count grows linearly with settings items, and settings-general depending back on the locale/theme services forms an intermediate layer that exists purely for the package split. After converging on feature-owner self-registration, General belongs to the shell (it belongs to no single feature) and preference rows ship with their feature packages. + **Injecting the Locale/Theme snapshots into React directly.** Inject results are cached by entry identity, so volatile values go stale; hand-rolling a React hook per service also bypasses the slot store's unified binding. ## Acceptance criteria -- The Settings shell depends only on the slot ledger, never on any section implementation. +- The Settings shell depends only on the slot ledger, never on any feature implementation; General's item list likewise depends only on the ledger. +- Adding a settings item = the feature package registering it itself (a section or a general item), with zero shell changes. - Locale and Theme writes go only through the setters; ongoing synchronization goes only through the change events. -- The General store initializes from the getters and is thereafter updated by the two events with local re-renders. +- Each feature row's store initializes from the getter and is thereafter updated by its own change event with local re-renders. - Layout applies the theme snapshot on its own and the theme service never accesses the DOM; no system branch appears in the presenter. - 中文/English and Light/Dark/System switch and are restored after a refresh; with the preference on system, a system color-scheme change takes effect immediately. - Models has only a navigation item and an empty content area; the Permission and Tool Call skeletons perform no writes. diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md index 195b2e5ffa..dfe93a0ca1 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.zh.md @@ -10,41 +10,48 @@ Status: proposed ## Proposal -Sidebar 声明 `sidebar.settings` 单坑位,`ui-settings` 占用它并声明 `settings.section` list 坑位。每个 section 由独立插件贡献;Settings 壳只从 slot ledger 读取 entry metadata 生成导航,通过 `only` 渲染当前 section。 +**协作导向(后续所有模块接入 Settings 的方式):功能属主自注册。** Settings 壳只提供组合面(一级 section 列表 + General 内的 item 列表),不 import 也不枚举任何功能;一个功能要出现在 Settings 里,由它自己的插件向对应坑位注册——locale 注册 Language 行,ui-theme 注册 Appearance 行,ui-models 注册 Models 一级面板。不为「某功能的设置页」单开 `ui-settings-*` 包:设置面属于功能包本身(做 Theme 功能,Theme 的设置选择就随 ui-theme 一起交付)。壳自带的唯一内容是第一个一级目录 General(骨架行 + item 坑位声明),因为它不属于任何单一功能。 + +Sidebar 声明 `sidebar.settings` 单坑位,`ui-settings` 占用它并声明 `settings.section` list 坑位。每个 section 由功能插件贡献;Settings 壳只从 slot ledger 读取 entry metadata 生成导航,通过 `only` 渲染当前 section。General 由壳自己注册(order 0)并声明 `settings.general.item` list 坑位,功能插件的偏好行按 order 排入。 Settings 入口是 sidebar Foot 的 Settings 行,点击直接打开 1080×700 居中浮层(黑 24% 遮罩);close 按钮、点击遮罩、ESC 均关闭。无任何中间菜单形态。 `@deepseek-ai/dsh-client-locale` 提供 `ctx.locale`,`ui-theme` 提供 `ctx.theme`。两个 service 都以 getter 读取、setter 写入并用 typed Cordis change event 发布 immutable snapshot;service 自己持久化偏好(只存 id,坏值回退默认)。 -General 的 apply 层订阅 `locale/change` 和 `theme/change`,把 snapshot 投影到该 section 声明的 Zustand store。React 组件只读 `useStore`、写注入的 setter callback,不读取 ctx 或 service。 +功能行的 apply 层各自订阅自家 change event(locale 订 `locale/change`,ui-theme 订 `theme/change`),把 snapshot 投影到该行注册时声明的 slot store。React 组件只读 `useStore`、写注入的 setter callback,不读取 ctx 或 service。 Theme 偏好三态:`light`、`dark`、`system`,默认 `system`(无持久化偏好或坏值时)。system 的解析属主题领域:ThemeService 持有 `prefers-color-scheme` matchMedia 监听(环境感知,非 DOM 呈现),偏好为 system 且系统配色变化时重发 snapshot;snapshot 同时携带 `preference` 与解析后的 `active` 定义。 Theme service 不操作 DOM。`ui-layout` 初始读取 Theme getter,随后订阅 `theme/change`,由 Layout 持有的 presenter 按 `active` 更新 `body[data-ds-dark-theme]` 和主题 token;presenter 不感知 system,只消费已解析结果。 -### 首期 section 范围 +### 首期注册面 -| section | 插件 | 首期内容 | +| 注册面 | 属主插件 | 首期内容 | |---|---|---| -| General | `ui-settings-general` | Language(Selector 下拉)与 Appearance(Light/Dark/System 三 cube)真实可切;Permission、Tool Call 仅视觉骨架,无写操作 | -| Models | `ui-settings-models` | 仅导航项,内容区为空 | -| Plugin | 不建包 | 首期不做,导航不出现该项(无目标的外链入口不上屏;后续插件注册 section 即自动出现) | +| General section(order 0)| `ui-settings` 壳自带 | Permission、Tool Call 视觉骨架(无写操作)+ `settings.general.item` 坑位声明 | +| Language 行(item order 0)| `locale` | Selector 下拉,中文/English 真实可切 | +| Appearance 行(item order 10)| `ui-theme` | Light/Dark/System 三 cube 真实可切(选中态看 preference) | +| Models section(order 10)| `ui-models` | 仅导航项,内容区为空;后续模型管理功能落在该包 | +| Plugin | 无 | 首期不做,导航不出现该项(后续插件功能包注册 section 即自动出现) | -首期只翻译 Settings 浮层内文案(General 各行 + 导航);其他页面文案不动。 +首期只翻译 Settings 浮层内文案;字典就近——壳文案(chrome + General 骨架)归 `settings` namespace,功能行文案归各功能包(`settings.locale`、`settings.theme`、`settings.models`)。 ### Slot topology ```text root └─ sidebar - └─ sidebar.settings single/root - └─ ui-settings - └─ settings.section list/root - ├─ general ui-settings-general - └─ models ui-settings-models + └─ sidebar.settings single/root + └─ ui-settings(壳) + └─ settings.section list/root + ├─ general (order 0) ui-settings 壳自带 + │ └─ settings.general.item list/root + │ ├─ language (0) locale 注册 + │ └─ appearance (10) ui-theme 注册 + └─ models (order 10) ui-models 注册 ``` -section contribution 使用 declaration-aware deferral,不依赖 client manifest 的 apply 顺序。 +section/item contribution 均使用 declaration-aware deferral,不依赖 client manifest 的 apply 顺序。`settings.general.item` 的 SlotMap 条目正家在 ui-settings contract;locale/ui-theme 因引用环(壳消费 ctx.locale)以逐字重复合并的方式消费该条目,declaration merging 保证副本一致。 ### Service contracts @@ -95,13 +102,16 @@ Locale 内置中文和 English;`setLocale`/`setTheme` 是唯一写入口,未 **Settings import 并枚举各 section。** 新增页面必须修改壳插件,破坏「每个功能由自己的插件占坑」的组合模型。 +**每个 section 单开 `ui-settings-*` 包(首版实现)。** 设置面与功能本体分家:改 Theme 行为要动两个包,包数随设置项线性膨胀,且 settings-general 反向依赖 locale/theme 服务形成纯粹为拆包而生的中间层。收敛为功能属主自注册后,General 归壳(不属任何单一功能),preference 行随功能包交付。 + **把 Locale/Theme snapshot 直接注入 React。** inject 结果按 entry identity 缓存,易变值会陈旧;为每个 service 自造 React hook 也绕开 slot store 的统一绑定。 ## Acceptance criteria -- Settings 壳只依赖 slot ledger,不依赖任一 section 实现。 +- Settings 壳只依赖 slot ledger,不依赖任一功能实现;General 的 item 列表同样只依赖 ledger。 +- 新增一个设置项 = 功能包自己注册(section 或 general item),零壳改动。 - Locale 与 Theme 的写入只走 setter,持续同步只走 change event。 -- General store 初始化走 getter,后续由两个 event 更新并局部重渲染。 +- 功能行 store 初始化走 getter,后续由自家 change event 更新并局部重渲染。 - Layout 独立应用 Theme snapshot,Theme service 不访问 DOM;presenter 不出现 system 分支。 - 中文/English 与 Light/Dark/System 能切换并刷新后恢复;偏好为 system 时系统配色变化即时生效。 - Models 只有导航项与空内容区;Permission、Tool Call 骨架无写操作。 @@ -109,4 +119,4 @@ Locale 内置中文和 English;`setLocale`/`setTheme` 是唯一写入口,未 ## Risks -slot 声明与 contribution 的 apply 顺序不固定,所有新 section 必须保留 declaration-aware registration 和幂等防护。service event 可能早于 section 首次渲染,General store 的 init 与 controller attach 都必须从 getter 对齐当前 snapshot。Layout 卸载时必须清理自己设置的全局属性,ThemeService dispose 时必须移除 matchMedia 监听,避免 HMR 后残留。 +slot 声明与 contribution 的 apply 顺序不固定,所有 section/item 注册方必须保留 declaration-aware registration,并以 ledger(而非本地 disposer)判定在位。service event 可能早于行首次渲染,功能行 store 的 init 与 inject attach 都必须从 getter 对齐当前 snapshot。`settings.general.item` 的重复合并副本(locale、ui-theme)与 ui-settings 正家必须逐字一致,漂移即三处一起改。Layout 卸载时必须清理自己设置的全局属性,ThemeService dispose 时必须移除 matchMedia 监听,避免 HMR 后残留。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 8412a313b4..39803aa603 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -233,11 +233,8 @@ - id: ui-settings name: '@deepseek-ai/dsh-client-ui-settings' -- id: ui-settings-general - name: '@deepseek-ai/dsh-client-ui-settings-general' - -- id: ui-settings-models - name: '@deepseek-ai/dsh-client-ui-settings-models' +- id: ui-models + name: '@deepseek-ai/dsh-client-ui-models' - id: ui-conversation name: '@deepseek-ai/dsh-client-ui-conversation' diff --git a/apps/cli/package.json b/apps/cli/package.json index 74a6e417e1..ddf8a08a87 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -31,8 +31,7 @@ "@deepseek-ai/dsh-client-ui-question": "workspace:^", "@deepseek-ai/dsh-client-ui-sidebar": "workspace:^", "@deepseek-ai/dsh-client-ui-settings": "workspace:^", - "@deepseek-ai/dsh-client-ui-settings-general": "workspace:^", - "@deepseek-ai/dsh-client-ui-settings-models": "workspace:^", + "@deepseek-ai/dsh-client-ui-models": "workspace:^", "@deepseek-ai/dsh-client-ui-theme": "workspace:^", "@deepseek-ai/dsh-client-ui-trajectory": "workspace:^", "@deepseek-ai/dsh-client-ui-workspace": "workspace:^", diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json index 7614ae2e31..3000fd1f8d 100644 --- a/apps/cli/tsconfig.json +++ b/apps/cli/tsconfig.json @@ -45,10 +45,7 @@ "path": "../../packages/client/ui-settings" }, { - "path": "../../packages/client/ui-settings-general" - }, - { - "path": "../../packages/client/ui-settings-models" + "path": "../../packages/client/ui-models" }, { "path": "../../packages/client/locale" diff --git a/apps/web/tests/session-title.snapshot.ts b/apps/web/tests/session-title.snapshot.ts index b8ee3408a3..35356fa0b3 100644 --- a/apps/web/tests/session-title.snapshot.ts +++ b/apps/web/tests/session-title.snapshot.ts @@ -14,8 +14,7 @@ const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [ { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] }, { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, { id: '@deepseek-ai/dsh-client-ui-settings', dir: 'ui-settings', url: '/plugins/ui-settings.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-sidebar', '@deepseek-ai/dsh-client-locale'] }, - { id: '@deepseek-ai/dsh-client-ui-settings-general', dir: 'ui-settings-general', url: '/plugins/ui-settings-general.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, - { id: '@deepseek-ai/dsh-client-ui-settings-models', dir: 'ui-settings-models', url: '/plugins/ui-settings-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, + { id: '@deepseek-ai/dsh-client-ui-models', dir: 'ui-models', url: '/plugins/ui-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, { id: '@deepseek-ai/dsh-client-ui-workspace', dir: 'ui-workspace', url: '/plugins/ui-workspace.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime', '@deepseek-ai/dsh-client-ui-conversation', '@deepseek-ai/dsh-client-ui-sidebar'] }, { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] }, diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index e232d8e123..738357a551 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -14,8 +14,7 @@ const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [ { id: '@deepseek-ai/dsh-client-ui-layout', dir: 'ui-layout', url: '/plugins/ui-layout.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-runtime'] }, { id: '@deepseek-ai/dsh-client-ui-sidebar', dir: 'ui-sidebar', url: '/plugins/ui-sidebar.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, { id: '@deepseek-ai/dsh-client-ui-settings', dir: 'ui-settings', url: '/plugins/ui-settings.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-sidebar', '@deepseek-ai/dsh-client-locale'] }, - { id: '@deepseek-ai/dsh-client-ui-settings-general', dir: 'ui-settings-general', url: '/plugins/ui-settings-general.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, - { id: '@deepseek-ai/dsh-client-ui-settings-models', dir: 'ui-settings-models', url: '/plugins/ui-settings-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, + { id: '@deepseek-ai/dsh-client-ui-models', dir: 'ui-models', url: '/plugins/ui-models.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-settings'] }, { id: '@deepseek-ai/dsh-client-ui-conversation', dir: 'ui-conversation', url: '/plugins/ui-conversation.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-layout'] }, { id: '@deepseek-ai/dsh-client-ui-workspace', diff --git a/packages/client/locale/package.json b/packages/client/locale/package.json index 340efe042e..d53d2e4269 100644 --- a/packages/client/locale/package.json +++ b/packages/client/locale/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-locale", - "description": "Locale plugin: LocaleService (zh/en preference with getter/setter/change event + persistence; ns x locale dictionaries, bind(ns) -> t)", + "description": "Locale plugin: LocaleService (zh/en preference with getter/setter/change event + persistence; ns x locale dictionaries, bind(ns) -> t); registers the Language settings row", "version": "0.0.1", "private": true, "type": "module", @@ -23,18 +23,29 @@ "./package.json": "./package.json" }, "dshClient": { - "inject": [], + "inject": [ + "@deepseek-ai/dsh-client-runtime" + ], "platform": "web", "immediately": true }, "license": "BSD-3-Clause", "peerDependencies": { + "@deepseek-ai/dsh-client-runtime": "^0.0.1", + "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", + "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", - "cordis": "^4.0.0-rc.7" + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" }, "devDependencies": { + "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", + "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", - "cordis": "^4.0.0-rc.7" + "@types/react": "~18.3.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" }, "files": [ "lib/index.js", @@ -47,5 +58,8 @@ "scripts": { "bundle": "tsdown", "watch": "tsdown --watch" + }, + "dependencies": { + "clsx": "^2.0.0" } } diff --git a/packages/client/locale/src/client/LanguageRow.module.css b/packages/client/locale/src/client/LanguageRow.module.css new file mode 100644 index 0000000000..f17a67d279 --- /dev/null +++ b/packages/client/locale/src/client/LanguageRow.module.css @@ -0,0 +1,47 @@ +/* Language row (figma 'Setting-Cell': gap 8, pad 16/0, hairline separator; + * the section column removes the separator on its last child). */ + +.row { + display: flex; + align-items: center; + gap: 8px; + padding: 16px 0; + border-bottom: 1px solid var(--dsw-alias-border-l2); +} + +.rowText { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; + padding-right: 48px; +} + +.title { + font-size: 14px; + font-weight: 400; + line-height: 22px; + color: var(--dsw-alias-label-primary); +} + +/* Selector pill (figma 'Selector': h36 r18, fill #F5F6F7, pad 0/14, gap 12). */ +.selector { + display: inline-flex; + align-items: center; + gap: 12px; + height: 36px; + padding: 0 14px; + border: none; + border-radius: 18px; + background: var(--dsw-alias-bg-module-platform); + font: inherit; + font-size: 14px; + line-height: 22px; + color: var(--dsw-alias-label-primary); + cursor: pointer; +} + +.chevron { + flex: none; +} diff --git a/packages/client/locale/src/client/LanguageRow.tsx b/packages/client/locale/src/client/LanguageRow.tsx new file mode 100644 index 0000000000..a824bc6752 --- /dev/null +++ b/packages/client/locale/src/client/LanguageRow.tsx @@ -0,0 +1,68 @@ +/** + * Language preference row registered into the General section item slot + * (figma 501:30011 'Setting-Cell'): title + selector pill opening the locale + * menu. Registered by this package — the locale feature owns its own + * settings surface. + */ +import { useState } from 'react' +import type { PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import { IconChevronDownOutline14, Menu } from '@deepseek-ai/dsh-client-ui-primitives' +import type {} from './settings-contract.ts' +import type { createLanguageRowStore } from './settings-store.ts' +import css from './LanguageRow.module.css' + +/** Injected business face: namespace-bound translate + the preference write. */ +export interface LanguageRowInjected { + /** Translate a `settings.locale` dictionary key to the active-locale text. */ + t: (key: string) => string + /** Switch the active locale (a registered locale id). */ + setLocale: (id: string) => void +} + +/** Full component props: runtime share + store share + injected face. */ +export type LanguageRowComponentProps = + PropsRuntime<'settings.general.item'> & PropsStore> & LanguageRowInjected + +/** + * Render the Language row. + * @param props - composed slot props. + * @returns the row element tree. + */ +export function LanguageRow({ t, setLocale, useStore }: LanguageRowComponentProps) { + const active = useStore(s => s.active) + const options = useStore(s => s.options) + const [open, setOpen] = useState(false) + const activeLabel = options.find(o => o.id === active)?.label ?? active + + return ( +
+
+
{t('language.title')}
+
+ { setOpen(false) }} + items={options.map(o => ({ id: o.id, label: o.label }))} + selectedId={active} + onSelect={(id) => { + setLocale(id) + setOpen(false) + }} + align="end" + portal + anchor={( + + )} + /> +
+ ) +} diff --git a/packages/client/locale/src/client/index.ts b/packages/client/locale/src/client/index.ts index 35f29a0e52..444594f9b8 100644 --- a/packages/client/locale/src/client/index.ts +++ b/packages/client/locale/src/client/index.ts @@ -1,10 +1,20 @@ /** * Browser-side locale registry. Bound translation functions retain stable - * identity for injected consumers. + * identity for injected consumers. The plugin also registers the Language + * preference row into the settings General section — the locale feature owns + * its own settings surface. */ import type { Context } from 'cordis' +import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots' +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import { en } from '../locales/en.ts' import { zh } from '../locales/zh.ts' +import type { LanguageRowInjected } from './LanguageRow.tsx' +import { LanguageRow } from './LanguageRow.tsx' +import { createLanguageRowStore } from './settings-store.ts' + +export type { LanguageRowComponentProps, LanguageRowInjected } from './LanguageRow.tsx' +export type { LanguageOptionRow, LanguageRowState } from './settings-store.ts' /** Translate a key with optional params. */ export type Translate = (key: string, params?: Record) => string @@ -53,6 +63,9 @@ export const FALLBACK_LOCALE: LocaleId = 'zh' /** Shared namespace for shell-level texts. */ export const COMMON_NS = 'common' +/** Namespace owning this feature's settings-row copy. */ +export const SETTINGS_NS = 'settings.locale' + /** localStorage key holding the persisted locale id. */ export const STORAGE_KEY = 'dsh.locale' @@ -183,16 +196,65 @@ function persistPreference(id: LocaleId): void { } } -/** Required services (none; the loader passes the export surface as an object plugin). */ -export const inject: string[] = [] +/** Required services: the slot registry (the feature registers its own settings row). */ +export const inject = ['slots'] /** - * Client plugin body: provide the locale service with base dictionaries. + * Client plugin body: provide the locale service with base dictionaries and + * register the feature-owned Language preference row into the General + * section's item slot (a feature owns its settings surface). * @param ctx - client cordis context. */ -export function apply(ctx: Context): void { +export function apply(ctx: ClientContext): void { const locale = new LocaleService(ctx) locale.register(COMMON_NS, 'zh', zh) locale.register(COMMON_NS, 'en', en) + locale.register(SETTINGS_NS, 'zh', { 'language.title': '语言' }) + locale.register(SETTINGS_NS, 'en', { 'language.title': 'Language' }) ctx.provide('locale', locale) + + const store = createLanguageRowStore() + let bound: BoundActions | undefined + const sync = (snapshot: LocaleSnapshot): void => { + bound?.sync( + snapshot.active, + snapshot.locales.map(l => ({ id: l.id, label: l.label })), + snapshot.revision, + ) + } + ctx.on('locale/change', sync) + const injected = (actions: BoundActions): LanguageRowInjected => { + bound = actions + // Re-sync from the getter so no event is lost between registration and + // first render (the store's revision guard drops stale duplicates). + sync(locale.getLocale()) + return { + t: locale.bind(SETTINGS_NS), + setLocale: (id) => { locale.setLocale(id) }, + } + } + // Declaration-aware registration; the LEDGER is the has-registered judge + // (not a local flag): after an HMR collapse re-declares the slot, the + // cascade already removed our entry, and a stale disposer must not block + // the re-registration. + ctx.effect(() => { + let dispose: (() => void) | undefined + const tryRegister = (): void => { + if (ctx.slots.spec('settings.general.item') === undefined) return + if (ctx.slots.entries('settings.general.item').some(e => e.component === LanguageRow)) return + dispose = ctx.slots.register({ + name: 'settings.general.item', + id: 'language', + order: 0, + store, + inject: injected, + }, LanguageRow) + } + const unsubscribe = ctx.slots.subscribe('settings.general.item', () => { tryRegister() }) + tryRegister() + return () => { + unsubscribe() + dispose?.() + } + }, 'locale: language settings row registration') } diff --git a/packages/client/locale/src/client/settings-contract.ts b/packages/client/locale/src/client/settings-contract.ts new file mode 100644 index 0000000000..add314122c --- /dev/null +++ b/packages/client/locale/src/client/settings-contract.ts @@ -0,0 +1,18 @@ +/** + * Settings-surface slot merge consumed by this package's Language row. The + * AUTHORITATIVE home for 'settings.general.item' is the ui-settings contract + * (declaring is claiming: the shell's General entry declares the slot); this + * file repeats the entry verbatim because the shell consumes ctx.locale + * (project reference ui-settings -> locale), so importing the shell's types + * from here would close a reference cycle. TypeScript declaration merging + * rejects diverging duplicates, so every program that sees both copies (the + * shell's own build, the client aggregate) enforces identity. + */ +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** One preference row inside the General section (duplicate-identical merge; authority: ui-settings contract). */ + 'settings.general.item': { kind: 'list'; scope: 'root'; owner: { children?: never } } + } +} + +export {} diff --git a/packages/client/locale/src/client/settings-store.ts b/packages/client/locale/src/client/settings-store.ts new file mode 100644 index 0000000000..485fd409f0 --- /dev/null +++ b/packages/client/locale/src/client/settings-store.ts @@ -0,0 +1,47 @@ +/** + * Language row slot store: a mirror of the locale service snapshot. The + * plugin's apply-world change listener is the only writer; the row component + * reads via props.useStore. + */ +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client' + +/** One selectable locale row (id + self-described label). */ +export interface LanguageOptionRow { + /** Locale id (the setLocale argument). */ + id: string + /** Display name in its own language (中文 / English). */ + label: string +} + +/** Store state mirrored from the locale snapshot. */ +export interface LanguageRowState { + /** Active locale id. */ + active: string + /** Selectable locales in display order. */ + options: LanguageOptionRow[] + /** Service revision; -1 until first sync so revision 0 lands as a change. */ + revision: number +} + +/** Declared action shape giving the exported factory a stable return type. */ +type LanguageRowActions = { + sync: (draft: LanguageRowState, active: string, options: LanguageOptionRow[], revision: number) => void +} + +/** + * Declares the Language row state and write surface. + * @returns the store handle. + */ +export function createLanguageRowStore(): EngineStoreHandle { + return defineStore({ + init: (): LanguageRowState => ({ active: '', options: [], revision: -1 }), + actions: { + sync: (d, active: string, options: LanguageOptionRow[], revision: number) => { + if (revision <= d.revision) return + d.active = active + d.options = options + d.revision = revision + }, + }, + }) +} diff --git a/packages/client/ui-settings-general/src/css-modules.d.ts b/packages/client/locale/src/css-modules.d.ts similarity index 100% rename from packages/client/ui-settings-general/src/css-modules.d.ts rename to packages/client/locale/src/css-modules.d.ts diff --git a/packages/client/locale/tests/invariant.spec.ts b/packages/client/locale/tests/invariant.spec.ts index e9f4fdee36..fa62ca79f6 100644 --- a/packages/client/locale/tests/invariant.spec.ts +++ b/packages/client/locale/tests/invariant.spec.ts @@ -1,8 +1,10 @@ +// @vitest-environment jsdom import { describe, expect, it } from 'vitest' import { Context } from 'cordis' import { apply as nodeApply } from '@deepseek-ai/dsh-client-locale' import { apply as clientApply, COMMON_NS, LocaleService, inject } from '@deepseek-ai/dsh-client-locale/client' import * as LocaleInvariant from '@deepseek-ai/dsh-client-locale/invariant' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' import InvariantService from '@deepseek-ai/dsh-invariants' describe('invariant companion', () => { @@ -18,8 +20,10 @@ describe('invariant companion', () => { }) it('client apply provides ctx.locale seeded with the zh/en common namespace', async () => { - expect(inject).toEqual([]) + // The feature registers its own Language settings row, hence the slots edge. + expect(inject).toEqual(['slots']) const ctx = new Context() + new SlotsService(ctx) await ctx.plugin({ inject, apply: clientApply }).await() const locale = ctx.get('locale') expect(locale).toBeInstanceOf(LocaleService) diff --git a/packages/client/locale/tsconfig.json b/packages/client/locale/tsconfig.json index 51f9171643..8585ba74ca 100644 --- a/packages/client/locale/tsconfig.json +++ b/packages/client/locale/tsconfig.json @@ -8,6 +8,15 @@ "src" ], "references": [ + { + "path": "../runtime" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-slots" + }, { "path": "../../../vendor/cordis" }, diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-models/README.md similarity index 92% rename from packages/client/ui-settings-models/README.md rename to packages/client/ui-models/README.md index c96e2843e4..b5f6c9bea9 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-models/README.md @@ -1,4 +1,4 @@ -# @deepseek-ai/dsh-client-ui-settings-models +# @deepseek-ai/dsh-client-ui-models Models settings section plugin: registers the `models` nav entry into `settings.section` with an intentionally empty content column — model management lands in a later phase. diff --git a/packages/client/ui-settings-models/package.json b/packages/client/ui-models/package.json similarity index 89% rename from packages/client/ui-settings-models/package.json rename to packages/client/ui-models/package.json index da8fa8c18d..df8cba7c8b 100644 --- a/packages/client/ui-settings-models/package.json +++ b/packages/client/ui-models/package.json @@ -1,6 +1,6 @@ { - "name": "@deepseek-ai/dsh-client-ui-settings-models", - "description": "Models settings section plugin: nav entry with an empty content column (model management lands later)", + "name": "@deepseek-ai/dsh-client-ui-models", + "description": "Models feature plugin: registers its Settings section (nav entry, empty content column; model management lands later)", "version": "0.0.1", "private": true, "type": "module", diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.tsx b/packages/client/ui-models/src/client/ModelsSection.tsx similarity index 100% rename from packages/client/ui-settings-models/src/client/ModelsSection.tsx rename to packages/client/ui-models/src/client/ModelsSection.tsx diff --git a/packages/client/ui-settings-models/src/client/index.ts b/packages/client/ui-models/src/client/index.ts similarity index 96% rename from packages/client/ui-settings-models/src/client/index.ts rename to packages/client/ui-models/src/client/index.ts index c35946fcc8..4f080ec928 100644 --- a/packages/client/ui-settings-models/src/client/index.ts +++ b/packages/client/ui-models/src/client/index.ts @@ -30,7 +30,7 @@ export function apply(ctx: ClientContext): void { ctx.locale.register('settings.models', 'en', { nav: 'Models' }), ] return () => { for (const dispose of disposers) dispose() } - }, 'ui-settings-models: nav copy dictionaries') + }, 'ui-models: nav copy dictionaries') // Declaration-aware registration; the LEDGER is the has-registered judge // (not a local flag): after an HMR collapse re-declares the slot, the // cascade already removed our entry, and a stale disposer must not block @@ -63,5 +63,5 @@ export function apply(ctx: ClientContext): void { unsubscribe() dispose?.() } - }, 'ui-settings-models: section registration') + }, 'ui-models: settings section registration') } diff --git a/packages/client/ui-settings-models/src/css-modules.d.ts b/packages/client/ui-models/src/css-modules.d.ts similarity index 100% rename from packages/client/ui-settings-models/src/css-modules.d.ts rename to packages/client/ui-models/src/css-modules.d.ts diff --git a/packages/client/ui-settings-models/src/index.ts b/packages/client/ui-models/src/index.ts similarity index 100% rename from packages/client/ui-settings-models/src/index.ts rename to packages/client/ui-models/src/index.ts diff --git a/packages/client/ui-settings-models/src/invariant.ts b/packages/client/ui-models/src/invariant.ts similarity index 81% rename from packages/client/ui-settings-models/src/invariant.ts rename to packages/client/ui-models/src/invariant.ts index 9ffdc668d7..c7c4996748 100644 --- a/packages/client/ui-settings-models/src/invariant.ts +++ b/packages/client/ui-models/src/invariant.ts @@ -1,16 +1,16 @@ /** - * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-settings-models`. - * @module @deepseek-ai/dsh-client-ui-settings-models/invariant + * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-models`. + * @module @deepseek-ai/dsh-client-ui-models/invariant */ /* jscpd:ignore-start */ import type { Context } from 'cordis' import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' -const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-settings-models' +const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-models' /** Cordis companion plugin name. */ -export const name = 'client-ui-settings-models-invariant' +export const name = 'client-ui-models-invariant' /** Service required before the companion can reserve package ownership. */ export const inject = ['invariants'] diff --git a/packages/client/ui-settings-models/tests/apply.spec.ts b/packages/client/ui-models/tests/apply.spec.ts similarity index 96% rename from packages/client/ui-settings-models/tests/apply.spec.ts rename to packages/client/ui-models/tests/apply.spec.ts index b7aa3cf2ab..1842000675 100644 --- a/packages/client/ui-settings-models/tests/apply.spec.ts +++ b/packages/client/ui-models/tests/apply.spec.ts @@ -3,7 +3,7 @@ import { Context } from 'cordis' import { describe, expect, it } from 'vitest' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' -import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-models/client' +import { apply, inject } from '@deepseek-ai/dsh-client-ui-models/client' import { ModelsSection } from '../src/client/ModelsSection.tsx' async function bench() { @@ -21,7 +21,7 @@ function declare(slots: SlotsService): () => void { ) } -describe('ui-settings-models apply', () => { +describe('ui-models apply', () => { it('declares the services it uses', () => { expect(inject).toEqual(['slots', 'locale']) }) diff --git a/packages/client/ui-settings-models/tests/invariant.spec.ts b/packages/client/ui-models/tests/invariant.spec.ts similarity index 82% rename from packages/client/ui-settings-models/tests/invariant.spec.ts rename to packages/client/ui-models/tests/invariant.spec.ts index 65c7c1094a..05fb52ee1b 100644 --- a/packages/client/ui-settings-models/tests/invariant.spec.ts +++ b/packages/client/ui-models/tests/invariant.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { Context } from 'cordis' -import * as ModelsInvariant from '@deepseek-ai/dsh-client-ui-settings-models/invariant' +import * as ModelsInvariant from '@deepseek-ai/dsh-client-ui-models/invariant' import InvariantService from '@deepseek-ai/dsh-invariants' import { ModelsSection } from '../src/client/ModelsSection.tsx' @@ -12,7 +12,7 @@ describe('invariant companion', () => { }) it('node-half apply is a no-op host placeholder', async () => { - const { apply } = await import('@deepseek-ai/dsh-client-ui-settings-models') + const { apply } = await import('@deepseek-ai/dsh-client-ui-models') apply() expect(true).toBe(true) // reaching here without throw is the contract }) diff --git a/packages/client/ui-settings-models/tsconfig.json b/packages/client/ui-models/tsconfig.json similarity index 100% rename from packages/client/ui-settings-models/tsconfig.json rename to packages/client/ui-models/tsconfig.json diff --git a/packages/client/ui-models/tsdown.config.ts b/packages/client/ui-models/tsdown.config.ts new file mode 100644 index 0000000000..fc044b07d6 --- /dev/null +++ b/packages/client/ui-models/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle('@deepseek-ai/dsh-client-ui-models', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md deleted file mode 100644 index 435dd8c1b4..0000000000 --- a/packages/client/ui-settings-general/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# @deepseek-ai/dsh-client-ui-settings-general - -General settings section plugin: registers the `general` entry into `settings.section`. Language (中文/English) and Appearance (Light/Dark/System) are live preferences wired to `ctx.locale` / `ctx.theme`; Permission and Tool Call rows are visual skeletons with no write surface. - -## Model Experience - -None, as the section renders browser preference UI; nothing here reaches a model request. - -#### KV Cache effect - -None; this package neither assembles nor sends a provider request. - -## Known Limitations and Deferred Work - -- **Permission and Tool Call are display skeletons** — the backing host services and RPC methods do not exist yet; the controls are disabled and write nothing. diff --git a/packages/client/ui-settings-general/package.json b/packages/client/ui-settings-general/package.json deleted file mode 100644 index 9b3d83e472..0000000000 --- a/packages/client/ui-settings-general/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "@deepseek-ai/dsh-client-ui-settings-general", - "description": "General settings section plugin: Language and Appearance preferences (live), Permission and Tool Call skeleton rows", - "version": "0.0.1", - "private": true, - "type": "module", - "main": "lib/index.js", - "types": "lib/types/index.d.ts", - "exports": { - ".": { - "types": "./lib/types/index.d.ts", - "default": "./lib/index.js" - }, - "./invariant": { - "types": "./lib/types/invariant.d.ts", - "default": "./lib/invariant.js" - }, - "./client": { - "types": "./lib/types/client/index.d.ts", - "default": "./lib/client.js" - }, - "./src/*": "./src/*", - "./package.json": "./package.json" - }, - "dshClient": { - "inject": [ - "@deepseek-ai/dsh-client-runtime", - "@deepseek-ai/dsh-client-ui-settings", - "@deepseek-ai/dsh-client-locale", - "@deepseek-ai/dsh-client-ui-theme" - ], - "platform": "web" - }, - "scripts": { - "bundle": "tsdown", - "watch": "tsdown --watch" - }, - "license": "BSD-3-Clause", - "dependencies": { - "clsx": "^2.0.0" - }, - "peerDependencies": { - "@deepseek-ai/dsh-client-runtime": "^0.0.1", - "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", - "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", - "@deepseek-ai/dsh-invariants": "^0.0.1", - "cordis": "^4.0.0-rc.7", - "react": "^18.2.0" - }, - "devDependencies": { - "@deepseek-ai/dsh-client-locale": "workspace:^", - "@deepseek-ai/dsh-client-runtime": "workspace:^", - "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", - "@deepseek-ai/dsh-client-ui-settings": "workspace:^", - "@deepseek-ai/dsh-client-ui-slots": "workspace:^", - "@deepseek-ai/dsh-client-ui-theme": "workspace:^", - "@deepseek-ai/dsh-invariants": "workspace:^", - "@types/react": "~18.3.1", - "cordis": "^4.0.0-rc.7", - "react": "^18.2.0" - }, - "files": [ - "lib/index.js", - "lib/invariant.js", - "lib/client.js", - "lib/types/**/*.d.ts", - "lib/types/**/*.d.ts.map", - "src" - ] -} diff --git a/packages/client/ui-settings-general/src/client/GeneralSection.tsx b/packages/client/ui-settings-general/src/client/GeneralSection.tsx deleted file mode 100644 index d2947c0435..0000000000 --- a/packages/client/ui-settings-general/src/client/GeneralSection.tsx +++ /dev/null @@ -1,118 +0,0 @@ -/** - * General settings section: Permission and Tool Call skeleton rows (visual - * only, no interaction), live Language and Appearance preference rows wired - * through the injected setLocale/setTheme callbacks and the snapshot-mirror - * store. Figma: Settings > Content > Options (501:29983). - */ -import { useState } from 'react' -import clsx from 'clsx' -import { - IconChevronDownOutline14, IconDarkOutline16, IconFollowsystemOutline16, IconLightOutline16, - Menu, -} from '@deepseek-ai/dsh-client-ui-primitives' -import type { GeneralSectionComponentProps, ThemePreferenceId } from './contract.ts' -import css from './GeneralSection.module.css' - -/** Appearance cube order and icons (figma 501:30015-30017: Light, Dark, System). */ -const THEME_CUBES: readonly { id: ThemePreferenceId; labelKey: string; Icon: typeof IconLightOutline16 }[] = [ - { id: 'light', labelKey: 'appearance.light', Icon: IconLightOutline16 }, - { id: 'dark', labelKey: 'appearance.dark', Icon: IconDarkOutline16 }, - { id: 'system', labelKey: 'appearance.system', Icon: IconFollowsystemOutline16 }, -] - -/** - * Render the General section content column. - * @param props - composed slot props (contract.ts). - * @returns the section element tree. - */ -export function GeneralSection(props: GeneralSectionComponentProps) { - const { t, setLocale, setTheme, useStore } = props - const localeActive = useStore(s => s.localeActive) - const localeOptions = useStore(s => s.localeOptions) - const themePreference = useStore(s => s.themePreference) - const [languageOpen, setLanguageOpen] = useState(false) - - const activeLocaleLabel = localeOptions.find(l => l.id === localeActive)?.label ?? localeActive - - return ( -
- {/* Permission (skeleton): disabled selector pill. */} -
-
-
{t('permission.title')}
-
{t('permission.desc')}
-
- -
- - {/* Tool Call (skeleton): schema cube pinned selected, code cube unselected. */} -
-
{t('toolcall.title')}
-
-
-
{t('toolcall.schema.title')}
-
{t('toolcall.schema.desc')}
-
-
-
{t('toolcall.code.title')}
-
{t('toolcall.code.desc')}
-
-
-
- - {/* Language: selector pill opens the locale menu. */} -
-
-
{t('language.title')}
-
- { setLanguageOpen(false) }} - items={localeOptions.map(l => ({ id: l.id, label: l.label }))} - selectedId={localeActive} - onSelect={(id) => { - setLocale(id) - setLanguageOpen(false) - }} - align="end" - portal - anchor={( - - )} - /> -
- - {/* Appearance: three preference cubes; selection follows the persisted - * preference, never the resolved active theme. */} -
-
{t('appearance.title')}
-
- {THEME_CUBES.map(({ id, labelKey, Icon }) => ( - - ))} -
-
-
- ) -} diff --git a/packages/client/ui-settings-general/src/client/contract.ts b/packages/client/ui-settings-general/src/client/contract.ts deleted file mode 100644 index 912d925615..0000000000 --- a/packages/client/ui-settings-general/src/client/contract.ts +++ /dev/null @@ -1,66 +0,0 @@ -/** - * General section component contract: the slot-store state shape, the - * injected business face, and the composed props type. The component imports - * only from here; service snapshot shapes are mirrored as plain rows so the - * presentation layer stays decoupled from the locale/theme packages. - */ -import type { PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' -// Type-only: pulls the shell's SlotMap merge (the 'settings.section' entry). -import type {} from '@deepseek-ai/dsh-client-ui-settings/client' -import type { createGeneralSettingsStore } from './store.ts' - -/** One selectable locale row projected into the store (id + self-described label). */ -export interface LocaleOptionRow { - /** Locale id (the setLocale argument). */ - id: string - /** Display name in its own language (中文 / English). */ - label: string -} - -/** Theme preference union mirrored from the theme service snapshot. */ -export type ThemePreferenceId = 'light' | 'dark' | 'system' - -/** - * Store state: mirrors of the locale/theme service snapshots, written only by - * the plugin's apply-world change listeners (components have no write path — - * preference writes go through the injected callbacks to the services, and - * the resulting change events flow back into this mirror). - */ -export interface GeneralSettingsState { - /** Active locale id. */ - localeActive: string - /** Selectable locales in display order. */ - localeOptions: LocaleOptionRow[] - /** Locale service revision (re-renders translated copy on dictionary/locale changes); -1 until first sync. */ - localeRevision: number - /** Persisted theme preference (selection state reads this, never the resolved active theme). */ - themePreference: ThemePreferenceId - /** Theme service revision; -1 until first sync. */ - themeRevision: number -} - -/** - * Registrant-private injected share of the General section (assembled in - * apply): the namespace-bound translate function (stable identity — re-render - * on locale change comes from the store revision, not from `t`) and the two - * preference write callbacks. - */ -export interface GeneralSectionInjected { - /** Translate a `settings.general` dictionary key to the active-locale text. */ - t: (key: string) => string - /** Switch the active locale (a registered locale id). */ - setLocale: (id: string) => void - /** Switch the theme preference. */ - setTheme: (id: ThemePreferenceId) => void -} - -/** Store handle type for the props share (type-only; the factory stays internal to apply and tests). */ -export type GeneralSettingsStoreHandle = ReturnType - -/** - * Full component props of the General section: the section owner share - * (empty marker) plus the store share and the injected face. No child slots - * are declared; menu open state is component-local viewing state. - */ -export type GeneralSectionComponentProps = - PropsRuntime<'settings.section'> & PropsStore & GeneralSectionInjected diff --git a/packages/client/ui-settings-general/src/client/index.ts b/packages/client/ui-settings-general/src/client/index.ts deleted file mode 100644 index 52655be7fa..0000000000 --- a/packages/client/ui-settings-general/src/client/index.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * General settings section plugin, browser half. Registers the `general` - * entry into the shell-declared `settings.section` list slot; Language and - * Appearance are live preferences projected from ctx.locale / ctx.theme - * through this entry's slot store. Export discipline: packages/client/AGENTS.md. - */ -import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' -import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots' -// Type-only: pulls the shell's SlotMap merge (the 'settings.section' entry). -import type {} from '@deepseek-ai/dsh-client-ui-settings/client' -// Type-only: the locale/theme Context+Events merges and snapshot shapes. -import type { LocaleSnapshot } from '@deepseek-ai/dsh-client-locale/client' -import type { ThemeSnapshot } from '@deepseek-ai/dsh-client-ui-theme/client' -import type { GeneralSectionInjected } from './contract.ts' -import { createGeneralSettingsStore } from './store.ts' -import { en, zh } from './locales.ts' -import { GeneralSection } from './GeneralSection.tsx' - -export type { - GeneralSectionComponentProps, GeneralSectionInjected, GeneralSettingsState, - GeneralSettingsStoreHandle, LocaleOptionRow, ThemePreferenceId, -} from './contract.ts' - -/** Dictionary namespace owned by this section (also the nav-label reference prefix). */ -const NS = 'settings.general' - -/** - * Required services (cordis fiber inject). The target slot is declared by - * ui-settings' apply, whose activation order relative to this one is NOT - * constrained; registration goes through declaration-aware deferral. - */ -export const inject = ['slots', 'locale', 'theme'] - -/** - * Register the `settings.general` dictionaries and the General section entry - * once the `settings.section` declaration is on the ledger. The slot store - * mirrors the locale/theme snapshots: change listeners attach here in apply, - * write through the bound actions captured at inject time, and the inject - * factory re-syncs from the getters so no event is lost between registration - * and first render (the store's revision guard drops stale duplicates). - * @param ctx - client root context. - */ -export function apply(ctx: ClientContext): void { - ctx.effect(() => { - const disposeZh = ctx.locale.register(NS, 'zh', zh) - const disposeEn = ctx.locale.register(NS, 'en', en) - return () => { - disposeZh() - disposeEn() - } - }, 'ui-settings-general: dictionaries') - - const store = createGeneralSettingsStore() - let bound: BoundActions | undefined - - const syncLocale = (snapshot: LocaleSnapshot): void => { - bound?.syncLocale( - snapshot.active, - snapshot.locales.map(l => ({ id: l.id, label: l.label })), - snapshot.revision, - ) - } - const syncTheme = (snapshot: ThemeSnapshot): void => { - bound?.syncTheme(snapshot.preference, snapshot.revision) - } - ctx.on('locale/change', syncLocale) - ctx.on('theme/change', syncTheme) - - const injected = (actions: BoundActions): GeneralSectionInjected => { - bound = actions - syncLocale(ctx.locale.getLocale()) - syncTheme(ctx.theme.getTheme()) - return { - t: ctx.locale.bind(NS), - setLocale: (id) => { ctx.locale.setLocale(id) }, - setTheme: (id) => { ctx.theme.setTheme(id) }, - } - } - - ctx.effect(() => { - let dispose: (() => void) | undefined - // Presence is judged on the ledger, not on the local disposer: an HMR - // collapse of the declaring entry removes this entry from the slot core - // while `dispose` stays set (the stale disposer is a no-op), so a local - // guard would block the re-registration when the declaration returns. - const registered = (): boolean => - ctx.slots.entries('settings.section').some(e => e.component === GeneralSection) - const tryRegister = (): void => { - if (ctx.slots.spec('settings.section') === undefined || registered()) return - dispose = ctx.slots.register({ - name: 'settings.section', - id: 'general', - order: 0, - label: ctx.locale.bind(NS)('nav'), - store, - inject: injected, - }, GeneralSection) - } - // Nav labels are registrant-localized: re-register on locale change so - // the ledger carries fresh text (the version bump re-renders the shell). - // The ledger check mirrors tryRegister: after an HMR collapse `dispose` - // stays set while the entry is gone — relabeling then must stay quiet. - const offLocale = ctx.on('locale/change', () => { - if (dispose === undefined || !registered()) return - dispose() - dispose = undefined - tryRegister() - }) - const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) - tryRegister() - return () => { - offLocale() - unsubscribe() - dispose?.() - } - }, 'ui-settings-general: section registration') -} diff --git a/packages/client/ui-settings-general/src/client/store.ts b/packages/client/ui-settings-general/src/client/store.ts deleted file mode 100644 index 121e3f52a9..0000000000 --- a/packages/client/ui-settings-general/src/client/store.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * General section slot store: locale/theme snapshot mirrors. The plugin - * creates the handle at apply time (identity follows the fiber) and its - * change listeners are the only writers; components read via props.useStore. - */ -import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client' -import type { GeneralSettingsState, LocaleOptionRow, ThemePreferenceId } from './contract.ts' - -/** Declared action shape used to give the exported factory a stable return type. */ -type GeneralSettingsActions = { - syncLocale: (draft: GeneralSettingsState, active: string, options: LocaleOptionRow[], revision: number) => void - syncTheme: (draft: GeneralSettingsState, preference: ThemePreferenceId, revision: number) => void -} - -/** - * Declares the General section state and write surface. Revisions start at -1 - * so the apply-time initial sync (revision 0) always lands as a change. - * @returns the store handle. - */ -export function createGeneralSettingsStore(): EngineStoreHandle { - return defineStore({ - init: (): GeneralSettingsState => ({ - localeActive: '', - localeOptions: [], - localeRevision: -1, - themePreference: 'system', - themeRevision: -1, - }), - actions: { - syncLocale: (d, active: string, options: LocaleOptionRow[], revision: number) => { - if (revision <= d.localeRevision) return - d.localeActive = active - d.localeOptions = options - d.localeRevision = revision - }, - syncTheme: (d, preference: ThemePreferenceId, revision: number) => { - if (revision <= d.themeRevision) return - d.themePreference = preference - d.themeRevision = revision - }, - }, - }) -} diff --git a/packages/client/ui-settings-general/src/index.ts b/packages/client/ui-settings-general/src/index.ts deleted file mode 100644 index 94b9bdf674..0000000000 --- a/packages/client/ui-settings-general/src/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -/** Host loader entry for the browser implementation exported from `./client`. */ - -/** Host plugin body — no host-side behavior for the general settings plugin. */ -export function apply(): void {} diff --git a/packages/client/ui-settings-general/src/invariant.ts b/packages/client/ui-settings-general/src/invariant.ts deleted file mode 100644 index a40cc3cc00..0000000000 --- a/packages/client/ui-settings-general/src/invariant.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Package-owned invariant companion for `@deepseek-ai/dsh-client-ui-settings-general`. - * @module @deepseek-ai/dsh-client-ui-settings-general/invariant - */ - -/* jscpd:ignore-start */ -import type { Context } from 'cordis' -import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' - -const PACKAGE_NAME = '@deepseek-ai/dsh-client-ui-settings-general' - -/** Cordis companion plugin name. */ -export const name = 'client-ui-settings-general-invariant' -/** Service required before the companion can reserve package ownership. */ -export const inject = ['invariants'] - -/** - * No runtime invariant: a section plugin projecting two service change events - * into its own slot store — it emits no cordis events of its own and owns no - * cross-plugin mutable relation; snapshot/store agreement is asserted by this - * package's behavior specs. - */ -const install: InvariantInstaller = () => {} - -/** - * Register this package's invariant companion. - * @param ctx - Cordis context carrying the invariant service. - * @returns the installed registration's disposer after setup succeeds. - */ -export const apply = (ctx: Context): Promise<() => void> => - Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install)) -/* jscpd:ignore-end */ diff --git a/packages/client/ui-settings-general/tests/apply.spec.ts b/packages/client/ui-settings-general/tests/apply.spec.ts deleted file mode 100644 index 8654275831..0000000000 --- a/packages/client/ui-settings-general/tests/apply.spec.ts +++ /dev/null @@ -1,139 +0,0 @@ -/** apply wiring: dictionary registration, declaration-aware section entry, - * snapshot projection into the slot store, locale-driven relabeling, and - * recovery after an HMR collapse of the declaring entry. */ -import { Context } from 'cordis' -import { describe, expect, it } from 'vitest' -import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' -import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' -import { ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' -import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-general/client' -import type { GeneralSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-general/client' -import { GeneralSection } from '../src/client/GeneralSection.tsx' -import type { createGeneralSettingsStore } from '../src/client/store.ts' - -const NS = 'settings.general' - -async function bench() { - const ctx = new Context() - await ctx.plugin(SlotsService).await() - const locale = new LocaleService(ctx) - const theme = new ThemeService(ctx) - ctx.provide('locale', locale) - ctx.provide('theme', theme) - return { ctx, slots: ctx.get('slots') as SlotsService, locale, theme } -} - -/** Stand in for the settings shell: declare the section list slot from root. */ -function declareSection(slots: SlotsService): () => void { - return slots.register( - { name: 'root', children: { 'settings.section': { kind: 'list', scope: 'root' } } } as never, - () => null, - ) -} - -/** Mirror the framework's inject choreography: bake a real instance from the - * declared handle and hand its actions to the entry's inject factory. */ -function faceOf(slots: SlotsService) { - const entry = slots.entries('settings.section')[0]! - const handle = entry.store as ReturnType - const instance = handle.create() - const face = (entry.inject as unknown as (a: typeof instance.actions) => GeneralSectionInjected)(instance.actions) - return { entry, instance, face } -} - -describe('ui-settings-general apply', () => { - it('declares the slot, locale, and theme services', () => { - expect(inject).toEqual(['slots', 'locale', 'theme']) - }) - - it('registers dictionaries and the section entry for declarations before or after apply', async () => { - const before = await bench() - declareSection(before.slots) - await before.ctx.plugin({ inject: [...inject], apply }).await() - const entry = before.slots.entries('settings.section')[0]! - expect(entry.component).toBe(GeneralSection) - expect(entry.options).toMatchObject({ id: 'general', order: 0, label: '通用设置' }) - expect(before.locale.bind(NS)('nav')).toBe('通用设置') - - const after = await bench() - const fiber = after.ctx.plugin({ inject: [...inject], apply }) - await fiber.await() - expect(after.slots.entries('settings.section')).toHaveLength(0) - declareSection(after.slots) - await Promise.resolve() - expect(after.slots.entries('settings.section')[0]!.component).toBe(GeneralSection) - // Teardown without a live registration exercises the undefined-disposer arm. - await fiber.dispose() - expect(after.slots.entries('settings.section')).toHaveLength(0) - }) - - it('projects service snapshots into the store and routes face writes back', async () => { - const b = await bench() - declareSection(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() - // Events ahead of any inject hit the unbound-actions arm without a store. - b.theme.setTheme('dark') - - const { instance, face } = faceOf(b.slots) - // The inject-time re-sync sealed the init window: both mirrors are current. - expect(instance.getSnapshot().localeActive).toBe('zh') - expect(instance.getSnapshot().localeOptions.map(l => l.id)).toEqual(['zh', 'en']) - expect(instance.getSnapshot().themePreference).toBe('dark') - expect(face.t('nav')).toBe('通用设置') - - face.setLocale('en') - expect(b.locale.getLocale().active).toBe('en') - expect(instance.getSnapshot().localeActive).toBe('en') - expect(face.t('nav')).toBe('General') - - face.setTheme('system') - expect(b.theme.getTheme().preference).toBe('system') - expect(instance.getSnapshot().themePreference).toBe('system') - }) - - it('re-registers with a fresh ledger label when the locale changes', async () => { - const b = await bench() - declareSection(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() - expect(b.slots.entries('settings.section')[0]!.options.label).toBe('通用设置') - b.locale.setLocale('en') - const entry = b.slots.entries('settings.section')[0]! - expect(entry.options.label).toBe('General') - expect(entry.component).toBe(GeneralSection) - }) - - it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => { - const b = await bench() - const host = declareSection(b.slots) - await b.ctx.plugin({ inject: [...inject], apply }).await() - expect(b.slots.entries('settings.section')).toHaveLength(1) - - // Collapse: the declarer dies, the cascade removes our entry while the - // apply closure still holds its (now stale) disposer. - host() - expect(b.slots.entries('settings.section')).toHaveLength(0) - - // A locale change inside the collapsed window must stay quiet. - b.locale.setLocale('en') - expect(b.slots.entries('settings.section')).toHaveLength(0) - - // Redeclaration restores the entry — with the current locale's label. - declareSection(b.slots) - await Promise.resolve() - const entry = b.slots.entries('settings.section')[0]! - expect(entry.component).toBe(GeneralSection) - expect(entry.options.label).toBe('General') - }) - - it('removes the entry and the dictionaries on teardown', async () => { - const b = await bench() - declareSection(b.slots) - const fiber = b.ctx.plugin({ inject: [...inject], apply }) - await fiber.await() - expect(b.slots.entries('settings.section')).toHaveLength(1) - await fiber.dispose() - expect(b.slots.entries('settings.section')).toHaveLength(0) - // Dictionary disposal: translation falls back to the bare key. - expect(b.locale.bind(NS)('nav')).toBe('nav') - }) -}) diff --git a/packages/client/ui-settings-general/tests/general-section.spec.tsx b/packages/client/ui-settings-general/tests/general-section.spec.tsx deleted file mode 100644 index e82ed0b1fc..0000000000 --- a/packages/client/ui-settings-general/tests/general-section.spec.tsx +++ /dev/null @@ -1,112 +0,0 @@ -// @vitest-environment jsdom -/** GeneralSection behavior: skeleton rows stay inert, Language menu drives - * setLocale, Appearance cubes follow the preference and drive setTheme. */ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' -import { createSnapshotStore, type SessionListState, type WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client' -import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' -import { GeneralSection } from '../src/client/GeneralSection.tsx' -import { createGeneralSettingsStore } from '../src/client/store.ts' -import { en } from '../src/client/locales.ts' -import type { GeneralSectionComponentProps } from '../src/client/contract.ts' - -afterEach(cleanup) - -const LOCALES = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }] - -/** Empty global standard-kit hooks (the section reads neither). */ -function emptySessions() { - const store = createSnapshotStore( - { ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' }) - return bindSnapshotSelector(store) -} -function emptyWorkspaces() { - const store = createSnapshotStore({ - items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, - baselinesReady: true, recentWorkspaceId: undefined, - }) - return bindSnapshotSelector(store) -} - -function mount(init?: { active?: string; preference?: 'light' | 'dark' | 'system' }) { - // Real store instance — the sanctioned zero-machinery path for tests. - const store = createGeneralSettingsStore().create() - store.actions.syncLocale(init?.active ?? 'en', LOCALES, 0) - store.actions.syncTheme(init?.preference ?? 'system', 0) - const setLocale = vi.fn() - const setTheme = vi.fn() - const props: GeneralSectionComponentProps = { - useSessions: emptySessions(), - useWorkspaces: emptyWorkspaces(), - useStore: bindSnapshotSelector(store), - actions: store.actions, - t: (key: string) => en[key] ?? key, - setLocale, - setTheme, - } - render() - return { store, setLocale, setTheme } -} - -const pressed = (name: RegExp): string | null => - screen.getByRole('button', { name }).getAttribute('aria-pressed') - -describe('GeneralSection', () => { - it('renders the four groups with skeleton rows inert', () => { - const b = mount() - // Permission: disabled selector showing the fixed value. - const permission = screen.getByRole('button', { name: /Read only/ }) as HTMLButtonElement - expect(permission.disabled).toBe(true) - fireEvent.click(permission) - // Tool Call: both mode cubes render as plain text, no buttons. - expect(screen.getByText('Schema mode')).toBeDefined() - expect(screen.getByText('Code mode')).toBeDefined() - expect(screen.queryByRole('button', { name: /Schema mode/ })).toBeNull() - expect(b.setLocale).not.toHaveBeenCalled() - expect(b.setTheme).not.toHaveBeenCalled() - }) - - it('opens the language menu, selects a locale, and closes', () => { - const b = mount({ active: 'en' }) - const trigger = screen.getByRole('button', { name: /English/ }) - expect(trigger.getAttribute('aria-expanded')).toBe('false') - fireEvent.click(trigger) - expect(trigger.getAttribute('aria-expanded')).toBe('true') - fireEvent.click(screen.getByRole('menuitem', { name: '中文' })) - expect(b.setLocale).toHaveBeenCalledWith('zh') - expect(trigger.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull() - }) - - it('closes the language menu on outside pointerdown without selecting', () => { - const b = mount({ active: 'en' }) - const trigger = screen.getByRole('button', { name: /English/ }) - fireEvent.click(trigger) - expect(screen.getByRole('menuitem', { name: '中文' })).toBeDefined() - fireEvent.pointerDown(document.body) - expect(trigger.getAttribute('aria-expanded')).toBe('false') - expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull() - expect(b.setLocale).not.toHaveBeenCalled() - }) - - it('reflects a store locale change in the trigger label (unknown id falls back to the id)', () => { - const b = mount({ active: 'en' }) - act(() => { b.store.actions.syncLocale('zh', LOCALES, 1) }) - expect(screen.getByRole('button', { name: /中文/ })).toBeDefined() - act(() => { b.store.actions.syncLocale('fr', LOCALES, 2) }) - expect(screen.getByRole('button', { name: /fr/ })).toBeDefined() - }) - - it('marks the appearance cube matching the preference and switches on click', () => { - const b = mount({ preference: 'dark' }) - expect(pressed(/Dark/)).toBe('true') - expect(pressed(/Light/)).toBe('false') - expect(pressed(/System/)).toBe('false') - fireEvent.click(screen.getByRole('button', { name: /Light/ })) - expect(b.setTheme).toHaveBeenCalledWith('light') - // Selection follows the store mirror, not the click echo. - act(() => { b.store.actions.syncTheme('light', 1) }) - expect(pressed(/Light/)).toBe('true') - expect(pressed(/Dark/)).toBe('false') - }) -}) diff --git a/packages/client/ui-settings-general/tests/invariant.spec.ts b/packages/client/ui-settings-general/tests/invariant.spec.ts deleted file mode 100644 index 7b0527c0ff..0000000000 --- a/packages/client/ui-settings-general/tests/invariant.spec.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { Context } from 'cordis' -import * as GeneralInvariant from '@deepseek-ai/dsh-client-ui-settings-general/invariant' -import InvariantService from '@deepseek-ai/dsh-invariants' - -describe('invariant companion', () => { - it('registers under the package name with an empty installer', async () => { - const ctx = new Context() - await ctx.plugin(InvariantService, { enabled: true }) - await expect(ctx.plugin(GeneralInvariant).await()).resolves.toBeDefined() - }) - - it('node-half apply is a no-op host placeholder', async () => { - const { apply } = await import('@deepseek-ai/dsh-client-ui-settings-general') - apply() - expect(true).toBe(true) // reaching here without throw is the contract - }) -}) diff --git a/packages/client/ui-settings-general/tests/store.spec.ts b/packages/client/ui-settings-general/tests/store.spec.ts deleted file mode 100644 index b291418471..0000000000 --- a/packages/client/ui-settings-general/tests/store.spec.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** General settings store: snapshot-mirror actions and the revision guard. */ -import { describe, expect, it } from 'vitest' -import { createGeneralSettingsStore } from '../src/client/store.ts' - -const LOCALES = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }] - -describe('createGeneralSettingsStore', () => { - it('init shape: empty mirrors with revisions at -1', () => { - const store = createGeneralSettingsStore().create() - expect(store.getSnapshot()).toEqual({ - localeActive: '', - localeOptions: [], - localeRevision: -1, - themePreference: 'system', - themeRevision: -1, - }) - }) - - it('syncLocale mirrors the snapshot and advances the revision', () => { - const store = createGeneralSettingsStore().create() - store.actions.syncLocale('zh', LOCALES, 0) - expect(store.getSnapshot().localeActive).toBe('zh') - expect(store.getSnapshot().localeOptions).toEqual(LOCALES) - expect(store.getSnapshot().localeRevision).toBe(0) - - store.actions.syncLocale('en', LOCALES, 1) - expect(store.getSnapshot().localeActive).toBe('en') - expect(store.getSnapshot().localeRevision).toBe(1) - }) - - it('syncLocale revision guard drops stale and duplicate writes', () => { - const store = createGeneralSettingsStore().create() - store.actions.syncLocale('en', LOCALES, 5) - // Stale (lower) and duplicate (equal) revisions leave the mirror intact. - store.actions.syncLocale('zh', LOCALES, 4) - store.actions.syncLocale('zh', LOCALES, 5) - expect(store.getSnapshot().localeActive).toBe('en') - expect(store.getSnapshot().localeRevision).toBe(5) - }) - - it('syncTheme mirrors the preference and guards its revision independently', () => { - const store = createGeneralSettingsStore().create() - store.actions.syncTheme('dark', 0) - expect(store.getSnapshot().themePreference).toBe('dark') - expect(store.getSnapshot().themeRevision).toBe(0) - - store.actions.syncTheme('light', 2) - expect(store.getSnapshot().themePreference).toBe('light') - - // Stale theme write is dropped; the locale revision axis is untouched. - store.actions.syncTheme('system', 1) - expect(store.getSnapshot().themePreference).toBe('light') - expect(store.getSnapshot().themeRevision).toBe(2) - expect(store.getSnapshot().localeRevision).toBe(-1) - }) -}) diff --git a/packages/client/ui-settings-general/tsconfig.json b/packages/client/ui-settings-general/tsconfig.json deleted file mode 100644 index 9b2cc5b838..0000000000 --- a/packages/client/ui-settings-general/tsconfig.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "extends": "../../../tsconfig.base.client.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], - "references": [ - { - "path": "../../../vendor/cordis" - }, - { - "path": "../ui-slots" - }, - { - "path": "../ui-primitives" - }, - { - "path": "../runtime" - }, - { - "path": "../ui-settings" - }, - { - "path": "../locale" - }, - { - "path": "../ui-theme" - }, - { - "path": "../../support/invariants" - } - ] -} diff --git a/packages/client/ui-settings-general/tsdown.config.ts b/packages/client/ui-settings-general/tsdown.config.ts deleted file mode 100644 index bf67c4f10f..0000000000 --- a/packages/client/ui-settings-general/tsdown.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { clientBundle } from '../tsdown.client.ts' - -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-general', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/ui-settings-models/tsdown.config.ts b/packages/client/ui-settings-models/tsdown.config.ts deleted file mode 100644 index 7a2688a097..0000000000 --- a/packages/client/ui-settings-models/tsdown.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -import { clientBundle } from '../tsdown.client.ts' - -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-models', ['lib/types/index.js', 'lib/types/invariant.js']) diff --git a/packages/client/ui-settings-general/src/client/GeneralSection.module.css b/packages/client/ui-settings/src/client/GeneralSection.module.css similarity index 75% rename from packages/client/ui-settings-general/src/client/GeneralSection.module.css rename to packages/client/ui-settings/src/client/GeneralSection.module.css index dffafc419d..5e053a49c5 100644 --- a/packages/client/ui-settings-general/src/client/GeneralSection.module.css +++ b/packages/client/ui-settings/src/client/GeneralSection.module.css @@ -1,6 +1,7 @@ -/* General section rows (figma 501:29983 'Options'): four groups, 16px - * vertical padding each, hairline separator under all but the last. The - * shell's content column owns the outer horizontal padding. */ +/* General section rows (figma 501:29983 'Options'): stacked groups, 16px + * vertical padding each, hairline separator under all but the last child + * (feature-contributed rows carry their own row chrome and separators; the + * :last-child rule strips the trailing one wherever the column ends). */ .section { display: flex; @@ -8,6 +9,10 @@ width: 100%; } +.section > :last-child { + border-bottom: none; +} + /* Title + trailing control row (figma 'Setting-Cell': gap 8, pad 16/0). */ .row { display: flex; @@ -26,10 +31,6 @@ border-bottom: 1px solid var(--dsw-alias-border-l2); } -.last { - border-bottom: none; -} - /* Leading text column (figma 'Frame 2036083120': gap 4, pad-right 48). */ .rowText { flex: 1; @@ -79,7 +80,7 @@ flex: none; } -/* Cube rows share an 8px gap; cubes stretch to equal height. */ +/* Tool Call mode cubes share an 8px gap. */ .cubeRow { display: flex; align-items: stretch; @@ -102,27 +103,6 @@ text-align: left; } -/* Appearance cube (figma '.Selector Cube' 276x82 r16, pad 20/32, centered - * icon-over-label column, gap 4). */ -.themeCube { - box-sizing: border-box; - width: 276px; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - gap: 4px; - padding: 20px 32px; - border: 1px solid var(--dsw-alias-border-l2); - border-radius: 16px; - background: transparent; - font: inherit; - font-size: 14px; - line-height: 22px; - color: var(--dsw-alias-label-primary); - cursor: pointer; -} - /* Selected cube: #F5F6F7 fill + #ADB2B8 border (static token — the bluish-400 * step has no alias-layer name). */ .selected { diff --git a/packages/client/ui-settings/src/client/GeneralSection.tsx b/packages/client/ui-settings/src/client/GeneralSection.tsx new file mode 100644 index 0000000000..31714a9238 --- /dev/null +++ b/packages/client/ui-settings/src/client/GeneralSection.tsx @@ -0,0 +1,51 @@ +/** + * Shell-owned General section (figma 501:29983 'Options'): Permission and + * Tool Call skeleton rows, then the feature-contributed preference rows from + * the `settings.general.item` slot (locale → Language, ui-theme → + * Appearance). The section column stacks rows; each row draws its own + * internals and separator. + */ +import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives' +import type { GeneralSectionComponentProps } from './contract/slots.ts' +import css from './GeneralSection.module.css' + +/** + * Render the General section content column. + * @param props - composed slot props (contract/slots.ts). + * @returns the section element tree. + */ +export function GeneralSection({ t, renderSlot }: GeneralSectionComponentProps) { + return ( +
+ {/* Permission (skeleton): disabled selector pill. */} +
+
+
{t('permission.title')}
+
{t('permission.desc')}
+
+ +
+ + {/* Tool Call (skeleton): schema cube pinned selected, code cube unselected. */} +
+
{t('toolcall.title')}
+
+
+
{t('toolcall.schema.title')}
+
{t('toolcall.schema.desc')}
+
+
+
{t('toolcall.code.title')}
+
{t('toolcall.code.desc')}
+
+
+
+ + {/* Feature-owned preference rows (Language, Appearance, …). */} + {renderSlot('settings.general.item', {})} +
+ ) +} diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts index 10e4e0ecbe..87db2f8999 100644 --- a/packages/client/ui-settings/src/client/contract/slots.ts +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -1,7 +1,11 @@ /** - * Settings shell slot contract: the shell occupies the sidebar-owned - * `sidebar.settings` hole and declares the `settings.section` list slot that - * section plugins (General, Models, …) contribute pages into. + * Settings shell slot contract. The shell occupies the sidebar-owned + * `sidebar.settings` hole, declares the `settings.section` list slot that + * feature plugins contribute top-level pages into, and ships the first + * section itself: General, whose `settings.general.item` list slot receives + * preference rows from the features that own them (locale → Language, + * ui-theme → Appearance). A feature owns its settings surface — adding a + * setting never means editing the shell. */ import type { PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls ui-sidebar's SlotMap merge (the 'sidebar.settings' entry) @@ -19,6 +23,16 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * re-render trigger). Sections render inside the panel content column. */ 'settings.section': { kind: 'list'; scope: 'root'; owner: SettingsSectionOwnerProps } + /** + * One preference row inside the General section, contributed by the + * feature plugin that owns the preference (locale → Language, ui-theme → + * Appearance). Options: `id` (row key), `order` (row position). Rows + * draw their own internals (row layout, separators via CSS); the section + * column only stacks them. NOTE: packages/client/locale and ui-theme + * repeat this entry verbatim (reference-cycle avoidance) — declaration + * merging enforces the copies stay identical; edit all three together. + */ + 'settings.general.item': { kind: 'list'; scope: 'root'; owner: { children?: never } } } } @@ -60,3 +74,21 @@ export type SettingsRootInjected = { */ export type SettingsRootComponentProps = PropsRuntime<'sidebar.settings'> & PropsRenderSlots<'settings.section'> & SettingsRootInjected + +/** + * Injected share of the shell-owned General section: the shell's own + * `settings` namespace translate function for the skeleton rows (Permission, + * Tool Call). Live preference rows arrive through the item slot with their + * own faces. + */ +export type GeneralSectionInjected = { + /** Translate a `settings` dictionary key to the active-locale text. */ + t: (key: string) => string +} + +/** + * Full component props of the shell-owned General section: the section owner + * share, the declared item render share, and the injected face. + */ +export type GeneralSectionComponentProps = + PropsRuntime<'settings.section'> & PropsRenderSlots<'settings.general.item'> & GeneralSectionInjected diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index 3613476ede..c360a84201 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -1,17 +1,24 @@ /** * Settings shell plugin, browser half. Occupies the sidebar-owned * `sidebar.settings` hole with the trigger row + modal panel, declares the - * `settings.section` list slot, and projects that ledger into the panel - * navigation. Export discipline: packages/client/AGENTS.md. + * `settings.section` list slot, projects that ledger into the panel + * navigation, and ships the first section itself: General, which declares + * the `settings.general.item` slot that feature plugins contribute + * preference rows into. Export discipline: packages/client/AGENTS.md. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' // Type-only: pulls the locale plugin's Context/Events merges (ctx.locale, // 'locale/change') into this program. import type {} from '@deepseek-ai/dsh-client-locale/client' -import type { SettingsRootInjected } from './contract/slots.ts' +import type { GeneralSectionInjected, SettingsRootInjected } from './contract/slots.ts' import { SettingsRoot } from './SettingsRoot.tsx' +import { GeneralSection } from './GeneralSection.tsx' +import { en, zh } from './locales.ts' -export type { SettingsRootComponentProps, SettingsRootInjected, SettingsSectionOwnerProps } from './contract/slots.ts' +export type { + GeneralSectionComponentProps, GeneralSectionInjected, + SettingsRootComponentProps, SettingsRootInjected, SettingsSectionOwnerProps, +} from './contract/slots.ts' /** * Required services (cordis fiber inject). The target slot is declared by @@ -22,18 +29,20 @@ export type { SettingsRootComponentProps, SettingsRootInjected, SettingsSectionO export const inject = ['slots', 'locale'] /** - * Register the settings shell into `sidebar.settings` once the declaration is - * on the ledger. + * Register the settings shell into `sidebar.settings` and the shell-owned + * General section into `settings.section`, each once its declaration is on + * the ledger. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => { const disposers = [ - ctx.locale.register('settings', 'zh', { trigger: '设置', title: '设置', close: '关闭' }), - ctx.locale.register('settings', 'en', { trigger: 'Settings', title: 'Settings', close: 'Close' }), + ctx.locale.register('settings', 'zh', zh), + ctx.locale.register('settings', 'en', en), ] return () => { for (const dispose of disposers) dispose() } }, 'ui-settings: shell copy dictionaries') + const injected = (): SettingsRootInjected => ({ translate: (ref) => { const colon = ref.indexOf(':') @@ -73,4 +82,38 @@ export function apply(ctx: ClientContext): void { dispose?.() } }, 'ui-settings: shell registration') + + // The shell's own General section: first page, declares the item slot the + // feature plugins (locale, ui-theme, …) contribute preference rows into. + // Same ledger-judged deferral; label re-registers on locale change. + const generalInjected = (): GeneralSectionInjected => ({ + t: ctx.locale.bind('settings'), + }) + ctx.effect(() => { + let dispose: (() => void) | undefined + const tryRegister = (): void => { + if (ctx.slots.spec('settings.section') === undefined) return + if (ctx.slots.entries('settings.section').some(e => e.component === GeneralSection)) return + dispose = ctx.slots.register({ + name: 'settings.section', + id: 'general', + order: 0, + label: ctx.locale.bind('settings')('general.nav'), + children: { 'settings.general.item': { kind: 'list', scope: 'root' } }, + inject: generalInjected, + }, GeneralSection) + } + const offLocale = ctx.on('locale/change', () => { + dispose?.() + dispose = undefined + tryRegister() + }) + const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) + tryRegister() + return () => { + offLocale() + unsubscribe() + dispose?.() + } + }, 'ui-settings: general section registration') } diff --git a/packages/client/ui-settings-general/src/client/locales.ts b/packages/client/ui-settings/src/client/locales.ts similarity index 64% rename from packages/client/ui-settings-general/src/client/locales.ts rename to packages/client/ui-settings/src/client/locales.ts index ff10ce5c37..6fc3295561 100644 --- a/packages/client/ui-settings-general/src/client/locales.ts +++ b/packages/client/ui-settings/src/client/locales.ts @@ -1,7 +1,9 @@ /** - * `settings.general` namespace dictionaries. Skeleton-row technical copy + * `settings` namespace dictionaries: shell chrome plus the shell-owned + * General section (nav label, skeleton rows). Skeleton-row technical copy * (Read only / Schema mode / Code mode and their descriptions) is shared - * verbatim across locales per the Figma design. + * verbatim across locales per the Figma design. Feature-owned rows + * (Language, Appearance) ship their copy in their own packages. */ import type { LocaleDict } from '@deepseek-ai/dsh-client-locale/client' @@ -16,27 +18,23 @@ const SHARED = { /** Simplified Chinese dictionary. */ export const zh: LocaleDict = { ...SHARED, - 'nav': '通用设置', + 'trigger': '设置', + 'title': '设置', + 'close': '关闭', + 'general.nav': '通用设置', 'permission.title': '权限', 'permission.desc': '选择默认权限模式', 'toolcall.title': '工具调用', - 'language.title': '语言', - 'appearance.title': '外观', - 'appearance.light': '浅色', - 'appearance.dark': '深色', - 'appearance.system': '跟随系统', } /** English dictionary. */ export const en: LocaleDict = { ...SHARED, - 'nav': 'General', + 'trigger': 'Settings', + 'title': 'Settings', + 'close': 'Close', + 'general.nav': 'General', 'permission.title': 'Permission', 'permission.desc': 'Choose default permission mode', 'toolcall.title': 'Tool Call', - 'language.title': 'Language', - 'appearance.title': 'Appearance', - 'appearance.light': 'Light', - 'appearance.dark': 'Dark', - 'appearance.system': 'System', } diff --git a/packages/client/ui-settings/tests/apply.spec.ts b/packages/client/ui-settings/tests/apply.spec.ts index a94406e4ce..95684404a1 100644 --- a/packages/client/ui-settings/tests/apply.spec.ts +++ b/packages/client/ui-settings/tests/apply.spec.ts @@ -4,8 +4,9 @@ import { describe, expect, it, vi } from 'vitest' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings/client' -import type { SettingsRootInjected } from '@deepseek-ai/dsh-client-ui-settings/client' +import type { GeneralSectionInjected, SettingsRootInjected } from '@deepseek-ai/dsh-client-ui-settings/client' import { SettingsRoot } from '../src/client/SettingsRoot.tsx' +import { GeneralSection } from '../src/client/GeneralSection.tsx' async function bench() { const ctx = new Context() @@ -77,11 +78,14 @@ describe('ui-settings apply', () => { declare(b.slots) await b.ctx.plugin({ inject: [...inject], apply }).await() const injected = injectedOf(b.slots) - expect(injected.sections()).toEqual([]) + // The shell ships its own General section (order 0) — the ledger is never + // empty once apply settles. + expect(injected.sections()).toEqual([{ id: 'general', order: 0, label: '通用设置' }]) b.slots.register({ name: 'settings.section', id: 'z', order: 20, label: 'Z' } as never, () => null) - b.slots.register({ name: 'settings.section', id: 'a' } as never, () => null) + b.slots.register({ name: 'settings.section', id: 'a', order: 5 } as never, () => null) expect(injected.sections()).toEqual([ - { id: 'a', order: 0, label: '' }, + { id: 'general', order: 0, label: '通用设置' }, + { id: 'a', order: 5, label: '' }, { id: 'z', order: 20, label: 'Z' }, ]) expect(injected.sectionsVersion()).toBe(b.slots.getVersion('settings.section')) @@ -118,3 +122,72 @@ describe('ui-settings apply', () => { expect(b.slots.spec('settings.section')).toBeUndefined() }) }) + +describe('ui-settings general section', () => { + it('registers the shell-owned General entry and declares the item slot', async () => { + const b = await bench() + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const entry = b.slots.entries('settings.section')[0]! + expect(entry.component).toBe(GeneralSection) + expect(entry.options).toEqual({ id: 'general', order: 0, label: '通用设置' }) + expect(b.slots.spec('settings.general.item')).toEqual({ kind: 'list', scope: 'root' }) + const injected = (entry.inject as () => GeneralSectionInjected)() + expect(injected.t('permission.title')).toBe('权限') + }) + + it('re-registers with fresh label text on locale change', async () => { + const b = await bench() + declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + b.locale.setLocale('en') + expect(b.slots.entries('settings.section')[0]!.options.label).toBe('General') + b.locale.setLocale('zh') + expect(b.slots.entries('settings.section')[0]!.options.label).toBe('通用设置') + }) + + it('locale change while settings.section is undeclared stays a no-op', async () => { + const b = await bench() + // No sidebar.settings declaration: the shell never registers, so + // settings.section is never declared either. + await b.ctx.plugin({ inject: [...inject], apply }).await() + b.locale.setLocale('en') + expect(b.slots.entries('settings.section')).toHaveLength(0) + b.locale.setLocale('zh') + }) + + it('re-registers after an HMR collapse of the whole chain (stale disposer must not block)', async () => { + const b = await bench() + const redeclare = declare(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries('settings.section')).toHaveLength(1) + // Root declarer unload: the cascade removes the shell entry, the + // settings.section declaration, and the General entry below it. + redeclare() + expect(b.slots.entries('settings.section')).toHaveLength(0) + expect(b.slots.spec('settings.general.item')).toBeUndefined() + declare(b.slots) + // Two deferral hops: the shell re-registers (re-declaring + // settings.section), then General re-registers into it. + await Promise.resolve() + await Promise.resolve() + const entry = b.slots.entries('settings.section')[0]! + expect(entry.component).toBe(GeneralSection) + expect(b.slots.spec('settings.general.item')).toEqual({ kind: 'list', scope: 'root' }) + // The recovered registration still rides the locale path. + b.locale.setLocale('en') + expect(b.slots.entries('settings.section')[0]!.options.label).toBe('General') + b.locale.setLocale('zh') + }) + + it('removes the General entry and its item declaration on teardown', async () => { + const b = await bench() + declare(b.slots) + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(b.slots.spec('settings.general.item')).toBeDefined() + await fiber.dispose() + expect(b.slots.entries('settings.section')).toHaveLength(0) + expect(b.slots.spec('settings.general.item')).toBeUndefined() + }) +}) diff --git a/packages/client/ui-settings/tests/general-section.spec.tsx b/packages/client/ui-settings/tests/general-section.spec.tsx new file mode 100644 index 0000000000..a944dd8b15 --- /dev/null +++ b/packages/client/ui-settings/tests/general-section.spec.tsx @@ -0,0 +1,47 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import type { GeneralSectionComponentProps } from '../src/client/contract/slots.ts' +import { GeneralSection } from '../src/client/GeneralSection.tsx' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) + +function mount() { + const renderSlot = vi.fn( + ((key: string) =>
) as GeneralSectionComponentProps['renderSlot'], + ) + const props: GeneralSectionComponentProps = { + t: (key) => en[key] ?? key, + renderSlot, + } + const view = render() + return { view, renderSlot } +} + +describe('GeneralSection', () => { + it('renders the Permission skeleton row with the disabled selector', () => { + mount() + expect(screen.getByText('Permission')).toBeTruthy() + expect(screen.getByText('Choose default permission mode')).toBeTruthy() + const selector = screen.getByRole('button', { name: /Read only/ }) as HTMLButtonElement + expect(selector.disabled).toBe(true) + }) + + it('renders the Tool Call skeleton cubes with schema pinned selected', () => { + mount() + expect(screen.getByText('Tool Call')).toBeTruthy() + const schema = screen.getByText('Schema mode') + const code = screen.getByText('Code mode') + expect(schema.parentElement!.className).toContain('selected') + expect(code.parentElement!.className).not.toContain('selected') + expect(screen.getByText('Traditional function calling — invoke tools one at a time')).toBeTruthy() + expect(screen.getByText('Chain multiple tools with code — multi-step orchestration')).toBeTruthy() + }) + + it('renders the feature-contributed item slot after the skeleton rows', () => { + const { renderSlot } = mount() + expect(renderSlot).toHaveBeenCalledWith('settings.general.item', {}) + expect(screen.getByTestId('slot-settings.general.item')).toBeTruthy() + }) +}) diff --git a/packages/client/ui-theme/package.json b/packages/client/ui-theme/package.json index 4c6ad92cd4..e60289b52d 100644 --- a/packages/client/ui-theme/package.json +++ b/packages/client/ui-theme/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-theme", - "description": "Theme plugin: ThemeService (light/dark/system preference, prefers-color-scheme resolution, theme/change snapshots; no DOM), --dsw-* token base stylesheets", + "description": "Theme plugin: ThemeService (light/dark/system preference, prefers-color-scheme resolution, theme/change snapshots; no DOM), --dsw-* token base stylesheets; registers the Appearance settings row", "version": "0.0.1", "private": true, "type": "module", @@ -24,18 +24,32 @@ "./package.json": "./package.json" }, "dshClient": { - "inject": [], + "inject": [ + "@deepseek-ai/dsh-client-runtime", + "@deepseek-ai/dsh-client-locale" + ], "platform": "web", "immediately": true }, "license": "BSD-3-Clause", "peerDependencies": { + "@deepseek-ai/dsh-client-locale": "^0.0.1", + "@deepseek-ai/dsh-client-runtime": "^0.0.1", + "@deepseek-ai/dsh-client-ui-primitives": "^0.0.1", + "@deepseek-ai/dsh-client-ui-slots": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", - "cordis": "^4.0.0-rc.7" + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" }, "devDependencies": { + "@deepseek-ai/dsh-client-locale": "workspace:^", + "@deepseek-ai/dsh-client-runtime": "workspace:^", + "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", + "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", - "cordis": "^4.0.0-rc.7" + "@types/react": "~18.3.1", + "cordis": "^4.0.0-rc.7", + "react": "^18.2.0" }, "files": [ "lib/index.js", @@ -48,5 +62,8 @@ "scripts": { "bundle": "tsdown", "watch": "tsdown --watch" + }, + "dependencies": { + "clsx": "^2.0.0" } } diff --git a/packages/client/ui-theme/src/client/AppearanceRow.module.css b/packages/client/ui-theme/src/client/AppearanceRow.module.css new file mode 100644 index 0000000000..9619caa823 --- /dev/null +++ b/packages/client/ui-theme/src/client/AppearanceRow.module.css @@ -0,0 +1,51 @@ +/* Appearance row (figma 'Frame 2117131228': title + cube row, column gap 8, + * pad 16/0, hairline separator; the section column strips it when last). */ + +.group { + display: flex; + flex-direction: column; + gap: 8px; + padding: 16px 0; + border-bottom: 1px solid var(--dsw-alias-border-l2); +} + +.title { + font-size: 14px; + font-weight: 400; + line-height: 22px; + color: var(--dsw-alias-label-primary); +} + +.cubeRow { + display: flex; + align-items: stretch; + gap: 8px; +} + +/* Appearance cube (figma '.Selector Cube' 276x82 r16, pad 20/32, centered + * icon-over-label column, gap 4). */ +.themeCube { + box-sizing: border-box; + width: 276px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 4px; + padding: 20px 32px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 16px; + background: transparent; + font: inherit; + font-size: 14px; + line-height: 22px; + color: var(--dsw-alias-label-primary); + cursor: pointer; +} + +/* Selected cube: #F5F6F7 fill + #ADB2B8 border (static token — the bluish-400 + * step has no alias-layer name). */ +.selected { + background: var(--dsw-alias-bg-module-platform); + border-color: var(--dsw-static-neutral-bluish-400); +} diff --git a/packages/client/ui-theme/src/client/AppearanceRow.tsx b/packages/client/ui-theme/src/client/AppearanceRow.tsx new file mode 100644 index 0000000000..b4aad1725d --- /dev/null +++ b/packages/client/ui-theme/src/client/AppearanceRow.tsx @@ -0,0 +1,63 @@ +/** + * Appearance preference row registered into the General section item slot + * (figma 501:30012 'Frame 2117131228'): title + three preference cubes. + * Registered by this package — the theme feature owns its own settings + * surface. Selection follows the persisted preference, never the resolved + * active theme. + */ +import clsx from 'clsx' +import { + IconDarkOutline16, IconFollowsystemOutline16, IconLightOutline16, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type { ThemePreference } from './index.ts' +import type {} from './settings-contract.ts' +import type { createAppearanceRowStore } from './settings-store.ts' +import css from './AppearanceRow.module.css' + +/** Injected business face: namespace-bound translate + the preference write. */ +export interface AppearanceRowInjected { + /** Translate a `settings.theme` dictionary key to the active-locale text. */ + t: (key: string) => string + /** Switch the theme preference. */ + setTheme: (id: ThemePreference) => void +} + +/** Full component props: runtime share + store share + injected face. */ +export type AppearanceRowComponentProps = + PropsRuntime<'settings.general.item'> & PropsStore> & AppearanceRowInjected + +/** Cube order and icons (figma 501:30015-30017: Light, Dark, System). */ +const CUBES: readonly { id: ThemePreference; labelKey: string; Icon: typeof IconLightOutline16 }[] = [ + { id: 'light', labelKey: 'appearance.light', Icon: IconLightOutline16 }, + { id: 'dark', labelKey: 'appearance.dark', Icon: IconDarkOutline16 }, + { id: 'system', labelKey: 'appearance.system', Icon: IconFollowsystemOutline16 }, +] + +/** + * Render the Appearance row. + * @param props - composed slot props. + * @returns the row element tree. + */ +export function AppearanceRow({ t, setTheme, useStore }: AppearanceRowComponentProps) { + const preference = useStore(s => s.preference) + return ( +
+
{t('appearance.title')}
+
+ {CUBES.map(({ id, labelKey, Icon }) => ( + + ))} +
+
+ ) +} diff --git a/packages/client/ui-theme/src/client/index.ts b/packages/client/ui-theme/src/client/index.ts index 5c7ca3fe12..ac79913062 100644 --- a/packages/client/ui-theme/src/client/index.ts +++ b/packages/client/ui-theme/src/client/index.ts @@ -2,9 +2,24 @@ * Browser theme registry over the `--dsw-*` token stylesheets. The service * owns the theme preference (light/dark/system), resolves `system` through * `prefers-color-scheme`, and publishes immutable snapshots; it never touches - * the DOM — ui-layout's presenter consumes the resolved snapshot. + * the DOM — ui-layout's presenter consumes the resolved snapshot. The plugin + * also registers the Appearance preference row into the settings General + * section — the theme feature owns its own settings surface. */ import type { Context } from 'cordis' +import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots' +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +// Type-only: pulls the locale plugin's Context merge (ctx.locale). +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type { AppearanceRowInjected } from './AppearanceRow.tsx' +import { AppearanceRow } from './AppearanceRow.tsx' +import { createAppearanceRowStore } from './settings-store.ts' + +export type { AppearanceRowComponentProps, AppearanceRowInjected } from './AppearanceRow.tsx' +export type { AppearanceRowState } from './settings-store.ts' + +/** Namespace owning this feature's settings-row copy. */ +export const SETTINGS_NS = 'settings.theme' /** Theme token dictionary: --dsw-alias-* overrides keyed by variable name. */ export type ThemeTokens = Record @@ -200,13 +215,75 @@ function persistPreference(preference: ThemePreference): void { } } -/** Required services (none; the loader passes the export surface as an object plugin). */ -export const inject: string[] = [] +/** Required services: slots + locale (the feature registers its own settings row with localized copy). */ +export const inject = ['slots', 'locale'] /** - * Client plugin body: provide the theme service. + * Client plugin body: provide the theme service and register the + * feature-owned Appearance preference row into the General section's item + * slot (a feature owns its settings surface). * @param ctx - client cordis context. */ -export function apply(ctx: Context): void { - ctx.provide('theme', new ThemeService(ctx)) +export function apply(ctx: ClientContext): void { + const theme = new ThemeService(ctx) + ctx.provide('theme', theme) + + ctx.effect(() => { + const disposers = [ + ctx.locale.register(SETTINGS_NS, 'zh', { + 'appearance.title': '外观', + 'appearance.light': '浅色', + 'appearance.dark': '深色', + 'appearance.system': '跟随系统', + }), + ctx.locale.register(SETTINGS_NS, 'en', { + 'appearance.title': 'Appearance', + 'appearance.light': 'Light', + 'appearance.dark': 'Dark', + 'appearance.system': 'System', + }), + ] + return () => { for (const dispose of disposers) dispose() } + }, 'ui-theme: settings row dictionaries') + + const store = createAppearanceRowStore() + let bound: BoundActions | undefined + const sync = (snapshot: ThemeSnapshot): void => { + bound?.sync(snapshot.preference, snapshot.revision) + } + ctx.on('theme/change', sync) + const injected = (actions: BoundActions): AppearanceRowInjected => { + bound = actions + // Re-sync from the getter so no event is lost between registration and + // first render (the store's revision guard drops stale duplicates). + sync(theme.getTheme()) + return { + t: ctx.locale.bind(SETTINGS_NS), + setTheme: (id) => { theme.setTheme(id) }, + } + } + // Declaration-aware registration; the LEDGER is the has-registered judge + // (not a local flag): after an HMR collapse re-declares the slot, the + // cascade already removed our entry, and a stale disposer must not block + // the re-registration. + ctx.effect(() => { + let dispose: (() => void) | undefined + const tryRegister = (): void => { + if (ctx.slots.spec('settings.general.item') === undefined) return + if (ctx.slots.entries('settings.general.item').some(e => e.component === AppearanceRow)) return + dispose = ctx.slots.register({ + name: 'settings.general.item', + id: 'appearance', + order: 10, + store, + inject: injected, + }, AppearanceRow) + } + const unsubscribe = ctx.slots.subscribe('settings.general.item', () => { tryRegister() }) + tryRegister() + return () => { + unsubscribe() + dispose?.() + } + }, 'ui-theme: appearance settings row registration') } diff --git a/packages/client/ui-theme/src/client/settings-contract.ts b/packages/client/ui-theme/src/client/settings-contract.ts new file mode 100644 index 0000000000..4354ca8728 --- /dev/null +++ b/packages/client/ui-theme/src/client/settings-contract.ts @@ -0,0 +1,17 @@ +/** + * Settings-surface slot merge consumed by this package's Appearance row. The + * AUTHORITATIVE home for 'settings.general.item' is the ui-settings contract + * (declaring is claiming: the shell's General entry declares the slot); this + * file repeats the entry verbatim because the settings shell sits above the + * feature layer, so importing its types from here would invert the layering. + * TypeScript declaration merging rejects diverging duplicates, so every + * program that sees both copies enforces identity. + */ +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** One preference row inside the General section (duplicate-identical merge; authority: ui-settings contract). */ + 'settings.general.item': { kind: 'list'; scope: 'root'; owner: { children?: never } } + } +} + +export {} diff --git a/packages/client/ui-theme/src/client/settings-store.ts b/packages/client/ui-theme/src/client/settings-store.ts new file mode 100644 index 0000000000..256b04a299 --- /dev/null +++ b/packages/client/ui-theme/src/client/settings-store.ts @@ -0,0 +1,37 @@ +/** + * Appearance row slot store: a mirror of the theme service snapshot. The + * plugin's apply-world change listener is the only writer; the row component + * reads via props.useStore. + */ +import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client' +import type { ThemePreference } from './index.ts' + +/** Store state mirrored from the theme snapshot. */ +export interface AppearanceRowState { + /** Persisted preference (selection state reads this, never the resolved active theme). */ + preference: ThemePreference + /** Service revision; -1 until first sync so revision 0 lands as a change. */ + revision: number +} + +/** Declared action shape giving the exported factory a stable return type. */ +type AppearanceRowActions = { + sync: (draft: AppearanceRowState, preference: ThemePreference, revision: number) => void +} + +/** + * Declares the Appearance row state and write surface. + * @returns the store handle. + */ +export function createAppearanceRowStore(): EngineStoreHandle { + return defineStore({ + init: (): AppearanceRowState => ({ preference: 'system', revision: -1 }), + actions: { + sync: (d, preference: ThemePreference, revision: number) => { + if (revision <= d.revision) return + d.preference = preference + d.revision = revision + }, + }, + }) +} diff --git a/packages/client/ui-theme/src/css-modules.d.ts b/packages/client/ui-theme/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-theme/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-theme/tests/invariant.spec.ts b/packages/client/ui-theme/tests/invariant.spec.ts index 6f4e867c4d..640599ea43 100644 --- a/packages/client/ui-theme/tests/invariant.spec.ts +++ b/packages/client/ui-theme/tests/invariant.spec.ts @@ -4,6 +4,8 @@ import { Context } from 'cordis' import { apply as nodeApply } from '@deepseek-ai/dsh-client-ui-theme' import { apply as clientApply, inject, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' import * as ThemeInvariant from '@deepseek-ai/dsh-client-ui-theme/invariant' +import { apply as localeApply } from '@deepseek-ai/dsh-client-locale/client' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' import InvariantService from '@deepseek-ai/dsh-invariants' describe('invariant companion', () => { @@ -18,9 +20,13 @@ describe('invariant companion', () => { expect(true).toBe(true) // reaching here without throw is the contract }) - it('client apply provides ctx.theme with no service prerequisites', async () => { - expect(inject).toEqual([]) + it('client apply provides ctx.theme over the slots/locale edges', async () => { + // The feature registers its own Appearance settings row with localized + // copy, hence the slots + locale edges. + expect(inject).toEqual(['slots', 'locale']) const ctx = new Context() + new SlotsService(ctx) + await ctx.plugin({ inject: ['slots'], apply: localeApply }).await() await ctx.plugin({ inject, apply: clientApply }).await() expect(ctx.get('theme')).toBeInstanceOf(ThemeService) }) diff --git a/packages/client/ui-theme/tsconfig.json b/packages/client/ui-theme/tsconfig.json index 51f9171643..7d5cc6f235 100644 --- a/packages/client/ui-theme/tsconfig.json +++ b/packages/client/ui-theme/tsconfig.json @@ -8,6 +8,18 @@ "src" ], "references": [ + { + "path": "../locale" + }, + { + "path": "../runtime" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-slots" + }, { "path": "../../../vendor/cordis" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2410252eb0..40fee92c16 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -140,18 +140,15 @@ importers: '@deepseek-ai/dsh-client-ui-layout': specifier: workspace:^ version: link:../../packages/client/ui-layout + '@deepseek-ai/dsh-client-ui-models': + specifier: workspace:^ + version: link:../../packages/client/ui-models '@deepseek-ai/dsh-client-ui-question': specifier: workspace:^ version: link:../../packages/client/ui-question '@deepseek-ai/dsh-client-ui-settings': specifier: workspace:^ version: link:../../packages/client/ui-settings - '@deepseek-ai/dsh-client-ui-settings-general': - specifier: workspace:^ - version: link:../../packages/client/ui-settings-general - '@deepseek-ai/dsh-client-ui-settings-models': - specifier: workspace:^ - version: link:../../packages/client/ui-settings-models '@deepseek-ai/dsh-client-ui-sidebar': specifier: workspace:^ version: link:../../packages/client/ui-sidebar @@ -750,13 +747,32 @@ importers: version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@vendor+loader) packages/client/locale: + dependencies: + clsx: + specifier: ^2.0.0 + version: 2.1.1 devDependencies: + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 cordis: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 packages/client/modules: devDependencies: @@ -865,6 +881,33 @@ importers: specifier: ^18.2.0 version: 18.3.1 + packages/client/ui-models: + devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-ui-settings': + specifier: workspace:^ + version: link:../ui-settings + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 + packages/client/ui-primitives: dependencies: clsx: @@ -979,70 +1022,6 @@ importers: specifier: ^18.2.0 version: 18.3.1 - packages/client/ui-settings-general: - dependencies: - clsx: - specifier: ^2.0.0 - version: 2.1.1 - devDependencies: - '@deepseek-ai/dsh-client-locale': - specifier: workspace:^ - version: link:../locale - '@deepseek-ai/dsh-client-runtime': - specifier: workspace:^ - version: link:../runtime - '@deepseek-ai/dsh-client-ui-primitives': - specifier: workspace:^ - version: link:../ui-primitives - '@deepseek-ai/dsh-client-ui-settings': - specifier: workspace:^ - version: link:../ui-settings - '@deepseek-ai/dsh-client-ui-slots': - specifier: workspace:^ - version: link:../ui-slots - '@deepseek-ai/dsh-client-ui-theme': - specifier: workspace:^ - version: link:../ui-theme - '@deepseek-ai/dsh-invariants': - specifier: workspace:^ - version: link:../../support/invariants - '@types/react': - specifier: ~18.3.1 - version: 18.3.31 - cordis: - specifier: ^4.0.0-rc.7 - version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) - react: - specifier: ^18.2.0 - version: 18.3.1 - - packages/client/ui-settings-models: - devDependencies: - '@deepseek-ai/dsh-client-locale': - specifier: workspace:^ - version: link:../locale - '@deepseek-ai/dsh-client-runtime': - specifier: workspace:^ - version: link:../runtime - '@deepseek-ai/dsh-client-ui-settings': - specifier: workspace:^ - version: link:../ui-settings - '@deepseek-ai/dsh-client-ui-slots': - specifier: workspace:^ - version: link:../ui-slots - '@deepseek-ai/dsh-invariants': - specifier: workspace:^ - version: link:../../support/invariants - '@types/react': - specifier: ~18.3.1 - version: 18.3.31 - cordis: - specifier: ^4.0.0-rc.7 - version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) - react: - specifier: ^18.2.0 - version: 18.3.1 - packages/client/ui-sidebar: dependencies: clsx: @@ -1087,13 +1066,35 @@ importers: version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) packages/client/ui-theme: + dependencies: + clsx: + specifier: ^2.0.0 + version: 2.1.1 devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../runtime + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../ui-slots '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 cordis: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 packages/client/ui-trajectory: devDependencies: diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index cb8ebb6a48..91554c5c5c 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -60,8 +60,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-workspace': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-theme': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-settings': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, - 'packages/client/ui-settings-general': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, - 'packages/client/ui-settings-models': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, + 'packages/client/ui-models': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/locale': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/web': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/examples/agent-spine-demo': { kind: 'indirect', reason: 'The bundle only mounts model-facing child plugins.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 81e0fc989c..49a502571e 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -116,8 +116,7 @@ "@deepseek-ai/dsh-client-ui-workspace": ["./packages/client/ui-workspace/src"], "@deepseek-ai/dsh-client-ui-theme": ["./packages/client/ui-theme/src"], "@deepseek-ai/dsh-client-ui-settings": ["./packages/client/ui-settings/src"], - "@deepseek-ai/dsh-client-ui-settings-general": ["./packages/client/ui-settings-general/src"], - "@deepseek-ai/dsh-client-ui-settings-models": ["./packages/client/ui-settings-models/src"], + "@deepseek-ai/dsh-client-ui-models": ["./packages/client/ui-models/src"], "@deepseek-ai/dsh-client-locale": ["./packages/client/locale/src"], "@deepseek-ai/dsh-client-web": ["./packages/client/web/src"], "@deepseek-ai/dsh-*": [ diff --git a/tsconfig.client.json b/tsconfig.client.json index abe80b8b12..55ff2d9a8c 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -39,8 +39,7 @@ { "path": "./packages/client/ui-trajectory" }, { "path": "./packages/client/ui-theme" }, { "path": "./packages/client/ui-settings" }, - { "path": "./packages/client/ui-settings-general" }, - { "path": "./packages/client/ui-settings-models" }, + { "path": "./packages/client/ui-models" }, { "path": "./packages/client/locale" }, { "path": "./packages/client/web" }, { "path": "./apps/web" } From 6ce5628bb140a40f5540eac2cbcc821ed8822cf5 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:51:48 +0800 Subject: [PATCH 098/113] docs: tighten PR guidance --- AGENTS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 63957cca16..ad79a04b10 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -111,7 +111,7 @@ Real-API tests and demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, - **Testing policy** — [docs/testing.md](docs/testing.md). Every non-trivial model- or product-user-visible behavior change adds or updates a keyless snapshot through a real runnable example in the same PR; package tests, e2e-only assertions, and mock-only fixtures do not substitute for the assembled application transcript. Fixtures must replay on macOS/Linux; fix fixtures, not normalizers. - **A tool's UI render intent is part of its design**, decided up front (`generic`/`terminal`/`diff`, `locations`); presentation methods are pure functions of `args` ([cookbook](docs/cookbook/adding-a-tool.md)). - **Plan unit, e2e, and snapshot coverage** for new seams, lifecycle shapes, and transcript surfaces; missing snapshot-harness support is part of the implementation, not deferred follow-up. -- **Keep PRs coherent and merge with merge commits.** Split an independently meaningful feature or design decision into a separate or stacked PR when combining it obscures ownership, intent, or verification. Never squash/rebase or rewrite pushed branches; put a review fix on its introducing PR, then merge down the stack ([guide](docs/cookbook/responding-to-pr-review-on-a-stack.md)). +- **Keep PRs coherent; use merge commits.** Split independent features or design decisions when combining them obscures ownership, intent, or verification. Never squash, rebase, or rewrite pushed branches; fix the introducing PR, then merge down its stack ([guide](docs/cookbook/responding-to-pr-review-on-a-stack.md)). - **Label PRs:** exactly one kind (`feature`/`bug-fix`/`doc`/`testing`/`cleanup`), all matching areas; the taxonomy remains extensible for recurring distinctions. - TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)). - Files end with exactly one trailing newline; `git diff --cached --check` (pre-commit) gates it. From f2cf29bd04596c450b6c05ceba1df490d2ba7537 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:52:48 +0800 Subject: [PATCH 099/113] docs: deduplicate paired code-block checks --- ...-20-core-data-structures-catalog.i18n.yaml | 4 +- ...2026-06-20-core-data-structures-catalog.md | 2 +- ...6-06-20-core-data-structures-catalog.zh.md | 2 +- ...-bilingual-docs-and-pairing-gate.i18n.yaml | 4 +- ...6-07-02-bilingual-docs-and-pairing-gate.md | 2 +- ...7-02-bilingual-docs-and-pairing-gate.zh.md | 2 +- docs/development.i18n.yaml | 4 +- docs/development.md | 2 +- docs/development.zh.md | 2 +- docs/i18n/README.i18n.yaml | 4 +- docs/i18n/README.md | 2 + docs/i18n/README.zh.md | 2 + scripts/doc-typecheck.ts | 13 +- scripts/paired-markdown-derivatives.spec.ts | 66 ++ scripts/paired-markdown-derivatives.ts | 63 ++ .../request-response.expected.json | 12 +- scripts/type-equiv.manifest.json | 945 +----------------- scripts/verify-type-equiv.ts | 15 +- 18 files changed, 175 insertions(+), 971 deletions(-) create mode 100644 scripts/paired-markdown-derivatives.spec.ts create mode 100644 scripts/paired-markdown-derivatives.ts diff --git a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.i18n.yaml b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.i18n.yaml index f59c523dce..0149872c3c 100644 --- a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.i18n.yaml +++ b/.agents/notes/implemented/process/2026-06-20-core-data-structures-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 -2026-06-20-core-data-structures-catalog.md: d7e9d3d9b14fe723e3396c8167fe714b7613e2b5 -2026-06-20-core-data-structures-catalog.zh.md: 8d2f16a46216cba8df0539be0abd2f1ad840eec3 +2026-06-20-core-data-structures-catalog.md: ef100f96b06c454cfd1ec092cc7fd23e712bdf7a +2026-06-20-core-data-structures-catalog.zh.md: 4ace2b8c8a6b08e7721c1df8003ccfbdb128daf1 diff --git a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md index d7e9d3d9b1..ef100f96b0 100644 --- a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md +++ b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.md @@ -33,7 +33,7 @@ The durability requirement was specific: the doc shows the **literal** current t - Complete type declarations and their JSDoc are pasted verbatim into a dedicated ` ```ts type-equiv ` fence. A concise ` ```ts public-api ` fence carries the source-equivalent ambient projection for a class whose implementation bodies do not belong in the catalog. `doc-typecheck` recognizes both and skips them (the bare declarations are not standalone-compilable), and **excludes them from the opt-out ratio** — they are a separately-checked category, not unchecked sketches. - A new `scripts/verify-type-equiv.ts` extracts each block via the TypeScript parser and asserts that its declaration structure and every JSDoc comment match the declared symbol, ignoring only formatting whitespace and non-JSDoc comments. Ordinary blocks retain the complete declaration. A `public-api` projection retains a class's public fields, constructor, accessors, and methods with their original JSDoc while removing implementation bodies and private or protected members. This is chosen over a compiled `_Check` assertion because source names and documentation identity, not assignability, are the properties the catalog preserves. -- Provenance lives in a central `scripts/type-equiv.manifest.json` (`{ doc, symbol, source }` entries), **not** in directive comments in the prose. The script enforces a **1:1 correspondence**: every type-equiv block has exactly one manifest entry and vice versa, so a block can never be silently unchecked and an entry can never rot. +- Provenance lives in a central `scripts/type-equiv.manifest.json` (`{ doc, symbol, source }` entries), **not** in directive comments in the prose. The script enforces a **1:1 correspondence** between each primary type-equiv block and one manifest entry, so a block can never be silently unchecked and an entry can never rot. A paired `.zh.md` block reuses the unsuffixed sibling's entry only when the complete tracked fence sequence matches in order, kind, and byte-exact body; otherwise the gate checks it independently, finds no manifest entry, and fails. - Wired into `doc-sync`, so relevant documentation changes run it locally and CI runs it with the other documentation checks. ### Maintenance is the author's job, with a gate backstop diff --git a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.zh.md b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.zh.md index 8d2f16a462..4ace2b8c8a 100644 --- a/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.zh.md +++ b/.agents/notes/implemented/process/2026-06-20-core-data-structures-catalog.zh.md @@ -33,7 +33,7 @@ Status: implemented - 完整的类型声明及其 JSDoc 会逐字粘贴到专用的 ` ```ts type-equiv ` 围栏中。简洁的 ` ```ts public-api ` 围栏承载与源码等价的类环境投影,用于实现体不应进入目录的类。`doc-typecheck` 会识别并跳过这两种围栏(裸声明无法独立编译),并且**将它们排除在 opt-out 比例之外**——它们是单独受检的类别,而不是未经检查的草图。 - 新增的 `scripts/verify-type-equiv.ts` 通过 TypeScript 解析器提取每个块,并断言其声明结构和每条 JSDoc 注释都与所声明的符号匹配,只忽略格式空白和非 JSDoc 注释。普通块保留完整声明。`public-api` 投影保留类的公共字段、构造函数、访问器和方法及其原始 JSDoc,同时移除实现体以及私有或受保护成员。之所以选择它而非编译式 `_Check` 断言,是因为目录所保留的是源码名称与文档一致性,而不是可赋值性。 -- 来源信息存放在集中的 `scripts/type-equiv.manifest.json`(`{ doc, symbol, source }` 条目)中,**而非**行文中的指令注释。脚本强制执行 **1:1 对应**:每个 type-equiv 块恰好有一条 manifest 条目,反之亦然;因此一个块永远不会被静默漏检,一条条目也永远不会腐烂。 +- 来源信息存放在集中的 `scripts/type-equiv.manifest.json`(`{ doc, symbol, source }` 条目)中,**而非**行文中的指令注释。脚本在每个主 type-equiv 块与一条 manifest 条目之间强制执行 **1:1 对应**,因此一个块永远不会被静默漏检,一条条目也永远不会腐烂。只有当配对 `.zh.md` 块的完整受跟踪围栏序列在顺序、类型和按字节精确的正文上均与无后缀兄弟文件匹配时,才会复用后者的条目;否则门禁会独立检查该块,发现没有 manifest 条目后失败。 - 接入 `doc-sync`,因此相关文档变更会在本地运行它,CI 也会与其他文档检查一起运行它。 ### 维护是作者的职责,门禁作为兜底 diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml index c3430eb57d..7b523ab8b4 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.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 -2026-07-02-bilingual-docs-and-pairing-gate.md: 08e149ccc2342695d6dae4f1845896def6bf4388 -2026-07-02-bilingual-docs-and-pairing-gate.zh.md: 91f25f33c20337ea688257829552795085e0a8c0 +2026-07-02-bilingual-docs-and-pairing-gate.md: ece3ccc183893a85335a36eb9b00cb42d32a1a37 +2026-07-02-bilingual-docs-and-pairing-gate.zh.md: dc8c648cc4ce9dd7739383c620ee2b1c3794f2ee diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md index 08e149ccc2..ece3ccc183 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md @@ -12,7 +12,7 @@ This repo's README and docs tree are read by people and agents inside and outsid - **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md). - **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR. -- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot. +- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot. Source-oriented code gates consume a `.zh.md` fence sequence as a derivative only when its unsuffixed sibling has the same tracked fences in the same order with byte-identical bodies; an incomplete, reordered, reclassified, or changed sequence stays independent, so the owning code gate or pairing gate reports the mismatch. - **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it. - **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration. - **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent. diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md index 91f25f33c2..dc8c648cc4 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md @@ -12,7 +12,7 @@ Status: implemented - **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。 - **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。 -- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。 +- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。只有当 `.zh.md` 围栏序列与其无后缀兄弟文件拥有顺序相同、正文按字节一致的同一组受跟踪围栏时,面向源码的代码门禁才会将其作为派生内容消费;不完整、顺序变更、重分类或已改动的序列仍会独立受检,因此由其所属的代码门禁或配对门禁报告不匹配。 - **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。 - **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。 - **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。 diff --git a/docs/development.i18n.yaml b/docs/development.i18n.yaml index 9d2573305e..db97881ae8 100644 --- a/docs/development.i18n.yaml +++ b/docs/development.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 -development.md: f706d54764bbf79d1f13ccb4c412e7b5717b1edb -development.zh.md: 15f5ae0c514ac412c302a99cb0a662acce510c44 +development.md: c46d84740e6f0a1f67158f39f9ea421cb57165d4 +development.zh.md: 9e13ab258e1db5406f84ece61959a995110578ae diff --git a/docs/development.md b/docs/development.md index f706d54764..c46d84740e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -166,7 +166,7 @@ The [core data structures](core-data-structures/core.md) docs paste source-equiv { "doc": "docs/core-data-structures/session.md", "symbol": "SessionEvent", "source": "packages/core/session/src/types.ts" } ``` -`pnpm run verify-type-equiv` (part of `doc-sync`) then extracts that symbol's declaration and attached JSDoc from source via the TypeScript parser and asserts the block matches both. For a class whose implementation bodies do not belong in the catalog, use ` ```ts public-api ` and set `"projection": "public-api"`; the checked projection retains the public fields, constructor, accessors, methods, and original class/member JSDoc while omitting bodies and private or protected members. Comparison ignores whitespace and non-JSDoc comments but requires every original JSDoc comment, including member documentation, so readers see the source contract beside the exact shape. The gate also enforces a 1:1 correspondence by document, symbol, and projection, so a block can't go silently unchecked and a stale entry can't linger. `doc-typecheck` skips both fence kinds (they aren't standalone-compilable) and excludes them from its opt-out ratio. When you change a documented declaration or its JSDoc, the gate fails until you update the paste; when you add or remove a block, update the manifest in the same change. +`pnpm run verify-type-equiv` (part of `doc-sync`) then extracts that symbol's declaration and attached JSDoc from source via the TypeScript parser and asserts the block matches both. For a class whose implementation bodies do not belong in the catalog, use ` ```ts public-api ` and set `"projection": "public-api"`; the checked projection retains the public fields, constructor, accessors, methods, and original class/member JSDoc while omitting bodies and private or protected members. Comparison ignores whitespace and non-JSDoc comments but requires every original JSDoc comment, including member documentation, so readers see the source contract beside the exact shape. The gate enforces a 1:1 correspondence by document, symbol, and projection between primary blocks and manifest entries; a paired `.zh.md` block reuses its unsuffixed sibling's entry only when the whole tracked fence sequence is byte-identical and ordered identically. `doc-typecheck` applies the same derivative rule to compilable fences, while skipping both source-equivalence fence kinds from compilation and its opt-out ratio. When you change a documented declaration or its JSDoc, the gate fails until you update the paste; when you add or remove a primary block, update the manifest in the same change. ## Architecture context diff --git a/docs/development.zh.md b/docs/development.zh.md index 15f5ae0c51..9e13ab258e 100644 --- a/docs/development.zh.md +++ b/docs/development.zh.md @@ -166,7 +166,7 @@ pnpm run demo:acp { "doc": "docs/core-data-structures/session.md", "symbol": "SessionEvent", "source": "packages/core/session/src/types.ts" } ``` -`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `"projection": "public-api"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码契约和确切形状。该门禁还按文档、符号和投影强制 1:1 对应,因此不会有块被静默漏检,也不会有陈旧条目滞留。`doc-typecheck` 跳过两种围栏(它们不能独立编译),并将其排除在 opt-out 比例之外。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个块时,请在同一个变更里更新 manifest。 +`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `"projection": "public-api"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码契约和确切形状。该门禁按文档、符号和投影,在主块与 manifest 条目之间强制 1:1 对应;只有当配对 `.zh.md` 块的完整受跟踪围栏序列与其无后缀兄弟文件按字节一致且顺序相同时,才会复用后者的条目。`doc-typecheck` 对可编译围栏应用同一派生规则,同时跳过两种源码等价围栏的编译,并将其排除在 opt-out 比例之外。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个主块时,请在同一个变更里更新 manifest。 ## 架构上下文 diff --git a/docs/i18n/README.i18n.yaml b/docs/i18n/README.i18n.yaml index 02f6151e29..b0d5a550df 100644 --- a/docs/i18n/README.i18n.yaml +++ b/docs/i18n/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 -README.md: a60572b0691702c949b44b82a7b1d732a888ed93 -README.zh.md: 04ae032233dfa01c145b5d6bdbe7353a366e11f1 +README.md: 053453bc622f58083a5e0e2992f1b8a820e3f3f9 +README.zh.md: 7f6242e8ff2a3ec69e2b84402dab447297047991 diff --git a/docs/i18n/README.md b/docs/i18n/README.md index a60572b069..053453bc62 100644 --- a/docs/i18n/README.md +++ b/docs/i18n/README.md @@ -28,6 +28,8 @@ This repo's documentation is read by people and agents both inside and outside t 3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all. 4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth. +Source-oriented code gates consume an exact `.zh.md` fence sequence as a derivative of its unsuffixed sibling instead of compiling or manifesting the same code twice. The sequence must match in length, order, fence kind, and byte-exact body; otherwise both copies remain independently checked and the pairing gate reports the structural mismatch. + `pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports. The practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI. diff --git a/docs/i18n/README.zh.md b/docs/i18n/README.zh.md index 04ae032233..7f6242e8ff 100644 --- a/docs/i18n/README.zh.md +++ b/docs/i18n/README.zh.md @@ -28,6 +28,8 @@ 3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。 4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。 +面向源码的代码门禁会把精确的 `.zh.md` 围栏序列视为其无后缀兄弟文件的派生内容,而不会再次编译相同代码或在 manifest 中重复登记。该序列必须在长度、顺序、围栏类型和按字节精确的正文上一致;否则两份副本仍会独立受检,配对门禁也会报告结构不匹配。 + `pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。 这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。 diff --git a/scripts/doc-typecheck.ts b/scripts/doc-typecheck.ts index 9a9e007758..69b9d67411 100644 --- a/scripts/doc-typecheck.ts +++ b/scripts/doc-typecheck.ts @@ -1,7 +1,8 @@ /** * Typecheck Markdown `ts` fences against the workspace API. `ignore-check` fences are reported as * opt-outs; generated catalog fragments and source-equivalence blocks are skipped here because their - * owning gates verify them. A build-coordinated mode consumes existing declarations without emit. + * owning gates verify them. Byte-identical `.zh.md` copies reuse their unsuffixed sibling's check. A + * build-coordinated mode consumes existing declarations without emit. */ import { execFileSync } from 'node:child_process' @@ -10,6 +11,7 @@ import { join, relative, resolve } from 'node:path' import ts from 'typescript' import { builtDeclarationPath } from './doc-typecheck-paths.ts' import { extractFences } from './md-fences.ts' +import { partitionPairedMarkdownDerivatives } from './paired-markdown-derivatives.ts' const root = resolve(import.meta.dirname, '..') @@ -206,7 +208,12 @@ for (const pattern of markdownGlobs) { } files.sort() -const all = files.flatMap(extractBlocks) +const extracted = files.flatMap(extractBlocks) +const { primary: all, derivatives } = partitionPairedMarkdownDerivatives( + extracted, + block => block.file, + block => `${block.kind}\0${block.code}`, +) const checked = all.filter(b => b.kind === 'check') const ignored = all.filter(b => b.kind === 'ignore') // Only compile-eligible fences belong in the opt-out ratio; every other skipped @@ -233,7 +240,7 @@ if (compilationError !== undefined) { const ratio = ignored.length / ratioDenominator const skipped = all.length - ratioDenominator -console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere).`) +console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere), ${derivatives.length} paired derivative(s).`) // Guard against the escape hatch becoming the norm. if (ratioDenominator >= 4 && ratio > 0.5) { console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`) diff --git a/scripts/paired-markdown-derivatives.spec.ts b/scripts/paired-markdown-derivatives.spec.ts new file mode 100644 index 0000000000..f5882e007f --- /dev/null +++ b/scripts/paired-markdown-derivatives.spec.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import { partitionPairedMarkdownDerivatives } from './paired-markdown-derivatives.ts' + +interface Block { + doc: string + kind: string + code: string +} + +const partition = (blocks: Block[]) => partitionPairedMarkdownDerivatives( + blocks, + block => block.doc, + block => `${block.kind}\0${block.code}`, +) + +describe('partitionPairedMarkdownDerivatives', () => { + it('treats a complete byte-identical Chinese sequence as derivative', () => { + const english = [ + { doc: 'docs/example.md', kind: 'ts', code: 'const one = 1' }, + { doc: 'docs/example.md', kind: 'type-equiv', code: 'interface Example {}' }, + ] + const chinese = english.map(block => ({ ...block, doc: 'docs/example.zh.md' })) + const unrelated = { doc: 'docs/other.md', kind: 'ts', code: 'const other = 2' } + + expect(partition([...english, ...chinese, unrelated])).toEqual({ + primary: [...english, unrelated], + derivatives: chinese, + }) + }) + + it('keeps reordered, changed, partial, and orphan Chinese sequences primary', () => { + const sequence = (doc: string) => [ + { doc, kind: 'ts', code: 'const one = 1' }, + { doc, kind: 'ts', code: 'const two = 2' }, + ] + const english = sequence('docs/example.md') + const changed = english.map((block, index) => ({ + ...block, + doc: 'docs/example.zh.md', + code: index === 0 ? 'const one = 0' : block.code, + })) + const reorderedEnglish = sequence('docs/reordered.md') + const reordered = [...reorderedEnglish].reverse().map(block => ({ ...block, doc: 'docs/reordered.zh.md' })) + const partialEnglish = sequence('docs/partial.md') + const partial = [{ ...partialEnglish[0]!, doc: 'docs/partial.zh.md' }] + const orphan = [{ doc: 'docs/orphan.zh.md', kind: 'ts', code: 'const orphan = true' }] + const blocks = [ + ...english, + ...changed, + ...reorderedEnglish, + ...reordered, + ...partialEnglish, + ...partial, + ...orphan, + ] + + expect(partition(blocks)).toEqual({ primary: blocks, derivatives: [] }) + }) + + it('requires the fence kind to match as well as the body', () => { + const english = { doc: 'docs/example.md', kind: 'type-equiv', code: 'interface Example {}' } + const chinese = { ...english, doc: 'docs/example.zh.md', kind: 'public-api' } + + expect(partition([english, chinese])).toEqual({ primary: [english, chinese], derivatives: [] }) + }) +}) diff --git a/scripts/paired-markdown-derivatives.ts b/scripts/paired-markdown-derivatives.ts new file mode 100644 index 0000000000..ead0c06923 --- /dev/null +++ b/scripts/paired-markdown-derivatives.ts @@ -0,0 +1,63 @@ +/** + * Separate byte-identical Chinese Markdown code blocks from the primary checks + * performed on their unsuffixed English siblings. The bilingual pairing gate + * owns cross-language identity; source-oriented gates consume one copy. + */ + +/** The result of separating canonical blocks from paired Chinese derivatives. */ +export interface MarkdownDerivativePartition { + /** Blocks that still require the caller's owning check. */ + primary: T[] + /** Chinese blocks covered by the byte-identical unsuffixed sequence. */ + derivatives: T[] +} + +/** Return the unsuffixed sibling of a Chinese Markdown path. */ +function unsuffixedSibling(doc: string): string | null { + return doc.endsWith('.zh.md') ? `${doc.slice(0, -'.zh.md'.length)}.md` : null +} + +/** + * Partition complete byte-identical `.zh.md` block sequences from primary + * blocks. A partial or reordered match stays primary so the caller fails + * closed; the translation-pairing gate reports the cross-language mismatch. + * + * @param blocks - Blocks in repository scan order. + * @param docOf - Repository-relative Markdown path owning a block. + * @param fingerprintOf - Block kind/info string plus byte-exact body. + * @returns Primary blocks and paired Chinese derivatives, preserving order. + */ +export function partitionPairedMarkdownDerivatives( + blocks: readonly T[], + docOf: (block: T) => string, + fingerprintOf: (block: T) => string, +): MarkdownDerivativePartition { + const byDoc = new Map() + for (const block of blocks) { + const doc = docOf(block) + const group = byDoc.get(doc) + if (group) group.push(block) + else byDoc.set(doc, [block]) + } + + const derivativeDocs = new Set() + for (const [doc, candidates] of byDoc) { + const sibling = unsuffixedSibling(doc) + if (sibling === null) continue + const originals = byDoc.get(sibling) + if (originals === undefined || originals.length !== candidates.length) continue + if (candidates.every((candidate, index) => { + const original = originals[index] + return original !== undefined && fingerprintOf(candidate) === fingerprintOf(original) + })) { + derivativeDocs.add(doc) + } + } + + const primary: T[] = [] + const derivatives: T[] = [] + for (const block of blocks) { + (derivativeDocs.has(docOf(block)) ? derivatives : primary).push(block) + } + return { primary, derivatives } +} diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index bc5355b931..36a701f376 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -16,19 +16,19 @@ }, { "role": "user", - "content": "# Development guide\n\nEnglish | [中文](development.zh.md)\n\nThis onboarding guide helps project contributors get started with the local environment, daily workflow, and CI flow; see the Agent Notes for design rationale and technical trade-offs.\n\n## Prerequisites\n\n- Node.js supports 22.19+ and 24+. CI covers 22.19, 24, and 26; see the [Node engine floor Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md).\n- Corepack-enabled pnpm. The repo pins `pnpm@11.7.0` in `package.json`; run `corepack enable` if `pnpm --version` does not resolve through Corepack.\n- Git.\n- Optional: a DeepSeek API key for the TUI, headless, and ACP automation demos and real-API e2e tests.\n\n## First-time setup\n\nInstall dependencies from the repo root:\n\n```sh\npnpm install\n```\n\nThe install also runs the root `postinstall` script, which installs lefthook from the repo dev dependency through `scripts/install-lefthook.mjs`; the wrapper script uses lefthook's reviewed `--force` mode so linked worktrees with an existing `core.hooksPath` do not fail normal `pnpm run …` commands.\n\nIf hooks are missing because dependencies were restored from cache or `postinstall` was skipped, install them manually:\n\n```sh\npnpm exec lefthook install --force\n```\n\nRun typecheck once after a fresh clone:\n\n```sh\npnpm run typecheck\n```\n\nThat first typecheck runs the whole-repo `tsc -b` graph: it emits every package/vendor `lib/types` and checks examples, tests, and scripts through the two no-emit aggregates described below.\n\n## TypeScript project layout\n\nThe repository's TypeScript configuration has exactly three roles; every tsconfig file plays one of them.\n\n| File | Role | Forms a program? |\n|---|---|---|\n| `tsconfig.json` | Solution root: `extends` base, `files: []`, references to the two aggregates. The whole-repo `tsc -b tsconfig.json` graph, the tsserver discovery entry, and — through the inherited `paths` — the resolution config for tsx running `examples/` and `scripts/` (their nearest tsconfig is this file). | No |\n| `tsconfig.host.json` | Host aggregate: host-side packages (via references), examples, tests, scripts, website. Excludes `packages/client`. | Yes |\n| `tsconfig.client.json` | Client aggregate: `packages/client/*` packages and their tests, `apps/web`. | Yes |\n| `tsconfig.base.json` | Shared compilerOptions and the source `paths` map. Also the resolution facade the vitest configs point vite-tsconfig-paths at: it has no `include`, so its `paths` apply to every importer. | No |\n| `tsconfig.base.client.json` | Browser compiler shape (`jsx`, DOM libs, `types: []`) extended by the client aggregate and every `packages/client/*` package. | No |\n\nHost and client stay two aggregate programs because both sides declaration-merge the cordis `Context` interface under the same keys with different services; one program seeing both merges reports a collision. The collision exists only inside a `ts.Program` — module resolution never triggers it — which is why the solution may reference both aggregates and one paths facade may span both sides. Two disciplines follow:\n\n- `tsconfig.base.json` never gains `include` or `files`: they would leak into every extending package project and narrow the facade's match-all scope.\n- A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges. Program-backed generators and gates (`scripts/ts-project.ts` consumers, doc-typecheck standalone mode) are host-only by decision; the client side gains program-backed tooling only with a concrete need.\n\nStatic analysis and tests resolve workspace imports through the base `paths` map to `src` and must pass on a clean tree; gates that consume built `lib/` output declare that dependency explicitly. Decision record: [solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md); the tsc-first emit pipeline is the [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md).\n\nIf a relevant local check consumes built package output, build once first:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` includes `publint`, which validates package entrypoints against the built `lib/*.js` files, and `verify-node-next-types`, which validates built declarations against a temporary NodeNext consumer. A fresh worktree has no bundled JS or declarations until `pnpm run build` runs; ordinary commits and pushes do not require that build unless their selected checks consume it.\n\n## Environment variables\n\nThe real DeepSeek adapter and key-backed agent demos read credentials from the environment or from a gitignored `.env` at the repo root:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` is optional and defaults to the public API. Never commit real credentials. The real-API e2e suites self-skip when `DEEPSEEK_API_KEY` is not set.\n\n## Git hooks\n\nlefthook is configured in `lefthook.yml` as a fast local checkpoint:\n\n- `pre-commit` runs staged-file ESLint fixes, checks the staged diff for whitespace errors, and runs the vendor manifest guard.\n- `pre-push` runs only the incremental repository typecheck (`tsc -b` over the root solution, covering both the host and client aggregates).\n\nThe vendor manifest guard checks that changes under `vendor/*/src` are staged with the matching `vendor/README.md` manifest update. See `vendor/README.md` before editing vendored code.\n\nThe hooks intentionally do not run tests, snapshots, documentation checks, builds, or hygiene. Contributors run the [checks relevant to the changed behavior](../AGENTS.md#run-relevant-checks-locally) once; CI owns exhaustive coverage, built-artifact smokes, and the Node 22.19, 24, and 26 compatibility matrix.\n\nContributors can opt into the comprehensive local gate set with `pnpm run check:all`. The command is independent of both Git hooks and is not an agent instruction.\n\n## CI gates\n\nThe keyless [CI workflow](../.github/workflows/ci.yml) groups independent gates into broad lanes and runs a smaller compatibility signal across supported Node versions. Artifact consumers wait for one build within their lane. The separate real-API workflow runs `pnpm run test:e2e` with its configured worker bound. See [scripts/run-gates.ts](../scripts/run-gates.ts) and the workflow files for the current gate and job inventory.\n\n## Daily commands\n\nUse these from the repo root:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\nWhen changing package public behavior, update the relevant README or JSDoc in the same change. `pnpm run doc-sync` catches checked TypeScript snippets, generated doc freshness, markdown wrap/link drift, type equivalence, translation pairing, Mermaid syntax, and doc budgets, but broader prose/API sync still needs review.\n\n## Demos\n\nThe one-shot Headless coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\nThe full-screen interactive coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:tui\n```\n\nThe self-referential cordis-agent demo can inspect and modify its live plugin runtime and needs the same credentials:\n\n```sh\npnpm run demo:cordis\n```\n\nThe ACP automation server exposes fresh agent sessions over JSON-RPC stdio and also needs `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO markers\n\nUse one of three comment tags to flag known issues in the code, ordered by urgency:\n\n- `FIXME` — an issue that should block a new release. A release should not ship with an open `FIXME` unless reviewers explicitly agree the change can be merged anyway.\n- `TODO` — an issue that should be fixed soon, once we have the resources.\n- `XXX` — an issue that we may fix someday; lowest priority, no commitment.\n\nPick the tag that matches the urgency so anyone scanning the code can tell a release blocker from a someday-maybe.\n\n## Documenting types verbatim (`ts type-equiv`)\n\nThe [core data structures](core-data-structures/core.md) docs paste source-equivalent declarations together with their original JSDoc so a reader sees the exact shape and source contract. To keep a paste from drifting when source changes, fence it as ` ```ts type-equiv ` (instead of ` ```ts `) and register it in `scripts/type-equiv.manifest.json` with the source file and symbol it mirrors:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv` (part of `doc-sync`) then extracts that symbol's declaration and attached JSDoc from source via the TypeScript parser and asserts the block matches both. For a class whose implementation bodies do not belong in the catalog, use ` ```ts public-api ` and set `\"projection\": \"public-api\"`; the checked projection retains the public fields, constructor, accessors, methods, and original class/member JSDoc while omitting bodies and private or protected members. Comparison ignores whitespace and non-JSDoc comments but requires every original JSDoc comment, including member documentation, so readers see the source contract beside the exact shape. The gate also enforces a 1:1 correspondence by document, symbol, and projection, so a block can't go silently unchecked and a stale entry can't linger. `doc-typecheck` skips both fence kinds (they aren't standalone-compilable) and excludes them from its opt-out ratio. When you change a documented declaration or its JSDoc, the gate fails until you update the paste; when you add or remove a block, update the manifest in the same change.\n\n## Architecture context\n\nRead `docs/architecture.md` before changing anything under `packages/`. The codebase is built around Cordis plugins, event-sourced sessions, typed service seams, and explicit extension points.\n" + "content": "# Development guide\n\nEnglish | [中文](development.zh.md)\n\nThis onboarding guide helps project contributors get started with the local environment, daily workflow, and CI flow; see the Agent Notes for design rationale and technical trade-offs.\n\n## Prerequisites\n\n- Node.js supports 22.19+ and 24+. CI covers 22.19, 24, and 26; see the [Node engine floor Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md).\n- Corepack-enabled pnpm. The repo pins `pnpm@11.7.0` in `package.json`; run `corepack enable` if `pnpm --version` does not resolve through Corepack.\n- Git.\n- Optional: a DeepSeek API key for the TUI, headless, and ACP automation demos and real-API e2e tests.\n\n## First-time setup\n\nInstall dependencies from the repo root:\n\n```sh\npnpm install\n```\n\nThe install also runs the root `postinstall` script, which installs lefthook from the repo dev dependency through `scripts/install-lefthook.mjs`; the wrapper script uses lefthook's reviewed `--force` mode so linked worktrees with an existing `core.hooksPath` do not fail normal `pnpm run …` commands.\n\nIf hooks are missing because dependencies were restored from cache or `postinstall` was skipped, install them manually:\n\n```sh\npnpm exec lefthook install --force\n```\n\nRun typecheck once after a fresh clone:\n\n```sh\npnpm run typecheck\n```\n\nThat first typecheck runs the whole-repo `tsc -b` graph: it emits every package/vendor `lib/types` and checks examples, tests, and scripts through the two no-emit aggregates described below.\n\n## TypeScript project layout\n\nThe repository's TypeScript configuration has exactly three roles; every tsconfig file plays one of them.\n\n| File | Role | Forms a program? |\n|---|---|---|\n| `tsconfig.json` | Solution root: `extends` base, `files: []`, references to the two aggregates. The whole-repo `tsc -b tsconfig.json` graph, the tsserver discovery entry, and — through the inherited `paths` — the resolution config for tsx running `examples/` and `scripts/` (their nearest tsconfig is this file). | No |\n| `tsconfig.host.json` | Host aggregate: host-side packages (via references), examples, tests, scripts, website. Excludes `packages/client`. | Yes |\n| `tsconfig.client.json` | Client aggregate: `packages/client/*` packages and their tests, `apps/web`. | Yes |\n| `tsconfig.base.json` | Shared compilerOptions and the source `paths` map. Also the resolution facade the vitest configs point vite-tsconfig-paths at: it has no `include`, so its `paths` apply to every importer. | No |\n| `tsconfig.base.client.json` | Browser compiler shape (`jsx`, DOM libs, `types: []`) extended by the client aggregate and every `packages/client/*` package. | No |\n\nHost and client stay two aggregate programs because both sides declaration-merge the cordis `Context` interface under the same keys with different services; one program seeing both merges reports a collision. The collision exists only inside a `ts.Program` — module resolution never triggers it — which is why the solution may reference both aggregates and one paths facade may span both sides. Two disciplines follow:\n\n- `tsconfig.base.json` never gains `include` or `files`: they would leak into every extending package project and narrow the facade's match-all scope.\n- A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges. Program-backed generators and gates (`scripts/ts-project.ts` consumers, doc-typecheck standalone mode) are host-only by decision; the client side gains program-backed tooling only with a concrete need.\n\nStatic analysis and tests resolve workspace imports through the base `paths` map to `src` and must pass on a clean tree; gates that consume built `lib/` output declare that dependency explicitly. Decision record: [solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md); the tsc-first emit pipeline is the [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md).\n\nIf a relevant local check consumes built package output, build once first:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` includes `publint`, which validates package entrypoints against the built `lib/*.js` files, and `verify-node-next-types`, which validates built declarations against a temporary NodeNext consumer. A fresh worktree has no bundled JS or declarations until `pnpm run build` runs; ordinary commits and pushes do not require that build unless their selected checks consume it.\n\n## Environment variables\n\nThe real DeepSeek adapter and key-backed agent demos read credentials from the environment or from a gitignored `.env` at the repo root:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` is optional and defaults to the public API. Never commit real credentials. The real-API e2e suites self-skip when `DEEPSEEK_API_KEY` is not set.\n\n## Git hooks\n\nlefthook is configured in `lefthook.yml` as a fast local checkpoint:\n\n- `pre-commit` runs staged-file ESLint fixes, checks the staged diff for whitespace errors, and runs the vendor manifest guard.\n- `pre-push` runs only the incremental repository typecheck (`tsc -b` over the root solution, covering both the host and client aggregates).\n\nThe vendor manifest guard checks that changes under `vendor/*/src` are staged with the matching `vendor/README.md` manifest update. See `vendor/README.md` before editing vendored code.\n\nThe hooks intentionally do not run tests, snapshots, documentation checks, builds, or hygiene. Contributors run the [checks relevant to the changed behavior](../AGENTS.md#run-relevant-checks-locally) once; CI owns exhaustive coverage, built-artifact smokes, and the Node 22.19, 24, and 26 compatibility matrix.\n\nContributors can opt into the comprehensive local gate set with `pnpm run check:all`. The command is independent of both Git hooks and is not an agent instruction.\n\n## CI gates\n\nThe keyless [CI workflow](../.github/workflows/ci.yml) groups independent gates into broad lanes and runs a smaller compatibility signal across supported Node versions. Artifact consumers wait for one build within their lane. The separate real-API workflow runs `pnpm run test:e2e` with its configured worker bound. See [scripts/run-gates.ts](../scripts/run-gates.ts) and the workflow files for the current gate and job inventory.\n\n## Daily commands\n\nUse these from the repo root:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\nWhen changing package public behavior, update the relevant README or JSDoc in the same change. `pnpm run doc-sync` catches checked TypeScript snippets, generated doc freshness, markdown wrap/link drift, type equivalence, translation pairing, Mermaid syntax, and doc budgets, but broader prose/API sync still needs review.\n\n## Demos\n\nThe one-shot Headless coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\nThe full-screen interactive coding agent needs `DEEPSEEK_API_KEY` in the environment or repo-root `.env`:\n\n```sh\npnpm run demo:tui\n```\n\nThe self-referential cordis-agent demo can inspect and modify its live plugin runtime and needs the same credentials:\n\n```sh\npnpm run demo:cordis\n```\n\nThe ACP automation server exposes fresh agent sessions over JSON-RPC stdio and also needs `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO markers\n\nUse one of three comment tags to flag known issues in the code, ordered by urgency:\n\n- `FIXME` — an issue that should block a new release. A release should not ship with an open `FIXME` unless reviewers explicitly agree the change can be merged anyway.\n- `TODO` — an issue that should be fixed soon, once we have the resources.\n- `XXX` — an issue that we may fix someday; lowest priority, no commitment.\n\nPick the tag that matches the urgency so anyone scanning the code can tell a release blocker from a someday-maybe.\n\n## Documenting types verbatim (`ts type-equiv`)\n\nThe [core data structures](core-data-structures/core.md) docs paste source-equivalent declarations together with their original JSDoc so a reader sees the exact shape and source contract. To keep a paste from drifting when source changes, fence it as ` ```ts type-equiv ` (instead of ` ```ts `) and register it in `scripts/type-equiv.manifest.json` with the source file and symbol it mirrors:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv` (part of `doc-sync`) then extracts that symbol's declaration and attached JSDoc from source via the TypeScript parser and asserts the block matches both. For a class whose implementation bodies do not belong in the catalog, use ` ```ts public-api ` and set `\"projection\": \"public-api\"`; the checked projection retains the public fields, constructor, accessors, methods, and original class/member JSDoc while omitting bodies and private or protected members. Comparison ignores whitespace and non-JSDoc comments but requires every original JSDoc comment, including member documentation, so readers see the source contract beside the exact shape. The gate enforces a 1:1 correspondence by document, symbol, and projection between primary blocks and manifest entries; a paired `.zh.md` block reuses its unsuffixed sibling's entry only when the whole tracked fence sequence is byte-identical and ordered identically. `doc-typecheck` applies the same derivative rule to compilable fences, while skipping both source-equivalence fence kinds from compilation and its opt-out ratio. When you change a documented declaration or its JSDoc, the gate fails until you update the paste; when you add or remove a primary block, update the manifest in the same change.\n\n## Architecture context\n\nRead `docs/architecture.md` before changing anything under `packages/`. The codebase is built around Cordis plugins, event-sourced sessions, typed service seams, and explicit extension points.\n" }, { "role": "assistant", - "content": "# 开发指南\n\n[English](development.md) | 中文\n\n本指南覆盖参与 DeepSeek Harness 开发所需的本地环境搭建、日常工作流与 CI 流程;设计动机与技术权衡请查阅相应 Agent Note。\n\n## 前置条件\n\n- Node.js 支持 22.19+ 与 24+。CI 覆盖 22.19、24 和 26;见 [Node 引擎下限 Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md)。\n- 启用了 Corepack 的 pnpm。仓库在 `package.json` 中固定使用 `pnpm@11.7.0`;如果 `pnpm --version` 无法通过 Corepack 解析,请先运行 `corepack enable`。\n- Git。\n- 可选:一个 DeepSeek API key,用于 TUI、headless 和 ACP(Agent Client Protocol)自动化 agent(智能体)演示以及真实 API 的 e2e 测试。\n\n## 首次搭建\n\n在仓库根目录安装依赖:\n\n```sh\npnpm install\n```\n\n安装过程同时会运行根目录的 `postinstall` 脚本,该脚本通过 `scripts/install-lefthook.mjs` 从仓库 dev 依赖安装 lefthook。包装脚本使用 lefthook 经过评审的 `--force` 模式,确保已存在 `core.hooksPath` 的关联 worktree 不会导致正常的 `pnpm run …` 命令失败。\n\n如果依赖是从缓存恢复或 `postinstall` 被跳过而导致缺少钩子,请手动安装:\n\n```sh\npnpm exec lefthook install --force\n```\n\n新克隆后请先运行一次类型检查:\n\n```sh\npnpm run typecheck\n```\n\n首次类型检查会执行全仓 `tsc -b tsconfig.json` 图:发射每个 package/vendor 的 `lib/types`,并通过下述两个 no-emit 聚合检查示例、测试和脚本。\n\n## TypeScript 项目布局\n\n仓库的 TypeScript 配置只有三种角色;每个 tsconfig 文件恰好扮演其中一种。\n\n| 文件 | 角色 | 是否构成 program? |\n|---|---|---|\n| `tsconfig.json` | solution 根:`extends` base、`files: []`、引用两个聚合。全仓 `tsc -b tsconfig.json` 图、tsserver 发现入口,并经继承的 `paths` 充当 tsx 运行 `examples/` 与 `scripts/` 时的解析配置(它们最近的 tsconfig 就是此文件)。 | 否 |\n| `tsconfig.host.json` | host 聚合:host 侧各包(经 references)、示例、测试、脚本、website。排除 `packages/client`。 | 是 |\n| `tsconfig.client.json` | client 聚合:`packages/client/*` 各包及其测试、`apps/web`。 | 是 |\n| `tsconfig.base.json` | 共享 compilerOptions 与源码 `paths` 映射。同时是各 vitest 配置让 vite-tsconfig-paths 指向的解析门面:它没有 `include`,因此其 `paths` 适用于任何 importer。 | 否 |\n| `tsconfig.base.client.json` | 浏览器编译形状(`jsx`、DOM lib、`types: []`),由 client 聚合和每个 `packages/client/*` 包 extends。 | 否 |\n\nhost 与 client 保持两个聚合 program,是因为两侧在相同键下以不同服务对 cordis `Context` 接口做声明合并;单一 program 同时看到两份合并会报冲突。这种冲突只存在于 `ts.Program` 内部——模块解析永远不会触发它——所以 solution 可以同时引用两个聚合,一个 paths 门面也可以横跨两侧。由此推出两条纪律:\n\n- `tsconfig.base.json` 永不添加 `include` 或 `files`:它们会泄漏进每个 extends 它的包项目,并收窄门面的全匹配范围。\n- 构造全仓 `ts.Program` 的脚本显式种子 `tsconfig.host.json` 或 `tsconfig.client.json`——永不种子根 solution,因为把两个聚合展平进一个 program 会撞上 `Context` 合并冲突。基于 program 的生成器与门禁(`scripts/ts-project.ts` 的消费者、doc-typecheck standalone 模式)按决策仅覆盖 host 侧;client 侧只在出现真实需求时再获得基于 program 的工具。\n\n静态分析和测试通过 base 的 `paths` 映射把工作区 import 解析到 `src`,且必须在干净树上通过;消费构建产物 `lib/` 的门禁显式声明该依赖。决策记录:[solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md);tsc-first 发射管线见 [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md)。\n\n如果相关的本地检查需要使用构建后的包产物,请先构建一次:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验 package 入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建,除非所选检查会使用这些产物。\n\n## 环境变量\n\n真实的 DeepSeek 适配器和需要密钥的 agent 演示从环境变量或仓库根目录一个被 gitignore 的 `.env` 文件读取凭证:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` 可选,默认为公开 API。请勿提交真实凭证。未设置 `DEEPSEEK_API_KEY` 时,真实 API 的 e2e 套件会自动跳过。\n\n## Git 钩子\n\nlefthook 在 `lefthook.yml` 中配置,作为快速的本地检查点:\n\n- `pre-commit` 运行对暂存文件的 ESLint 修复,检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫;\n- `pre-push` 只运行仓库增量类型检查(对根 solution 执行 `tsc -b`,覆盖 host 与 client 两个聚合)。\n\nvendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `vendor/README.md` manifest 更新一起暂存。请在编辑 vendor 代码前先阅读 `vendor/README.md`。\n\n这些钩子有意不运行测试、快照、文档检查、构建或 `hygiene`。贡献者只运行一次[与改动行为相关的检查](../AGENTS.md#run-relevant-checks-locally);CI 负责全量覆盖率门禁、构建产物冒烟测试,以及 Node 22.19、24 和 26 兼容性矩阵。\n\n贡献者可以选择运行 `pnpm run check:all`,执行全面的本地门禁集。该命令独立于两个 Git 钩子,也不是对 agent 的指令。\n\n## CI 门禁\n\nkeyless [CI 工作流](../.github/workflows/ci.yml) 将独立门禁分组到若干宽粒度 lane,并在受支持的 Node 版本上运行一组较小的兼容性检查。产物消费方在各自 lane 内等待一次 build。单独的真实 API 工作流按其配置的 worker 上限运行 `pnpm run test:e2e`。当前门禁和 job 清单以 [scripts/run-gates.ts](../scripts/run-gates.ts) 和工作流文件为准。\n\n## 日常命令\n\n在仓库根目录使用:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\n修改 package 的公开行为时,请在同一个变更中更新相关 README 或 JSDoc。`pnpm run doc-sync` 能检测到被检查的 TypeScript 片段、生成文档的新鲜度、Markdown 换行/链接漂移、type-equiv、翻译配对、Mermaid 语法和文档预算,但更广泛的行文/API 同步仍需评审把关。\n\n## 演示\n\n单次运行的 Headless coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\n全屏交互式 coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:tui\n```\n\n自指的 cordis-agent 演示可以检查并修改其实时插件运行时,并需要相同的凭证:\n\n```sh\npnpm run demo:cordis\n```\n\nACP 自动化服务器通过 JSON-RPC stdio 提供全新 agent 会话,同样需要 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO 标记\n\n请使用以下三种注释标签之一标记代码中的已知问题,按紧急程度排序:\n\n- `FIXME`:应当阻塞新版本发布的问题。除非评审者明确同意该更改可以合并,否则发布版本不应包含未解决的 `FIXME`;\n- `TODO`:应当尽快修复的问题,等资源到位即可处理;\n- `XXX`:也许某天会修复的问题,优先级最低,不作承诺。\n\n请选择与紧急程度匹配的标签,让浏览代码的人一眼分清「发布阻塞」和「有空再说」。\n\n## 逐字记录类型(`ts type-equiv`)\n\n[核心数据结构](core-data-structures/core.md)文档会把与源码等价的声明及其原始 JSDoc 一并粘贴,让读者看到确切形状和源码契约。为防止粘贴内容在源码变化时漂移,请将其围栏为 ` ```ts type-equiv `(而不是 ` ```ts `),并在 `scripts/type-equiv.manifest.json` 中登记它镜像的源文件和符号:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `\"projection\": \"public-api\"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码契约和确切形状。该门禁还按文档、符号和投影强制 1:1 对应,因此不会有块被静默漏检,也不会有陈旧条目滞留。`doc-typecheck` 跳过两种围栏(它们不能独立编译),并将其排除在 opt-out 比例之外。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个块时,请在同一个变更里更新 manifest。\n\n## 架构上下文\n\n在修改 `packages/` 目录下的任何内容之前,请先阅读 `docs/architecture.md`。这套代码围绕 Cordis 插件、事件溯源的会话、类型化的服务 seam 与显式扩展点构建。\n" + "content": "# 开发指南\n\n[English](development.md) | 中文\n\n本指南覆盖参与 DeepSeek Harness 开发所需的本地环境搭建、日常工作流与 CI 流程;设计动机与技术权衡请查阅相应 Agent Note。\n\n## 前置条件\n\n- Node.js 支持 22.19+ 与 24+。CI 覆盖 22.19、24 和 26;见 [Node 引擎下限 Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md)。\n- 启用了 Corepack 的 pnpm。仓库在 `package.json` 中固定使用 `pnpm@11.7.0`;如果 `pnpm --version` 无法通过 Corepack 解析,请先运行 `corepack enable`。\n- Git。\n- 可选:一个 DeepSeek API key,用于 TUI、headless 和 ACP(Agent Client Protocol)自动化 agent(智能体)演示以及真实 API 的 e2e 测试。\n\n## 首次搭建\n\n在仓库根目录安装依赖:\n\n```sh\npnpm install\n```\n\n安装过程同时会运行根目录的 `postinstall` 脚本,该脚本通过 `scripts/install-lefthook.mjs` 从仓库 dev 依赖安装 lefthook。包装脚本使用 lefthook 经过评审的 `--force` 模式,确保已存在 `core.hooksPath` 的关联 worktree 不会导致正常的 `pnpm run …` 命令失败。\n\n如果依赖是从缓存恢复或 `postinstall` 被跳过而导致缺少钩子,请手动安装:\n\n```sh\npnpm exec lefthook install --force\n```\n\n新克隆后请先运行一次类型检查:\n\n```sh\npnpm run typecheck\n```\n\n首次类型检查会执行全仓 `tsc -b tsconfig.json` 图:发射每个 package/vendor 的 `lib/types`,并通过下述两个 no-emit 聚合检查示例、测试和脚本。\n\n## TypeScript 项目布局\n\n仓库的 TypeScript 配置只有三种角色;每个 tsconfig 文件恰好扮演其中一种。\n\n| 文件 | 角色 | 是否构成 program? |\n|---|---|---|\n| `tsconfig.json` | solution 根:`extends` base、`files: []`、引用两个聚合。全仓 `tsc -b tsconfig.json` 图、tsserver 发现入口,并经继承的 `paths` 充当 tsx 运行 `examples/` 与 `scripts/` 时的解析配置(它们最近的 tsconfig 就是此文件)。 | 否 |\n| `tsconfig.host.json` | host 聚合:host 侧各包(经 references)、示例、测试、脚本、website。排除 `packages/client`。 | 是 |\n| `tsconfig.client.json` | client 聚合:`packages/client/*` 各包及其测试、`apps/web`。 | 是 |\n| `tsconfig.base.json` | 共享 compilerOptions 与源码 `paths` 映射。同时是各 vitest 配置让 vite-tsconfig-paths 指向的解析门面:它没有 `include`,因此其 `paths` 适用于任何 importer。 | 否 |\n| `tsconfig.base.client.json` | 浏览器编译形状(`jsx`、DOM lib、`types: []`),由 client 聚合和每个 `packages/client/*` 包 extends。 | 否 |\n\nhost 与 client 保持两个聚合 program,是因为两侧在相同键下以不同服务对 cordis `Context` 接口做声明合并;单一 program 同时看到两份合并会报冲突。这种冲突只存在于 `ts.Program` 内部——模块解析永远不会触发它——所以 solution 可以同时引用两个聚合,一个 paths 门面也可以横跨两侧。由此推出两条纪律:\n\n- `tsconfig.base.json` 永不添加 `include` 或 `files`:它们会泄漏进每个 extends 它的包项目,并收窄门面的全匹配范围。\n- 构造全仓 `ts.Program` 的脚本显式种子 `tsconfig.host.json` 或 `tsconfig.client.json`——永不种子根 solution,因为把两个聚合展平进一个 program 会撞上 `Context` 合并冲突。基于 program 的生成器与门禁(`scripts/ts-project.ts` 的消费者、doc-typecheck standalone 模式)按决策仅覆盖 host 侧;client 侧只在出现真实需求时再获得基于 program 的工具。\n\n静态分析和测试通过 base 的 `paths` 映射把工作区 import 解析到 `src`,且必须在干净树上通过;消费构建产物 `lib/` 的门禁显式声明该依赖。决策记录:[solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md);tsc-first 发射管线见 [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md)。\n\n如果相关的本地检查需要使用构建后的包产物,请先构建一次:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验 package 入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建,除非所选检查会使用这些产物。\n\n## 环境变量\n\n真实的 DeepSeek 适配器和需要密钥的 agent 演示从环境变量或仓库根目录一个被 gitignore 的 `.env` 文件读取凭证:\n\n```sh\nDEEPSEEK_API_KEY=sk-...\nDEEPSEEK_BASE_URL=https://... # optional\n```\n\n`DEEPSEEK_BASE_URL` 可选,默认为公开 API。请勿提交真实凭证。未设置 `DEEPSEEK_API_KEY` 时,真实 API 的 e2e 套件会自动跳过。\n\n## Git 钩子\n\nlefthook 在 `lefthook.yml` 中配置,作为快速的本地检查点:\n\n- `pre-commit` 运行对暂存文件的 ESLint 修复,检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫;\n- `pre-push` 只运行仓库增量类型检查(对根 solution 执行 `tsc -b`,覆盖 host 与 client 两个聚合)。\n\nvendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `vendor/README.md` manifest 更新一起暂存。请在编辑 vendor 代码前先阅读 `vendor/README.md`。\n\n这些钩子有意不运行测试、快照、文档检查、构建或 `hygiene`。贡献者只运行一次[与改动行为相关的检查](../AGENTS.md#run-relevant-checks-locally);CI 负责全量覆盖率门禁、构建产物冒烟测试,以及 Node 22.19、24 和 26 兼容性矩阵。\n\n贡献者可以选择运行 `pnpm run check:all`,执行全面的本地门禁集。该命令独立于两个 Git 钩子,也不是对 agent 的指令。\n\n## CI 门禁\n\nkeyless [CI 工作流](../.github/workflows/ci.yml) 将独立门禁分组到若干宽粒度 lane,并在受支持的 Node 版本上运行一组较小的兼容性检查。产物消费方在各自 lane 内等待一次 build。单独的真实 API 工作流按其配置的 worker 上限运行 `pnpm run test:e2e`。当前门禁和 job 清单以 [scripts/run-gates.ts](../scripts/run-gates.ts) 和工作流文件为准。\n\n## 日常命令\n\n在仓库根目录使用:\n\n```sh\npnpm run test # unit tests\npnpm run test:coverage # unit tests with per-file coverage gates\npnpm run test:e2e # real-API tests; self-skips without DEEPSEEK_API_KEY\npnpm run check:all # comprehensive opt-in gate set; not wired to Git hooks\npnpm run typecheck # tsc -b over the root solution: emits package/vendor lib/types, checks both aggregates\npnpm run lint # eslint .\npnpm run lint:fix # eslint . --fix\npnpm run doc-typecheck # compile checked TypeScript snippets in Markdown docs\npnpm run gen-cordis-catalog # regenerate docs/cordis-catalog/events.md + services.md from source\npnpm run verify-cordis-catalog # fail if either cordis catalog is stale\npnpm run verify-export-jsdoc # fail if a module-level package export lacks complete JSDoc\npnpm run gen-doc-graphs # regenerate generated relationship docs from source and curated graph definitions\npnpm run verify-doc-graphs # fail if generated relationship docs are stale\npnpm run verify-md-wrap # fail on hard-wrapped prose paragraphs in docs/README markdown\npnpm run verify-mermaid # fail if a ```mermaid diagram has invalid Mermaid syntax\npnpm run verify-type-equiv # fail if a ```ts type-equiv doc block drifts from its source type\npnpm run verify-doc-budgets # fail if a budgeted standing doc exceeds its word ceiling\npnpm run doc-sync # all Markdown/doc gates, scheduled concurrently; the doc-sync leaf list in scripts/run-gates.ts is the full list\npnpm run gen-module-graph # regenerate docs/module-graph.md from package peerDeps\npnpm run verify-module-graph # fail if docs/module-graph.md is stale\npnpm run build # emit lib/types intermediates, then bundle lib/index.* runtime files\npnpm run verify-node-next-types # fail if built declarations are not NodeNext-consumable\npnpm run hygiene # knip, publint, workspace constraints, and NodeNext declaration check\n```\n\n修改 package 的公开行为时,请在同一个变更中更新相关 README 或 JSDoc。`pnpm run doc-sync` 能检测到被检查的 TypeScript 片段、生成文档的新鲜度、Markdown 换行/链接漂移、type-equiv、翻译配对、Mermaid 语法和文档预算,但更广泛的行文/API 同步仍需评审把关。\n\n## 演示\n\n单次运行的 Headless coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:headless \"summarize this workspace\"\n```\n\n全屏交互式 coding agent 需要环境变量或仓库根目录 `.env` 中的 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:tui\n```\n\n自指的 cordis-agent 演示可以检查并修改其实时插件运行时,并需要相同的凭证:\n\n```sh\npnpm run demo:cordis\n```\n\nACP 自动化服务器通过 JSON-RPC stdio 提供全新 agent 会话,同样需要 `DEEPSEEK_API_KEY`:\n\n```sh\npnpm run demo:acp\n```\n\n## TODO 标记\n\n请使用以下三种注释标签之一标记代码中的已知问题,按紧急程度排序:\n\n- `FIXME`:应当阻塞新版本发布的问题。除非评审者明确同意该更改可以合并,否则发布版本不应包含未解决的 `FIXME`;\n- `TODO`:应当尽快修复的问题,等资源到位即可处理;\n- `XXX`:也许某天会修复的问题,优先级最低,不作承诺。\n\n请选择与紧急程度匹配的标签,让浏览代码的人一眼分清「发布阻塞」和「有空再说」。\n\n## 逐字记录类型(`ts type-equiv`)\n\n[核心数据结构](core-data-structures/core.md)文档会把与源码等价的声明及其原始 JSDoc 一并粘贴,让读者看到确切形状和源码契约。为防止粘贴内容在源码变化时漂移,请将其围栏为 ` ```ts type-equiv `(而不是 ` ```ts `),并在 `scripts/type-equiv.manifest.json` 中登记它镜像的源文件和符号:\n\n```json\n{ \"doc\": \"docs/core-data-structures/session.md\", \"symbol\": \"SessionEvent\", \"source\": \"packages/core/session/src/types.ts\" }\n```\n\n`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `\"projection\": \"public-api\"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码契约和确切形状。该门禁按文档、符号和投影,在主块与 manifest 条目之间强制 1:1 对应;只有当配对 `.zh.md` 块的完整受跟踪围栏序列与其无后缀兄弟文件按字节一致且顺序相同时,才会复用后者的条目。`doc-typecheck` 对可编译围栏应用同一派生规则,同时跳过两种源码等价围栏的编译,并将其排除在 opt-out 比例之外。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个主块时,请在同一个变更里更新 manifest。\n\n## 架构上下文\n\n在修改 `packages/` 目录下的任何内容之前,请先阅读 `docs/architecture.md`。这套代码围绕 Cordis 插件、事件溯源的会话、类型化的服务 seam 与显式扩展点构建。\n" }, { "role": "user", - "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p `), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required`, and every document whose class appears in `requiredClasses`, in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair. The classes are `non-readme` and `readme`; class matching is case-insensitive on the basename, so `missions/readme.md` is a README.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md`, `.agents/notes/**/AGENTS.md`, and their `CLAUDE.md` instruction symlinks — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. `non-readme` is closed: every current or future in-scope non-README document must merge bilingual. README coverage remains an explicit-file rollout until `readme` joins the closed set. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" + "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p `), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required`, and every document whose class appears in `requiredClasses`, in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair. The classes are `non-readme` and `readme`; class matching is case-insensitive on the basename, so `missions/readme.md` is a README.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\nSource-oriented code gates consume an exact `.zh.md` fence sequence as a derivative of its unsuffixed sibling instead of compiling or manifesting the same code twice. The sequence must match in length, order, fence kind, and byte-exact body; otherwise both copies remain independently checked and the pairing gate reports the structural mismatch.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md`, `.agents/notes/**/AGENTS.md`, and their `CLAUDE.md` instruction symlinks — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. `non-readme` is closed: every current or future in-scope non-README document must merge bilingual. README coverage remains an explicit-file rollout until `readme` joins the closed set. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" }, { "role": "assistant", - "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p `),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件,以及所属文档类别出现在 `requiredClasses` 中的每篇文档,都有完整配对。类别分为 `non-readme` 和 `readme`;判断类别时,basename 不区分大小写,因此 `missions/readme.md` 也属于 README。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md`、`.agents/notes/**/AGENTS.md` 以及指向它们的 `CLAUDE.md` 指令符号链接:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 已纳入强制范围:当前及今后所有纳入范围的非 README 文档,合并时都必须配齐双语文件。README 覆盖仍按显式文件逐步推进,直到 `readme` 加入这一强制范围。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" + "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p `),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件,以及所属文档类别出现在 `requiredClasses` 中的每篇文档,都有完整配对。类别分为 `non-readme` 和 `readme`;判断类别时,basename 不区分大小写,因此 `missions/readme.md` 也属于 README。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n面向源码的代码门禁会把精确的 `.zh.md` 围栏序列视为其无后缀兄弟文件的派生内容,而不会再次编译相同代码或在 manifest 中重复登记。该序列必须在长度、顺序、围栏类型和按字节精确的正文上一致;否则两份副本仍会独立受检,配对门禁也会报告结构不匹配。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md`、`.agents/notes/**/AGENTS.md` 以及指向它们的 `CLAUDE.md` 指令符号链接:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 已纳入强制范围:当前及今后所有纳入范围的非 README 文档,合并时都必须配齐双语文件。README 覆盖仍按显式文件逐步推进,直到 `readme` 加入这一强制范围。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" }, { "role": "user", @@ -40,11 +40,11 @@ }, { "role": "user", - "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot.\n- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it.\n- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Verification\n\nThe verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Rollout remains incremental until a document class is complete: explicit `required` entries and the date cutoff prevent regression during review batches, while a closed class makes every current and future member mandatory. The non-README class is closed, so only the README class can still appear as backlog.\n- The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" + "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot. Source-oriented code gates consume a `.zh.md` fence sequence as a derivative only when its unsuffixed sibling has the same tracked fences in the same order with byte-identical bodies; an incomplete, reordered, reclassified, or changed sequence stays independent, so the owning code gate or pairing gate reports the mismatch.\n- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it.\n- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Verification\n\nThe verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Rollout remains incremental until a document class is complete: explicit `required` entries and the date cutoff prevent regression during review batches, while a closed class makes every current and future member mandatory. The non-README class is closed, so only the README class can still appear as backlog.\n- The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" }, { "role": "assistant", - "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。\n- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。\n- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 验证\n\n验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 在文档类别全部完成之前,推进仍然是渐进的:显式 `required` 条目与日期分界可在评审批次期间防止回退,已纳入强制范围的类别则将其当前及今后的每个成员都列为必选项。非 README 类别已纳入强制范围,因此只有 README 类别仍可能出现 backlog(待翻清单)。\n- 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" + "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。只有当 `.zh.md` 围栏序列与其无后缀兄弟文件拥有顺序相同、正文按字节一致的同一组受跟踪围栏时,面向源码的代码门禁才会将其作为派生内容消费;不完整、顺序变更、重分类或已改动的序列仍会独立受检,因此由其所属的代码门禁或配对门禁报告不匹配。\n- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。\n- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 验证\n\n验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 在文档类别全部完成之前,推进仍然是渐进的:显式 `required` 条目与日期分界可在评审批次期间防止回退,已纳入强制范围的类别则将其当前及今后的每个成员都列为必选项。非 README 类别已纳入强制范围,因此只有 README 类别仍可能出现 backlog(待翻清单)。\n- 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" }, { "role": "user", diff --git a/scripts/type-equiv.manifest.json b/scripts/type-equiv.manifest.json index 0310306bfa..b546e26f15 100644 --- a/scripts/type-equiv.manifest.json +++ b/scripts/type-equiv.manifest.json @@ -1,5 +1,5 @@ { - "comment": "Maps each ` ```ts type-equiv ` or ` ```ts public-api ` block (by doc + declared symbol + projection) to the source declaration and original JSDoc it must match. Omit projection for the complete declaration; use public-api with a ` ```ts public-api ` block for a body-stripped public class declaration. verify-type-equiv.ts enforces a 1:1 correspondence: every source-equivalence block has exactly one entry here, and every entry resolves to exactly one block. Add an entry when you add a source-equivalence block; remove it when you remove the block.", + "comment": "Maps each primary ` ```ts type-equiv ` or ` ```ts public-api ` block (by doc + declared symbol + projection) to the source declaration and original JSDoc it must match. Paired `.zh.md` blocks are byte-identical derivatives checked through their unsuffixed sibling and have no duplicate entry. Omit projection for the complete declaration; use public-api with a ` ```ts public-api ` block for a body-stripped public class declaration. verify-type-equiv.ts enforces a 1:1 correspondence between primary blocks and entries. Add an entry when you add a primary source-equivalence block; remove it when you remove the block.", "entries": [ { "doc": "docs/core-data-structures/core.md", @@ -1248,949 +1248,6 @@ "doc": "docs/core-data-structures/session-query.md", "symbol": "SessionSearchHit", "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "Branded", - "source": "packages/util/brand/src/index.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "ContentBlockMap", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "AssistantProvenance", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "Message", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "MessageSourceMap", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "FinishReasonMap", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "LlmProviderInfo", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "LlmModelInfo", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "LlmModelContext", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "GenerateOptions", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "ToolSchema", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "LlmCallConfig", - "source": "packages/llm/llm/src/call-config.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "SessionEvent", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "SendOptions", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "AgentCancelCause", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "InjectOptions", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "ResolvedAgentInput", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "AgentMessageId", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "AgentMessage", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "CancelOptions", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "Agent", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "HookContext", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "PromptDecision", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "ContinuationDecision", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "RequestError", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "RequestErrorDecision", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "ContinuationStop", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/core.zh.md", - "symbol": "SessionStartSource", - "source": "packages/core/agent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/scope.zh.md", - "symbol": "ScopeKey", - "source": "packages/core/scope/src/index.ts" - }, - { - "doc": "docs/core-data-structures/scope.zh.md", - "symbol": "Scoped", - "source": "packages/core/scope/src/index.ts" - }, - { - "doc": "docs/core-data-structures/scope.zh.md", - "symbol": "Scope", - "source": "packages/core/scope/src/index.ts" - }, - { - "doc": "docs/core-data-structures/scope.zh.md", - "symbol": "ScopeLayer", - "source": "packages/core/scope/src/store.ts" - }, - { - "doc": "docs/core-data-structures/system-prompt.zh.md", - "symbol": "AssembleContext", - "source": "packages/core/system-prompt/src/index.ts" - }, - { - "doc": "docs/core-data-structures/system-prompt.zh.md", - "symbol": "PromptSection", - "source": "packages/core/system-prompt/src/index.ts" - }, - { - "doc": "docs/core-data-structures/system-prompt.zh.md", - "symbol": "ToolProviderResult", - "source": "packages/core/system-prompt/src/index.ts" - }, - { - "doc": "docs/core-data-structures/llm-streaming.zh.md", - "symbol": "StreamChunk", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/llm-streaming.zh.md", - "symbol": "LlmFailure", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/llm-streaming.zh.md", - "symbol": "TokenUsage", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/llm-streaming.zh.md", - "symbol": "ContentBlockMap", - "source": "packages/llm/llm/src/types.ts" - }, - { - "doc": "docs/core-data-structures/llm-streaming.zh.md", - "symbol": "AppIdentity", - "source": "packages/llm/llm/src/attribution.ts" - }, - { - "doc": "docs/core-data-structures/llm-streaming.zh.md", - "symbol": "BlockAssembler", - "source": "packages/llm/llm/src/assembler.ts", - "projection": "public-api" - }, - { - "doc": "docs/core-data-structures/llm-streaming.zh.md", - "symbol": "LlmAdapter", - "source": "packages/llm/llm/src/index.ts", - "projection": "public-api" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "PromptMessageData", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SessionEventMap", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "OutOfBandSessionEventMap", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "EpochHeader", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "TodoItem", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SessionEvent", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "TurnTriggerMap", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "TurnEndReasonMap", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SurfaceEventType", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SurfaceOp", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SurfaceIntent", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SessionSurface", - "source": "packages/core/session/src/surface.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SurfaceFoldReplacement", - "source": "packages/core/session/src/surface.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "SurfaceFoldResult", - "source": "packages/core/session/src/surface.ts" - }, - { - "doc": "docs/core-data-structures/session.zh.md", - "symbol": "Session", - "source": "packages/core/session/src/index.ts", - "projection": "public-api" - }, - { - "doc": "docs/core-data-structures/persistence.zh.md", - "symbol": "SessionHeader", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/persistence.zh.md", - "symbol": "CreateSessionOptions", - "source": "packages/core/session/src/types.ts" - }, - { - "doc": "docs/core-data-structures/persistence.zh.md", - "symbol": "SessionLocation", - "source": "packages/session-persistence/session-persistence/src/index.ts" - }, - { - "doc": "docs/core-data-structures/persistence.zh.md", - "symbol": "SessionPersistenceRevision", - "source": "packages/session-persistence/session-persistence/src/revision.ts" - }, - { - "doc": "docs/core-data-structures/persistence.zh.md", - "symbol": "SessionPersistenceSnapshot", - "source": "packages/session-persistence/session-persistence/src/index.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventSurface", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionRecord", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionLogSnapshot", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionSurfaceSnapshot", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionTitleObservation", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionTitleObservationResult", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventRecord", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionResultFilter", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventResultFilter", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventSearchDocument", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionSearchCursor", - "source": "packages/session-query/session-query/src/cursor.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionSearchRequest", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventSearchRequest", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionSearchPage", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventSearchPage", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventSearchHit", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionSearchHit", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionLineageNode", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionLineageTrace", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionQueryErrorCode", - "source": "packages/session-query/session-query/src/config.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventReadRequest", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventWindow", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventTraceRequest", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventTrace", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/session-query.zh.md", - "symbol": "SessionEventTraceObservation", - "source": "packages/session-query/session-query/src/types.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolOutputDefinition", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolDefinition", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ValueSchemaSpec", - "source": "packages/core/tools/src/schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ParameterPropertySpec", - "source": "packages/core/tools/src/schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ParameterSchemaSpec", - "source": "packages/core/tools/src/schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "InferValue", - "source": "packages/core/tools/src/schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "InferArgs", - "source": "packages/core/tools/src/schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolExecutionToken", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolExecutionInput", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolExecution", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolDispatchExecution", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolExecutionMode", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolRunContext", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolGuard", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolRestriction", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolFailure", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolExecutionSuccess", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolExecutionFailure", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ToolExecutionResult", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "PreToolDecision", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "PostToolDecision", - "source": "packages/core/tools/src/index.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "JsonSchemaScalar", - "source": "packages/core/tools/src/json-schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "JsonSchemaType", - "source": "packages/core/tools/src/json-schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "JsonSchemaNode", - "source": "packages/core/tools/src/json-schema.ts" - }, - { - "doc": "docs/core-data-structures/tools.zh.md", - "symbol": "ObjectJsonSchema", - "source": "packages/core/tools/src/json-schema.ts" - }, - { - "doc": "docs/core-data-structures/user-interaction.zh.md", - "symbol": "AskUserQuestionOption", - "source": "packages/ui/user-interaction/src/types.ts" - }, - { - "doc": "docs/core-data-structures/user-interaction.zh.md", - "symbol": "AskUserQuestionItem", - "source": "packages/ui/user-interaction/src/types.ts" - }, - { - "doc": "docs/core-data-structures/user-interaction.zh.md", - "symbol": "AskUserQuestionRequest", - "source": "packages/ui/user-interaction/src/index.ts" - }, - { - "doc": "docs/core-data-structures/user-interaction.zh.md", - "symbol": "AskUserQuestionAnswerItem", - "source": "packages/ui/user-interaction/src/types.ts" - }, - { - "doc": "docs/core-data-structures/user-interaction.zh.md", - "symbol": "AskUserQuestionAnswer", - "source": "packages/ui/user-interaction/src/types.ts" - }, - { - "doc": "docs/core-data-structures/user-interaction.zh.md", - "symbol": "UserInteractionProvider", - "source": "packages/ui/user-interaction/src/index.ts" - }, - { - "doc": "docs/core-data-structures/user-interaction.zh.md", - "symbol": "UserInteractionError", - "source": "packages/ui/user-interaction/src/index.ts" - }, - { - "doc": "docs/core-data-structures/approval.zh.md", - "symbol": "ApprovalRequestId", - "source": "packages/ui/user-approval/src/types.ts" - }, - { - "doc": "docs/core-data-structures/approval.zh.md", - "symbol": "ApprovalOutcome", - "source": "packages/ui/user-approval/src/types.ts" - }, - { - "doc": "docs/core-data-structures/approval.zh.md", - "symbol": "ApprovalPolicy", - "source": "packages/ui/user-approval/src/index.ts" - }, - { - "doc": "docs/core-data-structures/approval.zh.md", - "symbol": "ApprovalRequest", - "source": "packages/ui/user-approval/src/index.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "DshEnvironmentKey", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "DshEnvironment", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "BashExecRequest", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "BashExecSpec", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "BashRunResult", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "BashSandboxInfo", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "CollectedOutput", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "BashProcess", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/bash.zh.md", - "symbol": "BashProcessRead", - "source": "packages/bash/bash/src/types.ts" - }, - { - "doc": "docs/core-data-structures/sandbox.zh.md", - "symbol": "SandboxMode", - "source": "packages/sandbox/sandbox/src/index.ts" - }, - { - "doc": "docs/core-data-structures/sandbox.zh.md", - "symbol": "ConfinedSandboxMode", - "source": "packages/sandbox/sandbox/src/index.ts" - }, - { - "doc": "docs/core-data-structures/sandbox.zh.md", - "symbol": "SandboxExecutionPolicy", - "source": "packages/sandbox/sandbox/src/index.ts" - }, - { - "doc": "docs/core-data-structures/sandbox.zh.md", - "symbol": "SandboxEnforcement", - "source": "packages/sandbox/sandbox/src/index.ts" - }, - { - "doc": "docs/core-data-structures/sandbox.zh.md", - "symbol": "SandboxPolicy", - "source": "packages/sandbox/sandbox/src/index.ts" - }, - { - "doc": "docs/core-data-structures/sandbox.zh.md", - "symbol": "SandboxPolicyRequest", - "source": "packages/sandbox/sandbox-policy/src/index.ts" - }, - { - "doc": "docs/core-data-structures/sandbox.zh.md", - "symbol": "ConfinedArgv", - "source": "packages/sandbox/sandbox/src/index.ts" - }, - { - "doc": "docs/core-data-structures/code-runtime.zh.md", - "symbol": "CodeJsonValue", - "source": "packages/code-runtime/code-runtime/src/types.ts" - }, - { - "doc": "docs/core-data-structures/code-runtime.zh.md", - "symbol": "CodeRunRequest", - "source": "packages/code-runtime/code-runtime/src/types.ts" - }, - { - "doc": "docs/core-data-structures/code-runtime.zh.md", - "symbol": "CodeRunResult", - "source": "packages/code-runtime/code-runtime/src/types.ts" - }, - { - "doc": "docs/core-data-structures/code-runtime.zh.md", - "symbol": "CodeBindingNamespace", - "source": "packages/code-runtime/code-runtime/src/types.ts" - }, - { - "doc": "docs/core-data-structures/code-runtime.zh.md", - "symbol": "CodeBindingErrorClass", - "source": "packages/code-runtime/code-runtime/src/types.ts" - }, - { - "doc": "docs/core-data-structures/code-runtime.zh.md", - "symbol": "CodeBindingFunction", - "source": "packages/code-runtime/code-runtime/src/types.ts" - }, - { - "doc": "docs/core-data-structures/code-runtime.zh.md", - "symbol": "CodeRunFailure", - "source": "packages/code-runtime/code-runtime/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsTarget", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsTargetKey", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsVersion", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsInfo", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsPathInfo", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsDirEntry", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsWriteIntent", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsWriteOutcome", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsEditRequest", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsEditOutcome", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsErrorCode", - "source": "packages/fs/fs/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FsPolicyExec", - "source": "packages/fs/fs-policy/src/types.ts" - }, - { - "doc": "docs/core-data-structures/filesystem.zh.md", - "symbol": "FileReadOutcome", - "source": "packages/fs/tool-fs/src/read-render.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillSource", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillResourceBase", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillSummary", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillCandidate", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillDefinition", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillRegistration", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillLookupOptions", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "SkillProvider", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/skills.zh.md", - "symbol": "Config", - "source": "packages/skill/skill/src/index.ts" - }, - { - "doc": "docs/core-data-structures/compaction.zh.md", - "symbol": "CompactionResult", - "source": "packages/compact/compact/src/types.ts" - }, - { - "doc": "docs/core-data-structures/compaction.zh.md", - "symbol": "CompactionTrigger", - "source": "packages/compact/compact/src/index.ts" - }, - { - "doc": "docs/core-data-structures/compaction.zh.md", - "symbol": "PrunedEntry", - "source": "packages/compact/compact-tool-result-prune/src/types.ts" - }, - { - "doc": "docs/core-data-structures/compaction.zh.md", - "symbol": "PruneResult", - "source": "packages/compact/compact-tool-result-prune/src/types.ts" - }, - { - "doc": "docs/core-data-structures/subagent.zh.md", - "symbol": "SubagentCapabilities", - "source": "packages/subagent/subagent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/subagent.zh.md", - "symbol": "SubagentStartRequest", - "source": "packages/subagent/subagent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/subagent.zh.md", - "symbol": "SubagentResult", - "source": "packages/subagent/subagent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/subagent.zh.md", - "symbol": "SubagentStopReasonMap", - "source": "packages/subagent/subagent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/subagent.zh.md", - "symbol": "SubagentRun", - "source": "packages/subagent/subagent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/subagent.zh.md", - "symbol": "SubagentProvider", - "source": "packages/subagent/subagent/src/types.ts" - }, - { - "doc": "docs/core-data-structures/web.zh.md", - "symbol": "WebSearchRequest", - "source": "packages/web/web/src/types.ts" - }, - { - "doc": "docs/core-data-structures/web.zh.md", - "symbol": "WebSearchResult", - "source": "packages/web/web/src/types.ts" - }, - { - "doc": "docs/core-data-structures/web.zh.md", - "symbol": "WebSearchSource", - "source": "packages/web/web/src/types.ts" - }, - { - "doc": "docs/core-data-structures/web.zh.md", - "symbol": "WebFetchRequest", - "source": "packages/web/web/src/types.ts" - }, - { - "doc": "docs/core-data-structures/web.zh.md", - "symbol": "WebFetchResult", - "source": "packages/web/web/src/types.ts" - }, - { - "doc": "docs/core-data-structures/web.zh.md", - "symbol": "WebFetchBody", - "source": "packages/web/web/src/types.ts" - }, - { - "doc": "docs/core-data-structures/workflow.zh.md", - "symbol": "WorkflowStartRequest", - "source": "packages/workflow/workflow/src/types.ts" - }, - { - "doc": "docs/core-data-structures/workflow.zh.md", - "symbol": "WorkflowMeta", - "source": "packages/workflow/workflow/src/types.ts" - }, - { - "doc": "docs/core-data-structures/workflow.zh.md", - "symbol": "WorkflowResult", - "source": "packages/workflow/workflow/src/types.ts" - }, - { - "doc": "docs/core-data-structures/workflow.zh.md", - "symbol": "WorkflowRun", - "source": "packages/workflow/workflow/src/types.ts" } ] } diff --git a/scripts/verify-type-equiv.ts b/scripts/verify-type-equiv.ts index 7a3d2305d7..58cfea238d 100644 --- a/scripts/verify-type-equiv.ts +++ b/scripts/verify-type-equiv.ts @@ -4,12 +4,14 @@ * declaration; `public-api` entries preserve a class's body-stripped public * declaration. Blocks and entries have a one-to-one relationship; comparison * ignores whitespace and non-JSDoc comments but preserves declaration - * structure and every original JSDoc comment. + * structure and every original JSDoc comment. Byte-identical `.zh.md` blocks + * reuse the manifest-backed check of their unsuffixed sibling. */ import { globSync, readFileSync, existsSync } from 'node:fs' import { resolve, sep } from 'node:path' import ts from 'typescript' +import { partitionPairedMarkdownDerivatives } from './paired-markdown-derivatives.ts' const root = resolve(import.meta.dirname, '..') @@ -223,7 +225,12 @@ const docSet = new Set() for (const pattern of MARKDOWN_GLOBS) { for (const match of globSync(pattern, { cwd: root })) docSet.add(match.split(sep).join('/')) } -const blocks: EquivBlock[] = [...docSet].sort().flatMap(extractEquivBlocks) +const extractedBlocks: EquivBlock[] = [...docSet].sort().flatMap(extractEquivBlocks) +const { primary: blocks, derivatives } = partitionPairedMarkdownDerivatives( + extractedBlocks, + block => block.doc, + block => `${block.projection ?? 'declaration'}\0${block.code}`, +) const errors: string[] = [] // A manifest entry naming a doc that does not exist (or is outside the scanned @@ -299,11 +306,11 @@ for (const e of entries) { } if (errors.length === 0) { - console.log(`verify-type-equiv: ${verified} type-equiv block(s) match source structure and JSDoc (1:1 with manifest).`) + console.log(`verify-type-equiv: ${verified} type-equiv block(s) match source structure and JSDoc (1:1 with manifest); ${derivatives.length} paired derivative(s).`) process.exit(0) } console.error('verify-type-equiv: type-equiv verification failed:') for (const e of errors) console.error(` ${e}`) -console.error(`\n(checked ${blocks.length} block(s) across ${new Set(blocks.map(b => b.doc)).size} doc(s); manifest at scripts/type-equiv.manifest.json)`) +console.error(`\n(checked ${blocks.length} primary block(s) across ${new Set(blocks.map(b => b.doc)).size} doc(s), ${derivatives.length} paired derivative(s); manifest at scripts/type-equiv.manifest.json)`) process.exit(1) From a3ee5dd8a0c2ba5ddc850b485eb07f88cb11fff1 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:54:29 +0800 Subject: [PATCH 100/113] docs(gui): regenerate graphs and sync the note's English pair Generated docs follow the ui-models rename and the removed ui-settings-general package; the English note side picks up the feature-owner self-registration doctrine. --- ...-25-client-settings-locale-theme.i18n.yaml | 4 +- ...2026-07-25-client-settings-locale-theme.md | 2 +- docs/config-catalog.md | 3 +- docs/event-producer-consumer.md | 4 +- docs/module-graph.md | 41 +++++----- .../client/locale/tests/language-row.spec.tsx | 82 +++++++++++++++++++ .../locale/tests/settings-store.spec.ts | 30 +++++++ .../client/ui-settings/tests/apply.spec.ts | 6 +- .../tests/general-section.spec.tsx | 4 + .../ui-theme/tests/appearance-row.spec.tsx | 75 +++++++++++++++++ .../ui-theme/tests/settings-store.spec.ts | 28 +++++++ 11 files changed, 250 insertions(+), 29 deletions(-) create mode 100644 packages/client/locale/tests/language-row.spec.tsx create mode 100644 packages/client/locale/tests/settings-store.spec.ts create mode 100644 packages/client/ui-theme/tests/appearance-row.spec.tsx create mode 100644 packages/client/ui-theme/tests/settings-store.spec.ts diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml index 8583642403..39d7377c54 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.i18n.yaml +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.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 -2026-07-25-client-settings-locale-theme.md: e1245a9e1fac82fb0feb84af7a59945b17fa1daf -2026-07-25-client-settings-locale-theme.zh.md: 195b2e5ffa3556dd1b8bf2dd6ec8ae84115fbdb2 +2026-07-25-client-settings-locale-theme.md: 658e6bd3c2da39a98e476c60f10f3f51ad82e5ea +2026-07-25-client-settings-locale-theme.zh.md: dfe93a0ca1f53380c653886c73fe0c32b08d8443 diff --git a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md index 0dfcb4ea90..658e6bd3c2 100644 --- a/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md +++ b/.agents/notes/proposed/architecture/2026-07-25-client-settings-locale-theme.md @@ -119,4 +119,4 @@ Locale ships with 中文 and English built in; `setLocale`/`setTheme` are the on ## Risks -The apply order of slot declarations and contributions is not fixed, so every new section must keep declaration-aware registration and idempotence guards. Service events may fire before a section's first render, so both the General store's init and the controller attach must align to the current snapshot from the getters. Layout must clean up the global attributes it set on unmount, and ThemeService must remove its matchMedia listener on dispose, so nothing lingers after HMR. +The apply order of slot declarations and contributions is not fixed, so every section/item registrant must keep declaration-aware registration and judge presence by the ledger, not by a local disposer. Service events may fire before a row's first render, so both a feature row store's init and the inject attach must align to the current snapshot from the getter. The duplicated merge copies of `settings.general.item` (locale, ui-theme) must stay verbatim-identical to the ui-settings canonical home — any drift means changing all three together. Layout must clean up the global attributes it set on unmount, and ThemeService must remove its matchMedia listener on dispose, so nothing lingers after HMR. diff --git a/docs/config-catalog.md b/docs/config-catalog.md index ede904e1a5..1940811d35 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2022,10 +2022,9 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-client-runtime` ([`packages/client/runtime/src/index.ts`](../packages/client/runtime/src/index.ts)) - `@deepseek-ai/dsh-client-ui-conversation` ([`packages/client/ui-conversation/src/index.ts`](../packages/client/ui-conversation/src/index.ts)) - `@deepseek-ai/dsh-client-ui-layout` ([`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-models` ([`packages/client/ui-models/src/index.ts`](../packages/client/ui-models/src/index.ts)) - `@deepseek-ai/dsh-client-ui-question` — requires `tools` · `userInteraction` ([`packages/client/ui-question/src/index.ts`](../packages/client/ui-question/src/index.ts)) - `@deepseek-ai/dsh-client-ui-settings` ([`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts)) -- `@deepseek-ai/dsh-client-ui-settings-general` ([`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts)) -- `@deepseek-ai/dsh-client-ui-settings-models` ([`packages/client/ui-settings-models/src/index.ts`](../packages/client/ui-settings-models/src/index.ts)) - `@deepseek-ai/dsh-client-ui-sidebar` ([`packages/client/ui-sidebar/src/index.ts`](../packages/client/ui-sidebar/src/index.ts)) - `@deepseek-ai/dsh-client-ui-theme` ([`packages/client/ui-theme/src/index.ts`](../packages/client/ui-theme/src/index.ts)) - `@deepseek-ai/dsh-client-ui-trajectory` ([`packages/client/ui-trajectory/src/index.ts`](../packages/client/ui-trajectory/src/index.ts)) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 2c1e85fb3c..53cd56f4cf 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -63,8 +63,8 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `internal/dispatch` | - | [`compact`](../packages/compact/compact), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`pty-local`](../packages/pty/pty-local), `runtime`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`workflow`](../packages/workflow/workflow) | | `internal/plugin` | - | `hmr`, `modules`, `webserver` | | `internal/status` | - | [`agent`](../packages/core/agent) | -| `locale/change` | `locale` (`emit`) | `ui-settings-general`, `ui-settings-models` | +| `locale/change` | `locale` (`emit`) | `locale`, `ui-models`, `ui-settings` | | `slots/changed` | `runtime` (`emit`) | - | -| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-settings-general` | +| `theme/change` | `ui-theme` (`emit`) | `ui-layout`, `ui-theme` | Maintenance mode: generated: Cordis event declarations and producer/listener edges are resolved from the repository TypeScript Program. diff --git a/docs/module-graph.md b/docs/module-graph.md index c47bd92d83..4903e432cd 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -141,11 +141,10 @@ flowchart TD pkg_client_runtime["client-runtime"] pkg_client_ui_conversation["client-ui-conversation"] pkg_client_ui_layout["client-ui-layout"] + pkg_client_ui_models["client-ui-models"] pkg_client_ui_primitives["client-ui-primitives"] pkg_client_ui_question["client-ui-question"] pkg_client_ui_settings["client-ui-settings"] - pkg_client_ui_settings_general["client-ui-settings-general"] - pkg_client_ui_settings_models["client-ui-settings-models"] pkg_client_ui_sidebar["client-ui-sidebar"] pkg_client_ui_slots["client-ui-slots"] pkg_client_ui_theme["client-ui-theme"] @@ -228,13 +227,11 @@ flowchart TD pkg_subagent_subprocess --> pkg_invariants pkg_acp_snapshot --> pkg_invariants pkg_loader_smoke --> pkg_invariants - pkg_client_locale --> pkg_invariants pkg_client_modules --> pkg_invariants pkg_client_runtime --> pkg_invariants pkg_client_ui_primitives --> pkg_invariants pkg_client_ui_question --> pkg_invariants pkg_client_ui_slots --> pkg_invariants - pkg_client_ui_theme --> pkg_invariants pkg_client_ui_trajectory --> pkg_invariants pkg_client_web --> pkg_invariants pkg_client_web_react --> pkg_invariants @@ -250,25 +247,21 @@ flowchart TD pkg_client_hmr --> pkg_client_modules pkg_client_hmr --> pkg_host_webserver pkg_client_hmr --> pkg_invariants + pkg_client_locale --> pkg_client_runtime + pkg_client_locale --> pkg_client_ui_primitives + pkg_client_locale --> pkg_client_ui_slots + pkg_client_locale --> pkg_invariants pkg_client_ui_conversation --> pkg_client_runtime pkg_client_ui_conversation --> pkg_client_ui_primitives pkg_client_ui_conversation --> pkg_client_ui_slots pkg_client_ui_conversation --> pkg_invariants - pkg_client_ui_layout --> pkg_client_runtime - pkg_client_ui_layout --> pkg_client_ui_slots - pkg_client_ui_layout --> pkg_client_ui_theme - pkg_client_ui_layout --> pkg_invariants + pkg_client_ui_models --> pkg_client_runtime + pkg_client_ui_models --> pkg_client_ui_slots + pkg_client_ui_models --> pkg_invariants pkg_client_ui_settings --> pkg_client_runtime pkg_client_ui_settings --> pkg_client_ui_primitives pkg_client_ui_settings --> pkg_client_ui_slots pkg_client_ui_settings --> pkg_invariants - pkg_client_ui_settings_general --> pkg_client_runtime - pkg_client_ui_settings_general --> pkg_client_ui_primitives - pkg_client_ui_settings_general --> pkg_client_ui_slots - pkg_client_ui_settings_general --> pkg_invariants - pkg_client_ui_settings_models --> pkg_client_runtime - pkg_client_ui_settings_models --> pkg_client_ui_slots - pkg_client_ui_settings_models --> pkg_invariants pkg_client_ui_sidebar --> pkg_client_runtime pkg_client_ui_sidebar --> pkg_client_ui_primitives pkg_client_ui_sidebar --> pkg_client_ui_slots @@ -303,6 +296,11 @@ flowchart TD pkg_system_prompt --> pkg_scope pkg_web --> pkg_invariants pkg_web --> pkg_llm + pkg_client_ui_theme --> pkg_client_locale + pkg_client_ui_theme --> pkg_client_runtime + pkg_client_ui_theme --> pkg_client_ui_primitives + pkg_client_ui_theme --> pkg_client_ui_slots + pkg_client_ui_theme --> pkg_invariants pkg_lsp --> pkg_brand pkg_lsp --> pkg_invariants pkg_lsp --> pkg_llm @@ -355,6 +353,10 @@ flowchart TD pkg_app_boot --> pkg_invariants pkg_app_boot --> pkg_paths pkg_app_boot --> pkg_system_prompt + pkg_client_ui_layout --> pkg_client_runtime + pkg_client_ui_layout --> pkg_client_ui_slots + pkg_client_ui_layout --> pkg_client_ui_theme + pkg_client_ui_layout --> pkg_invariants pkg_code_runtime_worker --> pkg_code_runtime pkg_code_runtime_worker --> pkg_invariants pkg_code_runtime_worker --> pkg_session @@ -813,13 +815,11 @@ flowchart TD | [`subagent-subprocess`](../packages/subagent/subagent-subprocess) | `subagent` | [`invariants`](../packages/support/invariants) | | [`acp-snapshot`](../packages/support/acp-snapshot) | `support` | [`invariants`](../packages/support/invariants) | | [`loader-smoke`](../packages/support/loader-smoke) | `support` | [`invariants`](../packages/support/invariants) | -| [`client-locale`](../packages/client/locale) | `client` | [`invariants`](../packages/support/invariants) | | [`client-modules`](../packages/client/modules) | `client` | [`invariants`](../packages/support/invariants) | | [`client-runtime`](../packages/client/runtime) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-primitives`](../packages/client/ui-primitives) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-question`](../packages/client/ui-question) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-slots`](../packages/client/ui-slots) | `client` | [`invariants`](../packages/support/invariants) | -| [`client-ui-theme`](../packages/client/ui-theme) | `client` | [`invariants`](../packages/support/invariants) | | [`client-ui-trajectory`](../packages/client/ui-trajectory) | `client` | [`invariants`](../packages/support/invariants) | | [`client-web`](../packages/client/web) | `client` | [`invariants`](../packages/support/invariants) | | [`client-web-react`](../packages/client/web-react) | `client` | [`invariants`](../packages/support/invariants) | @@ -831,11 +831,10 @@ flowchart TD | [`llm`](../packages/llm/llm) | `llm` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | | [`client-connection`](../packages/client/connection) | `client` | [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/support/invariants) | | [`client-hmr`](../packages/client/hmr) | `client` | [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver), [`invariants`](../packages/support/invariants) | +| [`client-locale`](../packages/client/locale) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-conversation`](../packages/client/ui-conversation) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-theme`](../packages/client/ui-theme), [`invariants`](../packages/support/invariants) | +| [`client-ui-models`](../packages/client/ui-models) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`client-ui-settings-models`](../packages/client/ui-settings-models) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`helper`](../packages/sdk/helper) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants) | @@ -848,6 +847,7 @@ flowchart TD | [`session`](../packages/core/session) | `core` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`system-prompt`](../packages/core/system-prompt) | `core` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope) | | [`web`](../packages/web/web) | `web` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | +| [`client-ui-theme`](../packages/client/ui-theme) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -865,6 +865,7 @@ flowchart TD | [`session-title`](../packages/session-title/session-title) | `session-title` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-replay`](../packages/support/llm-replay) | `support` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`app-boot`](../packages/ui/app-boot) | `ui` | [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths), [`system-prompt`](../packages/core/system-prompt) | +| [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-theme`](../packages/client/ui-theme), [`invariants`](../packages/support/invariants) | | [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | `code-runtime` | [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session) | | [`lsp-local`](../packages/lsp/lsp-local) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`timeout`](../packages/util/timeout) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | diff --git a/packages/client/locale/tests/language-row.spec.tsx b/packages/client/locale/tests/language-row.spec.tsx new file mode 100644 index 0000000000..af33038970 --- /dev/null +++ b/packages/client/locale/tests/language-row.spec.tsx @@ -0,0 +1,82 @@ +// @vitest-environment jsdom +/** LanguageRow behavior: selector pill shows the active locale, the menu + * opens/closes, and selection drives setLocale. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { createSnapshotStore, type SessionListState, type WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import { LanguageRow } from '../src/client/LanguageRow.tsx' +import type { LanguageRowComponentProps } from '../src/client/LanguageRow.tsx' +import { createLanguageRowStore } from '../src/client/settings-store.ts' + +afterEach(cleanup) + +const OPTIONS = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }] + +/** Empty global standard-kit hooks (the row reads neither). */ +function emptySessions() { + const store = createSnapshotStore( + { ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' }) + return bindSnapshotSelector(store) +} +function emptyWorkspaces() { + const store = createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) + return bindSnapshotSelector(store) +} + +function mount(active = 'en') { + // Real store instance — the sanctioned zero-machinery path for tests. + const store = createLanguageRowStore().create() + store.actions.sync(active, OPTIONS, 0) + const setLocale = vi.fn() + const props: LanguageRowComponentProps = { + useSessions: emptySessions(), + useWorkspaces: emptyWorkspaces(), + useStore: bindSnapshotSelector(store), + actions: store.actions, + t: (key: string) => key === 'language.title' ? 'Language' : key, + setLocale, + } + render() + return { store, setLocale } +} + +describe('LanguageRow', () => { + it('shows the title and the active locale label on the selector pill', () => { + mount('en') + expect(screen.getByText('Language')).toBeDefined() + const trigger = screen.getByRole('button', { name: /English/ }) + expect(trigger.getAttribute('aria-expanded')).toBe('false') + }) + + it('opens the menu, selects a locale, and closes', () => { + const b = mount('en') + const trigger = screen.getByRole('button', { name: /English/ }) + fireEvent.click(trigger) + expect(trigger.getAttribute('aria-expanded')).toBe('true') + fireEvent.click(screen.getByRole('menuitem', { name: '中文' })) + expect(b.setLocale).toHaveBeenCalledWith('zh') + expect(trigger.getAttribute('aria-expanded')).toBe('false') + expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull() + }) + + it('closes on outside pointerdown without selecting', () => { + const b = mount('en') + fireEvent.click(screen.getByRole('button', { name: /English/ })) + expect(screen.getByRole('menuitem', { name: '中文' })).toBeDefined() + fireEvent.pointerDown(document.body) + expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull() + expect(b.setLocale).not.toHaveBeenCalled() + }) + + it('follows store changes; an unknown active id falls back to the id itself', () => { + const b = mount('en') + act(() => { b.store.actions.sync('zh', OPTIONS, 1) }) + expect(screen.getByRole('button', { name: /中文/ })).toBeDefined() + act(() => { b.store.actions.sync('fr', OPTIONS, 2) }) + expect(screen.getByRole('button', { name: /fr/ })).toBeDefined() + }) +}) diff --git a/packages/client/locale/tests/settings-store.spec.ts b/packages/client/locale/tests/settings-store.spec.ts new file mode 100644 index 0000000000..90e9487a96 --- /dev/null +++ b/packages/client/locale/tests/settings-store.spec.ts @@ -0,0 +1,30 @@ +/** Language row store: snapshot-mirror action and the revision guard. */ +import { describe, expect, it } from 'vitest' +import { createLanguageRowStore } from '../src/client/settings-store.ts' + +const OPTIONS = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }] + +describe('createLanguageRowStore', () => { + it('init shape: empty mirror with revision at -1', () => { + const store = createLanguageRowStore().create() + expect(store.getSnapshot()).toEqual({ active: '', options: [], revision: -1 }) + }) + + it('sync mirrors the snapshot and advances the revision', () => { + const store = createLanguageRowStore().create() + store.actions.sync('zh', OPTIONS, 0) + expect(store.getSnapshot()).toEqual({ active: 'zh', options: OPTIONS, revision: 0 }) + store.actions.sync('en', OPTIONS, 1) + expect(store.getSnapshot().active).toBe('en') + expect(store.getSnapshot().revision).toBe(1) + }) + + it('revision guard drops stale and duplicate writes', () => { + const store = createLanguageRowStore().create() + store.actions.sync('en', OPTIONS, 5) + store.actions.sync('zh', OPTIONS, 4) + store.actions.sync('zh', OPTIONS, 5) + expect(store.getSnapshot().active).toBe('en') + expect(store.getSnapshot().revision).toBe(5) + }) +}) diff --git a/packages/client/ui-settings/tests/apply.spec.ts b/packages/client/ui-settings/tests/apply.spec.ts index 95684404a1..2346012553 100644 --- a/packages/client/ui-settings/tests/apply.spec.ts +++ b/packages/client/ui-settings/tests/apply.spec.ts @@ -82,10 +82,12 @@ describe('ui-settings apply', () => { // empty once apply settles. expect(injected.sections()).toEqual([{ id: 'general', order: 0, label: '通用设置' }]) b.slots.register({ name: 'settings.section', id: 'z', order: 20, label: 'Z' } as never, () => null) - b.slots.register({ name: 'settings.section', id: 'a', order: 5 } as never, () => null) + // No order and no label: both projection defaults apply (order 0 ties + // keep registration sequence, so 'a' lands after the General entry). + b.slots.register({ name: 'settings.section', id: 'a' } as never, () => null) expect(injected.sections()).toEqual([ { id: 'general', order: 0, label: '通用设置' }, - { id: 'a', order: 5, label: '' }, + { id: 'a', order: 0, label: '' }, { id: 'z', order: 20, label: 'Z' }, ]) expect(injected.sectionsVersion()).toBe(b.slots.getVersion('settings.section')) diff --git a/packages/client/ui-settings/tests/general-section.spec.tsx b/packages/client/ui-settings/tests/general-section.spec.tsx index a944dd8b15..ce09aabf93 100644 --- a/packages/client/ui-settings/tests/general-section.spec.tsx +++ b/packages/client/ui-settings/tests/general-section.spec.tsx @@ -11,7 +11,11 @@ function mount() { const renderSlot = vi.fn( ((key: string) =>
) as GeneralSectionComponentProps['renderSlot'], ) + // Global standard kit stubs: the section consumes neither hook. + const unusedHook = (() => { throw new Error('unused by GeneralSection') }) as never const props: GeneralSectionComponentProps = { + useSessions: unusedHook, + useWorkspaces: unusedHook, t: (key) => en[key] ?? key, renderSlot, } diff --git a/packages/client/ui-theme/tests/appearance-row.spec.tsx b/packages/client/ui-theme/tests/appearance-row.spec.tsx new file mode 100644 index 0000000000..4782b674a8 --- /dev/null +++ b/packages/client/ui-theme/tests/appearance-row.spec.tsx @@ -0,0 +1,75 @@ +// @vitest-environment jsdom +/** AppearanceRow behavior: three cubes, selection follows the persisted + * preference, clicks drive setTheme. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { createSnapshotStore, type SessionListState, type WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client' +import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react' +import { AppearanceRow } from '../src/client/AppearanceRow.tsx' +import type { AppearanceRowComponentProps } from '../src/client/AppearanceRow.tsx' +import { createAppearanceRowStore } from '../src/client/settings-store.ts' +import type { ThemePreference } from '../src/client/index.ts' + +afterEach(cleanup) + +const COPY: Record = { + 'appearance.title': 'Appearance', + 'appearance.light': 'Light', + 'appearance.dark': 'Dark', + 'appearance.system': 'System', +} + +/** Empty global standard-kit hooks (the row reads neither). */ +function emptySessions() { + const store = createSnapshotStore( + { ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' }) + return bindSnapshotSelector(store) +} +function emptyWorkspaces() { + const store = createSnapshotStore({ + items: [], intent: undefined, state: 'idle', phase: 'ready', error: null, + baselinesReady: true, recentWorkspaceId: undefined, + }) + return bindSnapshotSelector(store) +} + +function mount(preference: ThemePreference = 'system') { + // Real store instance — the sanctioned zero-machinery path for tests. + const store = createAppearanceRowStore().create() + store.actions.sync(preference, 0) + const setTheme = vi.fn() + const props: AppearanceRowComponentProps = { + useSessions: emptySessions(), + useWorkspaces: emptyWorkspaces(), + useStore: bindSnapshotSelector(store), + actions: store.actions, + t: (key: string) => COPY[key] ?? key, + setTheme, + } + render() + return { store, setTheme } +} + +const pressed = (name: RegExp): string | null => + screen.getByRole('button', { name }).getAttribute('aria-pressed') + +describe('AppearanceRow', () => { + it('renders the title and three cubes with the preference cube selected', () => { + mount('dark') + expect(screen.getByText('Appearance')).toBeDefined() + expect(pressed(/Dark/)).toBe('true') + expect(pressed(/Light/)).toBe('false') + expect(pressed(/System/)).toBe('false') + }) + + it('click drives setTheme; selection follows the store mirror, not the click echo', () => { + const b = mount('dark') + fireEvent.click(screen.getByRole('button', { name: /Light/ })) + expect(b.setTheme).toHaveBeenCalledWith('light') + // No store write yet: selection is unchanged. + expect(pressed(/Dark/)).toBe('true') + act(() => { b.store.actions.sync('light', 1) }) + expect(pressed(/Light/)).toBe('true') + expect(pressed(/Dark/)).toBe('false') + }) +}) diff --git a/packages/client/ui-theme/tests/settings-store.spec.ts b/packages/client/ui-theme/tests/settings-store.spec.ts new file mode 100644 index 0000000000..540d0f5b3b --- /dev/null +++ b/packages/client/ui-theme/tests/settings-store.spec.ts @@ -0,0 +1,28 @@ +/** Appearance row store: snapshot-mirror action and the revision guard. */ +import { describe, expect, it } from 'vitest' +import { createAppearanceRowStore } from '../src/client/settings-store.ts' + +describe('createAppearanceRowStore', () => { + it('init shape: system preference with revision at -1', () => { + const store = createAppearanceRowStore().create() + expect(store.getSnapshot()).toEqual({ preference: 'system', revision: -1 }) + }) + + it('sync mirrors the preference and advances the revision', () => { + const store = createAppearanceRowStore().create() + store.actions.sync('dark', 0) + expect(store.getSnapshot()).toEqual({ preference: 'dark', revision: 0 }) + store.actions.sync('light', 2) + expect(store.getSnapshot().preference).toBe('light') + expect(store.getSnapshot().revision).toBe(2) + }) + + it('revision guard drops stale and duplicate writes', () => { + const store = createAppearanceRowStore().create() + store.actions.sync('dark', 3) + store.actions.sync('system', 2) + store.actions.sync('system', 3) + expect(store.getSnapshot().preference).toBe('dark') + expect(store.getSnapshot().revision).toBe(3) + }) +}) From 0c9f310008160bf8db955b496afa0941e53d3c70 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 02:57:54 +0800 Subject: [PATCH 101/113] test(gui): apply-level suites for the feature-owned settings rows Locale and ui-theme apply coverage on a real Context + SlotCore: dictionary assembly, declaration-aware registration both ways, inject-time getter re-sync, service write-back through the event flow, HMR collapse recovery, and teardown reclamation. Four settings-surface packages sit at full per-file coverage. --- packages/client/locale/tests/apply.spec.ts | 116 ++++++++++++++++++ packages/client/ui-theme/tests/apply.spec.ts | 117 +++++++++++++++++++ 2 files changed, 233 insertions(+) create mode 100644 packages/client/locale/tests/apply.spec.ts create mode 100644 packages/client/ui-theme/tests/apply.spec.ts diff --git a/packages/client/locale/tests/apply.spec.ts b/packages/client/locale/tests/apply.spec.ts new file mode 100644 index 0000000000..25dbdfe239 --- /dev/null +++ b/packages/client/locale/tests/apply.spec.ts @@ -0,0 +1,116 @@ +/** locale apply wiring: service + dictionaries provision, declaration-aware + * Language row registration, snapshot projection into the row store, and + * recovery after an HMR collapse of the declaring entry. */ +import { Context } from 'cordis' +import { describe, expect, it } from 'vitest' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { apply, inject, SETTINGS_NS } from '@deepseek-ai/dsh-client-locale/client' +import type { LanguageRowInjected, LocaleService } from '@deepseek-ai/dsh-client-locale/client' +import { LanguageRow } from '../src/client/LanguageRow.tsx' +import type { createLanguageRowStore } from '../src/client/settings-store.ts' + +const SLOT = 'settings.general.item' + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + return { ctx, slots: ctx.get('slots') as SlotsService } +} + +/** Stand in for the settings shell: declare the General item slot from root. */ +function declareItems(slots: SlotsService): () => void { + return slots.register( + { name: 'root', children: { [SLOT]: { kind: 'list', scope: 'root' } } } as never, + () => null, + ) +} + +/** Mirror the framework's inject choreography: bake a real instance from the + * declared handle and hand its actions to the entry's inject factory. */ +function faceOf(slots: SlotsService) { + const entry = slots.entries(SLOT).find(e => e.component === LanguageRow)! + const handle = entry.store as ReturnType + const instance = handle.create() + const face = (entry.inject as unknown as (a: typeof instance.actions) => LanguageRowInjected)(instance.actions) + return { entry, instance, face } +} + +describe('locale apply', () => { + it('declares the slot service', () => { + expect(inject).toEqual(['slots']) + }) + + it('provides the service with base + settings dictionaries and registers the row (declaration before or after apply)', async () => { + const before = await bench() + declareItems(before.slots) + await before.ctx.plugin({ inject: [...inject], apply }).await() + const locale = before.ctx.get('locale') as LocaleService + // Base dictionaries are registered: the (ns, locale) seats are occupied. + expect(() => locale.register('common', 'zh', {})).toThrow('already has locale') + expect(() => locale.register('common', 'en', {})).toThrow('already has locale') + expect(locale.bind(SETTINGS_NS)('language.title')).toBe('语言') + const entry = before.slots.entries(SLOT).find(e => e.component === LanguageRow)! + expect(entry.options).toMatchObject({ id: 'language', order: 0 }) + + const after = await bench() + const fiber = after.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(after.slots.entries(SLOT)).toHaveLength(0) + declareItems(after.slots) + await Promise.resolve() + expect(after.slots.entries(SLOT).some(e => e.component === LanguageRow)).toBe(true) + }) + + it('projects service snapshots into the row store and routes face writes back', async () => { + const b = await bench() + declareItems(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const locale = b.ctx.get('locale') as LocaleService + // An event ahead of any inject hits the unbound-actions arm. + locale.setLocale('en') + + const { instance, face } = faceOf(b.slots) + // The inject-time re-sync sealed the init window: the mirror is current. + expect(instance.getSnapshot().active).toBe('en') + expect(instance.getSnapshot().options.map(o => o.id)).toEqual(['zh', 'en']) + expect(face.t('language.title')).toBe('Language') + + face.setLocale('zh') + expect(locale.getLocale().active).toBe('zh') + expect(instance.getSnapshot().active).toBe('zh') + expect(face.t('language.title')).toBe('语言') + }) + + it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => { + const b = await bench() + const host = declareItems(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries(SLOT)).toHaveLength(1) + + // Collapse: the declarer dies, the cascade removes our entry while the + // apply closure still holds its (now stale) disposer. + host() + expect(b.slots.entries(SLOT)).toHaveLength(0) + + declareItems(b.slots) + await Promise.resolve() + expect(b.slots.entries(SLOT).some(e => e.component === LanguageRow)).toBe(true) + }) + + it('teardown removes the row; teardown without a declaration is quiet', async () => { + const b = await bench() + declareItems(b.slots) + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(b.slots.entries(SLOT)).toHaveLength(1) + await fiber.dispose() + expect(b.slots.entries(SLOT)).toHaveLength(0) + + // Never-declared bench: the effect disposer's dispose arm stays undefined. + const quiet = await bench() + const f2 = quiet.ctx.plugin({ inject: [...inject], apply }) + await f2.await() + await f2.dispose() + expect(quiet.slots.entries(SLOT)).toHaveLength(0) + }) +}) diff --git a/packages/client/ui-theme/tests/apply.spec.ts b/packages/client/ui-theme/tests/apply.spec.ts new file mode 100644 index 0000000000..9852b93e66 --- /dev/null +++ b/packages/client/ui-theme/tests/apply.spec.ts @@ -0,0 +1,117 @@ +/** ui-theme apply wiring: service provision, settings dictionaries riding the + * locale service, declaration-aware Appearance row registration, snapshot + * projection into the row store, and HMR collapse recovery. */ +import { Context } from 'cordis' +import { describe, expect, it } from 'vitest' +import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' +import { apply, inject, SETTINGS_NS } from '@deepseek-ai/dsh-client-ui-theme/client' +import type { AppearanceRowInjected, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' +import { AppearanceRow } from '../src/client/AppearanceRow.tsx' +import type { createAppearanceRowStore } from '../src/client/settings-store.ts' + +const SLOT = 'settings.general.item' + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + const locale = new LocaleService(ctx) + ctx.provide('locale', locale) + return { ctx, slots: ctx.get('slots') as SlotsService, locale } +} + +/** Stand in for the settings shell: declare the General item slot from root. */ +function declareItems(slots: SlotsService): () => void { + return slots.register( + { name: 'root', children: { [SLOT]: { kind: 'list', scope: 'root' } } } as never, + () => null, + ) +} + +/** Mirror the framework's inject choreography: bake a real instance from the + * declared handle and hand its actions to the entry's inject factory. */ +function faceOf(slots: SlotsService) { + const entry = slots.entries(SLOT).find(e => e.component === AppearanceRow)! + const handle = entry.store as ReturnType + const instance = handle.create() + const face = (entry.inject as unknown as (a: typeof instance.actions) => AppearanceRowInjected)(instance.actions) + return { entry, instance, face } +} + +describe('ui-theme apply', () => { + it('declares the slot and locale services', () => { + expect(inject).toEqual(['slots', 'locale']) + }) + + it('provides the service, registers localized copy, and registers the row (declaration before or after apply)', async () => { + const before = await bench() + declareItems(before.slots) + await before.ctx.plugin({ inject: [...inject], apply }).await() + expect(before.locale.bind(SETTINGS_NS)('appearance.title')).toBe('外观') + before.locale.setLocale('en') + expect(before.locale.bind(SETTINGS_NS)('appearance.title')).toBe('Appearance') + const entry = before.slots.entries(SLOT).find(e => e.component === AppearanceRow)! + expect(entry.options).toMatchObject({ id: 'appearance', order: 10 }) + + const after = await bench() + const fiber = after.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(after.slots.entries(SLOT)).toHaveLength(0) + declareItems(after.slots) + await Promise.resolve() + expect(after.slots.entries(SLOT).some(e => e.component === AppearanceRow)).toBe(true) + }) + + it('projects service snapshots into the row store and routes face writes back', async () => { + const b = await bench() + declareItems(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + const theme = b.ctx.get('theme') as ThemeService + // An event ahead of any inject hits the unbound-actions arm. + theme.setTheme('dark') + + const { instance, face } = faceOf(b.slots) + // The inject-time re-sync sealed the init window: the mirror is current. + expect(instance.getSnapshot().preference).toBe('dark') + expect(face.t('appearance.dark')).toBe('深色') + + face.setTheme('system') + expect(theme.getTheme().preference).toBe('system') + expect(instance.getSnapshot().preference).toBe('system') + }) + + it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => { + const b = await bench() + const host = declareItems(b.slots) + await b.ctx.plugin({ inject: [...inject], apply }).await() + expect(b.slots.entries(SLOT)).toHaveLength(1) + + // Collapse: the declarer dies, the cascade removes our entry while the + // apply closure still holds its (now stale) disposer. + host() + expect(b.slots.entries(SLOT)).toHaveLength(0) + + declareItems(b.slots) + await Promise.resolve() + expect(b.slots.entries(SLOT).some(e => e.component === AppearanceRow)).toBe(true) + }) + + it('teardown removes the row and the dictionaries; teardown without a declaration is quiet', async () => { + const b = await bench() + declareItems(b.slots) + const fiber = b.ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(b.slots.entries(SLOT)).toHaveLength(1) + await fiber.dispose() + expect(b.slots.entries(SLOT)).toHaveLength(0) + // Dictionary disposal: translation falls back to the bare key. + expect(b.locale.bind(SETTINGS_NS)('appearance.title')).toBe('appearance.title') + + // Never-declared bench: the effect disposer's dispose arm stays undefined. + const quiet = await bench() + const f2 = quiet.ctx.plugin({ inject: [...inject], apply }) + await f2.await() + await f2.dispose() + expect(quiet.slots.entries(SLOT)).toHaveLength(0) + }) +}) From c5d323e8e599e63dc0c3eeff4f8c46209e9fc953 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 03:22:35 +0800 Subject: [PATCH 102/113] fix(gui): follow-ups for the feature-owned settings surfaces The ui-layout apply bench provides a real LocaleService before the theme plugin boots (ui-theme now injects slots/locale to register its Appearance row); drop locale's unused clsx dependency. --- packages/client/locale/package.json | 3 --- packages/client/ui-layout/package.json | 1 + packages/client/ui-layout/tests/apply.spec.ts | 4 ++++ packages/client/ui-layout/tsconfig.json | 3 +++ pnpm-lock.yaml | 7 +++---- 5 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/client/locale/package.json b/packages/client/locale/package.json index d53d2e4269..4d75496dc8 100644 --- a/packages/client/locale/package.json +++ b/packages/client/locale/package.json @@ -58,8 +58,5 @@ "scripts": { "bundle": "tsdown", "watch": "tsdown --watch" - }, - "dependencies": { - "clsx": "^2.0.0" } } diff --git a/packages/client/ui-layout/package.json b/packages/client/ui-layout/package.json index 17459ee5d2..b816533474 100644 --- a/packages/client/ui-layout/package.json +++ b/packages/client/ui-layout/package.json @@ -43,6 +43,7 @@ "react": "^18.2.0" }, "devDependencies": { + "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-client-ui-theme": "workspace:^", diff --git a/packages/client/ui-layout/tests/apply.spec.ts b/packages/client/ui-layout/tests/apply.spec.ts index 29ad4b3058..910b5a3132 100644 --- a/packages/client/ui-layout/tests/apply.spec.ts +++ b/packages/client/ui-layout/tests/apply.spec.ts @@ -9,6 +9,7 @@ import { Context } from 'cordis' import { describe, expect, it, vi } from 'vitest' import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client' +import { LocaleService } from '@deepseek-ai/dsh-client-locale/client' import { apply as themeApply, inject as themeInject, ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client' import { apply, inject, LayoutService } from '@deepseek-ai/dsh-client-ui-layout/client' import { apply as nodeApply } from '@deepseek-ai/dsh-client-ui-layout' @@ -17,6 +18,9 @@ import * as invariant from '@deepseek-ai/dsh-client-ui-layout/invariant' async function bench() { const ctx = new Context() const slotsFiber = ctx.plugin(SlotsService) + // Theme now injects ['slots', 'locale'] (it registers its Appearance + // settings row); seat a real locale service so the theme fiber activates. + ctx.provide('locale', new LocaleService(ctx)) await ctx.plugin({ inject: themeInject, apply: themeApply }).await() await slotsFiber.await() return { ctx, slots: ctx.get('slots') as SlotsService } diff --git a/packages/client/ui-layout/tsconfig.json b/packages/client/ui-layout/tsconfig.json index 4401e8e4db..731eec8012 100644 --- a/packages/client/ui-layout/tsconfig.json +++ b/packages/client/ui-layout/tsconfig.json @@ -11,6 +11,9 @@ { "path": "../../../vendor/cordis" }, + { + "path": "../locale" + }, { "path": "../ui-slots" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 40fee92c16..612cea101f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -747,10 +747,6 @@ importers: version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@vendor+loader) packages/client/locale: - dependencies: - clsx: - specifier: ^2.0.0 - version: 2.1.1 devDependencies: '@deepseek-ai/dsh-client-runtime': specifier: workspace:^ @@ -859,6 +855,9 @@ importers: packages/client/ui-layout: devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale '@deepseek-ai/dsh-client-runtime': specifier: workspace:^ version: link:../runtime From 78e57ab53e9ac175f9c6321ced5fe35a7517163e Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 03:28:39 +0800 Subject: [PATCH 103/113] docs: record PR label taxonomy --- ...07-25-semantic-pr-label-taxonomy.i18n.yaml | 6 ++ .../2026-07-25-semantic-pr-label-taxonomy.md | 60 +++++++++++++++++++ ...026-07-25-semantic-pr-label-taxonomy.zh.md | 60 +++++++++++++++++++ AGENTS.md | 2 +- 4 files changed, 127 insertions(+), 1 deletion(-) create mode 100644 .agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.i18n.yaml create mode 100644 .agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md create mode 100644 .agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md diff --git a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.i18n.yaml b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.i18n.yaml new file mode 100644 index 0000000000..9be3fb4b13 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.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 +2026-07-25-semantic-pr-label-taxonomy.md: cf25691e55d100cc2cc12246b17f5edbba35feea +2026-07-25-semantic-pr-label-taxonomy.zh.md: 2978bdc80a660f67f84821e473dc229e13b2bc4d diff --git a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md new file mode 100644 index 0000000000..cf25691e55 --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md @@ -0,0 +1,60 @@ +# Agent Note: Semantic pull request label taxonomy + +Status: implemented + +English | [中文](2026-07-25-semantic-pr-label-taxonomy.zh.md) + +## Problem + +Pull requests need two different signals: what kind of change they make and which repository domains they affect. A flat or broadly named label set conflates those questions, hides work in distinct areas such as `session` and `llm`, and gives reviewers and automation weak inputs. + +The repository also gains new domains over time. Treating today's area labels as a closed set would force future work into inaccurate labels or a generic catch-all. + +## Decision + +Every open or merged pull request carries exactly one kind and every materially affected area. Closed pull requests that were never merged are outside the maintained historical corpus. Other operational labels may coexist, but they do not satisfy either dimension. + +### Kinds + +| Kind | Meaning | +|---|---| +| `feature` | Adds or intentionally changes behavior. | +| `bug-fix` | Corrects incorrect behavior. | +| `doc` | Changes documentation only. | +| `testing` | Changes tests or testing infrastructure without changing product behavior. | +| `cleanup` | Preserves behavior while maintaining or simplifying the implementation or repository process. | + +The kind records the change's dominant intent: accompanying tests and documentation do not turn a feature or bug fix into a testing or documentation change. + +Areas record semantic repository domains rather than temporary initiatives, ownership, or every path touched incidentally. A pull request may carry several areas when it changes several domains. + +### Current areas + +The 43 current areas are listed below. The group names organize the list for readability; they are not labels or another taxonomy level. + +| Group | Areas | +|---|---| +| Agent and model | `agent`, `agent-loop`, `session`, `llm`, `model-context`, `compaction`, `tools`, `persistence` | +| Orchestration | `subagent`, `workflow`, `planning`, `tasks`, `telemetry`, `storage`, `workspace` | +| Capabilities | `bash`, `pty`, `filesystem`, `lsp`, `skills`, `web-search`, `code-mode`, `sandbox`, `mcp`, `hooks`, `cordis` | +| Interfaces | `ui`, `web`, `tui`, `acp`, `json-rpc`, `cli`, `python-sdk`, `desktop`, `vscode`, `website` | +| Repository and release | `dev-infra`, `ci`, `build`, `dependencies`, `platform`, `i18n`, `release` | + +### Extensibility + +The area set is intentionally extensible. Add an area when a recurring, meaningful repository domain is missing; do not add a label for one pull request, a temporary project, a status, or a person or team. Rename, split, or retire an area when the domain model changes, and update this list and the affected open and merged pull requests together. + +The kind set stays narrow because kinds are mutually exclusive. A new kind requires a distinct change intent that cannot be represented by the current five; it is not a substitute for an area. + +## Alternatives considered + +- **One undifferentiated label set.** Rejected because kind and area answer different questions; mixing them makes the presence of one label say nothing about whether the other dimension was considered. +- **A fixed, closed area set.** Rejected because repository domains evolve. A closed set would preserve spelling at the cost of semantic accuracy. +- **One broad `core` area or package-derived labels.** Rejected because domains such as `session`, `llm`, and `agent` remain independently meaningful across package boundaries, while incidental file paths are not the scope reviewers or automation need. +- **Exactly one area per pull request.** Rejected because coherent changes can legitimately span several domains, and dropping secondary areas hides affected contracts. + +## Consequences + +- Reviewers and automation receive one stable intent signal plus a complete semantic scope. +- Selecting labels remains a judgment call: paths and title prefixes can suggest areas, but they cannot replace reading the change. +- Taxonomy changes carry maintenance work. Area additions, renames, splits, and removals update this decision record and backfill open and merged pull requests so historical queries keep their meaning. diff --git a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md new file mode 100644 index 0000000000..2978bdc80a --- /dev/null +++ b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md @@ -0,0 +1,60 @@ +# Agent Note: 语义化 PR 标签分类体系 + +Status: implemented + +[English](2026-07-25-semantic-pr-label-taxonomy.md) | 中文 + +## 问题 + +PR(Pull Request)需要传达两个不同的信号:它带来哪一类变更,以及会影响仓库中的哪些领域。一套扁平或命名宽泛的标签会混淆这两个问题,掩盖 `session`、`llm` 等不同领域的工作,也让评审人和自动化流程得到的输入缺乏有效信息。 + +仓库还会随时间发展出新的领域。如果把当前的领域标签视为封闭集合,未来的工作就只能归入不准确的标签或通用兜底标签。 + +## 决策 + +每项开放或已合并的 PR 都带有恰好一个类型标签,以及所有受到实质影响的领域标签。未合并即关闭的 PR 不属于持续维护的历史记录集合。其他管理用途的标签可以并存,但都不能满足这两个维度中的任一个。 + +### 类型 + +| 类型 | 含义 | +|---|---| +| `feature` | 新增行为或有意改变行为。 | +| `bug-fix` | 修正错误行为。 | +| `doc` | 仅修改文档。 | +| `testing` | 修改测试或测试基础设施,但不改变产品行为。 | +| `cleanup` | 在保持行为不变的前提下,维护或简化实现或仓库流程。 | + +类型记录变更的主要意图:配套测试与文档并不会把一项功能或缺陷修复变成测试或文档变更。 + +领域记录仓库中的语义领域,而不是临时项目、归属关系或偶然触及的每条路径。如果一项 PR 修改了多个领域,就可以带有多个领域标签。 + +### 当前领域 + +当前的 43 个领域如下。分组名称仅用于提高列表的可读性;它们既不是标签,也不是分类体系中的另一个层级。 + +| 分组 | 领域 | +|---|---| +| agent(智能体)与模型 | `agent`, `agent-loop`, `session`, `llm`, `model-context`, `compaction`, `tools`, `persistence` | +| 编排 | `subagent`, `workflow`, `planning`, `tasks`, `telemetry`, `storage`, `workspace` | +| 能力 | `bash`, `pty`, `filesystem`, `lsp`, `skills`, `web-search`, `code-mode`, `sandbox`, `mcp`, `hooks`, `cordis` | +| 接口 | `ui`, `web`, `tui`, `acp`, `json-rpc`, `cli`, `python-sdk`, `desktop`, `vscode`, `website` | +| 仓库与发布 | `dev-infra`, `ci`, `build`, `dependencies`, `platform`, `i18n`, `release` | + +### 可扩展性 + +领域集合有意保持可扩展。当分类体系缺少一个会反复涉及且具有实际意义的仓库领域时,就新增领域;不要仅为一项 PR、临时项目、状态、个人或团队新增标签。当领域模型发生变化时,重命名、拆分或退役相应领域,同时更新本列表以及所有受影响的开放和已合并 PR。 + +类型集合保持精简,因为各类型互斥。新增类型的前提是存在一种当前五类无法表达的独立变更意图;类型不能用来替代领域。 + +## 曾考虑的替代方案 + +- **一套不区分维度的标签。** 不予采纳,因为类型与领域回答的是不同问题;两者混在一起时,存在一个维度的标签并不表示另一个维度也经过了考虑。 +- **一套固定、封闭的领域集合。** 不予采纳,因为仓库领域会持续演变。封闭集合会以牺牲语义准确性为代价来维持拼写不变。 +- **一个宽泛的 `core` 领域,或从包(package)结构派生的标签。** 不予采纳,因为 `session`、`llm` 和 `agent` 等领域在跨越包边界时仍各自具有意义,而偶然涉及的文件路径并不是评审人或自动化流程所需的范围信息。 +- **每项 PR 恰好一个领域。** 不予采纳,因为一项内聚的变更可以合理地跨越多个领域;省略次要领域会隐藏受影响的契约。 + +## 后果 + +- 评审人和自动化流程获得一个稳定的意图信号,以及完整的语义范围。 +- 选择标签仍然需要判断:路径和标题前缀可以提示领域,但不能替代阅读变更内容。 +- 变更分类体系会产生维护工作。新增、重命名、拆分或移除领域时,需要更新本决策记录,并回填开放和已合并的 PR,使历史查询保持原有含义。 diff --git a/AGENTS.md b/AGENTS.md index ad79a04b10..a8f811229a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -112,7 +112,7 @@ Real-API tests and demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, - **A tool's UI render intent is part of its design**, decided up front (`generic`/`terminal`/`diff`, `locations`); presentation methods are pure functions of `args` ([cookbook](docs/cookbook/adding-a-tool.md)). - **Plan unit, e2e, and snapshot coverage** for new seams, lifecycle shapes, and transcript surfaces; missing snapshot-harness support is part of the implementation, not deferred follow-up. - **Keep PRs coherent; use merge commits.** Split independent features or design decisions when combining them obscures ownership, intent, or verification. Never squash, rebase, or rewrite pushed branches; fix the introducing PR, then merge down its stack ([guide](docs/cookbook/responding-to-pr-review-on-a-stack.md)). -- **Label PRs:** exactly one kind (`feature`/`bug-fix`/`doc`/`testing`/`cleanup`), all matching areas; the taxonomy remains extensible for recurring distinctions. +- **Label PRs:** exactly one kind (`feature`/`bug-fix`/`doc`/`testing`/`cleanup`), all matching areas; the [taxonomy](.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md) remains extensible for recurring distinctions. - TODO markers: `FIXME`/`TODO`/`XXX` by urgency ([semantics](docs/development.md)). - Files end with exactly one trailing newline; `git diff --cached --check` (pre-commit) gates it. From 37bfac749b36fda839cb66f8681658d0ecc691de Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 03:29:11 +0800 Subject: [PATCH 104/113] docs: enforce bilingual README coverage --- ...-bilingual-docs-and-pairing-gate.i18n.yaml | 4 +- ...6-07-02-bilingual-docs-and-pairing-gate.md | 4 +- ...7-02-bilingual-docs-and-pairing-gate.zh.md | 4 +- docs/i18n/README.i18n.yaml | 4 +- docs/i18n/README.md | 4 +- docs/i18n/README.zh.md | 4 +- docs/i18n/style-samples.md | 4 +- .../request-response.expected.json | 8 +-- scripts/translation-pairing.manifest.json | 3 +- scripts/translation-pairing.spec.ts | 40 +++++++++++++ scripts/translation-pairing.ts | 57 +++++++++++++++++++ scripts/verify-translation-pairing.ts | 18 +++--- 12 files changed, 126 insertions(+), 28 deletions(-) diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml index 7b523ab8b4..bdda20cd5e 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.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 -2026-07-02-bilingual-docs-and-pairing-gate.md: ece3ccc183893a85335a36eb9b00cb42d32a1a37 -2026-07-02-bilingual-docs-and-pairing-gate.zh.md: dc8c648cc4ce9dd7739383c620ee2b1c3794f2ee +2026-07-02-bilingual-docs-and-pairing-gate.md: 45a587586b1387d7c351f9c268bd038fcd549ed5 +2026-07-02-bilingual-docs-and-pairing-gate.zh.md: 4875e48b43f2324ae117bb7aec1bf81dce3bc2bb diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md index ece3ccc183..45a587586b 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.md @@ -13,7 +13,7 @@ This repo's README and docs tree are read by people and agents inside and outsid - **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md). - **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR. - **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot. Source-oriented code gates consume a `.zh.md` fence sequence as a derivative only when its unsuffixed sibling has the same tracked fences in the same order with byte-identical bodies; an incomplete, reordered, reclassified, or changed sequence stays independent, so the owning code gate or pairing gate reports the mismatch. -- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it. +- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. Both classes are closed. README discovery covers every case-insensitive README basename outside vendored, dependency, and ignored build-output trees, including future top-level directories. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it. - **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration. - **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent. @@ -40,5 +40,5 @@ Paired sibling files with locale suffixes are the dominant Chinese big-tech conv - Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, "who confirmed these consistent, and when" is answerable from git blame on the yaml. - When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring. - Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list. -- Rollout remains incremental until a document class is complete: explicit `required` entries and the date cutoff prevent regression during review batches, while a closed class makes every current and future member mandatory. The non-README class is closed, so only the README class can still appear as backlog. +- Explicit `required` entries and the date cutoff preserve the reviewed rollout history, while the two closed classes make every current and future in-scope document mandatory. No document class can grow a new backlog. - The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism. diff --git a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md index dc8c648cc4..4875e48b43 100644 --- a/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md +++ b/.agents/notes/implemented/process/2026-07-02-bilingual-docs-and-pairing-gate.zh.md @@ -13,7 +13,7 @@ Status: implemented - **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。 - **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。 - **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。只有当 `.zh.md` 围栏序列与其无后缀兄弟文件拥有顺序相同、正文按字节一致的同一组受跟踪围栏时,面向源码的代码门禁才会将其作为派生内容消费;不完整、顺序变更、重分类或已改动的序列仍会独立受检,因此由其所属的代码门禁或配对门禁报告不匹配。 -- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。 +- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。这两个类别均已纳入强制范围。README 发现会覆盖 vendor 源码、依赖目录与被忽略的构建产物目录之外所有文件名不区分大小写匹配 README 的文件,包括今后新增的顶层目录。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。 - **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。 - **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。 @@ -40,5 +40,5 @@ Status: implemented - 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。 - 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。 - 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。 -- 在文档类别全部完成之前,推进仍然是渐进的:显式 `required` 条目与日期分界可在评审批次期间防止回退,已纳入强制范围的类别则将其当前及今后的每个成员都列为必选项。非 README 类别已纳入强制范围,因此只有 README 类别仍可能出现 backlog(待翻清单)。 +- 显式 `required` 条目与日期分界保留已经评审的推进历史,而两个已纳入强制范围的类别会将当前及今后所有范围内的文档列为必选项。任何文档类别都不能新增 backlog(待翻清单)。 - 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。 diff --git a/docs/i18n/README.i18n.yaml b/docs/i18n/README.i18n.yaml index b0d5a550df..51e3ffbca8 100644 --- a/docs/i18n/README.i18n.yaml +++ b/docs/i18n/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 -README.md: 053453bc622f58083a5e0e2992f1b8a820e3f3f9 -README.zh.md: 7f6242e8ff2a3ec69e2b84402dab447297047991 +README.md: 25c4698b2efacbb0cb1dd5b8f27ad94be051c558 +README.zh.md: e5faefff97d4ef8de9bf05613f257ede06c5e4a7 diff --git a/docs/i18n/README.md b/docs/i18n/README.md index 053453bc62..25c4698b2e 100644 --- a/docs/i18n/README.md +++ b/docs/i18n/README.md @@ -38,7 +38,7 @@ The gate's limit, stated plainly: **a green gate means the pair was confirmed co ## Scope, exclusions, and rollout -**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch. +**Scope**: every non-vendor README, plus every document under `.agents/notes/**`, `docs/**`, and `python/**`. README matching is case-insensitive on the basename and covers future directories without another manifest edit. Dependency and ignored build-output trees are discovery exclusions, not source documentation. **Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them): @@ -47,7 +47,7 @@ The gate's limit, stated plainly: **a green gate means the pair was confirmed co - `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction. - [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior. -**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. `non-readme` is closed: every current or future in-scope non-README document must merge bilingual. README coverage remains an explicit-file rollout until `readme` joins the closed set. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract. +**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. Both `non-readme` and `readme` are closed: every current or future in-scope document must merge bilingual. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract. ## Division of labor diff --git a/docs/i18n/README.zh.md b/docs/i18n/README.zh.md index 7f6242e8ff..e5faefff97 100644 --- a/docs/i18n/README.zh.md +++ b/docs/i18n/README.zh.md @@ -38,7 +38,7 @@ ## 范围、排除与推进 -**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。 +**范围**:除 vendor 源码外的全部 README,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部文档。匹配 README 时只看文件名且不区分大小写,因此今后新增的目录无需再修改 manifest。依赖目录和被忽略的构建产物目录只在发现阶段排除,并非源文档。 **排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`): @@ -47,7 +47,7 @@ - `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。 - [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。 -**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 已纳入强制范围:当前及今后所有纳入范围的非 README 文档,合并时都必须配齐双语文件。README 覆盖仍按显式文件逐步推进,直到 `readme` 加入这一强制范围。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。 +**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 与 `readme` 均已纳入强制范围:当前及今后所有纳入范围的文档,合并时都必须配齐双语文件。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。 ## 分工 diff --git a/docs/i18n/style-samples.md b/docs/i18n/style-samples.md index c62ae259d0..53d8851325 100644 --- a/docs/i18n/style-samples.md +++ b/docs/i18n/style-samples.md @@ -70,9 +70,9 @@ ## ⑦ 推进策略(长段拆分示范) -> **Enforcement frontier**: a document class enters the manifest's `requiredClasses` set only after its back-catalog has been translated and reviewed. The `non-readme` class is closed, so every current or future in-scope non-README document must merge bilingual; README coverage remains an explicit-file rollout until that class is ready to close. […] Pairing a document is a commitment: every later edit to either side must carry the counterpart along, so close a class only when translation review can sustain it. +> **Enforcement frontier**: a document class enters the manifest's `requiredClasses` set only after its back-catalog has been translated and reviewed. The `non-readme` and `readme` classes are closed, so every current or future in-scope document must merge bilingual. […] Pairing a document is a commitment: every later edit to either side must carry the counterpart along, so close a class only when translation review can sustain it. -**执行红线**:只有在某个文档类别的存量文档全部完成翻译和评审后,该类别才会进入 manifest(元数据清单)的 `requiredClasses` 集合。`non-readme` 类别已纳入强制范围,因此当前及今后所有纳入范围的非 README 文档,合入时都必须配齐双语文件;README 覆盖仍按显式文件逐步推进,直到该类别具备整体纳入强制范围的条件。(……)一旦文档完成配对,后续修改任一侧都必须同步更新另一侧。因此,只有在翻译评审能力足以持续支撑时,才应将整个类别纳入强制范围。 +**执行红线**:只有在某个文档类别的存量文档全部完成翻译和评审后,该类别才会进入 manifest(元数据清单)的 `requiredClasses` 集合。`non-readme` 与 `readme` 类别均已纳入强制范围,因此当前及今后所有纳入范围的文档,合入时都必须配齐双语文件。(……)一旦文档完成配对,后续修改任一侧都必须同步更新另一侧。因此,只有在翻译评审能力足以持续支撑时,才应将整个类别纳入强制范围。 ## 从样例提炼的要点 diff --git a/scripts/snapshots/translation-prompt-v4/request-response.expected.json b/scripts/snapshots/translation-prompt-v4/request-response.expected.json index 36a701f376..2314b67221 100644 --- a/scripts/snapshots/translation-prompt-v4/request-response.expected.json +++ b/scripts/snapshots/translation-prompt-v4/request-response.expected.json @@ -24,11 +24,11 @@ }, { "role": "user", - "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p `), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required`, and every document whose class appears in `requiredClasses`, in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair. The classes are `non-readme` and `readme`; class matching is case-insensitive on the basename, so `missions/readme.md` is a README.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\nSource-oriented code gates consume an exact `.zh.md` fence sequence as a derivative of its unsuffixed sibling instead of compiling or manifesting the same code twice. The sequence must match in length, order, fence kind, and byte-exact body; otherwise both copies remain independently checked and the pairing gate reports the structural mismatch.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: the root `README.md`, everything under `.agents/notes/**`, `docs/**`, and `python/**`. Package READMEs (`packages/**`) join the scope in a later batch.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md`, `.agents/notes/**/AGENTS.md`, and their `CLAUDE.md` instruction symlinks — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. `non-readme` is closed: every current or future in-scope non-README document must merge bilingual. README coverage remains an explicit-file rollout until `readme` joins the closed set. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" + "content": "# Bilingual documentation\n\nEnglish | [中文](README.zh.md)\n\nThis repo's documentation is read by people and agents both inside and outside the company, so the README, Agent Notes, and docs tree are maintained in English and Simplified Chinese. This page defines the pairing contract, the enforcement gate, and the rollout policy; [translation-rules.md](translation-rules.md) defines how to translate; [terminology.md](terminology.md) is the terminology source of truth. The committed agent workflow lives in [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md).\n\n## The pairing contract\n\n- **Both languages carry equal authority.** A document may be authored and reviewed in either language first — a Chinese-first Agent Note is as legitimate as an English-first one — and the counterpart is translated from it. Neither file outranks the other; what binds them is that they must say the same thing.\n- **A pair is three sibling files.** The English `foo.md`, the Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`, all in the same directory. No locale directories, no separate translation repo, no interleaved bilingual files. Pairs merge whole: a PR never lands one language without the other two files.\n- **The consistency record.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last time the two were confirmed to say the same thing:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n Blob hashes, not commit hashes, so the record is computable for files edited in the same PR (`git hash-object foo.md`) and consistency is a pure content comparison. The recorded hash also recovers the exact last-confirmed text of either side (`git cat-file -p `), so an out-of-sync pair is updated by diffing the edited side against its last-confirmed state and patching the counterpart minimally — never by re-translating whole files. After bringing the pair back in line, `pnpm run verify-translation-pairing --write` re-records both hashes; that yaml diff is the reviewable act of confirming consistency.\n- **Language switcher.** Both files link to each other immediately after their H1 heading: the English file carries `English | [中文](foo.zh.md)` and the Chinese file carries `[English](foo.md) | 中文`.\n- **Structure mirrors the counterpart.** Heading depths and order, list kinds, ordered-list starts, list item counts, table row and column counts, link targets, and verbatim code blocks match one to one across the pair — see [translation-rules.md](translation-rules.md) for the full preservation rules. Existing Markdown gates apply to `.zh.md` files unchanged (`verify-md-wrap`, `verify-md-links`).\n\n## The gate: verify-translation-pairing\n\n`pnpm run verify-translation-pairing` (part of `doc-sync`, which contributors run locally for documentation changes and CI runs exhaustively) enforces the contract mechanically:\n\n1. Every file listed as `required`, and every document whose class appears in `requiredClasses`, in [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) has a complete pair. The classes are `non-readme` and `readme`; class matching is case-insensitive on the basename, so `missions/readme.md` is a README.\n2. Every pair that exists at all — required or not — is complete and consistent: all three files present, each side's current blob hash equals the recorded one (editing either side without re-confirming the pair goes red), both sides carry the language switcher, and the structural signatures match in order — heading depths, verbatim code blocks (info string and content), table row and column counts, list kinds, ordered-list starts, item counts, and every link target apart from the switcher.\n3. Files listed as `excluded` have no `.zh.md` and no `.i18n.yaml` at all.\n4. Every date-named document (`yyyy-mm-dd-*.md`) dated on or after the manifest's `requiredSince` cutoff has a complete pair — new date-named Agent Notes merge bilingual from birth.\n\nSource-oriented code gates consume an exact `.zh.md` fence sequence as a derivative of its unsuffixed sibling instead of compiling or manifesting the same code twice. The sequence must match in length, order, fence kind, and byte-exact body; otherwise both copies remain independently checked and the pairing gate reports the structural mismatch.\n\n`pnpm run verify-translation-pairing --list` prints the current pairing state of every document in scope — missing, out-of-sync, or ok — and is the work list for translation batches. It never fails; it reports.\n\nThe practical rule this gate creates: **when a PR edits either side of a paired document, the same PR updates the counterpart and re-records the pair** (run the [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill, then `--write`), exactly like the repo's existing doc-sync rule for code and READMEs. A PR that leaves a pair out of sync goes red in CI.\n\nThe gate's limit, stated plainly: **a green gate means the pair was confirmed consistent at these exact contents, not that the confirmation was sound.** It checks hashes and shape; it cannot judge whether the two sides actually say the same thing, or whether the wording is accurate, well-termed, and natural — that is the reviewer's half of the contract, per [translation-rules.md](translation-rules.md). A re-recorded pair with a sloppy counterpart passes the gate; it must not pass review.\n\n## Scope, exclusions, and rollout\n\n**Scope**: every non-vendor README, plus every document under `.agents/notes/**`, `docs/**`, and `python/**`. README matching is case-insensitive on the basename and covers future directories without another manifest edit. Dependency and ignored build-output trees are discovery exclusions, not source documentation.\n\n**Excluded** (never paired, and the gate rejects a `.zh.md` or `.i18n.yaml` for them):\n\n- `docs/cordis-catalog/`, `docs/tool-catalog/`, `docs/config-catalog.md`, `docs/persistence-catalog.md`, `docs/module-graph.md`, `docs/agent-lifecycle.md`, `docs/capability-seams.md`, `docs/event-producer-consumer.md`, `docs/graph-atlas.md`, and `docs/tool-execution-pipeline.md` — generated files; their generators emit English only today, so a hand-written translation would go stale on every regeneration. The planned follow-up is to teach the generators to emit Chinese alongside English, at which point these leave the exclusion list.\n- `docs/AGENTS.md`, `.agents/notes/**/AGENTS.md`, and their `CLAUDE.md` instruction symlinks — agent instructions, maintained in English only like the root `AGENTS.md`.\n- `docs/i18n/terminology.md` and [style-samples.md](style-samples.md) — both are bilingual by construction.\n- [translation-prompt.md](translation-prompt.md) — the automated pipeline's prompt template; its body is machine-consumed verbatim, so a paired translation would change pipeline behavior.\n\n**Enforcement frontier**: `requiredClasses` closes a whole document class after its back-catalog has been translated. Both `non-readme` and `readme` are closed: every current or future in-scope document must merge bilingual. The manifest's `required` list retains already-admitted files, and a date-named document (`yyyy-mm-dd-*.md`, i.e. an Agent Note) dated on or after `requiredSince` must merge with its pair regardless of class. `--list` reports any unclosed-class backlog while every existing pair remains governed by the full contract.\n\n## Division of labor\n\nCounterparts here are produced by an agent running [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) and reviewed by a human — inference is cheap here, review attention is the scarce resource. The gate checks pair completeness, recorded hashes, switchers, and its documented structural signature. Review still owns translation quality, terminology, and structural requirements that the signature does not encode. The prompt contract is executable: [scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) renders the committed template (terminology injected; the template carries its own calibrated rules) into either direction and parses the three-section response, while `verify-translation-prompt` exercises both render directions and the checked-in example in `doc-sync`.\n" }, { "role": "assistant", - "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p `),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件,以及所属文档类别出现在 `requiredClasses` 中的每篇文档,都有完整配对。类别分为 `non-readme` 和 `readme`;判断类别时,basename 不区分大小写,因此 `missions/readme.md` 也属于 README。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n面向源码的代码门禁会把精确的 `.zh.md` 围栏序列视为其无后缀兄弟文件的派生内容,而不会再次编译相同代码或在 manifest 中重复登记。该序列必须在长度、顺序、围栏类型和按字节精确的正文上一致;否则两份副本仍会独立受检,配对门禁也会报告结构不匹配。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:根 `README.md`,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部内容。包(package)README(`packages/**`)在后续批次加入范围。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md`、`.agents/notes/**/AGENTS.md` 以及指向它们的 `CLAUDE.md` 指令符号链接:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 已纳入强制范围:当前及今后所有纳入范围的非 README 文档,合并时都必须配齐双语文件。README 覆盖仍按显式文件逐步推进,直到 `readme` 加入这一强制范围。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" + "content": "# 双语文档\n\n[English](README.md) | 中文\n\n本仓库的文档会被公司内外的人和 agent(智能体)阅读,因此 README、Agent Note(agent 决策记录)与 docs 目录树以英文和简体中文双语维护。本页定义配对契约、强制门禁与推进策略;[translation-rules.md](translation-rules.md) 定义如何翻译;[terminology.md](terminology.md) 是术语真源。仓库内置的 agent 工作流见 [.agents/skills/dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md)。\n\n## 配对契约\n\n- **两种语言同权。** 一篇文档可以先用任一语言撰写和评审(先写中文的 Agent Note 与先写英文的一样正当),另一侧由它翻译而来。两个文件谁也不高于谁;约束它们的是二者必须说同样的话。\n- **一对文档是三个同目录文件。** 英文 `foo.md`、中文 `foo.zh.md`,加一份一致性记录 `foo.i18n.yaml`,都在同一目录。不用语言目录,不用独立翻译仓库,不用中英混排的单文件。配对必须整体合并:PR(Pull Request)永远不会只带一种语言而缺其余两个文件。\n- **一致性记录。**`foo.i18n.yaml` 保存两侧文件在上一次被确认「说同样的话」时各自的完整 git blob hash:\n\n ```yaml\n foo.md: 3f786850e387550fdab836ed7e6dc881de23001b\n foo.zh.md: 89e6c98d92887913cadf06b2adb97f26cde4849b\n ```\n\n 用 blob hash 而不是 commit hash,这样同一个 PR 里改动的文件也能算出记录(`git hash-object foo.md`),一致性是纯内容比较。记录的 hash 还能还原任一侧上次确认时的确切文本(`git cat-file -p `),所以失去同步的配对是「把被改的一侧与其上次确认状态做 diff、再最小化地修补另一侧」,从不整篇重译。两侧对齐后,`pnpm run verify-translation-pairing --write` 重新记录两个 hash;那份 yaml diff 就是「确认一致」这个动作本身,可以被评审。\n- **语言切换行。** 两个文件在各自 H1 标题之后立即互链:英文文件带 `English | [中文](foo.zh.md)`,中文文件带 `[English](foo.md) | 中文`。\n- **结构与另一侧一一对应。** 标题深度与顺序、列表类型、有序列表起始编号、列表项数量、表格行列数、链接目标与逐字节一致的代码块在配对两侧一一对应;完整保持规则见 [translation-rules.md](translation-rules.md)。既有 Markdown 门禁对 `.zh.md` 文件原样生效(`verify-md-wrap`、`verify-md-links`)。\n\n## 门禁:verify-translation-pairing\n\n`pnpm run verify-translation-pairing`(`doc-sync`(文档同步门禁)的一环,贡献者会针对文档变更在本地运行,CI 则会完整运行)机械地强制执行这份契约:\n\n1. [scripts/translation-pairing.manifest.json](../../scripts/translation-pairing.manifest.json) 中 `required` 列出的每个文件,以及所属文档类别出现在 `requiredClasses` 中的每篇文档,都有完整配对。类别分为 `non-readme` 和 `readme`;判断类别时,basename 不区分大小写,因此 `missions/readme.md` 也属于 README。\n2. 任何已存在的配对(无论是否 required)都完整且一致:三个文件齐全、每一侧的当前 blob hash 等于记录值(改了任一侧而没重新确认配对就变红)、双方都带语言切换行、结构签名按序一致:标题深度、逐字节一致的代码块(信息字符串与内容)、表格行列数、列表类型、有序列表起始编号、列表项数量,以及除切换行之外的每个链接目标。\n3. 列为 `excluded` 的文件完全没有 `.zh.md`,也没有 `.i18n.yaml`。\n4. 凡文件名符合 `yyyy-mm-dd-*.md` 且日期不早于 manifest(元数据清单)中 `requiredSince` 分界日期的文档,都必须有完整配对;新建的日期命名 Agent Note 从创建起便须配齐中英文。\n\n面向源码的代码门禁会把精确的 `.zh.md` 围栏序列视为其无后缀兄弟文件的派生内容,而不会再次编译相同代码或在 manifest 中重复登记。该序列必须在长度、顺序、围栏类型和按字节精确的正文上一致;否则两份副本仍会独立受检,配对门禁也会报告结构不匹配。\n\n`pnpm run verify-translation-pairing --list` 打印范围内每篇文档的当前配对状态(missing、out-of-sync 或 ok),是翻译批次的工作清单。它从不失败;它只报告。\n\n这个门禁带来的实际规则是:**当一个 PR 修改了已配对文档的任一侧时,同一个 PR 更新另一侧并重新记录配对**(运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) skill(技能),再 `--write`),与本仓库既有的代码与 README 的 doc-sync 规则完全一致。留下失去同步的配对的 PR 会在 CI 变红。\n\n把门禁的边界说白:**门禁通过意味着这组文档在当前内容上的一致性得到了确认,不代表确认本身正确可靠。** 它检查记录的 hash 与结构签名;它无法判断两侧是否真的在说同样的话,也无法判断措辞是否准确、术语是否得当、行文是否自然;这部分契约由评审者把关,见 [translation-rules.md](translation-rules.md)。重新记录了 hash 但另一侧翻得潦草的配对能通过门禁;它不得通过评审。\n\n## 范围、排除与推进\n\n**范围**:除 vendor 源码外的全部 README,以及 `.agents/notes/**`、`docs/**` 与 `python/**` 下的全部文档。匹配 README 时只看文件名且不区分大小写,因此今后新增的目录无需再修改 manifest。依赖目录和被忽略的构建产物目录只在发现阶段排除,并非源文档。\n\n**排除**(永不配对,门禁拒绝为它们建 `.zh.md` 或 `.i18n.yaml`):\n\n- `docs/cordis-catalog/`、`docs/tool-catalog/`、`docs/config-catalog.md`、`docs/persistence-catalog.md`、`docs/module-graph.md`、`docs/agent-lifecycle.md`、`docs/capability-seams.md`、`docs/event-producer-consumer.md`、`docs/graph-atlas.md` 与 `docs/tool-execution-pipeline.md`:生成文件;生成器目前只输出英文,手写译文在每次重新生成时必然陈旧。计划中的后续工作是让生成器同时输出中文,届时这些文件移出排除清单。\n- `docs/AGENTS.md`、`.agents/notes/**/AGENTS.md` 以及指向它们的 `CLAUDE.md` 指令符号链接:agent 指令,与根 `AGENTS.md` 一样只以英文维护。\n- `docs/i18n/terminology.md` 与 [style-samples.md](style-samples.md):二者本身即为中英对照文档。\n- [translation-prompt.md](translation-prompt.md):自动翻译流水线的提示词模板;正文逐字进入模型请求,配对翻译会改变流水线行为。\n\n**执行红线**:某个文档类别的存量文档全部翻译完成后,`requiredClasses` 会将整个类别纳入强制范围。`non-readme` 与 `readme` 均已纳入强制范围:当前及今后所有纳入范围的文档,合并时都必须配齐双语文件。manifest 的 `required` 列表保留已纳入的文件;以日期命名的文档(`yyyy-mm-dd-*.md`,即 Agent Note)只要日期不早于 `requiredSince`,就无论所属类别都必须与对侧文件一同合并。`--list` 会报告尚未纳入强制范围的类别中的任何 backlog(待翻清单),而每个已存在的配对仍受完整契约约束。\n\n## 分工\n\n这里的对侧文件由运行 [dsh-translate-docs](../../.agents/skills/dsh-translate-docs/SKILL.md) 的 agent 生成,再由人评审:在这里推理(inference)很便宜,评审注意力才是稀缺资源。门禁负责检查配对是否完整、记录的 hash、语言切换行以及本文列出的结构签名;翻译质量、术语和签名未涵盖的结构要求仍由评审把关。提示词契约也有可执行实现:[scripts/translation-prompt.ts](../../scripts/translation-prompt.ts) 会把仓库内置的模板(注入术语表;模板自带经人工校准的规则)渲染为英译中或中译英两个方向的提示词,并解析三段式响应;`doc-sync` 中的 `verify-translation-prompt` 会检查两个渲染方向与仓库内示例。\n" }, { "role": "user", @@ -40,11 +40,11 @@ }, { "role": "user", - "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot. Source-oriented code gates consume a `.zh.md` fence sequence as a derivative only when its unsuffixed sibling has the same tracked fences in the same order with byte-identical bodies; an incomplete, reordered, reclassified, or changed sequence stays independent, so the owning code gate or pairing gate reports the mismatch.\n- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it.\n- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Verification\n\nThe verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Rollout remains incremental until a document class is complete: explicit `required` entries and the date cutoff prevent regression during review batches, while a closed class makes every current and future member mandatory. The non-README class is closed, so only the README class can still appear as backlog.\n- The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" + "content": "# Agent Note: Bilingual documentation via paired sibling files and a pairing gate\n\nStatus: implemented\n\nEnglish | [中文](2026-07-02-bilingual-docs-and-pairing-gate.zh.md)\n\n## Problem\n\nThis repo's README and docs tree are read by people and agents inside and outside the company, in both English and Chinese. Maintaining a second language by hand, with no mechanism, is how translations rot: one side moves on, the other silently lies, and no gate notices. The repo's standing answer to invariants of this kind is to encode them as a mechanical check (see [quality gates](2026-06-11-quality-gates.md) and [doc-sync enforcement](2026-06-11-doc-sync-enforcement.md)), so the bilingual policy ships with one.\n\n## Decision\n\n- **Paired sibling files with equal authority.** A documentation pair is three sibling files: English `foo.md`, Chinese `foo.zh.md`, and a consistency record `foo.i18n.yaml`. Neither language is canonical — a document may be authored and reviewed Chinese-first and translated to English afterwards, or the reverse; what binds the pair is that both sides must say the same thing, and pairs merge whole (both languages plus the record, never one alone). Policy: [docs/i18n/README.md](../../../../docs/i18n/README.md); translation rules: [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md); terminology source of truth: [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md).\n- **A sidecar record of both blob hashes makes consistency checkable.** `foo.i18n.yaml` holds the full git blob hash of each side as of the last confirmed-consistent state. An edit to either side without re-confirming the pair is then mechanically detectable as a pure content comparison — no history lookup — and the hashes are computable for files edited in the same PR, which a commit-hash record is not. Re-recording (`verify-translation-pairing --write`) produces a reviewable yaml diff: confirming consistency is an explicit, visible act in the PR.\n- **`verify-translation-pairing` joins `doc-sync`.** The gate ([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts)) enforces: sources selected explicitly, by document class, or by the manifest's `requiredSince` cutoff have complete pairs; every existing pair is complete (all three files) and consistent (both hashes match, switcher links both ways, structural signatures identical); and excluded generated, instruction, or bilingual-by-construction files stay unpaired. The `requiredClasses` set in [scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) closes a translated class for all present and future files instead of relying on an enumerated snapshot. Source-oriented code gates consume a `.zh.md` fence sequence as a derivative only when its unsuffixed sibling has the same tracked fences in the same order with byte-identical bodies; an incomplete, reordered, reclassified, or changed sequence stays independent, so the owning code gate or pairing gate reports the mismatch.\n- **The enforcement frontier advances in coherent review batches, then closes by class.** Explicit `required` entries admit related files while their back-catalog is still being reviewed; after that catalog is complete, its `non-readme` or `readme` class enters `requiredClasses` and can no longer grow a backlog. Both classes are closed. README discovery covers every case-insensitive README basename outside vendored, dependency, and ignored build-output trees, including future top-level directories. A site-published pair uses `pairedPages()` so the root locale projects `.zh.md` and `/en/` projects `.md`; creating a counterpart alone does not publish it.\n- **Pairing records are metadata, not Cordis Loader configuration.** Cordis configuration discovery accepts actual `.cordis.yml` and `.cordis.yaml` files while excluding `*.i18n.yaml`, even when the document name contains `cordis`. This preserves validation of executable Loader entries without parsing translation hashes as configuration.\n- **Translation is agent work with human review.** The committed workflow is [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md), following the same pattern as [dsh-code-review](../../../skills/dsh-code-review/SKILL.md): the skill carries the workflow and defers to the docs as sources of truth. The skill directs the orchestrating agent to delegate translation writing to a subagent.\n\n## Verification\n\nThe verification contract covers each boundary independently. `verify-translation-pairing` pins pair completeness, hashes, switchers, and structure; [`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) pins locale-specific source selection for published pairs; [`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) pins discovery of Loader YAML and exclusion of translation records; and the [translation-prompt runnable snapshot](../../../../scripts/translation-prompt.snapshot.ts) pins the rendered system message, five reviewed example pairs, source request, and consumed response. Together these checks make pair drift, publication drift, configuration misclassification, and model-visible prompt drift review-visible.\n\n## Alternatives considered\n\n- **English as the canonical source with a fingerprint inside the translation** — the design first proposed for this Agent Note: `.zh.md` files carried an HTML comment recording the English source's blob hash, and translation flowed EN → ZH only. Revised in review: the team wants Chinese-first authoring (write and review a Chinese Agent Note, then translate to English) with the two languages holding equal authority, which a one-directional canonical model cannot express. The sidecar record covering BOTH sides replaced the in-file one-directional fingerprint; the blob-hash mechanics survived unchanged.\n- **Locale directories (`docs/en/` + `docs/zh/`, the Kubernetes/ECharts model)** — rejected: this repo has no docs-site framework to map locales to routes, moving every English file would churn every existing cross-reference, and `verify-md-links`/`verify-doc-refs` would need path-mapping logic instead of working unchanged.\n- **A separate translation repo (the PingCAP `docs`/`docs-cn` model)** — rejected: right for a docs product with independent release trains, overkill for a monorepo's own documentation; it also puts the translation outside the reach of this repo's gates.\n- **Interleaved bilingual files (single file, both languages)** — rejected: doubles every diff, breaks the one-line-per-paragraph convention's diff ergonomics, and makes partial inconsistency invisible.\n- **Commit-hash records (the MDN `l10n.sourceCommit` model)** — rejected in favor of blob hashes: a same-PR edit has no commit hash yet, so the MDN model cannot express \"consistent as of the state this PR introduces\", and verifying it requires git history instead of file content.\n- **Comparing git timestamps of the pair (no record)** — rejected: formatting-only edits would false-positive, and a counterpart committed after an unrelated edit would false-negative; content identity is the only signal that means what the gate claims.\n\n## Industry precedent\n\nPaired sibling files with locale suffixes are the dominant Chinese big-tech convention (ant-design `index.zh-CN.md`/`index.en-US.md`; arco-design `README.zh-CN.md` with a top-of-file switcher; Apache ShardingSphere's 387 `.cn.md`/`.en.md` pairs) — but none of those repos *enforce* pairing or consistency in CI; the convention holds by review alone. Consistency automation exists outside China: MDN's `l10n.sourceCommit` front-matter fingerprint, Vue's Ryu-Cho action (upstream-commit watcher that opens issues/PRs for stale translations), Kubernetes' localization drift scripts, and Microsoft's Azure co-op-translator (source-hash-driven LLM re-translation in CI). This design combines the two: the Chinese-ecosystem file layout with a hash-pair gate, plus a committed agent skill in place of a bot service.\n\n## Consequences\n\n- Editing either side of a paired document obligates the same PR to update the counterpart and re-record the pair — the gate makes the doc-sync rule bilingual, and CI (not reviewer memory) carries the invariant.\n- Every pair adds a third file to the tree. The record is machine-written (`--write`), so the cost is directory noise, not maintenance effort; in exchange, \"who confirmed these consistent, and when\" is answerable from git blame on the yaml.\n- When the two sides disagree, no mechanical rule picks a winner — the PR review does. That is the price of equal authority, accepted deliberately: the alternative (a canonical language) forbids Chinese-first authoring.\n- Generated docs (`cordis-catalog/`, `tool-catalog/`, `module-graph.md`) are excluded for now; the planned follow-up is to teach their generators to emit Chinese alongside English, at which point they leave the exclusion list.\n- Explicit `required` entries and the date cutoff preserve the reviewed rollout history, while the two closed classes make every current and future in-scope document mandatory. No document class can grow a new backlog.\n- The recorded hashes double as the update tool (`git cat-file -p ` recovers either side's last-confirmed text for a minimal diff-based update), so re-translation of whole files is never forced by the mechanism.\n" }, { "role": "assistant", - "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。只有当 `.zh.md` 围栏序列与其无后缀兄弟文件拥有顺序相同、正文按字节一致的同一组受跟踪围栏时,面向源码的代码门禁才会将其作为派生内容消费;不完整、顺序变更、重分类或已改动的序列仍会独立受检,因此由其所属的代码门禁或配对门禁报告不匹配。\n- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。\n- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 验证\n\n验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 在文档类别全部完成之前,推进仍然是渐进的:显式 `required` 条目与日期分界可在评审批次期间防止回退,已纳入强制范围的类别则将其当前及今后的每个成员都列为必选项。非 README 类别已纳入强制范围,因此只有 README 类别仍可能出现 backlog(待翻清单)。\n- 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" + "content": "# Agent Note:通过配对兄弟文件与配对门禁实现双语文档\n\nStatus: implemented\n\n[English](2026-07-02-bilingual-docs-and-pairing-gate.md) | 中文\n\n## 问题\n\n本仓库的 README 与 docs 目录树会被公司内外的人和 agent(智能体)以中英两种语言阅读。在没有机制的情况下纯靠手工维护第二语言,正是译文腐烂的根源:一侧持续演进,另一侧默默失实,而没有门禁会注意到。对于这类不变式,本仓库一贯的做法是将其编码为机械检查(见[质量门禁](2026-06-11-quality-gates.md)与 [doc-sync 强制](2026-06-11-doc-sync-enforcement.md)),因此双语政策随附一道门禁一起交付。\n\n## 决策\n\n- **配对兄弟文件,两种语言同权。** 一对文档由三个兄弟文件组成:英文 `foo.md`、中文 `foo.zh.md`,以及一份一致性记录 `foo.i18n.yaml`。没有哪种语言是正典:一篇文档可以先用中文撰写和评审、之后再译成英文,反之亦可;约束配对的是:两侧必须表达相同的内容,且配对整体合并(两种语言加记录,绝不单独落一侧)。政策见 [docs/i18n/README.md](../../../../docs/i18n/README.md);翻译规则见 [docs/i18n/translation-rules.md](../../../../docs/i18n/translation-rules.md);术语真源见 [docs/i18n/terminology.md](../../../../docs/i18n/terminology.md)。\n- **伴随记录保存两侧 blob hash,使一致性可检查。** `foo.i18n.yaml` 保存两侧文件在上一次确认一致时各自的完整 git blob hash。此后修改了任一侧而未重新确认配对,都能被机械检测出来(纯内容比较,无需查询历史),而且同一个 PR(Pull Request)内改动的文件也能计算出 hash,commit hash 式的记录做不到这一点。重新记录(`verify-translation-pairing --write`)会产生一份可评审的 yaml diff:确认一致在 PR 中是一个显式、可见的动作。\n- **`verify-translation-pairing` 加入 `doc-sync`。** 门禁([scripts/verify-translation-pairing.ts](../../../../scripts/verify-translation-pairing.ts))强制执行以下规则:通过显式指定、文档类别或 manifest(元数据清单)的 `requiredSince` 分界日期选中的源文档必须有完整配对;任何已存在的配对必须完整(三个文件齐全)且一致(两个 hash 匹配、切换行双向互链、结构签名一致);被排除的生成文档、指令文档或本身即双语的文档不得配对。[scripts/translation-pairing.manifest.json](../../../../scripts/translation-pairing.manifest.json) 中的 `requiredClasses` 集合会将已完成翻译的类别纳入强制范围,对其当前及今后所有文件强制执行契约,而不再依赖一份枚举式快照。只有当 `.zh.md` 围栏序列与其无后缀兄弟文件拥有顺序相同、正文按字节一致的同一组受跟踪围栏时,面向源码的代码门禁才会将其作为派生内容消费;不完整、顺序变更、重分类或已改动的序列仍会独立受检,因此由其所属的代码门禁或配对门禁报告不匹配。\n- **执行红线按连贯的评审批次推进,再以类别为单位完成强制覆盖。** 在存量文档仍处于评审阶段时,显式 `required` 条目会纳入相关文件;存量文档全部完成后,其 `non-readme` 或 `readme` 类别进入 `requiredClasses`,不再产生新的 backlog。这两个类别均已纳入强制范围。README 发现会覆盖 vendor 源码、依赖目录与被忽略的构建产物目录之外所有文件名不区分大小写匹配 README 的文件,包括今后新增的顶层目录。发布到文档站的配对使用 `pairedPages()`,由根 locale 投影 `.zh.md`,由 `/en/` 投影 `.md`;仅创建对侧文件并不会发布它。\n- **配对记录是元数据,而不是 Cordis Loader 配置。** Cordis 配置发现会接受实际的 `.cordis.yml` 和 `.cordis.yaml` 文件,同时排除 `*.i18n.yaml`,即使文档名中包含 `cordis` 也不例外。这样既能继续校验可执行的 Loader 配置项,又不会把翻译 hash 当作配置来解析。\n- **翻译是 agent 的工作,由人评审。** 仓库内置的工作流是 [.agents/skills/dsh-translate-docs](../../../skills/dsh-translate-docs/SKILL.md),与 [dsh-code-review](../../../skills/dsh-code-review/SKILL.md) 模式相同:skill(技能)承载工作流,并将文档作为真源。该 skill 要求编排 agent 把翻译写作委派给 subagent。\n\n## 验证\n\n验证契约分别覆盖每个边界。`verify-translation-pairing` 固定配对完整性、hash、切换行和结构;[`project-doc-site.spec.ts`](../../../../scripts/project-doc-site.spec.ts) 固定已发布配对按 locale 选择对应源文件;[`cordis-config-files.spec.ts`](../../../../scripts/cordis-config-files.spec.ts) 固定 Loader YAML 的发现以及翻译记录的排除;[翻译提示词可运行快照](../../../../scripts/translation-prompt.snapshot.ts)则固定渲染后的系统消息、五对经评审的示例、源请求和响应消费结果。这些检查共同使配对漂移、发布漂移、配置误分类和模型可见提示词漂移都可在评审中看见。\n\n## 曾考虑的替代方案\n\n- **英文为正典源、指纹放在译文内**:本 Agent Note 最初提出的设计:`.zh.md` 文件携带一条 HTML 注释记录英文源的 blob hash,翻译只沿 EN → ZH 单向流动。评审中修订:团队需要中文先行的撰写方式(先写、先审中文 Agent Note,再译英文),两种语言同权,而单向正典模型无法表达这一点。覆盖**两侧**的伴随记录取代了文件内的单向指纹;blob hash 的机制本身保持不变。\n- **语言目录(`docs/en/` + `docs/zh/`,Kubernetes/ECharts 模式)**:否决。本仓库没有将 locale 映射到路由的文档站框架;如果移动所有英文文件,所有既有交叉引用都要随之修改;且 `verify-md-links`/`verify-doc-refs` 将需要路径映射逻辑,而非原样工作。\n- **独立翻译仓库(PingCAP `docs`/`docs-cn` 模式)**:否决。适合有独立发布节奏的文档产品,对 monorepo 自身的文档而言过重;还会把译文置于本仓库门禁触及不到的地方。\n- **中英混排单文件(一个文件、两种语言)**:否决。每个 diff 都翻倍,破坏一段一行约定的 diff 易读性,且局部不一致不可见。\n- **Commit hash 式记录(MDN `l10n.sourceCommit` 模式)**:否决,改用 blob hash。同一个 PR 内的改动还没有 commit hash,MDN 模式无法表达「与本 PR 引入的状态一致」,且校验它需要 git 历史而非文件内容。\n- **比较配对两侧的 git 时间戳(无记录)**:否决。纯格式化的改动会误报,一次无关改动之后提交的对侧文件会漏报;只有内容同一性这个信号才与门禁的承诺名实相符。\n\n## 业界先例\n\n带语言后缀的配对兄弟文件是中国大厂的主流约定(ant-design 的 `index.zh-CN.md`/`index.en-US.md`;arco-design 的 `README.zh-CN.md` 加顶部切换行;Apache ShardingSphere 的 387 对 `.cn.md`/`.en.md`),但这些仓库都没有在 CI 中**强制**配对或一致性检查;约定纯靠评审维系。一致性自动化存在于中国以外:MDN 的 `l10n.sourceCommit` front-matter 指纹、Vue 的 Ryu-Cho action(监视上游 commit,为陈旧译文自动开 issue/PR)、Kubernetes 的本地化漂移脚本、微软 Azure co-op-translator(CI 中由源 hash 驱动的 LLM 重译)。本设计将两者结合:中文生态的文件布局,加上 hash 配对门禁,再加一个仓库内置的 agent skill 替代 bot 服务。\n\n## 后果\n\n- 修改已配对文档的任一侧,同一个 PR 就有义务更新对侧并重新记录配对。门禁将 doc-sync 规则双语化,不变式由 CI(而非评审者的记忆)承载。\n- 每个配对给目录树多添一个文件。记录由机器写入(`--write`),代价是目录噪音而非维护负担;换来的是「谁在何时确认过这对文档一致」可以从 yaml 的 git blame 直接回答。\n- 两侧说法冲突时,没有机械规则裁决谁赢,由 PR 评审裁决。这是同权的代价,且是有意接受的:另一个选项(正典语言)会禁止中文先行撰写。\n- 生成文档(`cordis-catalog/`、`tool-catalog/`、`module-graph.md`)暂被排除;计划中的后续工作是让生成器在输出英文的同时输出中文,届时将这些文件移出排除清单。\n- 显式 `required` 条目与日期分界保留已经评审的推进历史,而两个已纳入强制范围的类别会将当前及今后所有范围内的文档列为必选项。任何文档类别都不能新增 backlog(待翻清单)。\n- 记录的 hash 兼作更新工具(`git cat-file -p ` 能还原任一侧上次确认的文本,用于基于 diff 的最小更新),因此这套机制从不强迫整篇重译。\n" }, { "role": "user", diff --git a/scripts/translation-pairing.manifest.json b/scripts/translation-pairing.manifest.json index 35688f62b7..1667a8eaef 100644 --- a/scripts/translation-pairing.manifest.json +++ b/scripts/translation-pairing.manifest.json @@ -1,6 +1,7 @@ { "requiredClasses": [ - "non-readme" + "non-readme", + "readme" ], "requiredSince": "2026-07-14", "required": [ diff --git a/scripts/translation-pairing.spec.ts b/scripts/translation-pairing.spec.ts index b8b880565a..5c10f80abb 100644 --- a/scripts/translation-pairing.spec.ts +++ b/scripts/translation-pairing.spec.ts @@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest' import { datedDocumentDate, isIsoDate, + isTranslationScopeFile, parseTranslationMarkdown, parseTranslationPairingManifest, requiresPairByDate, @@ -82,6 +83,45 @@ describe('document-class pairing frontier', () => { expect(requiresTranslationPair('docs/legacy/README.md', manifest)).toBe(true) expect(requiresTranslationPair('docs/new/README.md', manifest)).toBe(false) }) + + it('requires both document classes after the README frontier closes', () => { + const closed = parseTranslationPairingManifest(JSON.stringify({ + ...manifest, + requiredClasses: ['non-readme', 'readme'], + })) + expect(requiresTranslationPair('docs/guide.md', closed)).toBe(true) + expect(requiresTranslationPair('future/subtree/README.md', closed)).toBe(true) + }) +}) + +describe('translation scope discovery', () => { + it.each([ + 'README.md', + 'apps/cli/README.md', + 'future/subtree/readme.md', + 'packages/example/README.zh.md', + 'native/example/README.i18n.yaml', + '.agents/notes/proposed/feature.md', + 'docs/guide.md', + 'python/guide.md', + ])('includes %s', (file) => { + expect(isTranslationScopeFile(file)).toBe(true) + }) + + it.each([ + 'packages/example/guide.md', + 'examples/tutorial.md', + 'website/reference.md', + 'packages/example/README.txt', + 'vendor/example/README.md', + 'packages/example/node_modules/dependency/README.md', + 'packages/example/lib/README.md', + 'coverage/report/README.md', + 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-macos-arm64/README.md', + 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/README.md', + ])('excludes non-source or non-README path %s', (file) => { + expect(isTranslationScopeFile(file)).toBe(false) + }) }) describe('date-based pairing frontier', () => { diff --git a/scripts/translation-pairing.ts b/scripts/translation-pairing.ts index 92c38e8896..a41bcc3077 100644 --- a/scripts/translation-pairing.ts +++ b/scripts/translation-pairing.ts @@ -26,6 +26,63 @@ const TRANSLATION_DOCUMENT_CLASSES: TranslationDocumentClass[] = ['readme', 'non const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/ const DATED_DOCUMENT = /(?:^|\/)(\d{4}-\d{2}-\d{2})-[^/]*\.md$/ +const README_ARTIFACT = /(?:^|\/)readme(?:\.md|\.zh\.md|\.i18n\.yaml)$/i +const NON_SOURCE_DIRECTORIES = new Set([ + 'node_modules', + 'lib', + '.pnpm-store', + '.cache', + 'coverage', + '.sessions', + '.storages', + 'tmp', + 'dist-exe', + '__pycache__', + '.pytest_cache', + '.artifacts', + 'vendor', +]) + +/** Glob traversal exclusions corresponding to the non-source path predicate. */ +export const TRANSLATION_SCOPE_GLOB_EXCLUDES = [ + '**/node_modules/**', + '**/lib/**', + '**/.pnpm-store/**', + '**/.cache/**', + '**/coverage/**', + '**/.doc-typecheck-*/**', + '**/.node-next-types-*/**', + '**/.sessions/**', + '**/.storages/**', + '**/tmp/**', + '**/dist-exe/**', + '**/__pycache__/**', + '**/.pytest_cache/**', + 'apps/web/dist/**', + '.artifacts/**', + 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-*/**', + 'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/**', + 'vendor/**', +] + +/** Whether a repository-relative path belongs to a dependency or generated tree. */ +function isTranslationSourceExcluded(file: string): boolean { + const segments = file.split('/') + return segments.some(segment => NON_SOURCE_DIRECTORIES.has(segment) + || segment.startsWith('.doc-typecheck-') + || segment.startsWith('.node-next-types-')) + || file.startsWith('apps/web/dist/') + || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/dsh-jsonrpc-agent-') + || file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/') +} + +/** Whether one discovered Markdown or sidecar path belongs to the bilingual source corpus. */ +export function isTranslationScopeFile(file: string): boolean { + return !isTranslationSourceExcluded(file) && (README_ARTIFACT.test(file) + || file.startsWith('.agents/notes/') + || file.startsWith('docs/') + || file.startsWith('python/')) +} /** Whether a string names one real calendar day in canonical ISO form. */ export function isIsoDate(value: string): boolean { diff --git a/scripts/verify-translation-pairing.ts b/scripts/verify-translation-pairing.ts index 9372064707..8e688d02e9 100644 --- a/scripts/verify-translation-pairing.ts +++ b/scripts/verify-translation-pairing.ts @@ -15,7 +15,9 @@ import { linksTo, parseTranslationMarkdown, parseTranslationPairingManifest, + isTranslationScopeFile, requiresTranslationPair, + TRANSLATION_SCOPE_GLOB_EXCLUDES, translationDocumentClass, translationStructureDiff, translationStructureSignature, @@ -25,17 +27,12 @@ const root = resolve(import.meta.dirname, '..') const listMode = process.argv.includes('--list') const writeMode = process.argv.includes('--write') -/** Scope of the bilingual contract: root docs, Agent Notes, the docs tree, and the Python SDK tree. */ +/** Discover source Markdown and pairing sidecars before applying the corpus predicate. */ const SCOPE_PATTERNS = [ - 'README.md', - 'README.zh.md', - 'README.i18n.yaml', + '**/*.md', + '**/*.i18n.yaml', '.agents/notes/**/*.md', '.agents/notes/**/*.i18n.yaml', - 'docs/**/*.md', - 'docs/**/*.i18n.yaml', - 'python/**/*.md', - 'python/**/*.i18n.yaml', ] const manifest = parseTranslationPairingManifest(readFileSync(join(root, 'scripts/translation-pairing.manifest.json'), 'utf8')) @@ -93,7 +90,10 @@ function renderMeta(source: string, sourceHash: string, zh: string, zhHash: stri // Enumerate the scope once. const files = new Set() for (const pattern of SCOPE_PATTERNS) { - for (const match of globSync(pattern, { cwd: root })) files.add(match.split(sep).join('/')) + for (const match of globSync(pattern, { cwd: root, exclude: TRANSLATION_SCOPE_GLOB_EXCLUDES })) { + const normalized = match.split(sep).join('/') + if (isTranslationScopeFile(normalized)) files.add(normalized) + } } const translations = [...files].filter(f => f.endsWith('.zh.md')).sort() const metas = [...files].filter(f => f.endsWith('.i18n.yaml')).sort() From a04ce7afbb6dde19d5e2973794f183667f27c1c4 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sun, 26 Jul 2026 04:15:56 +0800 Subject: [PATCH 105/113] refactor(client): shared declaration-aware registration deferral MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The five settings-surface registrants carried near-identical spec-check/ledger-judge/subscribe scaffolding (three jscpd clones); ui-slots now owns deferRegistration() — ledger-judged presence, refresh for registrant-localized labels, one-call disposal — and every registrant shrinks to its registration body. --- packages/client/locale/src/client/index.ts | 23 ++----- packages/client/ui-models/src/client/index.ts | 32 +++------ .../client/ui-settings/src/client/index.ts | 46 ++++--------- packages/client/ui-slots/src/deferred.ts | 66 +++++++++++++++++++ packages/client/ui-slots/src/index.ts | 1 + packages/client/ui-theme/src/client/index.ts | 23 ++----- 6 files changed, 97 insertions(+), 94 deletions(-) create mode 100644 packages/client/ui-slots/src/deferred.ts diff --git a/packages/client/locale/src/client/index.ts b/packages/client/locale/src/client/index.ts index 444594f9b8..ea6f9d8da9 100644 --- a/packages/client/locale/src/client/index.ts +++ b/packages/client/locale/src/client/index.ts @@ -5,7 +5,7 @@ * its own settings surface. */ import type { Context } from 'cordis' -import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots' +import { deferRegistration, type BoundActions } from '@deepseek-ai/dsh-client-ui-slots' import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import { en } from '../locales/en.ts' import { zh } from '../locales/zh.ts' @@ -233,28 +233,15 @@ export function apply(ctx: ClientContext): void { setLocale: (id) => { locale.setLocale(id) }, } } - // Declaration-aware registration; the LEDGER is the has-registered judge - // (not a local flag): after an HMR collapse re-declares the slot, the - // cascade already removed our entry, and a stale disposer must not block - // the re-registration. ctx.effect(() => { - let dispose: (() => void) | undefined - const tryRegister = (): void => { - if (ctx.slots.spec('settings.general.item') === undefined) return - if (ctx.slots.entries('settings.general.item').some(e => e.component === LanguageRow)) return - dispose = ctx.slots.register({ + const deferred = deferRegistration(ctx.slots, 'settings.general.item', LanguageRow, () => + ctx.slots.register({ name: 'settings.general.item', id: 'language', order: 0, store, inject: injected, - }, LanguageRow) - } - const unsubscribe = ctx.slots.subscribe('settings.general.item', () => { tryRegister() }) - tryRegister() - return () => { - unsubscribe() - dispose?.() - } + }, LanguageRow)) + return () => { deferred.dispose() } }, 'locale: language settings row registration') } diff --git a/packages/client/ui-models/src/client/index.ts b/packages/client/ui-models/src/client/index.ts index 4f080ec928..5abcb65bcf 100644 --- a/packages/client/ui-models/src/client/index.ts +++ b/packages/client/ui-models/src/client/index.ts @@ -5,6 +5,7 @@ * discipline: packages/client/AGENTS.md. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls the shell's SlotMap merge (the 'settings.section' entry). import type {} from '@deepseek-ai/dsh-client-ui-settings/client' // Type-only: pulls the locale plugin's Context merge (ctx.locale). @@ -31,37 +32,20 @@ export function apply(ctx: ClientContext): void { ] return () => { for (const dispose of disposers) dispose() } }, 'ui-models: nav copy dictionaries') - // Declaration-aware registration; the LEDGER is the has-registered judge - // (not a local flag): after an HMR collapse re-declares the slot, the - // cascade already removed our entry, and a stale disposer must not block - // the re-registration. ctx.effect(() => { - let dispose: (() => void) | undefined - const tryRegister = (): void => { - if (ctx.slots.spec('settings.section') === undefined) return - if (ctx.slots.entries('settings.section').some(e => e.component === ModelsSection)) return - dispose = ctx.slots.register({ + const deferred = deferRegistration(ctx.slots, 'settings.section', ModelsSection, () => + ctx.slots.register({ name: 'settings.section', id: 'models', order: 10, label: ctx.locale.bind('settings.models')('nav'), - }, ModelsSection) - } - // Nav labels are registrant-localized: re-register on locale change so - // the ledger carries fresh text (the version bump re-renders the shell). - // Dispose-then-requery: after an HMR collapse the disposer is stale and - // the ledger/spec re-check keeps this path an idempotent no-op. - const offLocale = ctx.on('locale/change', () => { - dispose?.() - dispose = undefined - tryRegister() - }) - const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) - tryRegister() + }, ModelsSection)) + // Nav labels are registrant-localized: refresh on locale change so the + // ledger carries fresh text (the version bump re-renders the shell). + const offLocale = ctx.on('locale/change', () => { deferred.refresh() }) return () => { offLocale() - unsubscribe() - dispose?.() + deferred.dispose() } }, 'ui-models: settings section registration') } diff --git a/packages/client/ui-settings/src/client/index.ts b/packages/client/ui-settings/src/client/index.ts index c360a84201..9d379c301e 100644 --- a/packages/client/ui-settings/src/client/index.ts +++ b/packages/client/ui-settings/src/client/index.ts @@ -7,6 +7,7 @@ * preference rows into. Export discipline: packages/client/AGENTS.md. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pulls the locale plugin's Context/Events merges (ctx.locale, // 'locale/change') into this program. import type {} from '@deepseek-ai/dsh-client-locale/client' @@ -60,60 +61,37 @@ export function apply(ctx: ClientContext): void { })) .sort((a, b) => a.order - b.order), }) - // Declaration-aware registration; the LEDGER is the has-registered judge - // (not a local flag): after an HMR collapse re-declares the slot, the - // cascade already removed our entry, and a stale disposer must not block - // the re-registration. ctx.effect(() => { - let dispose: (() => void) | undefined - const tryRegister = (): void => { - if (ctx.slots.spec('sidebar.settings') === undefined) return - if (ctx.slots.entries('sidebar.settings').some(e => e.component === SettingsRoot)) return - dispose = ctx.slots.register({ + const deferred = deferRegistration(ctx.slots, 'sidebar.settings', SettingsRoot, () => + ctx.slots.register({ name: 'sidebar.settings', children: { 'settings.section': { kind: 'list', scope: 'root' } }, inject: injected, - }, SettingsRoot) - } - const unsubscribe = ctx.slots.subscribe('sidebar.settings', () => { tryRegister() }) - tryRegister() - return () => { - unsubscribe() - dispose?.() - } + }, SettingsRoot)) + return () => { deferred.dispose() } }, 'ui-settings: shell registration') // The shell's own General section: first page, declares the item slot the // feature plugins (locale, ui-theme, …) contribute preference rows into. - // Same ledger-judged deferral; label re-registers on locale change. const generalInjected = (): GeneralSectionInjected => ({ t: ctx.locale.bind('settings'), }) ctx.effect(() => { - let dispose: (() => void) | undefined - const tryRegister = (): void => { - if (ctx.slots.spec('settings.section') === undefined) return - if (ctx.slots.entries('settings.section').some(e => e.component === GeneralSection)) return - dispose = ctx.slots.register({ + const deferred = deferRegistration(ctx.slots, 'settings.section', GeneralSection, () => + ctx.slots.register({ name: 'settings.section', id: 'general', order: 0, label: ctx.locale.bind('settings')('general.nav'), children: { 'settings.general.item': { kind: 'list', scope: 'root' } }, inject: generalInjected, - }, GeneralSection) - } - const offLocale = ctx.on('locale/change', () => { - dispose?.() - dispose = undefined - tryRegister() - }) - const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() }) - tryRegister() + }, GeneralSection)) + // Nav labels are registrant-localized: refresh on locale change so the + // ledger carries fresh text (the version bump re-renders the shell). + const offLocale = ctx.on('locale/change', () => { deferred.refresh() }) return () => { offLocale() - unsubscribe() - dispose?.() + deferred.dispose() } }, 'ui-settings: general section registration') } diff --git a/packages/client/ui-slots/src/deferred.ts b/packages/client/ui-slots/src/deferred.ts new file mode 100644 index 0000000000..af85c27f97 --- /dev/null +++ b/packages/client/ui-slots/src/deferred.ts @@ -0,0 +1,66 @@ +/** + * Declaration-aware registration deferral: the shared timing machinery for + * registering into a slot whose declaring entry activates in unconstrained + * order (dshClient.inject edges never sequence apply). Presence is judged on + * the LEDGER, not a local flag — after an HMR collapse re-declares the slot, + * the cascade has already removed the entry while the local disposer went + * stale, and a flag guard would block the re-registration. + */ + +/** Minimal registry face the deferral reads (SlotsService satisfies it). */ +export interface DeferralRegistry { + /** Declared spec lookup (undefined = not declared yet). */ + spec(name: string): unknown + /** Current entries of the slot (component identity is the presence judge). */ + entries(name: string): readonly { component: unknown }[] + /** Subscribe to the slot's ledger changes; returns the unsubscriber. */ + subscribe(name: string, listener: () => void): () => void +} + +/** Handle over one deferred registration. */ +export interface DeferredRegistration { + /** + * Drop the current registration (stale disposers are harmless no-ops) and + * immediately re-attempt — the refresh path for registrants whose options + * carry localized text. + */ + refresh(): void + /** Unsubscribe and unregister (idempotent through the slot core). */ + dispose(): void +} + +/** + * Register into `name` as soon as its declaration is on the ledger, and + * re-register whenever the declaration reappears after a collapse. + * @param registry - the slot registry face. + * @param name - target slot name. + * @param component - the component whose ledger presence marks "registered". + * @param register - performs the actual registration; returns its disposer. + * @returns the deferral handle (dispose in the owning effect's disposer). + */ +export function deferRegistration( + registry: DeferralRegistry, + name: string, + component: unknown, + register: () => () => void, +): DeferredRegistration { + let dispose: (() => void) | undefined + const tryRegister = (): void => { + if (registry.spec(name) === undefined) return + if (registry.entries(name).some(e => e.component === component)) return + dispose = register() + } + const unsubscribe = registry.subscribe(name, () => { tryRegister() }) + tryRegister() + return { + refresh() { + dispose?.() + dispose = undefined + tryRegister() + }, + dispose() { + unsubscribe() + dispose?.() + }, + } +} diff --git a/packages/client/ui-slots/src/index.ts b/packages/client/ui-slots/src/index.ts index 677bc4e0df..e3bc57797d 100644 --- a/packages/client/ui-slots/src/index.ts +++ b/packages/client/ui-slots/src/index.ts @@ -18,6 +18,7 @@ import type { BoundActions, HandleOf, PropsStore, SnapshotSelectorHook, StoreDec export * from './store.ts' export * from './renderer.ts' +export * from './deferred.ts' /** Slot contract table. Owners extend via declaration merging; entries are {@link SlotEntryDef}. */ export interface SlotMap {} diff --git a/packages/client/ui-theme/src/client/index.ts b/packages/client/ui-theme/src/client/index.ts index ac79913062..dd11c98f06 100644 --- a/packages/client/ui-theme/src/client/index.ts +++ b/packages/client/ui-theme/src/client/index.ts @@ -7,7 +7,7 @@ * section — the theme feature owns its own settings surface. */ import type { Context } from 'cordis' -import type { BoundActions } from '@deepseek-ai/dsh-client-ui-slots' +import { deferRegistration, type BoundActions } from '@deepseek-ai/dsh-client-ui-slots' import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' // Type-only: pulls the locale plugin's Context merge (ctx.locale). import type {} from '@deepseek-ai/dsh-client-locale/client' @@ -262,28 +262,15 @@ export function apply(ctx: ClientContext): void { setTheme: (id) => { theme.setTheme(id) }, } } - // Declaration-aware registration; the LEDGER is the has-registered judge - // (not a local flag): after an HMR collapse re-declares the slot, the - // cascade already removed our entry, and a stale disposer must not block - // the re-registration. ctx.effect(() => { - let dispose: (() => void) | undefined - const tryRegister = (): void => { - if (ctx.slots.spec('settings.general.item') === undefined) return - if (ctx.slots.entries('settings.general.item').some(e => e.component === AppearanceRow)) return - dispose = ctx.slots.register({ + const deferred = deferRegistration(ctx.slots, 'settings.general.item', AppearanceRow, () => + ctx.slots.register({ name: 'settings.general.item', id: 'appearance', order: 10, store, inject: injected, - }, AppearanceRow) - } - const unsubscribe = ctx.slots.subscribe('settings.general.item', () => { tryRegister() }) - tryRegister() - return () => { - unsubscribe() - dispose?.() - } + }, AppearanceRow)) + return () => { deferred.dispose() } }, 'ui-theme: appearance settings row registration') } From 586ccb677ec0abd4cab2afd98a98965d5f570341 Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 04:18:03 +0800 Subject: [PATCH 106/113] docs: refine semantic PR label taxonomy --- ...07-25-semantic-pr-label-taxonomy.i18n.yaml | 4 +-- .../2026-07-25-semantic-pr-label-taxonomy.md | 23 ++++++++++++----- ...026-07-25-semantic-pr-label-taxonomy.zh.md | 25 +++++++++++++------ 3 files changed, 37 insertions(+), 15 deletions(-) diff --git a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.i18n.yaml b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.i18n.yaml index 9be3fb4b13..8bc3f87435 100644 --- a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.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 -2026-07-25-semantic-pr-label-taxonomy.md: cf25691e55d100cc2cc12246b17f5edbba35feea -2026-07-25-semantic-pr-label-taxonomy.zh.md: 2978bdc80a660f67f84821e473dc229e13b2bc4d +2026-07-25-semantic-pr-label-taxonomy.md: 61b7a829b8c44836cf9c6d0d8a7df463df309d89 +2026-07-25-semantic-pr-label-taxonomy.zh.md: cc0c5e7a8953bc97de51f90349a0e2542be5b77e diff --git a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md index cf25691e55..61b7a829b8 100644 --- a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md +++ b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.md @@ -20,26 +20,32 @@ Every open or merged pull request carries exactly one kind and every materially |---|---| | `feature` | Adds or intentionally changes behavior. | | `bug-fix` | Corrects incorrect behavior. | -| `doc` | Changes documentation only. | +| `doc` | Makes documentation the dominant intent. | | `testing` | Changes tests or testing infrastructure without changing product behavior. | | `cleanup` | Preserves behavior while maintaining or simplifying the implementation or repository process. | The kind records the change's dominant intent: accompanying tests and documentation do not turn a feature or bug fix into a testing or documentation change. -Areas record semantic repository domains rather than temporary initiatives, ownership, or every path touched incidentally. A pull request may carry several areas when it changes several domains. +Areas record semantic repository domains rather than temporary initiatives, ownership, or every path touched incidentally. Area labels are not a hierarchy: a pull request may carry several when it changes distinct contracts, but an umbrella and a narrower label do not both describe the same work. ### Current areas -The 43 current areas are listed below. The group names organize the list for readability; they are not labels or another taxonomy level. +The 45 current areas are listed below. The group names organize the list for readability; they are not labels or another taxonomy level. | Group | Areas | |---|---| | Agent and model | `agent`, `agent-loop`, `session`, `llm`, `model-context`, `compaction`, `tools`, `persistence` | -| Orchestration | `subagent`, `workflow`, `planning`, `tasks`, `telemetry`, `storage`, `workspace` | -| Capabilities | `bash`, `pty`, `filesystem`, `lsp`, `skills`, `web-search`, `code-mode`, `sandbox`, `mcp`, `hooks`, `cordis` | -| Interfaces | `ui`, `web`, `tui`, `acp`, `json-rpc`, `cli`, `python-sdk`, `desktop`, `vscode`, `website` | +| Orchestration | `subagent`, `workflow`, `planning`, `tasks`, `schedule`, `telemetry`, `storage`, `workspace` | +| Capabilities | `bash`, `pty`, `filesystem`, `lsp`, `skills`, `web-search`, `code-mode`, `artifact`, `attachment`, `sandbox`, `mcp`, `hooks`, `cordis` | +| Interfaces | `ui`, `gui`, `tui`, `acp`, `json-rpc`, `cli`, `python-sdk`, `vscode`, `website` | | Repository and release | `dev-infra`, `ci`, `build`, `dependencies`, `platform`, `i18n`, `release` | +`gui` covers browser and Electron graphical applications, including standalone graphical developer tools; `vscode` remains the editor extension integration. `ui` covers shared cross-interface commands, approval interaction, presentation, and app boot; it coexists with `gui`, `tui`, or a protocol area only when the pull request also changes that shared contract. + +`tasks` owns background work tied to a running process, while `schedule` owns durable time-triggered jobs. `tools` owns generic registry, schema, and execution contracts; a concrete capability receives `tools` only when it changes one of those contracts. `attachment` owns durable media references and multimodal input delivery, while `artifact` owns model-declared deliverable identity and preview lifecycle; neither borrows `tools` or `ui` for its implementation parts. + +Names follow semantic ownership rather than lexical resemblance. `hooks` means the Claude Code and Codex agent bridges, not local Git hooks; `platform` means product portability, not CI runner selection; and `build` means compilation, bundling, and built package artifacts, not documentation generators. + ### Extensibility The area set is intentionally extensible. Add an area when a recurring, meaningful repository domain is missing; do not add a label for one pull request, a temporary project, a status, or a person or team. Rename, split, or retire an area when the domain model changes, and update this list and the affected open and merged pull requests together. @@ -51,10 +57,15 @@ The kind set stays narrow because kinds are mutually exclusive. A new kind requi - **One undifferentiated label set.** Rejected because kind and area answer different questions; mixing them makes the presence of one label say nothing about whether the other dimension was considered. - **A fixed, closed area set.** Rejected because repository domains evolve. A closed set would preserve spelling at the cost of semantic accuracy. - **One broad `core` area or package-derived labels.** Rejected because domains such as `session`, `llm`, and `agent` remain independently meaningful across package boundaries, while incidental file paths are not the scope reviewers or automation need. +- **Separate browser and desktop areas.** Rejected because browser delivery and Electron packaging expose one graphical client domain; splitting them classifies the delivery shell rather than the semantic work. +- **Broad implementation areas in place of a domain.** Rejected because a durable scheduled job is not a background task, an attachment is not merely its source interface or filesystem implementation, and an artifact is not merely its declaring tool or preview interface. +- **Umbrella and leaf areas for the same contract.** Rejected because duplicate labels inflate scope without adding information. Multiple areas remain correct when a pull request changes genuinely distinct contracts. - **Exactly one area per pull request.** Rejected because coherent changes can legitimately span several domains, and dropping secondary areas hides affected contracts. ## Consequences - Reviewers and automation receive one stable intent signal plus a complete semantic scope. +- `gui` queries cover browser and desktop delivery together, while `ui` queries retain only shared cross-interface contracts. +- `schedule`, `attachment`, and `artifact` queries identify those domains directly instead of approximating them through implementation dependencies. - Selecting labels remains a judgment call: paths and title prefixes can suggest areas, but they cannot replace reading the change. - Taxonomy changes carry maintenance work. Area additions, renames, splits, and removals update this decision record and backfill open and merged pull requests so historical queries keep their meaning. diff --git a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md index 2978bdc80a..cc0c5e7a89 100644 --- a/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md +++ b/.agents/notes/implemented/process/2026-07-25-semantic-pr-label-taxonomy.zh.md @@ -20,26 +20,32 @@ PR(Pull Request)需要传达两个不同的信号:它带来哪一类变更 |---|---| | `feature` | 新增行为或有意改变行为。 | | `bug-fix` | 修正错误行为。 | -| `doc` | 仅修改文档。 | +| `doc` | 以文档变更为主要意图。 | | `testing` | 修改测试或测试基础设施,但不改变产品行为。 | | `cleanup` | 在保持行为不变的前提下,维护或简化实现或仓库流程。 | 类型记录变更的主要意图:配套测试与文档并不会把一项功能或缺陷修复变成测试或文档变更。 -领域记录仓库中的语义领域,而不是临时项目、归属关系或偶然触及的每条路径。如果一项 PR 修改了多个领域,就可以带有多个领域标签。 +领域记录仓库中的语义领域,而不是临时项目、归属关系或偶然触及的每条路径。领域标签不构成层级:一项 PR 修改不同契约时可以带有多个领域标签,但不能用一个总括标签和一个较窄标签重复描述同一项工作。 ### 当前领域 -当前的 43 个领域如下。分组名称仅用于提高列表的可读性;它们既不是标签,也不是分类体系中的另一个层级。 +当前的 45 个领域如下。分组名称仅用于提高列表的可读性;它们既不是标签,也不是分类体系中的另一个层级。 | 分组 | 领域 | |---|---| | agent(智能体)与模型 | `agent`, `agent-loop`, `session`, `llm`, `model-context`, `compaction`, `tools`, `persistence` | -| 编排 | `subagent`, `workflow`, `planning`, `tasks`, `telemetry`, `storage`, `workspace` | -| 能力 | `bash`, `pty`, `filesystem`, `lsp`, `skills`, `web-search`, `code-mode`, `sandbox`, `mcp`, `hooks`, `cordis` | -| 接口 | `ui`, `web`, `tui`, `acp`, `json-rpc`, `cli`, `python-sdk`, `desktop`, `vscode`, `website` | +| 编排 | `subagent`, `workflow`, `planning`, `tasks`, `schedule`, `telemetry`, `storage`, `workspace` | +| 能力 | `bash`, `pty`, `filesystem`, `lsp`, `skills`, `web-search`, `code-mode`, `artifact`, `attachment`, `sandbox`, `mcp`, `hooks`, `cordis` | +| 接口 | `ui`, `gui`, `tui`, `acp`, `json-rpc`, `cli`, `python-sdk`, `vscode`, `website` | | 仓库与发布 | `dev-infra`, `ci`, `build`, `dependencies`, `platform`, `i18n`, `release` | +`gui` 涵盖浏览器和 Electron 图形应用,包括独立的图形化开发者工具;`vscode` 仍表示编辑器扩展集成。`ui` 涵盖共享的跨接口命令、审批交互、呈现和应用启动;只有当 PR 还修改这项共享契约时,它才与 `gui`、`tui` 或某个协议领域并用。 + +`tasks` 负责与运行中进程绑定的后台工作,`schedule` 则负责持久化的定时作业。`tools` 负责通用的注册表契约、schema 契约和执行契约;具体能力只有在修改其中一项契约时才带有 `tools`。`attachment` 负责持久化的媒体引用和多模态输入传递,`artifact` 则负责模型声明的交付物标识和预览生命周期;二者都不会因实现包含工具或界面部分而借用 `tools` 或 `ui`。 + +标签名称以语义归属为准,而不是词面相似性。`hooks` 指 Claude Code 和 Codex 的 agent 桥接,而不是本地 Git 钩子;`platform` 指产品可移植性,而不是 CI 运行器选择;`build` 指编译、打包和已构建的包(package)产物,而不是文档生成器。 + ### 可扩展性 领域集合有意保持可扩展。当分类体系缺少一个会反复涉及且具有实际意义的仓库领域时,就新增领域;不要仅为一项 PR、临时项目、状态、个人或团队新增标签。当领域模型发生变化时,重命名、拆分或退役相应领域,同时更新本列表以及所有受影响的开放和已合并 PR。 @@ -50,11 +56,16 @@ PR(Pull Request)需要传达两个不同的信号:它带来哪一类变更 - **一套不区分维度的标签。** 不予采纳,因为类型与领域回答的是不同问题;两者混在一起时,存在一个维度的标签并不表示另一个维度也经过了考虑。 - **一套固定、封闭的领域集合。** 不予采纳,因为仓库领域会持续演变。封闭集合会以牺牲语义准确性为代价来维持拼写不变。 -- **一个宽泛的 `core` 领域,或从包(package)结构派生的标签。** 不予采纳,因为 `session`、`llm` 和 `agent` 等领域在跨越包边界时仍各自具有意义,而偶然涉及的文件路径并不是评审人或自动化流程所需的范围信息。 +- **一个宽泛的 `core` 领域,或从包结构派生的标签。** 不予采纳,因为 `session`、`llm` 和 `agent` 等领域在跨越包边界时仍各自具有意义,而偶然涉及的文件路径并不是评审人或自动化流程所需的范围信息。 +- **为浏览器和桌面端分别设置领域。** 不予采纳,因为浏览器交付和 Electron 打包共同呈现同一个图形客户端领域;拆开二者将按交付形态而非工作的语义进行分类。 +- **以宽泛的实现领域替代语义领域。** 不予采纳,因为持久化的定时作业不是后台任务,附件不只是其来源接口或文件系统实现,产物也不只是声明它的工具或预览接口。 +- **同一项契约同时使用总括领域与细分领域。** 不予采纳,因为重复标签只会虚增范围,不会增加信息。一项 PR 确实修改不同契约时,多个领域标签仍然合理。 - **每项 PR 恰好一个领域。** 不予采纳,因为一项内聚的变更可以合理地跨越多个领域;省略次要领域会隐藏受影响的契约。 ## 后果 - 评审人和自动化流程获得一个稳定的意图信号,以及完整的语义范围。 +- `gui` 查询会同时覆盖浏览器与桌面端交付,`ui` 查询则只涵盖共享的跨接口契约。 +- `schedule`、`attachment` 与 `artifact` 查询直接对应各自领域,无需通过实现依赖近似归类。 - 选择标签仍然需要判断:路径和标题前缀可以提示领域,但不能替代阅读变更内容。 - 变更分类体系会产生维护工作。新增、重命名、拆分或移除领域时,需要更新本决策记录,并回填开放和已合并的 PR,使历史查询保持原有含义。 From 226dc7a249845aaae8f99a340109c214d20139bf Mon Sep 17 00:00:00 2001 From: Tianyi Cui <53024+tianyicui@users.noreply.github.com> Date: Sun, 26 Jul 2026 05:03:53 +0800 Subject: [PATCH 107/113] docs: translate remaining READMEs --- apps/cli/README.i18n.yaml | 6 + apps/cli/README.md | 2 + apps/cli/README.zh.md | 27 +++ examples/README.i18n.yaml | 6 + examples/README.md | 2 + examples/README.zh.md | 35 ++++ examples/acp-agent/README.i18n.yaml | 6 + examples/acp-agent/README.md | 2 + examples/acp-agent/README.zh.md | 30 +++ examples/cordis-agent/README.i18n.yaml | 6 + examples/cordis-agent/README.md | 2 + examples/cordis-agent/README.zh.md | 35 ++++ examples/headless-agent/README.i18n.yaml | 6 + examples/headless-agent/README.md | 2 + examples/headless-agent/README.zh.md | 26 +++ examples/jsonrpc-agent/README.i18n.yaml | 6 + examples/jsonrpc-agent/README.md | 2 + examples/jsonrpc-agent/README.zh.md | 27 +++ examples/tui-agent/README.i18n.yaml | 6 + examples/tui-agent/README.md | 2 + examples/tui-agent/README.zh.md | 80 +++++++ native/README.i18n.yaml | 6 + native/README.md | 2 + native/README.zh.md | 22 ++ native/landlock-run/README.i18n.yaml | 6 + native/landlock-run/README.md | 2 + native/landlock-run/README.zh.md | 60 ++++++ .../packages/entry/README.i18n.yaml | 6 + native/landlock-run/packages/entry/README.md | 2 + .../landlock-run/packages/entry/README.zh.md | 18 ++ .../packages/linux-arm64/README.i18n.yaml | 6 + .../packages/linux-arm64/README.md | 2 + .../packages/linux-arm64/README.zh.md | 9 + .../packages/linux-x64/README.i18n.yaml | 6 + .../landlock-run/packages/linux-x64/README.md | 2 + .../packages/linux-x64/README.zh.md | 9 + packages/README.i18n.yaml | 6 + packages/README.md | 2 + packages/README.zh.md | 56 +++++ packages/acp/README.i18n.yaml | 6 + packages/acp/README.md | 2 + packages/acp/README.zh.md | 11 + packages/acp/acp/README.i18n.yaml | 6 + packages/acp/acp/README.md | 2 + packages/acp/acp/README.zh.md | 79 +++++++ packages/bash/README.i18n.yaml | 6 + packages/bash/README.md | 2 + packages/bash/README.zh.md | 14 ++ packages/bash/bash-local/README.i18n.yaml | 6 + packages/bash/bash-local/README.md | 2 + packages/bash/bash-local/README.zh.md | 49 +++++ packages/bash/bash-sandbox/README.i18n.yaml | 6 + packages/bash/bash-sandbox/README.md | 2 + packages/bash/bash-sandbox/README.zh.md | 90 ++++++++ packages/bash/bash/README.i18n.yaml | 6 + packages/bash/bash/README.md | 2 + packages/bash/bash/README.zh.md | 49 +++++ packages/bash/tool-bash/README.i18n.yaml | 6 + packages/bash/tool-bash/README.md | 2 + packages/bash/tool-bash/README.zh.md | 158 ++++++++++++++ packages/client/connection/README.i18n.yaml | 6 + packages/client/connection/README.md | 2 + packages/client/connection/README.zh.md | 22 ++ packages/client/hmr/README.i18n.yaml | 6 + packages/client/hmr/README.md | 2 + packages/client/hmr/README.zh.md | 21 ++ packages/client/i18n/README.i18n.yaml | 6 + packages/client/i18n/README.md | 2 + packages/client/i18n/README.zh.md | 18 ++ packages/client/modules/README.i18n.yaml | 6 + packages/client/modules/README.md | 2 + packages/client/modules/README.zh.md | 22 ++ packages/client/runtime/README.i18n.yaml | 6 + packages/client/runtime/README.md | 2 + packages/client/runtime/README.zh.md | 33 +++ .../client/ui-conversation/README.i18n.yaml | 6 + packages/client/ui-conversation/README.md | 2 + packages/client/ui-conversation/README.zh.md | 33 +++ packages/client/ui-layout/README.i18n.yaml | 6 + packages/client/ui-layout/README.md | 2 + packages/client/ui-layout/README.zh.md | 23 +++ .../client/ui-primitives/README.i18n.yaml | 6 + packages/client/ui-primitives/README.md | 2 + packages/client/ui-primitives/README.zh.md | 23 +++ packages/client/ui-question/README.i18n.yaml | 6 + packages/client/ui-question/README.md | 2 + packages/client/ui-question/README.zh.md | 22 ++ packages/client/ui-sidebar/README.i18n.yaml | 6 + packages/client/ui-sidebar/README.md | 2 + packages/client/ui-sidebar/README.zh.md | 25 +++ packages/client/ui-slots/README.i18n.yaml | 6 + packages/client/ui-slots/README.md | 2 + packages/client/ui-slots/README.zh.md | 35 ++++ packages/client/ui-theme/README.i18n.yaml | 6 + packages/client/ui-theme/README.md | 2 + packages/client/ui-theme/README.zh.md | 19 ++ .../client/ui-trajectory/README.i18n.yaml | 6 + packages/client/ui-trajectory/README.md | 2 + packages/client/ui-trajectory/README.zh.md | 17 ++ packages/client/ui-workspace/README.i18n.yaml | 6 + packages/client/ui-workspace/README.md | 2 + packages/client/ui-workspace/README.zh.md | 22 ++ packages/client/web-react/README.i18n.yaml | 6 + packages/client/web-react/README.md | 2 + packages/client/web-react/README.zh.md | 19 ++ packages/client/web/README.i18n.yaml | 6 + packages/client/web/README.md | 2 + packages/client/web/README.zh.md | 26 +++ packages/code-runtime/README.i18n.yaml | 6 + packages/code-runtime/README.md | 2 + packages/code-runtime/README.zh.md | 12 ++ .../code-runtime-worker/README.i18n.yaml | 6 + .../code-runtime-worker/README.md | 2 + .../code-runtime-worker/README.zh.md | 54 +++++ .../code-runtime/README.i18n.yaml | 6 + packages/code-runtime/code-runtime/README.md | 2 + .../code-runtime/code-runtime/README.zh.md | 36 ++++ packages/compact/README.i18n.yaml | 6 + packages/compact/README.md | 2 + packages/compact/README.zh.md | 14 ++ .../compact/compact-basic/README.i18n.yaml | 6 + packages/compact/compact-basic/README.md | 2 + packages/compact/compact-basic/README.zh.md | 161 +++++++++++++++ .../README.i18n.yaml | 6 + .../compact-tool-result-prune/README.md | 2 + .../compact-tool-result-prune/README.zh.md | 62 ++++++ packages/compact/compact/README.i18n.yaml | 6 + packages/compact/compact/README.md | 2 + packages/compact/compact/README.zh.md | 82 ++++++++ packages/context/README.i18n.yaml | 6 + packages/context/README.md | 2 + packages/context/README.zh.md | 13 ++ .../session-reference/README.i18n.yaml | 6 + packages/context/session-reference/README.md | 2 + .../context/session-reference/README.zh.md | 50 +++++ .../context/time-context/README.i18n.yaml | 6 + packages/context/time-context/README.md | 2 + packages/context/time-context/README.zh.md | 70 +++++++ .../workspace-context/README.i18n.yaml | 6 + packages/context/workspace-context/README.md | 2 + .../context/workspace-context/README.zh.md | 169 +++++++++++++++ packages/cordis/README.i18n.yaml | 6 + packages/cordis/README.md | 2 + packages/cordis/README.zh.md | 9 + packages/cordis/tool-cordis/README.i18n.yaml | 6 + packages/cordis/tool-cordis/README.md | 2 + packages/cordis/tool-cordis/README.zh.md | 87 ++++++++ packages/core/README.i18n.yaml | 6 + packages/core/README.md | 2 + packages/core/README.zh.md | 20 ++ packages/core/agent-loop/README.i18n.yaml | 6 + packages/core/agent-loop/README.md | 2 + packages/core/agent-loop/README.zh.md | 129 ++++++++++++ packages/core/agent/README.i18n.yaml | 6 + packages/core/agent/README.md | 2 + packages/core/agent/README.zh.md | 116 +++++++++++ packages/core/scope/README.i18n.yaml | 6 + packages/core/scope/README.md | 2 + packages/core/scope/README.zh.md | 36 ++++ packages/core/session/README.i18n.yaml | 6 + packages/core/session/README.md | 2 + packages/core/session/README.zh.md | 147 +++++++++++++ packages/core/system-prompt/README.i18n.yaml | 6 + packages/core/system-prompt/README.md | 2 + packages/core/system-prompt/README.zh.md | 86 ++++++++ packages/core/tools/README.i18n.yaml | 6 + packages/core/tools/README.md | 2 + packages/core/tools/README.zh.md | 195 ++++++++++++++++++ packages/examples/README.i18n.yaml | 6 + packages/examples/README.md | 2 + packages/examples/README.zh.md | 23 +++ packages/examples/acp-demo/README.i18n.yaml | 6 + packages/examples/acp-demo/README.md | 2 + packages/examples/acp-demo/README.zh.md | 59 ++++++ .../agent-spine-demo/README.i18n.yaml | 6 + packages/examples/agent-spine-demo/README.md | 2 + .../examples/agent-spine-demo/README.zh.md | 83 ++++++++ packages/examples/cli-demo/README.i18n.yaml | 6 + packages/examples/cli-demo/README.md | 2 + packages/examples/cli-demo/README.zh.md | 79 +++++++ .../examples/jsonrpc-demo/README.i18n.yaml | 6 + packages/examples/jsonrpc-demo/README.md | 2 + packages/examples/jsonrpc-demo/README.zh.md | 33 +++ packages/examples/tui-demo/README.i18n.yaml | 6 + packages/examples/tui-demo/README.md | 2 + packages/examples/tui-demo/README.zh.md | 112 ++++++++++ packages/fs/README.i18n.yaml | 6 + packages/fs/README.md | 2 + packages/fs/README.zh.md | 20 ++ packages/fs/fs-local/README.i18n.yaml | 6 + packages/fs/fs-local/README.md | 2 + packages/fs/fs-local/README.zh.md | 41 ++++ packages/fs/fs-policy/README.i18n.yaml | 6 + packages/fs/fs-policy/README.md | 2 + packages/fs/fs-policy/README.zh.md | 73 +++++++ packages/fs/fs-sandbox/README.i18n.yaml | 6 + packages/fs/fs-sandbox/README.md | 2 + packages/fs/fs-sandbox/README.zh.md | 35 ++++ packages/fs/fs/README.i18n.yaml | 6 + packages/fs/fs/README.md | 2 + packages/fs/fs/README.zh.md | 62 ++++++ packages/fs/tool-fs-search/README.i18n.yaml | 6 + packages/fs/tool-fs-search/README.md | 2 + packages/fs/tool-fs-search/README.zh.md | 124 +++++++++++ packages/fs/tool-fs/README.i18n.yaml | 6 + packages/fs/tool-fs/README.md | 2 + packages/fs/tool-fs/README.zh.md | 151 ++++++++++++++ packages/goal/README.i18n.yaml | 6 + packages/goal/README.md | 2 + packages/goal/README.zh.md | 14 ++ packages/goal/command-goal/README.i18n.yaml | 6 + packages/goal/command-goal/README.md | 2 + packages/goal/command-goal/README.zh.md | 58 ++++++ packages/goal/goal-session/README.i18n.yaml | 6 + packages/goal/goal-session/README.md | 2 + packages/goal/goal-session/README.zh.md | 73 +++++++ packages/goal/goal/README.i18n.yaml | 6 + packages/goal/goal/README.md | 2 + packages/goal/goal/README.zh.md | 58 ++++++ packages/goal/tool-goal/README.i18n.yaml | 6 + packages/goal/tool-goal/README.md | 2 + packages/goal/tool-goal/README.zh.md | 80 +++++++ packages/guard/README.i18n.yaml | 6 + packages/guard/README.md | 2 + packages/guard/README.zh.md | 11 + .../guard/repeat-tool-guard/README.i18n.yaml | 6 + packages/guard/repeat-tool-guard/README.md | 2 + packages/guard/repeat-tool-guard/README.zh.md | 94 +++++++++ packages/hooks/README.i18n.yaml | 6 + packages/hooks/README.md | 2 + packages/hooks/README.zh.md | 13 ++ packages/hooks/hook-protocol/README.i18n.yaml | 6 + packages/hooks/hook-protocol/README.md | 2 + packages/hooks/hook-protocol/README.zh.md | 45 ++++ packages/hooks/hooks-claude/README.i18n.yaml | 6 + packages/hooks/hooks-claude/README.md | 2 + packages/hooks/hooks-claude/README.zh.md | 97 +++++++++ packages/hooks/hooks-codex/README.i18n.yaml | 6 + packages/hooks/hooks-codex/README.md | 2 + packages/hooks/hooks-codex/README.zh.md | 100 +++++++++ packages/host/apiproxy/README.i18n.yaml | 6 + packages/host/apiproxy/README.md | 2 + packages/host/apiproxy/README.zh.md | 33 +++ packages/host/webserver/README.i18n.yaml | 6 + packages/host/webserver/README.md | 2 + packages/host/webserver/README.zh.md | 25 +++ packages/llm/README.i18n.yaml | 6 + packages/llm/README.md | 2 + packages/llm/README.zh.md | 15 ++ packages/llm/llm-deepseek/README.i18n.yaml | 6 + packages/llm/llm-deepseek/README.md | 2 + packages/llm/llm-deepseek/README.zh.md | 94 +++++++++ packages/llm/llm-pi-ai/README.i18n.yaml | 6 + packages/llm/llm-pi-ai/README.md | 2 + packages/llm/llm-pi-ai/README.zh.md | 102 +++++++++ packages/llm/llm-retry/README.i18n.yaml | 6 + packages/llm/llm-retry/README.md | 2 + packages/llm/llm-retry/README.zh.md | 43 ++++ packages/llm/llm/README.i18n.yaml | 6 + packages/llm/llm/README.md | 2 + packages/llm/llm/README.zh.md | 80 +++++++ packages/llm/token-meter/README.i18n.yaml | 6 + packages/llm/token-meter/README.md | 2 + packages/llm/token-meter/README.zh.md | 46 +++++ packages/lsp/README.i18n.yaml | 6 + packages/lsp/README.md | 2 + packages/lsp/README.zh.md | 15 ++ packages/lsp/lsp-local/README.i18n.yaml | 6 + packages/lsp/lsp-local/README.md | 2 + packages/lsp/lsp-local/README.zh.md | 58 ++++++ packages/lsp/lsp/README.i18n.yaml | 6 + packages/lsp/lsp/README.md | 2 + packages/lsp/lsp/README.zh.md | 44 ++++ packages/lsp/tool-lsp/README.i18n.yaml | 6 + packages/lsp/tool-lsp/README.md | 2 + packages/lsp/tool-lsp/README.zh.md | 90 ++++++++ packages/mcp/README.i18n.yaml | 6 + packages/mcp/README.md | 2 + packages/mcp/README.zh.md | 9 + packages/mcp/mcp-client/README.i18n.yaml | 6 + packages/mcp/mcp-client/README.md | 2 + packages/mcp/mcp-client/README.zh.md | 108 ++++++++++ packages/plan/README.i18n.yaml | 6 + packages/plan/README.md | 2 + packages/plan/README.zh.md | 11 + packages/plan/plan-mode/README.i18n.yaml | 6 + packages/plan/plan-mode/README.md | 2 + packages/plan/plan-mode/README.zh.md | 91 ++++++++ packages/pty/README.i18n.yaml | 6 + packages/pty/README.md | 2 + packages/pty/README.zh.md | 13 ++ packages/pty/pty-local/README.i18n.yaml | 6 + packages/pty/pty-local/README.md | 2 + packages/pty/pty-local/README.zh.md | 36 ++++ packages/pty/pty/README.i18n.yaml | 6 + packages/pty/pty/README.md | 2 + packages/pty/pty/README.zh.md | 41 ++++ packages/pty/tool-pty/README.i18n.yaml | 6 + packages/pty/tool-pty/README.md | 2 + packages/pty/tool-pty/README.zh.md | 71 +++++++ packages/sandbox/README.i18n.yaml | 6 + packages/sandbox/README.md | 2 + packages/sandbox/README.zh.md | 15 ++ .../sandbox/sandbox-local/README.i18n.yaml | 6 + packages/sandbox/sandbox-local/README.md | 2 + packages/sandbox/sandbox-local/README.zh.md | 40 ++++ .../sandbox/sandbox-policy/README.i18n.yaml | 6 + packages/sandbox/sandbox-policy/README.md | 2 + packages/sandbox/sandbox-policy/README.zh.md | 41 ++++ packages/sandbox/sandbox/README.i18n.yaml | 6 + packages/sandbox/sandbox/README.md | 2 + packages/sandbox/sandbox/README.zh.md | 42 ++++ packages/sdk/README.i18n.yaml | 6 + packages/sdk/README.md | 2 + packages/sdk/README.zh.md | 17 ++ packages/sdk/create-sdk/README.i18n.yaml | 6 + packages/sdk/create-sdk/README.md | 2 + packages/sdk/create-sdk/README.zh.md | 25 +++ packages/sdk/helper/README.i18n.yaml | 6 + packages/sdk/helper/README.md | 2 + packages/sdk/helper/README.zh.md | 29 +++ packages/sdk/scripts/README.i18n.yaml | 6 + packages/sdk/scripts/README.md | 2 + packages/sdk/scripts/README.zh.md | 37 ++++ packages/sdk/telemetry/README.i18n.yaml | 6 + packages/sdk/telemetry/README.md | 2 + packages/sdk/telemetry/README.zh.md | 30 +++ packages/session-persistence/README.i18n.yaml | 6 + packages/session-persistence/README.md | 2 + packages/session-persistence/README.zh.md | 14 ++ .../README.i18n.yaml | 6 + .../session-checkpoint-policy/README.md | 2 + .../session-checkpoint-policy/README.zh.md | 47 +++++ .../README.i18n.yaml | 6 + .../session-persistence-jsonl/README.md | 2 + .../session-persistence-jsonl/README.zh.md | 75 +++++++ .../README.i18n.yaml | 6 + .../session-persistence-sqlite/README.md | 2 + .../session-persistence-sqlite/README.zh.md | 61 ++++++ .../session-persistence/README.i18n.yaml | 6 + .../session-persistence/README.md | 2 + .../session-persistence/README.zh.md | 83 ++++++++ packages/session-query/README.i18n.yaml | 6 + packages/session-query/README.md | 2 + packages/session-query/README.zh.md | 13 ++ .../session-query-sqlite/README.i18n.yaml | 6 + .../session-query-sqlite/README.md | 2 + .../session-query-sqlite/README.zh.md | 54 +++++ .../session-query/README.i18n.yaml | 6 + .../session-query/session-query/README.md | 2 + .../session-query/session-query/README.zh.md | 56 +++++ .../tool-session-query/README.i18n.yaml | 6 + .../tool-session-query/README.md | 2 + .../tool-session-query/README.zh.md | 76 +++++++ packages/session-title/README.i18n.yaml | 6 + packages/session-title/README.md | 2 + packages/session-title/README.zh.md | 14 ++ .../README.i18n.yaml | 6 + .../session-title-all-messages-llm/README.md | 2 + .../README.zh.md | 28 +++ .../README.i18n.yaml | 6 + .../session-title-first-message-llm/README.md | 2 + .../README.zh.md | 28 +++ .../session-title-llm/README.i18n.yaml | 6 + .../session-title/session-title-llm/README.md | 2 + .../session-title-llm/README.zh.md | 47 +++++ .../session-title/README.i18n.yaml | 6 + .../session-title/session-title/README.md | 2 + .../session-title/session-title/README.zh.md | 54 +++++ packages/skill/README.i18n.yaml | 6 + packages/skill/README.md | 2 + packages/skill/README.zh.md | 13 ++ packages/skill/skill-local/README.i18n.yaml | 6 + packages/skill/skill-local/README.md | 2 + packages/skill/skill-local/README.zh.md | 54 +++++ packages/skill/skill/README.i18n.yaml | 6 + packages/skill/skill/README.md | 2 + packages/skill/skill/README.zh.md | 53 +++++ packages/skill/tool-skill/README.i18n.yaml | 6 + packages/skill/tool-skill/README.md | 2 + packages/skill/tool-skill/README.zh.md | 148 +++++++++++++ packages/spill/README.i18n.yaml | 6 + packages/spill/README.md | 2 + packages/spill/README.zh.md | 15 ++ packages/spill/spill-local/README.i18n.yaml | 6 + packages/spill/spill-local/README.md | 2 + packages/spill/spill-local/README.zh.md | 34 +++ packages/spill/spill-policy/README.i18n.yaml | 6 + packages/spill/spill-policy/README.md | 2 + packages/spill/spill-policy/README.zh.md | 56 +++++ packages/spill/spill/README.i18n.yaml | 6 + packages/spill/spill/README.md | 2 + packages/spill/spill/README.zh.md | 42 ++++ packages/storage/README.i18n.yaml | 6 + packages/storage/README.md | 2 + packages/storage/README.zh.md | 14 ++ .../storage/storage-domain/README.i18n.yaml | 6 + packages/storage/storage-domain/README.md | 2 + packages/storage/storage-domain/README.zh.md | 35 ++++ .../storage/storage-json/README.i18n.yaml | 6 + packages/storage/storage-json/README.md | 2 + packages/storage/storage-json/README.zh.md | 38 ++++ .../storage/storage-sqlite/README.i18n.yaml | 6 + packages/storage/storage-sqlite/README.md | 2 + packages/storage/storage-sqlite/README.zh.md | 43 ++++ packages/storage/storage/README.i18n.yaml | 6 + packages/storage/storage/README.md | 2 + packages/storage/storage/README.zh.md | 41 ++++ packages/subagent/README.i18n.yaml | 6 + packages/subagent/README.md | 2 + packages/subagent/README.zh.md | 19 ++ .../subagent/subagent-acp/README.i18n.yaml | 6 + packages/subagent/subagent-acp/README.md | 2 + packages/subagent/subagent-acp/README.zh.md | 103 +++++++++ .../subagent/subagent-fork/README.i18n.yaml | 6 + packages/subagent/subagent-fork/README.md | 2 + packages/subagent/subagent-fork/README.zh.md | 61 ++++++ .../subagent-inprocess/README.i18n.yaml | 6 + .../subagent/subagent-inprocess/README.md | 2 + .../subagent/subagent-inprocess/README.zh.md | 112 ++++++++++ .../subagent/subagent-spawn/README.i18n.yaml | 6 + packages/subagent/subagent-spawn/README.md | 2 + packages/subagent/subagent-spawn/README.zh.md | 56 +++++ .../subagent-subprocess/README.i18n.yaml | 6 + .../subagent/subagent-subprocess/README.md | 2 + .../subagent/subagent-subprocess/README.zh.md | 55 +++++ packages/subagent/subagent/README.i18n.yaml | 6 + packages/subagent/subagent/README.md | 2 + packages/subagent/subagent/README.zh.md | 82 ++++++++ .../subagent/tool-subagent/README.i18n.yaml | 6 + packages/subagent/tool-subagent/README.md | 2 + packages/subagent/tool-subagent/README.zh.md | 81 ++++++++ packages/support/README.i18n.yaml | 6 + packages/support/README.md | 2 + packages/support/README.zh.md | 16 ++ .../support/acp-snapshot/README.i18n.yaml | 6 + packages/support/acp-snapshot/README.md | 2 + packages/support/acp-snapshot/README.zh.md | 72 +++++++ .../agent-loop-testkit/README.i18n.yaml | 6 + packages/support/agent-loop-testkit/README.md | 2 + .../support/agent-loop-testkit/README.zh.md | 33 +++ packages/support/invariants/README.i18n.yaml | 6 + packages/support/invariants/README.md | 2 + packages/support/invariants/README.zh.md | 85 ++++++++ .../support/llm-mock-server/README.i18n.yaml | 6 + packages/support/llm-mock-server/README.md | 2 + packages/support/llm-mock-server/README.zh.md | 86 ++++++++ packages/support/llm-replay/README.i18n.yaml | 6 + packages/support/llm-replay/README.md | 2 + packages/support/llm-replay/README.zh.md | 70 +++++++ .../support/loader-smoke/README.i18n.yaml | 6 + packages/support/loader-smoke/README.md | 2 + packages/support/loader-smoke/README.zh.md | 23 +++ packages/tasks/README.i18n.yaml | 6 + packages/tasks/README.md | 2 + packages/tasks/README.zh.md | 12 ++ packages/tasks/tasks/README.i18n.yaml | 6 + packages/tasks/tasks/README.md | 2 + packages/tasks/tasks/README.zh.md | 43 ++++ packages/tasks/tool-tasks/README.i18n.yaml | 6 + packages/tasks/tool-tasks/README.md | 2 + packages/tasks/tool-tasks/README.zh.md | 86 ++++++++ packages/timeout/README.i18n.yaml | 6 + packages/timeout/README.md | 2 + packages/timeout/README.zh.md | 11 + .../timeout/timeout-policy/README.i18n.yaml | 6 + packages/timeout/timeout-policy/README.md | 2 + packages/timeout/timeout-policy/README.zh.md | 57 +++++ packages/todo/README.i18n.yaml | 6 + packages/todo/README.md | 2 + packages/todo/README.zh.md | 11 + packages/todo/tool-todo/README.i18n.yaml | 6 + packages/todo/tool-todo/README.md | 2 + packages/todo/tool-todo/README.zh.md | 63 ++++++ packages/ui/README.i18n.yaml | 6 + packages/ui/README.md | 2 + packages/ui/README.zh.md | 22 ++ packages/ui/app-boot/README.i18n.yaml | 6 + packages/ui/app-boot/README.md | 2 + packages/ui/app-boot/README.zh.md | 48 +++++ packages/ui/commands/README.i18n.yaml | 6 + packages/ui/commands/README.md | 2 + packages/ui/commands/README.zh.md | 41 ++++ packages/ui/jsonrpc/README.i18n.yaml | 6 + packages/ui/jsonrpc/README.md | 2 + packages/ui/jsonrpc/README.zh.md | 47 +++++ packages/ui/permission/README.i18n.yaml | 6 + packages/ui/permission/README.md | 2 + packages/ui/permission/README.zh.md | 24 +++ packages/ui/tool-ask-user/README.i18n.yaml | 6 + packages/ui/tool-ask-user/README.md | 2 + packages/ui/tool-ask-user/README.zh.md | 57 +++++ packages/ui/tui/README.i18n.yaml | 6 + packages/ui/tui/README.md | 2 + packages/ui/tui/README.zh.md | 165 +++++++++++++++ packages/ui/user-approval/README.i18n.yaml | 6 + packages/ui/user-approval/README.md | 2 + packages/ui/user-approval/README.zh.md | 63 ++++++ packages/ui/user-interaction/README.i18n.yaml | 6 + packages/ui/user-interaction/README.md | 2 + packages/ui/user-interaction/README.zh.md | 39 ++++ packages/util/README.i18n.yaml | 6 + packages/util/README.md | 2 + packages/util/README.zh.md | 20 ++ packages/util/brand/README.i18n.yaml | 6 + packages/util/brand/README.md | 2 + packages/util/brand/README.zh.md | 28 +++ packages/util/paths/README.i18n.yaml | 6 + packages/util/paths/README.md | 2 + packages/util/paths/README.zh.md | 24 +++ packages/util/retention/README.i18n.yaml | 6 + packages/util/retention/README.md | 2 + packages/util/retention/README.zh.md | 97 +++++++++ packages/util/timeout/README.i18n.yaml | 6 + packages/util/timeout/README.md | 2 + packages/util/timeout/README.zh.md | 70 +++++++ packages/web/README.i18n.yaml | 6 + packages/web/README.md | 2 + packages/web/README.zh.md | 18 ++ packages/web/tool-web/README.i18n.yaml | 6 + packages/web/tool-web/README.md | 2 + packages/web/tool-web/README.zh.md | 131 ++++++++++++ packages/web/web-fetch-local/README.i18n.yaml | 6 + packages/web/web-fetch-local/README.md | 2 + packages/web/web-fetch-local/README.zh.md | 51 +++++ .../web/web-search-deepseek/README.i18n.yaml | 6 + packages/web/web-search-deepseek/README.md | 2 + packages/web/web-search-deepseek/README.zh.md | 79 +++++++ packages/web/web-search-exa/README.i18n.yaml | 6 + packages/web/web-search-exa/README.md | 2 + packages/web/web-search-exa/README.zh.md | 42 ++++ .../web-search-perplexity/README.i18n.yaml | 6 + packages/web/web-search-perplexity/README.md | 2 + .../web/web-search-perplexity/README.zh.md | 65 ++++++ packages/web/web/README.i18n.yaml | 6 + packages/web/web/README.md | 2 + packages/web/web/README.zh.md | 61 ++++++ packages/workflow/README.i18n.yaml | 6 + packages/workflow/README.md | 2 + packages/workflow/README.zh.md | 16 ++ packages/workflow/tool-ralph/README.i18n.yaml | 6 + packages/workflow/tool-ralph/README.md | 2 + packages/workflow/tool-ralph/README.zh.md | 93 +++++++++ .../workflow/tool-workflow/README.i18n.yaml | 6 + packages/workflow/tool-workflow/README.md | 2 + packages/workflow/tool-workflow/README.zh.md | 80 +++++++ .../workflow-workerthread/README.i18n.yaml | 6 + .../workflow/workflow-workerthread/README.md | 2 + .../workflow-workerthread/README.zh.md | 124 +++++++++++ packages/workflow/workflow/README.i18n.yaml | 6 + packages/workflow/workflow/README.md | 2 + packages/workflow/workflow/README.zh.md | 59 ++++++ packages/workspace/README.i18n.yaml | 6 + packages/workspace/README.md | 2 + packages/workspace/README.zh.md | 11 + packages/workspace/workspace/README.i18n.yaml | 6 + packages/workspace/workspace/README.md | 2 + packages/workspace/workspace/README.zh.md | 39 ++++ scripts/doc-budgets.manifest.json | 2 +- 559 files changed, 11227 insertions(+), 1 deletion(-) create mode 100644 apps/cli/README.i18n.yaml create mode 100644 apps/cli/README.zh.md create mode 100644 examples/README.i18n.yaml create mode 100644 examples/README.zh.md create mode 100644 examples/acp-agent/README.i18n.yaml create mode 100644 examples/acp-agent/README.zh.md create mode 100644 examples/cordis-agent/README.i18n.yaml create mode 100644 examples/cordis-agent/README.zh.md create mode 100644 examples/headless-agent/README.i18n.yaml create mode 100644 examples/headless-agent/README.zh.md create mode 100644 examples/jsonrpc-agent/README.i18n.yaml create mode 100644 examples/jsonrpc-agent/README.zh.md create mode 100644 examples/tui-agent/README.i18n.yaml create mode 100644 examples/tui-agent/README.zh.md create mode 100644 native/README.i18n.yaml create mode 100644 native/README.zh.md create mode 100644 native/landlock-run/README.i18n.yaml create mode 100644 native/landlock-run/README.zh.md create mode 100644 native/landlock-run/packages/entry/README.i18n.yaml create mode 100644 native/landlock-run/packages/entry/README.zh.md create mode 100644 native/landlock-run/packages/linux-arm64/README.i18n.yaml create mode 100644 native/landlock-run/packages/linux-arm64/README.zh.md create mode 100644 native/landlock-run/packages/linux-x64/README.i18n.yaml create mode 100644 native/landlock-run/packages/linux-x64/README.zh.md create mode 100644 packages/README.i18n.yaml create mode 100644 packages/README.zh.md create mode 100644 packages/acp/README.i18n.yaml create mode 100644 packages/acp/README.zh.md create mode 100644 packages/acp/acp/README.i18n.yaml create mode 100644 packages/acp/acp/README.zh.md create mode 100644 packages/bash/README.i18n.yaml create mode 100644 packages/bash/README.zh.md create mode 100644 packages/bash/bash-local/README.i18n.yaml create mode 100644 packages/bash/bash-local/README.zh.md create mode 100644 packages/bash/bash-sandbox/README.i18n.yaml create mode 100644 packages/bash/bash-sandbox/README.zh.md create mode 100644 packages/bash/bash/README.i18n.yaml create mode 100644 packages/bash/bash/README.zh.md create mode 100644 packages/bash/tool-bash/README.i18n.yaml create mode 100644 packages/bash/tool-bash/README.zh.md create mode 100644 packages/client/connection/README.i18n.yaml create mode 100644 packages/client/connection/README.zh.md create mode 100644 packages/client/hmr/README.i18n.yaml create mode 100644 packages/client/hmr/README.zh.md create mode 100644 packages/client/i18n/README.i18n.yaml create mode 100644 packages/client/i18n/README.zh.md create mode 100644 packages/client/modules/README.i18n.yaml create mode 100644 packages/client/modules/README.zh.md create mode 100644 packages/client/runtime/README.i18n.yaml create mode 100644 packages/client/runtime/README.zh.md create mode 100644 packages/client/ui-conversation/README.i18n.yaml create mode 100644 packages/client/ui-conversation/README.zh.md create mode 100644 packages/client/ui-layout/README.i18n.yaml create mode 100644 packages/client/ui-layout/README.zh.md create mode 100644 packages/client/ui-primitives/README.i18n.yaml create mode 100644 packages/client/ui-primitives/README.zh.md create mode 100644 packages/client/ui-question/README.i18n.yaml create mode 100644 packages/client/ui-question/README.zh.md create mode 100644 packages/client/ui-sidebar/README.i18n.yaml create mode 100644 packages/client/ui-sidebar/README.zh.md create mode 100644 packages/client/ui-slots/README.i18n.yaml create mode 100644 packages/client/ui-slots/README.zh.md create mode 100644 packages/client/ui-theme/README.i18n.yaml create mode 100644 packages/client/ui-theme/README.zh.md create mode 100644 packages/client/ui-trajectory/README.i18n.yaml create mode 100644 packages/client/ui-trajectory/README.zh.md create mode 100644 packages/client/ui-workspace/README.i18n.yaml create mode 100644 packages/client/ui-workspace/README.zh.md create mode 100644 packages/client/web-react/README.i18n.yaml create mode 100644 packages/client/web-react/README.zh.md create mode 100644 packages/client/web/README.i18n.yaml create mode 100644 packages/client/web/README.zh.md create mode 100644 packages/code-runtime/README.i18n.yaml create mode 100644 packages/code-runtime/README.zh.md create mode 100644 packages/code-runtime/code-runtime-worker/README.i18n.yaml create mode 100644 packages/code-runtime/code-runtime-worker/README.zh.md create mode 100644 packages/code-runtime/code-runtime/README.i18n.yaml create mode 100644 packages/code-runtime/code-runtime/README.zh.md create mode 100644 packages/compact/README.i18n.yaml create mode 100644 packages/compact/README.zh.md create mode 100644 packages/compact/compact-basic/README.i18n.yaml create mode 100644 packages/compact/compact-basic/README.zh.md create mode 100644 packages/compact/compact-tool-result-prune/README.i18n.yaml create mode 100644 packages/compact/compact-tool-result-prune/README.zh.md create mode 100644 packages/compact/compact/README.i18n.yaml create mode 100644 packages/compact/compact/README.zh.md create mode 100644 packages/context/README.i18n.yaml create mode 100644 packages/context/README.zh.md create mode 100644 packages/context/session-reference/README.i18n.yaml create mode 100644 packages/context/session-reference/README.zh.md create mode 100644 packages/context/time-context/README.i18n.yaml create mode 100644 packages/context/time-context/README.zh.md create mode 100644 packages/context/workspace-context/README.i18n.yaml create mode 100644 packages/context/workspace-context/README.zh.md create mode 100644 packages/cordis/README.i18n.yaml create mode 100644 packages/cordis/README.zh.md create mode 100644 packages/cordis/tool-cordis/README.i18n.yaml create mode 100644 packages/cordis/tool-cordis/README.zh.md create mode 100644 packages/core/README.i18n.yaml create mode 100644 packages/core/README.zh.md create mode 100644 packages/core/agent-loop/README.i18n.yaml create mode 100644 packages/core/agent-loop/README.zh.md create mode 100644 packages/core/agent/README.i18n.yaml create mode 100644 packages/core/agent/README.zh.md create mode 100644 packages/core/scope/README.i18n.yaml create mode 100644 packages/core/scope/README.zh.md create mode 100644 packages/core/session/README.i18n.yaml create mode 100644 packages/core/session/README.zh.md create mode 100644 packages/core/system-prompt/README.i18n.yaml create mode 100644 packages/core/system-prompt/README.zh.md create mode 100644 packages/core/tools/README.i18n.yaml create mode 100644 packages/core/tools/README.zh.md create mode 100644 packages/examples/README.i18n.yaml create mode 100644 packages/examples/README.zh.md create mode 100644 packages/examples/acp-demo/README.i18n.yaml create mode 100644 packages/examples/acp-demo/README.zh.md create mode 100644 packages/examples/agent-spine-demo/README.i18n.yaml create mode 100644 packages/examples/agent-spine-demo/README.zh.md create mode 100644 packages/examples/cli-demo/README.i18n.yaml create mode 100644 packages/examples/cli-demo/README.zh.md create mode 100644 packages/examples/jsonrpc-demo/README.i18n.yaml create mode 100644 packages/examples/jsonrpc-demo/README.zh.md create mode 100644 packages/examples/tui-demo/README.i18n.yaml create mode 100644 packages/examples/tui-demo/README.zh.md create mode 100644 packages/fs/README.i18n.yaml create mode 100644 packages/fs/README.zh.md create mode 100644 packages/fs/fs-local/README.i18n.yaml create mode 100644 packages/fs/fs-local/README.zh.md create mode 100644 packages/fs/fs-policy/README.i18n.yaml create mode 100644 packages/fs/fs-policy/README.zh.md create mode 100644 packages/fs/fs-sandbox/README.i18n.yaml create mode 100644 packages/fs/fs-sandbox/README.zh.md create mode 100644 packages/fs/fs/README.i18n.yaml create mode 100644 packages/fs/fs/README.zh.md create mode 100644 packages/fs/tool-fs-search/README.i18n.yaml create mode 100644 packages/fs/tool-fs-search/README.zh.md create mode 100644 packages/fs/tool-fs/README.i18n.yaml create mode 100644 packages/fs/tool-fs/README.zh.md create mode 100644 packages/goal/README.i18n.yaml create mode 100644 packages/goal/README.zh.md create mode 100644 packages/goal/command-goal/README.i18n.yaml create mode 100644 packages/goal/command-goal/README.zh.md create mode 100644 packages/goal/goal-session/README.i18n.yaml create mode 100644 packages/goal/goal-session/README.zh.md create mode 100644 packages/goal/goal/README.i18n.yaml create mode 100644 packages/goal/goal/README.zh.md create mode 100644 packages/goal/tool-goal/README.i18n.yaml create mode 100644 packages/goal/tool-goal/README.zh.md create mode 100644 packages/guard/README.i18n.yaml create mode 100644 packages/guard/README.zh.md create mode 100644 packages/guard/repeat-tool-guard/README.i18n.yaml create mode 100644 packages/guard/repeat-tool-guard/README.zh.md create mode 100644 packages/hooks/README.i18n.yaml create mode 100644 packages/hooks/README.zh.md create mode 100644 packages/hooks/hook-protocol/README.i18n.yaml create mode 100644 packages/hooks/hook-protocol/README.zh.md create mode 100644 packages/hooks/hooks-claude/README.i18n.yaml create mode 100644 packages/hooks/hooks-claude/README.zh.md create mode 100644 packages/hooks/hooks-codex/README.i18n.yaml create mode 100644 packages/hooks/hooks-codex/README.zh.md create mode 100644 packages/host/apiproxy/README.i18n.yaml create mode 100644 packages/host/apiproxy/README.zh.md create mode 100644 packages/host/webserver/README.i18n.yaml create mode 100644 packages/host/webserver/README.zh.md create mode 100644 packages/llm/README.i18n.yaml create mode 100644 packages/llm/README.zh.md create mode 100644 packages/llm/llm-deepseek/README.i18n.yaml create mode 100644 packages/llm/llm-deepseek/README.zh.md create mode 100644 packages/llm/llm-pi-ai/README.i18n.yaml create mode 100644 packages/llm/llm-pi-ai/README.zh.md create mode 100644 packages/llm/llm-retry/README.i18n.yaml create mode 100644 packages/llm/llm-retry/README.zh.md create mode 100644 packages/llm/llm/README.i18n.yaml create mode 100644 packages/llm/llm/README.zh.md create mode 100644 packages/llm/token-meter/README.i18n.yaml create mode 100644 packages/llm/token-meter/README.zh.md create mode 100644 packages/lsp/README.i18n.yaml create mode 100644 packages/lsp/README.zh.md create mode 100644 packages/lsp/lsp-local/README.i18n.yaml create mode 100644 packages/lsp/lsp-local/README.zh.md create mode 100644 packages/lsp/lsp/README.i18n.yaml create mode 100644 packages/lsp/lsp/README.zh.md create mode 100644 packages/lsp/tool-lsp/README.i18n.yaml create mode 100644 packages/lsp/tool-lsp/README.zh.md create mode 100644 packages/mcp/README.i18n.yaml create mode 100644 packages/mcp/README.zh.md create mode 100644 packages/mcp/mcp-client/README.i18n.yaml create mode 100644 packages/mcp/mcp-client/README.zh.md create mode 100644 packages/plan/README.i18n.yaml create mode 100644 packages/plan/README.zh.md create mode 100644 packages/plan/plan-mode/README.i18n.yaml create mode 100644 packages/plan/plan-mode/README.zh.md create mode 100644 packages/pty/README.i18n.yaml create mode 100644 packages/pty/README.zh.md create mode 100644 packages/pty/pty-local/README.i18n.yaml create mode 100644 packages/pty/pty-local/README.zh.md create mode 100644 packages/pty/pty/README.i18n.yaml create mode 100644 packages/pty/pty/README.zh.md create mode 100644 packages/pty/tool-pty/README.i18n.yaml create mode 100644 packages/pty/tool-pty/README.zh.md create mode 100644 packages/sandbox/README.i18n.yaml create mode 100644 packages/sandbox/README.zh.md create mode 100644 packages/sandbox/sandbox-local/README.i18n.yaml create mode 100644 packages/sandbox/sandbox-local/README.zh.md create mode 100644 packages/sandbox/sandbox-policy/README.i18n.yaml create mode 100644 packages/sandbox/sandbox-policy/README.zh.md create mode 100644 packages/sandbox/sandbox/README.i18n.yaml create mode 100644 packages/sandbox/sandbox/README.zh.md create mode 100644 packages/sdk/README.i18n.yaml create mode 100644 packages/sdk/README.zh.md create mode 100644 packages/sdk/create-sdk/README.i18n.yaml create mode 100644 packages/sdk/create-sdk/README.zh.md create mode 100644 packages/sdk/helper/README.i18n.yaml create mode 100644 packages/sdk/helper/README.zh.md create mode 100644 packages/sdk/scripts/README.i18n.yaml create mode 100644 packages/sdk/scripts/README.zh.md create mode 100644 packages/sdk/telemetry/README.i18n.yaml create mode 100644 packages/sdk/telemetry/README.zh.md create mode 100644 packages/session-persistence/README.i18n.yaml create mode 100644 packages/session-persistence/README.zh.md create mode 100644 packages/session-persistence/session-checkpoint-policy/README.i18n.yaml create mode 100644 packages/session-persistence/session-checkpoint-policy/README.zh.md create mode 100644 packages/session-persistence/session-persistence-jsonl/README.i18n.yaml create mode 100644 packages/session-persistence/session-persistence-jsonl/README.zh.md create mode 100644 packages/session-persistence/session-persistence-sqlite/README.i18n.yaml create mode 100644 packages/session-persistence/session-persistence-sqlite/README.zh.md create mode 100644 packages/session-persistence/session-persistence/README.i18n.yaml create mode 100644 packages/session-persistence/session-persistence/README.zh.md create mode 100644 packages/session-query/README.i18n.yaml create mode 100644 packages/session-query/README.zh.md create mode 100644 packages/session-query/session-query-sqlite/README.i18n.yaml create mode 100644 packages/session-query/session-query-sqlite/README.zh.md create mode 100644 packages/session-query/session-query/README.i18n.yaml create mode 100644 packages/session-query/session-query/README.zh.md create mode 100644 packages/session-query/tool-session-query/README.i18n.yaml create mode 100644 packages/session-query/tool-session-query/README.zh.md create mode 100644 packages/session-title/README.i18n.yaml create mode 100644 packages/session-title/README.zh.md create mode 100644 packages/session-title/session-title-all-messages-llm/README.i18n.yaml create mode 100644 packages/session-title/session-title-all-messages-llm/README.zh.md create mode 100644 packages/session-title/session-title-first-message-llm/README.i18n.yaml create mode 100644 packages/session-title/session-title-first-message-llm/README.zh.md create mode 100644 packages/session-title/session-title-llm/README.i18n.yaml create mode 100644 packages/session-title/session-title-llm/README.zh.md create mode 100644 packages/session-title/session-title/README.i18n.yaml create mode 100644 packages/session-title/session-title/README.zh.md create mode 100644 packages/skill/README.i18n.yaml create mode 100644 packages/skill/README.zh.md create mode 100644 packages/skill/skill-local/README.i18n.yaml create mode 100644 packages/skill/skill-local/README.zh.md create mode 100644 packages/skill/skill/README.i18n.yaml create mode 100644 packages/skill/skill/README.zh.md create mode 100644 packages/skill/tool-skill/README.i18n.yaml create mode 100644 packages/skill/tool-skill/README.zh.md create mode 100644 packages/spill/README.i18n.yaml create mode 100644 packages/spill/README.zh.md create mode 100644 packages/spill/spill-local/README.i18n.yaml create mode 100644 packages/spill/spill-local/README.zh.md create mode 100644 packages/spill/spill-policy/README.i18n.yaml create mode 100644 packages/spill/spill-policy/README.zh.md create mode 100644 packages/spill/spill/README.i18n.yaml create mode 100644 packages/spill/spill/README.zh.md create mode 100644 packages/storage/README.i18n.yaml create mode 100644 packages/storage/README.zh.md create mode 100644 packages/storage/storage-domain/README.i18n.yaml create mode 100644 packages/storage/storage-domain/README.zh.md create mode 100644 packages/storage/storage-json/README.i18n.yaml create mode 100644 packages/storage/storage-json/README.zh.md create mode 100644 packages/storage/storage-sqlite/README.i18n.yaml create mode 100644 packages/storage/storage-sqlite/README.zh.md create mode 100644 packages/storage/storage/README.i18n.yaml create mode 100644 packages/storage/storage/README.zh.md create mode 100644 packages/subagent/README.i18n.yaml create mode 100644 packages/subagent/README.zh.md create mode 100644 packages/subagent/subagent-acp/README.i18n.yaml create mode 100644 packages/subagent/subagent-acp/README.zh.md create mode 100644 packages/subagent/subagent-fork/README.i18n.yaml create mode 100644 packages/subagent/subagent-fork/README.zh.md create mode 100644 packages/subagent/subagent-inprocess/README.i18n.yaml create mode 100644 packages/subagent/subagent-inprocess/README.zh.md create mode 100644 packages/subagent/subagent-spawn/README.i18n.yaml create mode 100644 packages/subagent/subagent-spawn/README.zh.md create mode 100644 packages/subagent/subagent-subprocess/README.i18n.yaml create mode 100644 packages/subagent/subagent-subprocess/README.zh.md create mode 100644 packages/subagent/subagent/README.i18n.yaml create mode 100644 packages/subagent/subagent/README.zh.md create mode 100644 packages/subagent/tool-subagent/README.i18n.yaml create mode 100644 packages/subagent/tool-subagent/README.zh.md create mode 100644 packages/support/README.i18n.yaml create mode 100644 packages/support/README.zh.md create mode 100644 packages/support/acp-snapshot/README.i18n.yaml create mode 100644 packages/support/acp-snapshot/README.zh.md create mode 100644 packages/support/agent-loop-testkit/README.i18n.yaml create mode 100644 packages/support/agent-loop-testkit/README.zh.md create mode 100644 packages/support/invariants/README.i18n.yaml create mode 100644 packages/support/invariants/README.zh.md create mode 100644 packages/support/llm-mock-server/README.i18n.yaml create mode 100644 packages/support/llm-mock-server/README.zh.md create mode 100644 packages/support/llm-replay/README.i18n.yaml create mode 100644 packages/support/llm-replay/README.zh.md create mode 100644 packages/support/loader-smoke/README.i18n.yaml create mode 100644 packages/support/loader-smoke/README.zh.md create mode 100644 packages/tasks/README.i18n.yaml create mode 100644 packages/tasks/README.zh.md create mode 100644 packages/tasks/tasks/README.i18n.yaml create mode 100644 packages/tasks/tasks/README.zh.md create mode 100644 packages/tasks/tool-tasks/README.i18n.yaml create mode 100644 packages/tasks/tool-tasks/README.zh.md create mode 100644 packages/timeout/README.i18n.yaml create mode 100644 packages/timeout/README.zh.md create mode 100644 packages/timeout/timeout-policy/README.i18n.yaml create mode 100644 packages/timeout/timeout-policy/README.zh.md create mode 100644 packages/todo/README.i18n.yaml create mode 100644 packages/todo/README.zh.md create mode 100644 packages/todo/tool-todo/README.i18n.yaml create mode 100644 packages/todo/tool-todo/README.zh.md create mode 100644 packages/ui/README.i18n.yaml create mode 100644 packages/ui/README.zh.md create mode 100644 packages/ui/app-boot/README.i18n.yaml create mode 100644 packages/ui/app-boot/README.zh.md create mode 100644 packages/ui/commands/README.i18n.yaml create mode 100644 packages/ui/commands/README.zh.md create mode 100644 packages/ui/jsonrpc/README.i18n.yaml create mode 100644 packages/ui/jsonrpc/README.zh.md create mode 100644 packages/ui/permission/README.i18n.yaml create mode 100644 packages/ui/permission/README.zh.md create mode 100644 packages/ui/tool-ask-user/README.i18n.yaml create mode 100644 packages/ui/tool-ask-user/README.zh.md create mode 100644 packages/ui/tui/README.i18n.yaml create mode 100644 packages/ui/tui/README.zh.md create mode 100644 packages/ui/user-approval/README.i18n.yaml create mode 100644 packages/ui/user-approval/README.zh.md create mode 100644 packages/ui/user-interaction/README.i18n.yaml create mode 100644 packages/ui/user-interaction/README.zh.md create mode 100644 packages/util/README.i18n.yaml create mode 100644 packages/util/README.zh.md create mode 100644 packages/util/brand/README.i18n.yaml create mode 100644 packages/util/brand/README.zh.md create mode 100644 packages/util/paths/README.i18n.yaml create mode 100644 packages/util/paths/README.zh.md create mode 100644 packages/util/retention/README.i18n.yaml create mode 100644 packages/util/retention/README.zh.md create mode 100644 packages/util/timeout/README.i18n.yaml create mode 100644 packages/util/timeout/README.zh.md create mode 100644 packages/web/README.i18n.yaml create mode 100644 packages/web/README.zh.md create mode 100644 packages/web/tool-web/README.i18n.yaml create mode 100644 packages/web/tool-web/README.zh.md create mode 100644 packages/web/web-fetch-local/README.i18n.yaml create mode 100644 packages/web/web-fetch-local/README.zh.md create mode 100644 packages/web/web-search-deepseek/README.i18n.yaml create mode 100644 packages/web/web-search-deepseek/README.zh.md create mode 100644 packages/web/web-search-exa/README.i18n.yaml create mode 100644 packages/web/web-search-exa/README.zh.md create mode 100644 packages/web/web-search-perplexity/README.i18n.yaml create mode 100644 packages/web/web-search-perplexity/README.zh.md create mode 100644 packages/web/web/README.i18n.yaml create mode 100644 packages/web/web/README.zh.md create mode 100644 packages/workflow/README.i18n.yaml create mode 100644 packages/workflow/README.zh.md create mode 100644 packages/workflow/tool-ralph/README.i18n.yaml create mode 100644 packages/workflow/tool-ralph/README.zh.md create mode 100644 packages/workflow/tool-workflow/README.i18n.yaml create mode 100644 packages/workflow/tool-workflow/README.zh.md create mode 100644 packages/workflow/workflow-workerthread/README.i18n.yaml create mode 100644 packages/workflow/workflow-workerthread/README.zh.md create mode 100644 packages/workflow/workflow/README.i18n.yaml create mode 100644 packages/workflow/workflow/README.zh.md create mode 100644 packages/workspace/README.i18n.yaml create mode 100644 packages/workspace/README.zh.md create mode 100644 packages/workspace/workspace/README.i18n.yaml create mode 100644 packages/workspace/workspace/README.zh.md diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml new file mode 100644 index 0000000000..9769d5153b --- /dev/null +++ b/apps/cli/README.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 +README.md: 83b60ea72580facbceb155d053223567fdc8446b +README.zh.md: ca25547f4c5ed2627e692187e6ca9e947f1b3eac diff --git a/apps/cli/README.md b/apps/cli/README.md index 4ff9034dd3..83b60ea725 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -1,5 +1,7 @@ # `@deepseek-ai/dsh` +English | [中文](README.zh.md) + The `dsh` command-line entry follows the `apps/` assembly tier: `apps/*` are product assemblies over `packages/*` libraries. Plain `dsh` boots the interactive TUI coding agent, `dsh -p "task"` runs one headless turn, and `dsh web` serves the browser UI. Argv is parsed once through a [Commander](https://github.com/tj/commander.js) adapter ([`src/args.ts`](src/args.ts)): one program whose default (no subcommand) is the TUI/headless surface (`--config`, `-p`/`--prompt`, `--resume`) and whose `web` subcommand is the browser UI. `src/bin.ts` switches on the resolved mode and dynamic-imports only that mode's module. `dsh --help` lists every mode and `dsh web --help` renders the web usage, `dsh --version` prints this app's version, and an unknown option or a mistyped `--resume` fails loud (stderr, exit 1) instead of misrouting. `dsh web`'s `--host`/`--port` are unvalidated pass-through overrides: the `dsh-host-webserver` schema is the single source of both the default (the shipped `cordis.yml` value when a flag is absent) and validity, and rejects a bad value at boot. diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md new file mode 100644 index 0000000000..ca25547f4c --- /dev/null +++ b/apps/cli/README.zh.md @@ -0,0 +1,27 @@ +# `@deepseek-ai/dsh` + +[English](README.md) | 中文 + +`dsh` 命令行入口遵循 `apps/` 组装层:`apps/*` 是位于 `packages/*` 库之上的产品组装。直接运行 `dsh` 会启动交互式 TUI 编码 agent(智能体),`dsh -p "task"` 运行一个无头轮次,`dsh web` 则提供浏览器 UI。 + +Argv 只会通过 [Commander](https://github.com/tj/commander.js) 适配器([`src/args.ts`](src/args.ts))解析一次:同一个程序的默认形式(无子命令)是 TUI/无头界面(`--config`、`-p`/`--prompt`、`--resume`),`web` 子命令则是浏览器 UI。`src/bin.ts` 按解析后的 mode 分支,仅动态导入该 mode 的模块。`dsh --help` 列出所有 mode,`dsh web --help` 渲染 Web 用法,`dsh --version` 打印此应用的版本;未知选项或拼错的 `--resume` 会明确报错(stderr,退出码 1),而不会被错路由。`dsh web` 的 `--host`/`--port` 是未验证的直通覆盖:`dsh-host-webserver` schema 是默认值(标志缺失时使用已交付的 `cordis.yml` 值)和有效性的唯一真源,并在启动时拒绝错误值。 + +TUI 界面: + +- 启动已交付的默认配置(`examples/tui-agent/cordis.yml`),或由 `--config ` 指定的树(演示/测试用于启动其他示例树的逃生口),并通过 [`dsh-app-boot`](../../packages/ui/app-boot/README.md) 完成启动; +- 使用 `dsh --resume ` 恢复已持久化会话。当 Node 宿主公开 `process.execve` 时,还会提供 TUI 的原地移交宿主:选择器预检并刷新当前会话后,宿主会释放应用,并以规范化的 `dsh --resume ` 替换进程;不支持进程替换的运行时保留屏幕上显示的命令回退。该标志通过 `RESUME_SESSION_ID_KEY` 在启动上下文中提供 id(不使用环境变量),已交付的配置通过 `!!js` 读取它;缺失或无法读取的 id 会明确报错,而不会创建新会话; +- 将 **调用目录** 视为 workspace:会话、相对路径和 workspace 指令都从 cwd 解析; +- 告知 agent 自身源码所在位置:启动后添加一个命名此 harness checkout 的提示词段。该路径从启动器的真实路径解析,因此在 PATH 符号链接和任意 cwd 下仍然有效,使自指的 `cordis` 工具集可以读取并修改它; +- 应用 `~/.dsh` 中的个人覆盖(参见 [app-boot 的个人配置](../../packages/ui/app-boot/README.md#personal-config)):`.env` 填补环境缺口(环境中已有的值 > 项目 `.env` > 个人 `.env`),`config.yaml` 则修补已启动的树。 + +Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 + +## 安装(开发机) + +将从源码运行的启动器符号链接到 PATH 上;它通过自身真实路径解析 checkout,因此代码更改会在下次启动时生效,无需构建: + +```sh +ln -sf "$(pwd)/bin/dsh" ~/.local/bin/dsh +``` + +`pnpm run dsh` 从仓库根目录运行同一入口并直接转发参数,例如 `pnpm run dsh -p "task"`。构建形式(`lib/bin.js`,通过 `pnpm run build`)会在普通 Node 下启动同一配置。 diff --git a/examples/README.i18n.yaml b/examples/README.i18n.yaml new file mode 100644 index 0000000000..a96133c3c8 --- /dev/null +++ b/examples/README.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 +README.md: 8fd261e624771dc568582b6d22e9985072a06715 +README.zh.md: 2ff0d0bef382435588fce01c23aa7b74e1a149b5 diff --git a/examples/README.md b/examples/README.md index f1f3967634..8fd261e624 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,5 +1,7 @@ # Examples +English | [中文](README.zh.md) + Runnable demos (not workspaces) that showcase how the harness is wired. Each example is a **thin leaf**: a `cordis.yml` that picks swappable backends, loads one app package, and may add optional product tools. The composition and boot glue live in [`@deepseek-ai/dsh-tui-demo`](../packages/examples/tui-demo), [`@deepseek-ai/dsh-cli-demo`](../packages/examples/cli-demo), [`@deepseek-ai/dsh-acp-demo`](../packages/examples/acp-demo), and their shared [`@deepseek-ai/dsh-agent-spine-demo`](../packages/examples/agent-spine-demo) bundle. There is no `start.ts`; the terminal `demo:*` scripts boot through the [`dsh`](../apps/cli/README.md) CLI (which mounts the `tui-demo` bundle), and the headless/ACP scripts invoke the `cli-demo`/`acp-demo` bins. ## headless-agent diff --git a/examples/README.zh.md b/examples/README.zh.md new file mode 100644 index 0000000000..2ff0d0bef3 --- /dev/null +++ b/examples/README.zh.md @@ -0,0 +1,35 @@ +# 示例 + +[English](README.md) | 中文 + +展示 harness 如何接线的可运行演示(不是 workspace)。每个示例都是一个 **轻量叶节点**:一份选择可替换后端、加载一个应用包(package)并可添加可选产品工具的 `cordis.yml`。组合和启动粘合代码位于 [`@deepseek-ai/dsh-tui-demo`](../packages/examples/tui-demo)、[`@deepseek-ai/dsh-cli-demo`](../packages/examples/cli-demo)、[`@deepseek-ai/dsh-acp-demo`](../packages/examples/acp-demo) 及它们共享的 [`@deepseek-ai/dsh-agent-spine-demo`](../packages/examples/agent-spine-demo) 组合包中。没有 `start.ts`;终端 `demo:*` 脚本通过 [`dsh`](../apps/cli/README.md) CLI(命令行界面)启动(该 CLI 挂载 `tui-demo` 组合包),无头/ACP(Agent Client Protocol)脚本则调用 `cli-demo`/`acp-demo` bin。 + +## headless-agent + +非交互式 agent(智能体)演示:接受一个位置任务,在 `@deepseek-ai/dsh-cli-demo` 应用上运行一个完整模型/工具轮次,持久化新会话,打印 `text`、`json` 或 `stream-json`,然后退出。 + +运行:`pnpm run demo:headless "task"`(需要 `DEEPSEEK_API_KEY`)。输出契约、安全边界和快照套件详见 [headless-agent/README.md](headless-agent/README.md)。 + +## tui-agent + +交互式编码 agent:DeepSeek V4、文件系统与 bash 工具、subagent、工作流、`todo_write`、压缩(compaction)和全屏 TUI。这里也是 TUI PTY 与快照场景的归属地。 + +运行:`pnpm run demo:tui`(需要 `DEEPSEEK_API_KEY`)。使用 `pnpm run demo:code-mode` 运行其 Code Mode 覆盖。控制与组合详见 [tui-agent/README.md](tui-agent/README.md)。 + +## jsonrpc-agent + +通过 Python SDK 驱动的无人值守编码 agent:JSON-RPC stdio、仅前台 `bash`、`read`/`write`/`edit`、一个前台 `subagent`、`todo_write`、JSONL 持久化和压缩。它不包含终端 UI、stdout 日志、批准、skill 和后台任务控制。详见 [jsonrpc-agent/README.md](jsonrpc-agent/README.md)。 + +## cordis-agent + +**自指** 演示:编码主干加 [`@deepseek-ai/dsh-tool-cordis`](../packages/cordis/tool-cordis),其三个工具(`cordis_inspect`/`cordis_mount`/`cordis_unmount`)使 agent 可以检查自身所在的实时 cordis 运行时,将模型编写的插件挂载到其中(事件监听器、一个专为自身创建的全新工具,或一个供另一挂载项注入的服务),并再次释放它们。所有动态挂载都归入同一 `cordis-dynamic` fiber 子树。`ctx.fs`/`ctx.web` 服务仅作为提供方随行,是这些插件构建所依赖的能力。 + +运行:`pnpm run demo:cordis`(需要 `DEEPSEEK_API_KEY`)。分阶段演示脚本详见 [cordis-agent/README.md](cordis-agent/README.md),设计与沙箱注意事项详见[工具集 Agent Note](../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md)。 + +## acp-agent + +作为 **Agent Client Protocol (ACP)** 自动化服务器通过 JSON-RPC stdio 公开的 agent,由 [`@deepseek-ai/dsh-acp-demo`](../packages/examples/acp-demo) 提供。程序化客户端可以创建新会话、发送文本提示词、消费已提交的 assistant 文本、回答一次性权限请求并取消工作。它拥有 ACP 无密钥快照套件。 + +运行:`pnpm run demo:acp`(需要 `DEEPSEEK_API_KEY`);`pnpm run demo:code-mode acp` 通过 `code-mode.cordis.yml` 覆盖以 Code Mode 启动同一服务器。协议与快照测试契约详见 [acp-agent/README.md](acp-agent/README.md)。 + +默认 `cordis.yml` 组合 [`@deepseek-ai/dsh-sandbox-local`](../packages/sandbox/sandbox-local)、[`@deepseek-ai/dsh-bash-sandbox`](../packages/bash/bash-sandbox) 和 [`@deepseek-ai/dsh-user-approval`](../packages/ui/user-approval)。`workspace-write` 将 bash 和文件系统变更限制在每个会话 workspace 中;范围更广的重试会通过 ACP 成为一次性机器权限请求。 diff --git a/examples/acp-agent/README.i18n.yaml b/examples/acp-agent/README.i18n.yaml new file mode 100644 index 0000000000..22842fcd04 --- /dev/null +++ b/examples/acp-agent/README.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 +README.md: 4b3d86b00613cc7c37a8898ef3b39d40a167e66b +README.zh.md: 5bcd85f2b4ae34a11b980bf196d3401f764004d8 diff --git a/examples/acp-agent/README.md b/examples/acp-agent/README.md index 892a32cdc7..4b3d86b006 100644 --- a/examples/acp-agent/README.md +++ b/examples/acp-agent/README.md @@ -1,5 +1,7 @@ # acp-agent example +English | [中文](README.zh.md) + Automation-oriented [Agent Client Protocol](https://agentclientprotocol.com) server over JSON-RPC stdio. It is intended for parent agents, subagent providers, and other programmatic clients, not as the product UI. ```sh diff --git a/examples/acp-agent/README.zh.md b/examples/acp-agent/README.zh.md new file mode 100644 index 0000000000..5bcd85f2b4 --- /dev/null +++ b/examples/acp-agent/README.zh.md @@ -0,0 +1,30 @@ +# acp-agent 示例 + +[English](README.md) | 中文 + +通过 JSON-RPC stdio 提供的自动化导向 [Agent Client Protocol](https://agentclientprotocol.com) 服务器。它面向父 agent(智能体)、subagent 提供方和其他程序化客户端,而非产品 UI。 + +```sh +pnpm run demo:acp # needs DEEPSEEK_API_KEY (repo-root .env or env) +pnpm run demo:code-mode acp # same protocol with the Code Mode tool transport +``` + +该叶节点加载 ACP 应用、DeepSeek 适配器、受沙箱限制的 bash 与文件系统栈、一次性批准策略、压缩(compaction)、subagent、工作流、钩子、派生会话查询索引和重复守卫。应用为每次 `session/new` 创建一个新 agent,将会话持久化到 JSONL,并保持 stdout 只含协议内容。[`session-query.cordis.yml`](session-query.cordis.yml) 为其专用快照显式选用 workspace 授权的查询工具和通用超时/溢出策略;[`fs.cordis.yml`](fs.cordis.yml) 为文件系统场景添加溢出存储,[`code-mode.cordis.yml`](code-mode.cordis.yml) 则添加 `run_code` 及其生成的 TypeScript SDK。 + +## 协议通道 + +Stdout 只携带以换行分隔的 ACP JSON-RPC。`@deepseek-ai/dsh-acp-demo` 不安装 stdout logger;叶节点的附加项必须使用 stderr 输出诊断信息。 + +自动化契约(支持的方法、基线提示词内容、已提交文本输出,以及有意缺少的 UI 界面)位于 [`@deepseek-ai/dsh-acp`](../../packages/acp/acp/README.md)。 + +## 会话 workspace 与权限 + +每次 `session/new` 都提供一个绝对 `cwd`。受沙箱限制的 bash 与文件系统变更会根据该会话 cwd 解析 `workspace-write`,因此并发会话可以使用不同的项目根目录;平台临时根目录仍是共享可写暂存空间(参见[沙箱契约](../../packages/sandbox/sandbox/README.md))。`DSH_PERMISSION_MODE` 在部署和测试中选择 `workspace-write` 或 `danger-full-access`。 + +在 `workspace-write` 下,模型请求扩大沙箱权限的重试会触发 `session/request_permission`,选项为 `allow_once` 和 `reject_once`。客户端以程序方式决策;解除对话框或答案不可用时会失败闭合。选定结果仅适用于该次重试,并通过常规工具结果/审计路径记录。服务器绝不公开权限选择器,也不持久化客户端策略。 + +## 快照测试 + +此示例拥有 ACP 快照套件。它会启动真实自动化服务器,通过 `dsh-llm-replay` 回放已提交的模型流,并比较规范化后的协议输出与重新持久化的会话日志。录制使用真实模型;刷新会复用已提交的回放输入。覆盖场景包括抛出/挂起行为,可选 `workspace/` fixture(测试前置数据)则为外部状态检查预置环境。 + +大多数场景锁定后端行为,而非 ACP 专用行为;[仅面向自动化的 ACP 决策](../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md#snapshot-boundary)说明了为何该覆盖仍与传输层耦合。 diff --git a/examples/cordis-agent/README.i18n.yaml b/examples/cordis-agent/README.i18n.yaml new file mode 100644 index 0000000000..7f4f2ae9dd --- /dev/null +++ b/examples/cordis-agent/README.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 +README.md: 1309fe9b2935d3224f097ceb2e80501c8075a933 +README.zh.md: 2e3e7d7206d0d676ae7d9c9b3a2c2f8be26aafe7 diff --git a/examples/cordis-agent/README.md b/examples/cordis-agent/README.md index a0bb2188da..1309fe9b29 100644 --- a/examples/cordis-agent/README.md +++ b/examples/cordis-agent/README.md @@ -1,5 +1,7 @@ # cordis-agent +English | [中文](README.zh.md) + The self-referential harness demo: the DeepSeek V4 coding spine on the full-screen TUI plus [`@deepseek-ai/dsh-tool-cordis`](../../packages/cordis/tool-cordis/README.md), which hands the model three tools over the **live cordis runtime it is running inside** — inspect it, mount new plugins into it, and dispose them again. The `ctx.fs` and `ctx.web` services are mounted (provider-only, no model-facing file/web tools) so the plugins the agent writes have real capabilities to build on; Node built-ins are trapped in the sandbox and redirect to those services. The design (sandbox semantics, mount lifecycle, cross-mount composition, caveats) lives in [the toolset Agent Note](../../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md). ## Run it diff --git a/examples/cordis-agent/README.zh.md b/examples/cordis-agent/README.zh.md new file mode 100644 index 0000000000..2e3e7d7206 --- /dev/null +++ b/examples/cordis-agent/README.zh.md @@ -0,0 +1,35 @@ +# cordis-agent + +[English](README.md) | 中文 + +自指 harness 演示:在全屏 TUI 上运行 DeepSeek V4 编码主干,并加载 [`@deepseek-ai/dsh-tool-cordis`](../../packages/cordis/tool-cordis/README.md)。后者通过 agent(智能体)所在的 **实时 cordis 运行时** 向模型提供三个工具:检查运行时、将新插件挂载到其中,以及再次释放它们。`ctx.fs` 和 `ctx.web` 服务也会挂载(仅作为提供方,不包含面向模型的文件/Web 工具),使 agent 编写的插件可以构建于真实能力之上;Node 内置模块在沙箱中被截获并重定向到这些服务。设计(沙箱语义、挂载生命周期、跨挂载组合、注意事项)详见[工具集 Agent Note](../../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md)。 + +## 运行 + +```sh +# repo root .env (gitignored) or exported env: +# DEEPSEEK_API_KEY=sk-… +# DEEPSEEK_BASE_URL=https://… # optional; defaults to the public API +pnpm run demo:cordis +``` + +预期演示分阶段进行:先验证监听器链接,再让 agent 扩展自身: + +``` +> Mount a plugin that listens to the 'agent/status' event and logs every status change, then run `echo hi` with bash. + [tool call] cordis_mount({"code": "return { name: 'status-logger', apply(ctx) { ctx.on('agent/status', (agent, status) => console.log('status →', status)) } }"}) + [tool result] mounted dyn-1 (plugin "status-logger", state: active) + [tool call] bash({"command": "echo hi"}) +[cordis:dyn-1] status → … ← the mounted listener firing, live +> Now give yourself a reverse_text tool and use it on "harness". + [tool call] cordis_mount({"code": "return { name: 'reverse-text', inject: ['tools'], apply(ctx) { ctx.tools.register(harness.defineTool({ name: 'reverse_text', … })) } }"}) + [tool call] reverse_text({"text": "harness"}) ← a tool the agent built for itself, one step earlier +> Unmount both. + [tool call] cordis_unmount({"id": "dyn-1"}) +``` + +请求 `cordis_inspect` 并使用 `what: "api"` 或 `what: "events"`,即可查看为 agent 生成、供其编写插件时参考的服务/事件资料。还可尝试两个协作挂载(一个中调用 `ctx.provide`,另一个中使用 `inject`),观察 cordis 如何暂停并恢复消费方。 + +## 端到端测试 + +`tests/keyless-smoke.e2e.ts` 使用虚拟密钥通过 Loader 启动真实 `cordis.yml`,并断言横幅、包名解析和 EOF 后干净退出。`tests/cordis-tools.e2e.ts` 是带密钥的冒烟测试:真实模型挂载状态监听器,测试验证其带标记的 console 行;然后创建并使用 `reverse_text` 工具,再通过 provide/inject 组合两个挂载。[`packages/cordis/tool-cordis`](../../packages/cordis/tool-cordis) 在每文件 100% 覆盖率门禁下承载单元覆盖。 diff --git a/examples/headless-agent/README.i18n.yaml b/examples/headless-agent/README.i18n.yaml new file mode 100644 index 0000000000..7c4dbaf463 --- /dev/null +++ b/examples/headless-agent/README.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 +README.md: 445804a2611e5e8093eadf345ad10a2a7984c012 +README.zh.md: 68ec718afe0b2aca276be2689cbae74167ee1c7b diff --git a/examples/headless-agent/README.md b/examples/headless-agent/README.md index a1e2455ed3..445804a261 100644 --- a/examples/headless-agent/README.md +++ b/examples/headless-agent/README.md @@ -1,5 +1,7 @@ # headless-agent +English | [中文](README.zh.md) + Headless one-shot agent wiring: DeepSeek V4 + local bash and filesystem tools + subagent delegation + workflows and fresh-agent Ralph iteration + `todo_write` + JSONL persistence, with [`@deepseek-ai/dsh-cli-demo`](../../packages/examples/cli-demo) as the app front door. ## Run it diff --git a/examples/headless-agent/README.zh.md b/examples/headless-agent/README.zh.md new file mode 100644 index 0000000000..68ec718afe --- /dev/null +++ b/examples/headless-agent/README.zh.md @@ -0,0 +1,26 @@ +# headless-agent + +[English](README.md) | 中文 + +无头单次 agent(智能体)接线:DeepSeek V4 + 本地 bash 与文件系统工具 + subagent 委托 + 工作流与新 agent Ralph 迭代 + `todo_write` + JSONL 持久化,并以 [`@deepseek-ai/dsh-cli-demo`](../../packages/examples/cli-demo) 作为应用入口。 + +## 运行 + +```sh +# repo root .env (gitignored) or exported env: +# DEEPSEEK_API_KEY=sk-… +# DEEPSEEK_BASE_URL=https://… # optional; defaults to the public API +pnpm run demo:headless "fix the failing test in this workspace" +pnpm run demo:headless --output-format json -- "summarize the implementation" +pnpm run demo:headless --output-format stream-json -- "run the focused tests" +``` + +必须提供且只能提供一个非空位置任务;含空格的任务需要加引号。没有 `-p` 标志。`text` 打印最后一条包含文本的 assistant 消息,`json` 打印一条 DSH 原生结果记录,`stream-json` 则在该记录之前发出顶层会话的规范任务轮次事件。子会话只通过父工具事件和结果对外显示。 + +每次调用都会创建并持久化新会话,在一个轮次中运行所有模型和工具步骤,然后刷新、释放并退出。这是非交互式自动化:没有提示符、批准、恢复、第二轮次或 stdin 上下文。已配置工具可以修改启动 workspace、运行命令、spawn 子 agent,并消耗提供方 token。 + +## 高级与快照接线 + +[`advanced.cordis.yml`](advanced.cordis.yml) 在已交付叶节点上添加 Code Mode 和 Cordis 工具。[`advanced.cordis.snapshot.yml`](advanced.cordis.snapshot.yml) 只将实时 LLM(大语言模型)替换为回放。[`tests/`](tests/) 下的测试拥有无密钥真实 Loader 冒烟测试、密钥门控的外部状态验证冒烟测试,以及带父子会话 fixture(测试前置数据)的 `stream-json` 回放快照。 + +包级 [CLI 契约](../../packages/examples/cli-demo/README.md)记录输出记录、退出状态、取消、持久化以及模型/token 影响。 diff --git a/examples/jsonrpc-agent/README.i18n.yaml b/examples/jsonrpc-agent/README.i18n.yaml new file mode 100644 index 0000000000..59c18e0131 --- /dev/null +++ b/examples/jsonrpc-agent/README.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 +README.md: 6ee4e9d824315bde76b7a534679f018df9a6d3e8 +README.zh.md: dc9b6233e7074e7a9b13bf10bcd2f310b0ad7bf3 diff --git a/examples/jsonrpc-agent/README.md b/examples/jsonrpc-agent/README.md index 83c6e98fa5..6ee4e9d824 100644 --- a/examples/jsonrpc-agent/README.md +++ b/examples/jsonrpc-agent/README.md @@ -1,5 +1,7 @@ # jsonrpc-agent +English | [中文](README.zh.md) + The unattended coding-agent composition for the Python SDK's bundled JSON-RPC runtime. It intentionally loads no terminal UI, console logger, approval surface, or user-interaction tool because stdout belongs to the SDK protocol and turns are driven by the SDK. The model-facing tools are: diff --git a/examples/jsonrpc-agent/README.zh.md b/examples/jsonrpc-agent/README.zh.md new file mode 100644 index 0000000000..dc9b6233e7 --- /dev/null +++ b/examples/jsonrpc-agent/README.zh.md @@ -0,0 +1,27 @@ +# jsonrpc-agent + +[English](README.md) | 中文 + +面向 Python SDK 内置 JSON-RPC 运行时的无人值守编码 agent(智能体)组合。它有意不加载终端 UI、console logger、批准界面或用户交互工具,因为 stdout 属于 SDK 协议,轮次由 SDK 驱动。 + +面向模型的工具为: + +- `bash`,仅前台 +- `read`、`write` 和 `edit` +- `subagent`,使用一个前台进程内 spawn 提供方 +- `todo_write` + +周边运行时还加载 JSONL 会话持久化和自动上下文压缩(compaction)。`maxTokensAsSuccess` 将受 token 上限限制的模型轮次保留为已接受的评估结果,同时保留其 `max-tokens` 原因。 + +## 运行时环境 + +| 变量 | 用途 | +|---|---| +| `DEEPSEEK_API_KEY` | 传给 OpenAI 兼容宿主端点的凭据 | +| `DEEPSEEK_BASE_URL` | `dsh-llm-deepseek` 使用的宿主端点 | +| `DSH_CWD` | bash 和文件系统工具使用的 agent workspace | +| `DSH_MAX_TOKENS_AS_SUCCESS` | `true`(默认)接受受 token 上限限制的结果;`false` 将其报告为错误 | +| `DSH_SESSION_ROOT` | JSONL 轨迹目录 | +| `DSH_SYSTEM_PROMPT` | 由部署提供的编码人格 | + +通过 Python SDK 的 `cordis` 选项或 `DSH_CORDIS_CONFIG` 传入配置路径。内置可执行文件已携带此文件命名的每个插件;目标机器无需 Node.js。 diff --git a/examples/tui-agent/README.i18n.yaml b/examples/tui-agent/README.i18n.yaml new file mode 100644 index 0000000000..631848bb77 --- /dev/null +++ b/examples/tui-agent/README.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 +README.md: fdf3972f98f8ff9690b71469ae415dc18d339f10 +README.zh.md: 71f7ae949d034757a20adfae2cbe566011edc584 diff --git a/examples/tui-agent/README.md b/examples/tui-agent/README.md index 5196de053b..fdf3972f98 100644 --- a/examples/tui-agent/README.md +++ b/examples/tui-agent/README.md @@ -1,5 +1,7 @@ # tui-agent +English | [中文](README.zh.md) + The full-screen interactive coding agent: DeepSeek V4, local bash and filesystem tools, compaction, subagents, workflows and fresh-agent Ralph iteration, plan mode (`/plan` enters and `exit_plan_mode` reviews the exit), timeout/spill policy, and JSONL persistence through [`@deepseek-ai/dsh-tui-demo`](../../packages/examples/tui-demo), loaded from `cordis.yml`. The sibling [`headless-agent`](../headless-agent/README.md) runs the same capability class as a one-shot pipe-friendly task, and [`acp-agent`](../acp-agent/README.md) serves it over JSON-RPC. ## Run it diff --git a/examples/tui-agent/README.zh.md b/examples/tui-agent/README.zh.md new file mode 100644 index 0000000000..71f7ae949d --- /dev/null +++ b/examples/tui-agent/README.zh.md @@ -0,0 +1,80 @@ +# tui-agent + +[English](README.md) | 中文 + +全屏交互式编码 agent(智能体):DeepSeek V4、本地 bash 与文件系统工具、压缩(compaction)、subagent、工作流与新 agent Ralph 迭代、plan mode(`/plan` 进入,`exit_plan_mode` 评审退出)、超时/溢出策略,以及通过 [`@deepseek-ai/dsh-tui-demo`](../../packages/examples/tui-demo) 提供的 JSONL 持久化;该应用从 `cordis.yml` 加载。同级 [`headless-agent`](../headless-agent/README.md) 以适合单次管道的任务形式运行同一能力类,[`acp-agent`](../acp-agent/README.md) 则通过 JSON-RPC 提供该能力。 + +## 运行 + +```sh +# repo root .env (gitignored) or exported env: +# DEEPSEEK_API_KEY=sk-… +# DEEPSEEK_BASE_URL=https://… # optional; defaults to the public API +pnpm run demo:tui +``` + +演示脚本和可安装的 `dsh` CLI([`apps/cli`](../../apps/cli/README.md))都会作为已交付的默认配置启动此示例的 `cordis.yml`;`dsh` 还会应用 `~/.dsh` 中的个人覆盖,并将调用目录作为 workspace。 + +输入一项编码任务。agent 使用 `read`/`write`/`edit` 文件系统工具处理常规文件操作,使用 `bash`(加上面向后台任务的通用 `task_output`/`task_list`/`task_kill`)执行 shell 命令、搜索和测试。每次操作都在新的 `bash -c` 中运行(系统提示词要求模型传递 `workdir`,而不是使用 `cd`)。fs 工具和 bash 都会根据会话 workspace 解析相对路径。agent 还可以通过 `subagent`/`subagent_fork` 委托。 + +`todo_write` 任务跟踪器是选用的,不在已交付配置中:请将 `@deepseek-ai/dsh-tool-todo` 添加到 `cordis.yml`(或在 `~/.dsh` 下使用个人配置覆盖)以公开该工具。加载后,模型会把整表计划记录到会话日志,TUI 则渲染它。 + +TUI 渲染 Markdown 历史、推理、工具所有的终端/diff/通用卡片、token 总量,以及加载 `todo_write` 时的最新计划。较长的工具正文保留首尾预览;Ctrl+O 展开或折叠所有卡片。Enter 用于提交,或在 agent 运行时进行 steering(中途引导);Ctrl+R 切换推理,Escape 取消,`/help` 列出命令。`/plan` 为下一步骤选择 plan mode;`/plan ` 还会将消息提交到该步骤,`/plan off` 则在没有模型输入的情况下选择默认 mode。`/status` 会展开当前会话的标识、活动计数、精确 token/缓存 bucket、上下文用量和时间戳,而不中断正在运行的轮次。`/model` 打开当前提供方目录的键盘选择器;使用 Up/Down 和 Enter,或使用 `/model ` 和 `/model /` 直接选择。`ask_user_question` 会打开一个位于左下方的宽键盘面板,包含批次进度和编号选项。 + +### 恢复早先的会话 + +每次运行默认都会启动新会话(其事件日志落在 `./.sessions/` 下)。如需 **继续** 先前对话,请将其 id 传给已安装的 `dsh` CLI:此时 `main` agent 会重新水化持久日志,而不会从头开始,因此模型会将早先轮次视为历史: + +```sh +dsh --resume +``` + +`/resume` 打开可搜索键盘选择器,显示标题、活动、上一轮结果、模型路由、持久 goal 阶段和实时/已持久化状态。已安装的 `dsh` 宿主会刷新并释放当前应用,然后以 `dsh --resume ` 替换进程。TUI 仍会在退出时打印该命令,并在自定义宿主无法移交时显示它。`dsh --resume ` 在启动上下文中提供 id,`cordis.yml` 会读取它(`resumeSessionId: !!js "typeof resumeSessionId === 'string' ? resumeSessionId : undefined"`);没有标志时,agent 会开始新会话。缺失或无法读取的 id 不会启动 agent,而会发出 `agent-loop/config-start-failed`:TUI 打印失败并以非零状态退出。选择器没有跨进程会话锁,因此拥有并发宿主的部署必须自行协调会话所有权。 + +## Code Mode + +[`code-mode.cordis.yml`](code-mode.cordis.yml) 在同一树上覆盖 worker 线程运行时和 `tools: { mode: code }`。模型会收到一个 `run_code` 传输工具,加上一份为可见工具生成的 TypeScript SDK;只有程序输出会返回模型上下文。使用 `mode: both` 可在 `run_code` 旁同时公开原生调用。执行契约详见 [Code Mode Agent Note](../../.agents/notes/implemented/feature/2026-06-15-code-mode.md)。 + +```sh +pnpm run demo:code-mode # this overlay under the TUI (default UI) +pnpm run demo:code-mode acp # the acp-agent example's same-shaped overlay +``` + +尝试一项横跨多个工具调用的任务,例如: + +> 统计 docs/ 下每个 `*.md` 文件的行数,并将最大的三个写入 summary.txt。 + +然后观察 transcript(文本记录):一次 `run_code` 调用、一个循环调用工具的程序,以及模型筛选后的结果,而不是五次原始工具输出往返。 + +## 每个叶节点配置项所演示的内容 + +此示例是轻量叶节点 `cordis.yml`:它选择可替换后端、加载一个应用包(package),并添加有意放在共享主干外的产品工具。主干(会话、系统提示词、工具、agent、不变式、`agent-loop`)和入口集群(JSONL 持久化、pi-tui 通道、预创建的 `main` agent)位于 [`@deepseek-ai/dsh-tui-demo`](../../packages/examples/tui-demo) 应用及其加载的 [`@deepseek-ai/dsh-agent-spine-demo`](../../packages/examples/agent-spine-demo) 组合包中;叶节点负责接线后端与面向模型的可选工具: + +| 配置项 | 演示内容 | +|---|---| +| `hmr` (`@cordisjs/plugin-hmr`) | 开发/演示的编辑-重载循环:它是 **叶节点** 配置项(不内置到应用),因为它依赖 Loader 的内部模块访问 | +| `llm-deepseek` | 通过配置提供真实 `LlmAdapter`(`!!js process.env.…` 密钥);将一行替换为 `@deepseek-ai/dsh-llm-pi-ai` 即可使用库后端对照实现 | +| `bash` (`dsh-bash-local`) | 执行器实现:bash seam 的可替换一半。面向模型的 `bash` schema(`tool-bash`)和通用 `task_*` 控制(`tool-tasks`)由 `dsh-agent-spine-demo` 提供,因此叶节点只选择执行器 | +| `tui-agent` (`@deepseek-ai/dsh-tui-demo`) | 应用组合包:agent-spine 演示 + JSONL 持久化 + pi-tui 通道 + 预创建的 `main` agent | +| `subagent`, `subagent-spawn`, `subagent-fork` | subagent 提供方注册表加两个进程内后端:新子 agent,以及用父 agent 已完成轮次前缀播种的子 agent | +| `tool-subagent`, `tool-subagent-fork` | 两次面向模型的 `dsh-tool-subagent` 加载,每次绑定不同提供方,并以不同工具名(`subagent`、`subagent_fork`)公开 | +| `workflow-workerthread`, `tool-workflow` | worker 线程工作流引擎及其面向模型的 `workflow` 工具,子调用通过 spawn 后端路由 | +| `plan-mode` | 插件拥有的 `/plan [message]` 进入命令和 `/plan off` 退出命令、plan-mode 提示词策略、工具限制,以及经评审的 `exit_plan_mode` 转换 | +| `fs-local`, `fs-policy`, `tool-fs` | 文件系统栈:本地 `ctx.fs` 提供方、先读后写/编辑策略门禁(位于 `fs/*` 事件门禁),以及面向模型的 `read`/`write`/`edit` 工具。相对路径根据会话 workspace 解析 | + +## 端到端测试(`pnpm run test:e2e`) + +与 UI 无关的带密钥套件通过 `tests/harness.ts` 以程序方式组装完整栈(无 PTY、无 Loader): + +- `tests/full-loop.e2e.ts`:canary 测试:真实模型通过真实 bash 工具运行 `echo e2e-ok`;断言 `tool/call`/`tool/result` 会话事件和最终答案。 +- `tests/coding-task.e2e.ts`:类 swebench 冒烟测试:临时目录包含 `add.js`(其中 `a - b` 写在本应是 `a + b` 的位置)和失败的 `add.test.js`;agent 必须修复错误并验证。测试会自行重新运行 `node add.test.js` 并检查文件,不信任 agent 的声称。 +- `tests/resume.e2e.ts`:跨进程持久连续性:第一次运行告诉真实模型一个密码并将轮次持久化到临时 JSONL 根目录,然后释放整个上下文;第二次运行在同一根目录上创建新上下文,恢复会话 id 并要求模型回忆密码。只有重新水化的日志能够提供该回忆。 +- `tests/compaction.e2e.ts`:压缩冒烟测试:一项真实多步 bash 任务在故意设得很小的上下文窗口中运行,使自动压缩监听器在会话中途触发。测试验证外部状态:真实日志中出现 `compact/start…end` 对,表层缩减(替换节点遮蔽旧节点),且 agent 在压缩后仍给出正确最终答案。 +- `tests/todo-write.e2e.ts`:加载选用 `todo_write` 工具,由真实模型驱动,测试验证产生的 `todo/write` 会话事件。 +- `tests/code-mode.e2e.ts`:带密钥 Code Mode 证明:使用真实模型和双工具任务,断言线上工具列表精确为 `[run_code]`,`tool/code-dispatch` 事件位于父调用下,且筛选后的答案已返回。 + +这些测试在没有 `DEEPSEEK_API_KEY` 时自行跳过。无密钥 `tests/tui-keyless-smoke.e2e.ts` 通过 PTY 启动真实 Loader 树(唯一获准的 PTY 界面):基础启动 + `/plan` + `/exit`,一次带问题对话框和工具往返的脚本 LLM 对话,Code Mode 覆盖欢迎行,以及恢复失败退出路径。 + +## 快照测试 + +`tests/snapshots//session.jsonl` 提供已录制的用户提示词和模型分片;同级子日志驱动 subagent 和工作流。无密钥套件通过真实循环和工具实现执行这些脚本,然后比较可读的预期终端单元格/样式输出。使用 `pnpm run test:snapshot:refresh` 刷新仅展示变更;已录制模型旅程改变时,使用 DeepSeek 密钥运行 `pnpm run test:snapshot:record`。已实现的 [TUI 快照 Agent Note](../../.agents/notes/implemented/testing/2026-07-18-tui-terminal-state-snapshots.md) 拥有场景矩阵,以及已录制旅程、瞬时包快照与 PTY 覆盖之间的分工。 diff --git a/native/README.i18n.yaml b/native/README.i18n.yaml new file mode 100644 index 0000000000..4013fc656d --- /dev/null +++ b/native/README.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 +README.md: 84808b2ee9dafa4f9f980c35a81ebe12480a4f5d +README.zh.md: f73d4176454d9a577bf674a6bfe3f15cce3402b4 diff --git a/native/README.md b/native/README.md index 983e67f740..84808b2ee9 100644 --- a/native/README.md +++ b/native/README.md @@ -1,5 +1,7 @@ # native/ +English | [中文](README.zh.md) + Source of record for `node-addon-landlock-run`, the Landlock self-restrict-then-exec launcher the harness consumes from npm (`packages/sandbox/sandbox-local`, `packages/bash/bash-sandbox`). Launcher development happens HERE, next to the consumers; the standalone repository is the release mirror that packs and publishes the npm package family. ## Release mirror diff --git a/native/README.zh.md b/native/README.zh.md new file mode 100644 index 0000000000..f73d417645 --- /dev/null +++ b/native/README.zh.md @@ -0,0 +1,22 @@ +# native/ + +[English](README.md) | 中文 + +`node-addon-landlock-run` 的记录真源:这是 harness 从 npm 消费的 Landlock「先限制自身、再执行」启动器(`packages/sandbox/sandbox-local`、`packages/bash/bash-sandbox`)。启动器在此处开发,与消费方相邻;独立仓库是打包并发布 npm 包系列的发布镜像。 + +## 发布镜像 + +| 目录 | 镜像仓库 | 上次导出的发布版 | Commit | +|---|---|---|---| +| `landlock-run/` | https://github.com/deepseek-harness/node-addon-landlock-run | `v0.0.1` | `614f7fd7dc11e6eaceefba9e7ff1fbe28b51ba22` | + +该子树是一个自包含的 pnpm workspace,拥有自己的 `AGENTS.md`、文档、门禁和锁文件;它不属于 harness workspace(`pnpm-workspace.yaml` 不包含它),因此 harness 的安装、构建和 CI 门禁绝不会触及它。镜像的 `.github/` 不进入该子树;[.github/workflows/landlock-run.yml](../.github/workflows/landlock-run.yml)(手动触发)在此处运行子树的 CI 任务,对这些任务的更改会在下次导出时镜像到镜像仓库的 `ci.yml`。 + +## 导出流程(发布新版本) + +1. 先通过常规 harness PR 将启动器更改落地于此;触发 `Landlock Run` 工作流,并确保其所有任务通过。 +2. 在镜像 checkout 中替换 `.github/` 以外的所有内容:`git -C rm -rq -- . ':!.github'`,然后执行 `git -C archive HEAD:native/landlock-run | tar -x -C `,最后执行 `git -C add -A` 并提交。 +3. 在镜像中按照其发布清单(`docs/release.md`)操作:`pnpm release:commit ` → 合并 → 标记 `vX.Y.Z` → 两阶段 `Release` 工作流(先以 `publish=false` 预演,再从标签以 `publish=true` 发布)。 +4. 使用已发布的标签/commit 更新上方 manifest(元数据清单)表,并在同一更改中提升 harness 消费方的依赖范围。 + +镜像不得分叉:如果更改直接提交到镜像中(例如发布期间的热修复),必须在下次导出前将其移植回此处。 diff --git a/native/landlock-run/README.i18n.yaml b/native/landlock-run/README.i18n.yaml new file mode 100644 index 0000000000..7212b6a317 --- /dev/null +++ b/native/landlock-run/README.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 +README.md: 284d5df764cf5a5205973696211aee2366d3b76e +README.zh.md: 7163314abac0362afccee6fcc4506a84701cc27a diff --git a/native/landlock-run/README.md b/native/landlock-run/README.md index 2bb92843e6..284d5df764 100644 --- a/native/landlock-run/README.md +++ b/native/landlock-run/README.md @@ -1,5 +1,7 @@ # node-addon-landlock-run +English | [中文](README.zh.md) + A [Landlock](https://landlock.io/) self-restrict-then-exec launcher for confining subprocesses on Linux, distributed as prebuilt per-platform npm packages plus a thin JS entry package that resolves the binary and speaks its CLI contract. Built for agent harnesses and other hosts that need to run untrusted commands under a filesystem allow-list without confining themselves. The first tool is **`landlock-run`** — a self-restrict-then-exec [Landlock](https://landlock.io/) launcher (~300 lines of C11 over the raw kernel UAPI, statically linked against musl). It installs a Landlock ruleset on itself and `exec`s the wrapped command; the ruleset is inherited across `execve`, so the command and every process it spawns run confined while the invoking process stays unrestricted. Fail-closed: if the kernel cannot enforce, it exits without running the command. diff --git a/native/landlock-run/README.zh.md b/native/landlock-run/README.zh.md new file mode 100644 index 0000000000..7163314aba --- /dev/null +++ b/native/landlock-run/README.zh.md @@ -0,0 +1,60 @@ +# node-addon-landlock-run + +[English](README.md) | 中文 + +一个 [Landlock](https://landlock.io/)「先限制自身、再执行」启动器,用于在 Linux 上限制子进程。它以每平台预构建 npm 包加一个轻量 JS 入口包的形式发布;入口包负责解析二进制文件并遵循其 CLI(命令行界面)契约。该启动器面向需要在文件系统允许清单下运行不可信命令、但不能限制自身的 agent harness 和其他宿主。 + +第一个工具是 **`landlock-run`**:一个「先限制自身、再执行」的 [Landlock](https://landlock.io/) 启动器(基于原始内核 UAPI 编写,约 300 行 C11,并与 musl 静态链接)。它在自身上安装 Landlock 规则集,再 `exec` 被包装的命令;该规则集会跨 `execve` 继承,因此命令及其产生的每个进程都在限制下运行,调用进程仍不受限制。它采用失败闭合:如果内核无法强制执行,则不运行命令并直接退出。 + +## 安装 + +```sh +npm install node-addon-landlock-run +``` + +已发布包由一个入口包和可选平台包组成: + +```text +node-addon-landlock-run +node-addon-landlock-run-linux-x64 +node-addon-landlock-run-linux-arm64 +``` + +npm 的 `os`/`cpu` 字段使安装器只拉取匹配的平台包。系统有意不提供安装时构建回退:在没有对应平台包的宿主上,解析后的路径绝不存在,探测会报告 `unusable`,消费方以失败闭合方式处理。 + +## 用法 + +```js +import { grantArgs, launcherPath, probe } from 'node-addon-landlock-run'; + +const launcher = launcherPath(); +if (probe(launcher) !== 'unusable') { + const argv = [launcher, ...grantArgs({ readOnly: ['/'], readWrite: ['/tmp/work'] }), '--', 'bash', '-c', command]; + // spawn argv with your process runner of choice +} +``` + +公开 API 有意保持简小: + +- `launcherPath()`:当前宿主启动器的绝对路径(有意不检查是否存在;探测结果才是可用性信号)。 +- `probe(launcher?, { timeoutMs? })`:功能性强制执行探测,返回 `'full' | 'partial' | 'unusable'`。 +- `grantArgs({ readOnly?, readWrite? })`:启动器的授权 argv;未授予的一切都被拒绝。 +- `LAUNCHER_BIN`、`LAUNCHER_FAILURE_EXIT` (125):契约常量。 + +完整的二进制契约(argv 语法、退出码、报告行)锁定在 [docs/cli-contract.md](docs/cli-contract.md) 中。 + +## 支持范围 + +支持 linux-x64 和 linux-arm64,且内核已启用 Landlock(5.13+;ABI 级别决定强制执行为 `full` 还是 `partial`,详见 [docs/support-matrix.md](docs/support-matrix.md))。其他平台有意不提供对应包:消费方会在这些平台上运行其他限制后端。 + +## 开发 + +```sh +corepack enable +pnpm install +pnpm build:ts # entry packages → lib/ +pnpm build:native # this Linux architecture's binaries (apt-get install musl-tools) +pnpm test +``` + +二进制文件被 git 忽略,并且按架构原生构建:本地只构建当前机器的版本,CI 的每架构 runner 则是记录中的构建者。发布流程详见 [docs/release.md](docs/release.md)。 diff --git a/native/landlock-run/packages/entry/README.i18n.yaml b/native/landlock-run/packages/entry/README.i18n.yaml new file mode 100644 index 0000000000..2985be0419 --- /dev/null +++ b/native/landlock-run/packages/entry/README.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 +README.md: e402cdfe71c4eb81b977a21955fe3fff6bf55fd3 +README.zh.md: 03dd18969d8e5c94be31605201b74b126ae5c06d diff --git a/native/landlock-run/packages/entry/README.md b/native/landlock-run/packages/entry/README.md index 789b1ddf6b..e402cdfe71 100644 --- a/native/landlock-run/packages/entry/README.md +++ b/native/landlock-run/packages/entry/README.md @@ -1,5 +1,7 @@ # node-addon-landlock-run +English | [中文](README.zh.md) + Landlock self-restrict-then-exec launcher for confining subprocesses on Linux: this entry package resolves the per-platform prebuilt binary, runs its functional enforcement probe, and builds its grant argv — consumers never spell launcher flags or parse launcher output themselves. ```js diff --git a/native/landlock-run/packages/entry/README.zh.md b/native/landlock-run/packages/entry/README.zh.md new file mode 100644 index 0000000000..03dd18969d --- /dev/null +++ b/native/landlock-run/packages/entry/README.zh.md @@ -0,0 +1,18 @@ +# node-addon-landlock-run + +[English](README.md) | 中文 + +用于在 Linux 上限制子进程的 Landlock「先限制自身、再执行」启动器:此入口包解析每平台预构建二进制文件,运行功能性强制执行探测,并构建其授权 argv。消费方无需自行拼写启动器标志或解析启动器输出。 + +```js +import { grantArgs, launcherPath, probe } from 'node-addon-landlock-run'; + +const launcher = launcherPath(); +if (probe(launcher) !== 'unusable') { + const argv = [launcher, ...grantArgs({ readOnly: ['/'], readWrite: ['/tmp/work'] }), '--', 'bash', '-c', command]; +} +``` + +启动器在自身上安装 Landlock 规则集,再 `exec` 被包装的命令;该规则集会跨 `execve` 继承,因此整个进程树都在限制下运行。未授予的一切都被拒绝;启动器失败时以 `125` 退出且不运行命令:始终失败闭合,绝不失败开放。二进制契约锁定在仓库的 `docs/cli-contract.md` 中;C 源码作为 `src/main.c` 随该 tarball 分发,便于审计。 + +平台包(由 `os`/`cpu` 选择的可选依赖,内部不含 JavaScript):`node-addon-landlock-run-linux-x64`、`node-addon-landlock-run-linux-arm64`。在缺少对应包的宿主上,`launcherPath()` 返回确定且不存在的路径,`probe()` 报告 `'unusable'`;系统有意不提供安装时编译回退。 diff --git a/native/landlock-run/packages/linux-arm64/README.i18n.yaml b/native/landlock-run/packages/linux-arm64/README.i18n.yaml new file mode 100644 index 0000000000..b6b14f1eef --- /dev/null +++ b/native/landlock-run/packages/linux-arm64/README.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 +README.md: e5117988cf0bae2227edaa041700c2f75753899c +README.zh.md: 93fee68207a9f03a54f214c69904d44729ed71e5 diff --git a/native/landlock-run/packages/linux-arm64/README.md b/native/landlock-run/packages/linux-arm64/README.md index 1921c8f4b5..e5117988cf 100644 --- a/native/landlock-run/packages/linux-arm64/README.md +++ b/native/landlock-run/packages/linux-arm64/README.md @@ -1,5 +1,7 @@ # node-addon-landlock-run-linux-arm64 +English | [中文](README.zh.md) + Prebuilt `bin/landlock-run` Landlock launcher for linux-arm64 — a static musl binary compiled natively (no cross toolchain) from the C source shipped in [`node-addon-landlock-run`](https://www.npmjs.com/package/node-addon-landlock-run). npm's `os`/`cpu` fields select this package at install time; the entry package resolves it to a file path — it ships no JavaScript and is never imported. The binary is git-ignored and rides the npm tarball via the `files` list; the `prepack` gate refuses to pack when it is missing or has the wrong ELF architecture, and the release pipeline byte-pins the packed binary against the CI build it came from. Static musl linking means one binary for glibc and musl distros alike — hence no libc suffix in the name. diff --git a/native/landlock-run/packages/linux-arm64/README.zh.md b/native/landlock-run/packages/linux-arm64/README.zh.md new file mode 100644 index 0000000000..93fee68207 --- /dev/null +++ b/native/landlock-run/packages/linux-arm64/README.zh.md @@ -0,0 +1,9 @@ +# node-addon-landlock-run-linux-arm64 + +[English](README.md) | 中文 + +面向 linux-arm64 的预构建 `bin/landlock-run` Landlock 启动器:一个从 [`node-addon-landlock-run`](https://www.npmjs.com/package/node-addon-landlock-run) 中随包发布的 C 源码原生编译而成的静态 musl 二进制文件(不使用交叉工具链)。npm 的 `os`/`cpu` 字段在安装时选择此包;入口包将其解析为文件路径。该包不包含 JavaScript,也绝不会被导入。 + +该二进制文件被 git 忽略,并通过 `files` 列表进入 npm tarball;如果文件缺失或 ELF 架构错误,`prepack` 门禁会拒绝打包,发布流水线则会按字节将打包二进制文件锁定到其来源 CI 构建。静态 musl 链接使同一个二进制文件同时适用于 glibc 和 musl 发行版,因此名称中没有 libc 后缀。 + +同级包:`node-addon-landlock-run-linux-x64`。 diff --git a/native/landlock-run/packages/linux-x64/README.i18n.yaml b/native/landlock-run/packages/linux-x64/README.i18n.yaml new file mode 100644 index 0000000000..af3f916fb4 --- /dev/null +++ b/native/landlock-run/packages/linux-x64/README.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 +README.md: 68b5dfc9b6f437a387c3792ee047a1f11630aca0 +README.zh.md: b1fa2e3f16c20c4d7e287c17ab0ba946e6cadbea diff --git a/native/landlock-run/packages/linux-x64/README.md b/native/landlock-run/packages/linux-x64/README.md index ce741eb34c..68b5dfc9b6 100644 --- a/native/landlock-run/packages/linux-x64/README.md +++ b/native/landlock-run/packages/linux-x64/README.md @@ -1,5 +1,7 @@ # node-addon-landlock-run-linux-x64 +English | [中文](README.zh.md) + Prebuilt `bin/landlock-run` Landlock launcher for linux-x64 — a static musl binary compiled natively (no cross toolchain) from the C source shipped in [`node-addon-landlock-run`](https://www.npmjs.com/package/node-addon-landlock-run). npm's `os`/`cpu` fields select this package at install time; the entry package resolves it to a file path — it ships no JavaScript and is never imported. The binary is git-ignored and rides the npm tarball via the `files` list; the `prepack` gate refuses to pack when it is missing or has the wrong ELF architecture, and the release pipeline byte-pins the packed binary against the CI build it came from. Static musl linking means one binary for glibc and musl distros alike — hence no libc suffix in the name. diff --git a/native/landlock-run/packages/linux-x64/README.zh.md b/native/landlock-run/packages/linux-x64/README.zh.md new file mode 100644 index 0000000000..b1fa2e3f16 --- /dev/null +++ b/native/landlock-run/packages/linux-x64/README.zh.md @@ -0,0 +1,9 @@ +# node-addon-landlock-run-linux-x64 + +[English](README.md) | 中文 + +面向 linux-x64 的预构建 `bin/landlock-run` Landlock 启动器:一个从 [`node-addon-landlock-run`](https://www.npmjs.com/package/node-addon-landlock-run) 中随包发布的 C 源码原生编译而成的静态 musl 二进制文件(不使用交叉工具链)。npm 的 `os`/`cpu` 字段在安装时选择此包;入口包将其解析为文件路径。该包不包含 JavaScript,也绝不会被导入。 + +该二进制文件被 git 忽略,并通过 `files` 列表进入 npm tarball;如果文件缺失或 ELF 架构错误,`prepack` 门禁会拒绝打包,发布流水线则会按字节将打包二进制文件锁定到其来源 CI 构建。静态 musl 链接使同一个二进制文件同时适用于 glibc 和 musl 发行版,因此名称中没有 libc 后缀。 + +同级包:`node-addon-landlock-run-linux-arm64`。 diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml new file mode 100644 index 0000000000..9b2c44af22 --- /dev/null +++ b/packages/README.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 +README.md: d7427c3f9892f56185cc1175245f14a6ccea0d25 +README.zh.md: 6894aa7333f6ba4bc5723871fb77c18b5fb518a1 diff --git a/packages/README.md b/packages/README.md index cffc4a0554..d7427c3f98 100644 --- a/packages/README.md +++ b/packages/README.md @@ -1,5 +1,7 @@ # Packages +English | [中文](README.zh.md) + Packages use the `@deepseek-ai/dsh-*` scope. Each is a Cordis `Service` subclass or function plugin; contributions use `ctx.effect()`, `ctx.on()`, or `ctx.waterfall()`. Authoring rules: [package](AGENTS.md) and [root](../AGENTS.md#conventions). ## Hierarchy diff --git a/packages/README.zh.md b/packages/README.zh.md new file mode 100644 index 0000000000..6894aa7333 --- /dev/null +++ b/packages/README.zh.md @@ -0,0 +1,56 @@ +# 包 + +[English](README.md) | 中文 + +所有包都使用 `@deepseek-ai/dsh-*` scope。每个包都是 Cordis `Service` 子类或函数插件;所有贡献通过 `ctx.effect()`、`ctx.on()` 或 `ctx.waterfall()` 注册。编写规则见[包](AGENTS.md)与[根规则](../AGENTS.md#conventions)。 + +## 层级结构 + +包位于 `packages///`;组是容器,包名仍为 `@deepseek-ai/dsh-`。**每个组 README 是规范的包/ctx 键映射。** + +| 组 | 职责 | 发布预期 | +|---|---|---| +| [`core/`](core/README.md) | 产品 API 主干:会话、提示词、工具、agent(智能体)服务与具体循环 | 产品:稳定表面 | +| [`goal/`](goal/README.md) | 持久化的同会话 goal 状态与生命周期 | 产品:稳定表面 | +| [`llm/`](llm/README.md) | LLM(大语言模型)能力系列:抽象服务 + 提供方适配器 | 产品:稳定表面 | +| [`bash/`](bash/README.md) | Bash 能力系列:执行器 seam、本地实现、面向模型的工具 | 产品:稳定表面 | +| [`pty/`](pty/README.md) | 持久 PTY 能力系列:按所有者隔离的会话、本地实现和面向模型的工具 | 产品:稳定表面 | +| [`code-runtime/`](code-runtime/README.md) | 代码执行能力系列:面向模型所写程序的运行时 seam + worker 线程后端 | 产品:稳定表面 | +| [`sandbox/`](sandbox/README.md) | 进程限制 seam;bwrap/Landlock/Seatbelt 后端 | 产品:稳定表面 | +| [`fs/`](fs/README.md) | 文件系统能力系列:seam、本地实现、面向模型的文件工具、bash 后端发现工具 | 产品:稳定表面 | +| [`lsp/`](lsp/README.md) | LSP 能力系列:seam、通用 stdio 提供方和 `lsp` 工具 | 产品:稳定表面 | +| [`skill/`](skill/README.md) | Skill(技能)能力系列:提供方注册表、本地提供方和面向模型的目录/加载器 | 产品:稳定表面 | +| [`compact/`](compact/README.md) | 压缩(compaction)能力系列:抽象 seam + 基础后端(工具延后) | 产品:稳定表面 | +| [`context/`](context/README.md) | 模型可见请求上下文,包括 workspace 指令和时间上下文 | 产品:稳定表面 | +| [`subagent/`](subagent/README.md) | Subagent 能力系列:提供方注册表 seam 和面向模型的委托工具 | 产品:稳定表面 | +| [`tasks/`](tasks/README.md) | 通用后台任务运行时和面向模型的 `task_*` 控制工具 | 产品:稳定表面 | +| [`workflow/`](workflow/README.md) | 工作流能力系列:脚本引擎 seam、worker 线程引擎、面向模型的 `workflow` 与新 agent `ralph` 工具 | 产品:稳定表面 | +| [`web/`](web/README.md) | Web 能力系列:seam、搜索/获取提供方实现和面向模型的 Web 工具 | 产品:稳定表面 | +| [`spill/`](spill/README.md) | 溢出能力系列:存储 seam、本地实现、工具结果溢出策略 | 产品:稳定表面 | +| [`todo/`](todo/README.md) | Todo/规划系列:面向模型的 `todo_write` 工具 | 产品:稳定表面 | +| [`plan/`](plan/README.md) | Plan 协作状态,提供直接进入命令与经评审的退出 | 产品:稳定表面 | +| [`timeout/`](timeout/README.md) | 工具调用超时策略:`tools/execute` 截止时间强制执行器 | 产品:稳定表面 | +| [`guard/`](guard/README.md) | 循环卫生守卫:建议性重复调用提醒 | 产品:稳定表面 | +| [`cordis/`](cordis/README.md) | 自指运行时工具集:检查实时运行时的插件与服务,挂载/卸载模型所写插件([设计](../.agents/notes/implemented/feature/2026-07-08-self-referential-cordis-toolset.md)) | 产品:稳定表面 | +| [`hooks/`](hooks/README.md) | 钩子桥接 + 共享 Claude Code/Codex 协议格式库 | 产品:稳定表面 | +| [`session-persistence/`](session-persistence/README.md) | 持久化能力系列:seam + JSONL/SQLite 后端 | 产品:稳定表面 | +| [`session-query/`](session-query/README.md) | 会话检索系列:逻辑语料库、有界读取、血缘、事件关系、语义过滤和 SQLite 全文搜索 | 产品:稳定表面 | +| [`session-title/`](session-title/README.md) | 日志支撑的会话标题:回退服务、共享 LLM 策略和选用提供方 | 产品:稳定表面 | +| [`storage/`](storage/README.md) | 非会话存储中枢 + 后端 + 领域形式 | 产品:稳定表面 | +| [`workspace/`](workspace/README.md) | Workspace 实体 | 产品:稳定表面 | +| [`sdk/`](sdk/README.md) | 项目 SDK 工具 | 产品:稳定表面 | +| [`acp/`](acp/README.md) | 仅面向自动化的 Agent Client Protocol 服务器 | 产品:稳定表面 | +| [`ui/`](ui/README.md) | 人类/客户端集成:TUI 与 JSON-RPC、批准/交互 seam、用户问答工具 | 产品:稳定表面 | +| [`examples/`](examples/README.md) | 演示组合包(agent-spine + TUI/CLI/ACP/JSON-RPC bin),由叶节点加载 | 支持:示例基础设施 | +| [`support/`](support/README.md) | 支持基础设施(testkit、不变式、回放、Loader 冒烟测试) | 支持:兼容性预期较低 | +| [`util/`](util/README.md) | 组间共享的低层零依赖工具(`Branded`、Harness home/路径辅助函数、超时、保留策略) | 支持:小型、稳定、无 harness 依赖 | + +组用于区分产品 API 与支持基础设施。新包加入现有组;新组则更新其 README 和此表。 + +## 依赖 + +依赖图由工具生成:[docs/module-graph.md](../docs/module-graph.md)(`pnpm run gen-module-graph`,CI 中有新鲜度门禁)。 + +**扩展插件依赖接口,绝不依赖具体循环。** `dsh-agent-loop` 可替换;UI、钩子和工具插件使用 `dsh-agent`。包括 `dsh-agent-spine-demo` 在内的组合包可以依赖主干插件。能力拆分为接口/实现/消费方包;详见[能力 seam](../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)。 + +包 README 覆盖用途、API、扩展点和[模型体验](../docs/cookbook/adding-a-package.md#4-write-the-package-readme);列入模型无关[省略允许清单](../scripts/verify-package-readme-model-experience.ts)的包除外。它们还要包含 `## Known Limitations and Deferred Work`,或使用其[允许清单](../scripts/verify-package-readme-limitations.ts)。 diff --git a/packages/acp/README.i18n.yaml b/packages/acp/README.i18n.yaml new file mode 100644 index 0000000000..cf2cf1791a --- /dev/null +++ b/packages/acp/README.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 +README.md: 326615210e5cfc39004fc5ab7462623089ac4126 +README.zh.md: 9999ecdd019501c3f501a6c69fab5e0ccfaf555c diff --git a/packages/acp/README.md b/packages/acp/README.md index 480b15726d..326615210e 100644 --- a/packages/acp/README.md +++ b/packages/acp/README.md @@ -1,5 +1,7 @@ # acp/ — Agent Client Protocol automation +English | [中文](README.zh.md) + The ACP group exposes harness agents to programmatic clients. It is an interoperability transport, not a presentation or human-interaction layer. | Package | Role | diff --git a/packages/acp/README.zh.md b/packages/acp/README.zh.md new file mode 100644 index 0000000000..9999ecdd01 --- /dev/null +++ b/packages/acp/README.zh.md @@ -0,0 +1,11 @@ +# acp/:Agent Client Protocol 自动化 + +[English](README.md) | 中文 + +ACP(Agent Client Protocol)组将 harness 中的 agent(智能体)公开给程序化客户端。它是互操作传输层,而非展示层或人机交互层。 + +| 包 | 职责 | +|---|---| +| [`acp/`](acp/README.md) | 仅面向自动化的 ACP 服务器:新文本会话、已提交的 assistant 输出、机器权限策略、取消和由连接拥有的清理。 | + +与之匹配的进程外 subagent 客户端仍位于 [`subagent/subagent-acp`](../subagent/subagent-acp/README.md),因为它实现 subagent 提供方接口;任意 ACP 客户端都可以驱动同一服务器契约。 diff --git a/packages/acp/acp/README.i18n.yaml b/packages/acp/acp/README.i18n.yaml new file mode 100644 index 0000000000..5583a2b9a5 --- /dev/null +++ b/packages/acp/acp/README.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 +README.md: 1b188b994d17ce56e8d5df019ddef755338fcc88 +README.zh.md: f8abe9e45a5efffa436513f7d4a931c69c624b84 diff --git a/packages/acp/acp/README.md b/packages/acp/acp/README.md index 20b1ecbefe..1b188b994d 100644 --- a/packages/acp/acp/README.md +++ b/packages/acp/acp/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-acp +English | [中文](README.zh.md) + Automation-only [Agent Client Protocol](https://agentclientprotocol.com) server over JSON-RPC stdio. Programmatic clients create fresh harness agents, send text prompts, collect committed assistant text, resolve one-shot permission requests by policy, and cancel work. The primary in-repository client is [`dsh-subagent-acp`](../../subagent/subagent-acp/README.md). This package is a transport adapter, not a UI integration or a capability seam. It does not expose editor navigation, transcript replay, commands, modes, configuration pickers, elicitation, reasoning, plans, titles, or tool presentation. Interactive rendering and human questions belong to the web and TUI modules. diff --git a/packages/acp/acp/README.zh.md b/packages/acp/acp/README.zh.md new file mode 100644 index 0000000000..f8abe9e45a --- /dev/null +++ b/packages/acp/acp/README.zh.md @@ -0,0 +1,79 @@ +# @deepseek-ai/dsh-acp + +[English](README.md) | 中文 + +通过 JSON-RPC stdio 提供的仅面向自动化的 [Agent Client Protocol](https://agentclientprotocol.com) 服务器。程序化客户端可以创建新 harness agent(智能体)、发送文本提示词、收集已提交的 assistant 文本、通过策略解决一次性权限请求并取消工作。仓库中的主要客户端是 [`dsh-subagent-acp`](../../subagent/subagent-acp/README.md)。 + +此包(package)是传输适配器,而非 UI 集成或能力 seam。它不公开编辑器导航、transcript(文本记录)回放、命令、mode、配置选择器、信息征集、推理、计划、标题或工具展示。交互渲染与人类问题属于 Web 和 TUI 模块。 + +## 插件 + +`apply(ctx, config)` 在 stdin/stdout 上打开 `AgentSideConnection` 并驱动 `ctx.agents`。Stdout 专用于协议帧。 + +| 配置 | 默认值 | 含义 | +|---|---|---| +| `provider` | 无 | 每个已创建 agent 的初始提供方路由。 | +| `model` | 无 | 每个已创建 agent 的初始模型。 | + +两个字段都是可选的,以便由另一个 agent/request 监听器提供目标。可运行 ACP 组合同时要求两者。 + +## 协议契约 + +| 方法 | 行为 | +|---|---| +| `initialize` | 协商受支持的版本,并仅公布基线提示词(无图像、音频或嵌入上下文能力)。不公布会话、编辑器、终端、文件系统或 MCP 能力。 | +| `authenticate` | 空操作,因为服务器不公布身份验证方法。 | +| `session/new` | 使用绝对主 `cwd` 创建新 agent;接受空的 `additionalDirectories` 和 `mcpServers`,拒绝非空值。 | +| `session/prompt` | 连接文本块,将基线资源链接渲染为带方括号的文本引用,拒绝空输入或超出基线的输入,每个会话只允许一个正在处理的请求,并从该请求拥有的持久 `turn/end` 结算。 | +| `session/cancel` | 仅取消被定址的 agent,并将其待处理提示词结算为 `cancelled`;未知 id 为空操作。 | +| `session/update` | 为每个非空文本块发出一个 `agent_message_chunk`;这些文本块来自已提交的 `assistant/message`。省略原始增量和非消息事件。 | +| `session/request_permission` | 为携带工具调用 id 的桥接层所有批准请求提供一次性允许/拒绝选项。客户端可以自动回答。 | + +一个连接可以拥有多个会话。桥接层使用带品牌的 session id 为记录建键,并在路由事件或权限请求前检查精确的 agent 标识。每个会话都有独立的提示词槽位、workspace、取消路径和 disposer。 + +已提交消息输出有意以逐 token 延迟换取干净的自动化结果。未提交的提供方分片和重试尝试无法泄漏部分文本;推理与工具活动仍保留在会话日志中,以便其他界面观测。 + +## 生命周期 + +客户端断开与 Cordis 释放共用同一个记忆化清理流程。桥接层先拒绝新会话和提示词,结算待处理提示词,然后并行释放所有已拥有的 agent handle,并等待它们的循环/会话清理完成。因此,仅 ACP 的插件重载不会遗留 agent。 + +## 运行 + +`pnpm --dir /path/to/deepseek-harness run demo:acp` 启动仓库的自动化服务器组合。父 harness 可以通过 [`@deepseek-ai/dsh-subagent-acp`](../../subagent/subagent-acp/README.md) spawn 它;其他 ACP 客户端只需上述核心方法。 + +## 模型体验 + +### 提示词文本 + +#### 模型所见内容 + +`session/prompt` 文本块会原样连接为一条用户消息;基线资源链接会在该消息中表示为带方括号的 `[resource_link name=… uri=…]` 引用,模型可以使用自身工具打开它。协议元数据、客户端能力、权限选择和 session id 绝不进入模型请求。 + +#### Token 影响 + +提示词 token 取决于数据,并保留在该会话的历史中直到压缩。并发 ACP 会话保留独立上下文。 + +#### KV Cache 影响 + +仅追加;新用户消息位于可复用请求前缀之后,不会使先前缓存条目失效。 + +### 权限决策 + +#### 模型所见内容 + +没有直接内容。拥有该决策的工具通过常规工具结果路径记录允许、拒绝、取消或不可用结果。 + +#### Token 影响 + +只有拥有该决策的工具结果会贡献 token。 + +#### KV Cache 影响 + +通过所属工具结果仅追加。 + +## 已知限制与延后工作 + +- **仅新会话**:不支持加载、列出、恢复、删除和 fork。 +- **仅基线提示词和一个 workspace**:图像、音频、嵌入资源、非空附加目录和 MCP 服务器都会被拒绝;资源链接会被展平为文本引用,而不是已获取内容。 +- **仅已提交答案**:实时进度、推理、工具活动、计划、标题和用量不上线。 +- **连接拥有的生命期**:一个连接会释放其所有会话;尚未实现每会话关闭。 diff --git a/packages/bash/README.i18n.yaml b/packages/bash/README.i18n.yaml new file mode 100644 index 0000000000..6f9db27161 --- /dev/null +++ b/packages/bash/README.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 +README.md: 08b36270800cdd79c82d6781bbfb2e12e2dc2060 +README.zh.md: a98506a6cdf41e5b298b40e1b8e1faf0c4c917d2 diff --git a/packages/bash/README.md b/packages/bash/README.md index 2e2bb5692a..08b3627080 100644 --- a/packages/bash/README.md +++ b/packages/bash/README.md @@ -1,5 +1,7 @@ # bash/ — bash capability family +English | [中文](README.zh.md) + The canonical three-package capability seam (see [capability seams](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)): an abstract executor interface, concrete implementations, and the model-facing tool that consumes it. All **product** packages. | Package | Role | ctx key | diff --git a/packages/bash/README.zh.md b/packages/bash/README.zh.md new file mode 100644 index 0000000000..a98506a6cd --- /dev/null +++ b/packages/bash/README.zh.md @@ -0,0 +1,14 @@ +# bash/:bash 能力家族 + +[English](README.md) | 中文 + +规范的三包能力 seam(见[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)):抽象执行器接口、具体实现,以及消费该接口的面向模型工具。这些全是**产品** 包。 + +| 包 | 职责 | ctx key | +|---|---|---| +| `bash/` | 抽象 bash 执行器 seam(接口 + 词汇;沙箱结果事实携带 [`sandbox/`](../sandbox/README.md) seam 的模式/强制执行词汇) | `ctx.bash` | +| `bash-local/` | 本地子进程 `BashExecutor` 实现 | (注册 `ctx.bash`) | +| `bash-sandbox/` | 消费沙箱的 `BashExecutor`(通过 `ctx.sandbox` 包装每个命令 argv,标记拒绝/强制执行事实;扩展 `bash-local` 的机制) | (注册 `ctx.bash`) | +| `tool-bash/` | 面向模型的 `bash` schema;后台进程注册到通用 [`tasks/`](../tasks/README.md) 运行时 | (注册到 `ctx.tools`) | + +接口位于 `bash/bash/`。以 `bash-sandbox` 替换 `bash-local`,同时不改动接口或工具,正是这种拆分存在的意义:叶级 `cordis.yml` 选择一个执行器配置项;受限实现还需选择一个 `ctx.sandbox` 提供方配置项(见 [acp-agent 示例的默认组合](../../examples/acp-agent/))。 diff --git a/packages/bash/bash-local/README.i18n.yaml b/packages/bash/bash-local/README.i18n.yaml new file mode 100644 index 0000000000..c7e9587289 --- /dev/null +++ b/packages/bash/bash-local/README.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 +README.md: 1668f33e8acf6d749d4d3753478c12d48a19ac3c +README.zh.md: 0e0a4ad41b532e39f6f2470aa981a08b6d6230c1 diff --git a/packages/bash/bash-local/README.md b/packages/bash/bash-local/README.md index 5d99161fc0..1668f33e8a 100644 --- a/packages/bash/bash-local/README.md +++ b/packages/bash/bash-local/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-bash-local +English | [中文](README.zh.md) + Local-subprocess implementation of the `@deepseek-ai/dsh-bash` executor seam: `LocalBashExecutor` spawns `bash -c ` per call in its own process group, collects bounded output with size-limited full-stream spill files, and escalates kills SIGTERM→SIGKILL across the whole group. The package root exports the default and named `LocalBashExecutor` plugin plus its `Config`; subprocess plumbing stays internal to the implementation package. diff --git a/packages/bash/bash-local/README.zh.md b/packages/bash/bash-local/README.zh.md new file mode 100644 index 0000000000..0e0a4ad41b --- /dev/null +++ b/packages/bash/bash-local/README.zh.md @@ -0,0 +1,49 @@ +# @deepseek-ai/dsh-bash-local + +[English](README.md) | 中文 + +`@deepseek-ai/dsh-bash` 执行器 seam 的本地子进程实现:`LocalBashExecutor` 每次调用都会在独立进程组中 spawn `bash -c `,收集有界输出,并用限制大小的完整流 spill 文件保留超量内容,随后针对整个进程组从 SIGTERM 逐步升级为 SIGKILL。 + +包根目录导出默认与具名的 `LocalBashExecutor` 插件及其 `Config`;子进程管道细节保留在该实现包内部。 + +## 配置 + +```yaml +- id: bash + name: '@deepseek-ai/dsh-bash-local' + config: + cwd: /path/to/workspace # default: process.cwd() + timeoutMs: 120000 # default foreground timeout + maxTimeoutMs: 600000 # cap for per-call overrides + maxOutputBytes: 64000 # per-stream in-memory cap; overflow spills to disk + maxSpillBytes: 67108864 # per-stream full-output spill cap + graceMs: 3000 # kill escalation and post-exit pipe-drain grace +``` + +## 行为(以及设计来源) + +设计时调研了 Claude Code、OpenCode、Codex 和 pi 的 bash 工具,主要取舍如下: + +- **每次调用都 spawn,不保留 shell 状态**:每次调用都启动新的非登录 `bash -c`(行为确定,不读取 rc 文件)。调研的四种工具均会每次调用单独 spawn。`XXX(stateful-shell)` 位于 `src/run.ts`,记录了两种已验证的有状态设计(Claude Code 仅持久化 cwd;Codex 使用 PTY exec 会话),供真实工作流程需要时采用。 +- **使用逐步升级终止整个进程组**:子进程使用 `detached` spawn(拥有独立进程组);终止时先向该组发送 SIGTERM,经过 `graceMs` 宽限期后再发送 SIGKILL(默认 3 秒,沿用 OpenCode 的升级策略;管道与子 shell 会随父进程一起结束)。主 shell 退出后,继承的 stdout/stderr 管道也只获得同样有界的排空宽限期,因此存活的后代进程无法无限期地阻止命令结束。系统会容忍 ESRCH;脱离该组重新挂载的 daemon 仍可能存活,这与调研工具的局限相同。 +- **保留尾部的截断 + 有界 spill 文件**:输出超过 `maxOutputBytes` 后,内存中保留尾部(错误/结果通常聚集在末尾,沿用 pi/OpenCode 的理由),同时将完整流追加到临时文件,并在可用时报告该路径。前台 `BashExecRequest.stdoutMaxBytes` 可为某个受信任调用方提高单次 stdout 捕获预算;stderr 和后台任务仍使用 `maxOutputBytes`。某个流大于 `maxSpillBytes` 时,会丢弃已不完整的 spill,仅返回带截断标记的尾部。如果最终关闭 spill 时报告延迟写回失败,执行器同样不会公布路径,以免声称存在不完整的文件。 +- **适合模型的环境变量 + 凭证清理**:以 `process.env` 为基础,移除形似凭证的变量(`*KEY*`/`*SECRET*`/`*TOKEN*`)和所有环境中的 `DSH_*` 名称,再设置 `NO_COLOR=1 TERM=dumb PAGER=cat GIT_PAGER=cat`(Codex 硬编码的集合),防止分页器与 ANSI 颜色破坏结果。spec 的普通 `env` 在清理后合并,但会拒绝 `DSH_*`;受管 `dshEnv` 会拒绝普通名称并最后合并,防止遗留嵌套 harness 身份。提供的 stdin 会被写入后关闭;否则 fd 0 指向 `/dev/null`。详见 [stdin/env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md) 与 [受管环境 Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md)。 +- **后台进程**:`start()` 会立即返回实时 `BashProcess` 句柄,不应用超时(Claude Code 在转为后台时会解除超时);句柄的 `readOutput()` 使用全流字节偏移量进行增量读取;dispose 会终止每个运行中的进程并等待其退出。所有具有任务形态的事项(id、所有权、轮询、通知)都属于通用 [`ctx.tasks` 运行时](../../tasks/tasks/README.md),工具层会在其中注册该句柄;本执行器不会接触会话或注册表。 + +## 模型体验 + +通过 `dsh-tool-bash` 间接影响;该工具会渲染此执行器有界的 stdout/stderr 尾部、后台进程增量、spill 文件路径与基础设施失败。 + +#### KV Cache 影响 + +不会直接失效;请求前缀变更由具名消费方负责。 + +## 已知限制与暂缓事项 + +- **自身不受约束**:此执行器始终以 harness 进程的权限运行命令;需要限制的部署可以组合 [`dsh-bash-sandbox`](../bash-sandbox/README.md),每次调用的 allow/deny/ask 策略则属于 `tools/pre-execute`。 +- **没有持久 shell 或 PTY**:每次调用都启动新的非登录 `bash -c`;仅持久化 cwd 与交互式终端会话均继续暂缓,直到真实工作流程需要它们。 +- **仅支持 POSIX**:`bash` 二进制、独立进程组、进程组终止以及 SIGTERM→SIGKILL 升级都已硬编码;不支持 Windows。 +- **凭证清理依赖名称启发式规则**:只匹配 `*KEY*`/`*SECRET*`/`*TOKEN*`;名称不同的 secret(例如 `*PASSWORD*`)会继续传递,对误删变量引入白名单属于已记录的后续工作。 +- **不会删除已完成的 spill 文件**:有界的完整输出恢复文件(以及每个进程的私有 spill 目录)会在 OS tmpdir 下累积,直到外部机制进行清理;超大的不完整 spill 会被丢弃并立即尝试删除,但清理失败可能留下一个有界文件。 + +原始进程处理位于 `src/run.ts`;`src/index.ts` 负责服务接线。 diff --git a/packages/bash/bash-sandbox/README.i18n.yaml b/packages/bash/bash-sandbox/README.i18n.yaml new file mode 100644 index 0000000000..86168916fe --- /dev/null +++ b/packages/bash/bash-sandbox/README.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 +README.md: ca77a9c626784b29145712535d69de4afbd3a697 +README.zh.md: c1a65ead539ef3930d70d27f2b176a5346daded3 diff --git a/packages/bash/bash-sandbox/README.md b/packages/bash/bash-sandbox/README.md index 93e0c9e6f2..ca77a9c626 100644 --- a/packages/bash/bash-sandbox/README.md +++ b/packages/bash/bash-sandbox/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-bash-sandbox +English | [中文](README.zh.md) + Sandbox-consuming implementation of the [`@deepseek-ai/dsh-bash`](../bash/) executor seam. Load it **instead of** `@deepseek-ai/dsh-bash-local`, together with a [`ctx.sandbox`](../../sandbox/sandbox/) provider (e.g. [`@deepseek-ai/dsh-sandbox-local`](../../sandbox/sandbox-local/)) and a [`ctx.sandboxPolicy`](../../sandbox/sandbox-policy/) (which owns the default mode + workspace root, shared with the sandboxed filesystem) — no alternate tool plugin is needed; `dsh-tool-bash` detects the executor's `sandboxMode` capability and adds the escalation fields. The package root exports the default and named `SandboxBashExecutor` plugin plus its `Config`; quoting and result-classification helpers stay internal. diff --git a/packages/bash/bash-sandbox/README.zh.md b/packages/bash/bash-sandbox/README.zh.md new file mode 100644 index 0000000000..c1a65ead53 --- /dev/null +++ b/packages/bash/bash-sandbox/README.zh.md @@ -0,0 +1,90 @@ +# @deepseek-ai/dsh-bash-sandbox + +[English](README.md) | 中文 + +消费 [`@deepseek-ai/dsh-bash`](../bash/) 执行器 seam 的沙箱实现。加载它时,应**用它替代** `@deepseek-ai/dsh-bash-local`,并同时加载 [`ctx.sandbox`](../../sandbox/sandbox/) 提供方(例如 [`@deepseek-ai/dsh-sandbox-local`](../../sandbox/sandbox-local/))及 [`ctx.sandboxPolicy`](../../sandbox/sandbox-policy/);后者拥有默认模式 + 工作区根目录,并与受沙箱约束的文件系统共享这些设置。无需使用替代工具插件;`dsh-tool-bash` 会检测执行器的 `sandboxMode` 能力并添加升权字段。 + +包根目录导出默认与具名的 `SandboxBashExecutor` 插件及其 `Config`;引号处理与结果分类 helper 保留在内部。 + +每条命令的限制方式都是:把本执行器即将 spawn 的精确 `['bash', '-c', command]` argv 交给提供方,再 spawn 其返回的(已包装)argv。由哪种平台 runner 执行限制,以及是否有 runner 可用(必须快速失败并返回结构化 `SANDBOX_UNAVAILABLE` 错误,绝不能静默无约束运行),属于提供方职责;本包只拥有 bash 侧。 + +| 模式 | 文件影响 | +|---|---| +| `read-only`(默认) | 任何位置都不可写(在 `/dev` 中只有 `/dev/null` 节点可写,因此 `>/dev/null` 仍可正常工作) | +| `workspace-write` | 只能写入 `workspaceRoot` + `/tmp`(在 bwrap 下为临时目录,在 Landlock 下为宿主 `/tmp`,在 Seatbelt 下为 `/private/tmp` 加每用户临时目录) | +| `danger-full-access` | 不作限制;绝不咨询提供方。前台结果携带 `sandbox: { mode, denied: false }`;后台进程句柄不携带沙箱事实。 | + +语义: + +- **拒绝是结果事实。** 如果一次失败运行的 stderr 包含所选后端自身的拒绝方言,即提供方在每次包装时加上的特征(bwrap 下的 EROFS 文本、Landlock 下的 EACCES、Seatbelt 下的 EPERM),则结果报告 `BashRunResult.sandbox.denied: true`(从已收集的 stderr 尾部进行保守分类)。每次受限制运行还会携带执行时模式(`result.sandbox.mode`)与提供方强制执行完整性(`result.sandbox.enforcement`:`full`,或在较旧 Landlock ABI 上为 `partial`)。 +- **Runner 失败是沙箱失败,绝不是命令失败。** 前台执行会抛出 `SANDBOX_UNAVAILABLE`;已结算的后台进程会标记 `process.sandbox.runnerFailed`,bash 产生方通过通用 `task_output` 渲染它。spawn 失败也会经过结算,因此受限制的后台句柄会保留自身的模式/强制执行事实,并释放每进程计数。 +- **部署回退,每次调用策略。** [`ctx.sandboxPolicy`](../../sandbox/sandbox-policy/) 为每次工具调用解析完整的 `SandboxExecutionPolicy`:调用会话提供自身的模式覆盖与不可变 cwd 根目录,部署配置则为无 agent 调用提供回退。已批准的升权只更改该策略的模式,会话根目录仍然附着其上。`resolve()` 把策略带入 spec,因此来自不同项目的重叠命令会在各自的根目录与模式下运行、分类和报告。能力事实 `ctx.bash.sandboxMode` 报告已配置的默认值,因此工具层只在装载该执行器时才公布升权。模型只能通过结果事实了解沙箱:静态 bash 工具描述会解释拒绝标记,系统提示词中不会声明当前模式。 +- **只限制文件影响。** 设计上不限制网络与进程可见性:模式词汇不会声称覆盖后端未强制执行的范围。 +- 进程机制(spawn、进程组终止、输出收集/spill、后台句柄、凭证清理)继承自 [`dsh-bash-local`](../bash-local/);runner 选择位于 [`dsh-sandbox-local`](../../sandbox/sandbox-local/)。 + +seam 上仅拒绝:拒绝是一项已报告事实,本执行器绝不自行协商权限。批准问题位于工具层(`dsh-tool-bash`),由它驱动本包遵守的覆盖。 + +```yaml +- id: sandbox + name: '@deepseek-ai/dsh-sandbox-local' +- id: sandbox-policy + name: '@deepseek-ai/dsh-sandbox-policy' + config: + mode: read-only + workspaceRoot: !!js process.cwd() # fallback for calls without a session cwd +- id: bash + name: '@deepseek-ai/dsh-bash-sandbox' +``` + +无密钥消费方集成证明是 `tests/bwrap.e2e.ts`、`tests/landlock.e2e.ts` 和 `tests/seatbelt.e2e.ts`(通过 `ctx.bash` 驱动真实提供方 + 真实 runner,在真实世界验证,并在相应 runner 缺失时各自自行跳过)。agent-spine e2e 还会在一个 Cordis 上下文中驱动两个并发会话,并证明每个真实 bash 工具调用只能写入自身项目。可运行 demo 见 [acp-agent 示例的默认组合](../../../examples/acp-agent/)。 + +## 模型体验 + +### 间接的 Bash 工具 schema + +#### 模型看到的内容 + +基线是生成的 [`dsh-tool-bash` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-bash)。通过公布一个执行限制的 `sandboxMode`,此后端会为 `bash` 增加 `sandbox_permissions`,其 enum 为 `workspace-write` | `danger-full-access`,并增加 `justification`。后端不添加提示词文本,会话的有效模式仍不会声明。 + +#### Token 影响 + +在 `bash` 可见的请求上增加少量固定 schema;模式切换不增加上下文 token。 + +#### KV Cache 影响 + +执行器持续公布相同沙箱能力时,前缀保持稳定。更改这些能力会改变 `bash` schema,可能使从该定义起的复用失效;每会话模式切换不会导致失效。 + +### 间接的 Bash 工具结果 + +#### 模型看到的内容 + +在普通有界输出之后,被拒绝的调用会精确追加 `[sandbox: file access denied under mode]`。当升权可用时,接下来精确追加 `[sandbox: escalation available — retry this exact command once with sandbox_permissions (the narrowest wider mode that suffices) + justification; the approval prompt asks the user]`。已结算的后台 runner 失败则追加 `[sandbox: the sandbox runner itself failed under mode — the command did not run; this is a sandbox problem, not a command failure]`。 + +#### Token 影响 + +除普通输出外,正常允许的运行不会增加 token。拒绝或失败会增加上述有条件标记,并保留到压缩。 + +#### KV Cache 影响 + +仅追加;新可见内容位于可复用请求前缀之后,不会使现有 KV-cache 配置项失效。 + +### 间接的 Bash 工具错误 + +#### 模型看到的内容 + +如果没有 runner 能强制执行受限模式,前台调用会传播 [`SANDBOX_UNAVAILABLE` 错误;它由 `dsh-sandbox` 持有](../../sandbox/sandbox/README.md#confinement-error-indirectly)。如果 runner 在执行时失败,此后端会提供第一行 stderr 作为详细信息。 + +#### Token 影响 + +该次调用可见的是有条件错误文本,并保留在历史记录中直到压缩。 + +#### KV Cache 影响 + +仅追加;新可见内容位于可复用请求前缀之后,不会使现有 KV-cache 配置项失效。 + +## 已知限制与暂缓事项 + +- **限制只覆盖文件影响**:网络访问与进程可见性不变,因此这些模式不是通用安全沙箱。 +- **拒绝从失败命令的 stderr 推断**:后端特征使该推断可跨平台使用,但匹配的应用错误可能被分类为拒绝,也可能遗漏未出现在保留尾部中的拒绝。 +- **后台 runner 失败没有即时错误通道**:它记录在已结算进程上,并在调用方使用 `task_output` 读取通用任务时呈现。 +- **`danger-full-access` 有意绕过 `ctx.sandbox`**:它是显式无约束模式,不是更宽的沙箱 profile。 diff --git a/packages/bash/bash/README.i18n.yaml b/packages/bash/bash/README.i18n.yaml new file mode 100644 index 0000000000..f32efb60a0 --- /dev/null +++ b/packages/bash/bash/README.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 +README.md: b4ee66a1fa2696254a1f2f411b7db5d3190f8370 +README.zh.md: 151d4bd7ab257234584b9008c96e6356d7e39351 diff --git a/packages/bash/bash/README.md b/packages/bash/bash/README.md index 73fbb4fb3e..b4ee66a1fa 100644 --- a/packages/bash/bash/README.md +++ b/packages/bash/bash/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-bash +English | [中文](README.zh.md) + The **bash executor seam**: an abstract `BashExecutor` service (`ctx.bash`) defining WHAT a bash backend does — run foreground commands and start background processes — without saying HOW. Task ids, ownership, collection, cancellation, and notices belong to the generic `ctx.tasks` runtime. This package is the interface quarter of the bash capability, split so each concern can evolve (and be swapped) independently: diff --git a/packages/bash/bash/README.zh.md b/packages/bash/bash/README.zh.md new file mode 100644 index 0000000000..151d4bd7ab --- /dev/null +++ b/packages/bash/bash/README.zh.md @@ -0,0 +1,49 @@ +# @deepseek-ai/dsh-bash + +[English](README.md) | 中文 + +**bash 执行器 seam**:抽象 `BashExecutor` 服务(`ctx.bash`)定义 bash 后端做什么,即运行前台命令与启动后台进程,但不规定如何实现。task id、所有权、收集、取消与通知属于通用 `ctx.tasks` 运行时。 + +本包是 bash 能力中负责接口的四分之一,各项职责因此可以独立演进(和替换): + +| 包 | 职责 | +|---|---| +| `@deepseek-ai/dsh-bash`(本包) | 接口:抽象服务 + 词汇类型 | +| `@deepseek-ai/dsh-bash-local` | 实现:本地子进程 | +| `@deepseek-ai/dsh-bash-sandbox` | 实现:沿用 `dsh-bash-local` 的机制,但通过 [`ctx.sandbox`](../../sandbox/sandbox/) 限制每次 spawn,并将拒绝报告为结果事实 | +| `@deepseek-ai/dsh-tool-bash` | 基于 `ctx.bash`、面向模型的工具 schema | + +该拆分与 LLM seam(`LlmService`/`LlmAdapter`)及 agent 工具调研结果一致:pi 将执行隐藏在 `BashOperations` 接口之后(本地 shell/SSH/VM 后端),Codex 则隐藏在 exec-server 协议之后。`dsh-bash-sandbox` 正是这种替换的实际应用:沙箱执行器位于同一接口之后;消费方检测其 `sandboxMode` 能力并添加升权字段,无需导入实现。容器化或远程执行器也可以同样接入。 + +## 服务 API(`ctx.bash`) + +| 成员 | 语义 | +|---|---| +| `run(spec)` | 前台执行。命令完成时 resolve。**只会因基础设施失败而 reject**(工作目录不可用、shell 缺失、信号已在调用前中止);非零退出、超时终止和中止终止都会 resolve 为描述性 `BashRunResult`。 | +| `start(spec)` | 后台执行。立即返回不含任务语义的 `BashProcess` 句柄;**不应用超时**。调用方可以将其适配到 `ctx.tasks`。 | +| `sandboxMode` | 工具层的能力事实:沙箱执行器用于限制执行的默认模式(基类中为 `undefined`,即「此执行器不使用沙箱」)。`dsh-tool-bash` 会在注册时读取它,仅当组合确实支持升权字段时才公布这些字段。 | +| `BashProcess.readOutput()` | **增量** 读取输出:连续读取绝不会重复交付。因缓冲区边界丢失数据的读取会标记 `lossy`,并指向完整流 spill 文件。 | +| `BashProcess.kill()` | 终止进程组。如果进程已结束,返回 `false`。 | + +实现会继承 `BashExecutor` 并实现抽象方法。dispose 必须终止每个运行中的进程并等待其退出,详见 HMR 安全测试。 + +## 词汇 + +`BashExecRequest`(command、workdir?、timeoutMs?、stdoutMaxBytes?、signal?、stdin?、env?、dshEnv?、sandboxPolicy?)在执行前解析为 `BashExecSpec`(command、workdir、timeoutMs、stdoutMaxBytes、signal?、stdin?、env?、dshEnv?、sandboxPolicy)。`stdoutMaxBytes` 是受信任前台运行的捕获预算,用于必须解析完整有界 stdout 的消费方;面向模型的 bash 工具不公开该字段。`sandboxPolicy` 在请求上可选,在已解析 spec 上必填但可为 null:它携带完整的每次调用模式与工作区根目录。沙箱工具路径通过 `ctx.sandboxPolicy` 从调用会话解析它;沙箱执行器的直接调用方回退到部署策略,非沙箱执行器则携带该字段但不作限制。 + +每会话沙箱模式覆盖词汇(`'sandbox/mode'` 事件、`effectiveSandboxMode(events)` fold 以及 `setSandboxMode(session, mode)` 写入路径)不位于此处。它是所有强制执行家族共享的策略状态,属于 [`@deepseek-ai/dsh-sandbox-policy`](../../sandbox/sandbox-policy/)。`run()` 返回 `BashRunResult`;`start()` 返回 `BashProcess`,其增量读取与终止方法由 `dsh-tool-bash` 适配为通用任务注册。沙箱执行器会在前台结果与已结算进程句柄上标记 `BashSandboxInfo`。详见 `src/types.ts` 与 [core-data-structures/bash.md](../../../docs/core-data-structures/bash.md)。 + +`stdin` 与普通 `env` 由同进程插件(hooks 桥接、原生插件)设置,用于向 hook 命令提供其 JSON payload 和 `CLAUDE_PROJECT_DIR`/`CLAUDE_PLUGIN_ROOT` 值。`dshEnv` 是受类型限制、仅允许受管 key 的独立受信任 overlay;导出的 `DSH_ENV_PREFIX` 是该 namespace、其 `DshEnvironmentKey` 模板类型、执行器清理、注册表验证、派生内置名称与模型指引的单一真源。模型 bash 使用 `ctx.bashEnv` 收集的当前快照。实现会移除继承的受管 key,拒绝普通 `env` 中的这些名称,再合并 `dshEnv`,因此省略的当前事实不会回退到陈旧环境状态。面向模型的工具不公开任何一个字段。这三者在已解析 spec 上仍然可选;缺失表示没有输入/overlay。详见 [bash-stdin-env Agent Note](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md) 与 [会话环境 Agent Note](../../../.agents/notes/implemented/feature/2026-07-10-agent-session-identity-and-log-location.md)。 + +## 模型体验 + +通过 `dsh-tool-bash` 间接影响;该工具会将执行器输出与沙箱事实转为指引和保留的工具结果 token。 + +#### KV Cache 影响 + +不会直接失效;请求前缀变更由具名消费方负责。 + +## 已知限制与暂缓事项 + +- **没有交互式输入词汇**:`stdin` 只会在 spawn 时写入一次并关闭;seam 不提供向运行中任务继续输入的通道,也没有 PTY 会话概念。 +- **前台超时始终由执行器拥有**:seam 上的调用方拥有 deadline 模式已由 [工具调用超时策略 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md) 明确暂缓。 diff --git a/packages/bash/tool-bash/README.i18n.yaml b/packages/bash/tool-bash/README.i18n.yaml new file mode 100644 index 0000000000..a529b56b56 --- /dev/null +++ b/packages/bash/tool-bash/README.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 +README.md: 965ae25a5e29a4f767adfcb73e4a77f1060e4b46 +README.zh.md: 60be5c5ca5624719f5ca651a78b6ba56f3f3df06 diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index e58145ee67..965ae25a5e 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-tool-bash +English | [中文](README.zh.md) + The model-facing `bash` tool registered over the `ctx.bash` executor seam. Foreground execution stays behind that seam; a background process handle is registered with the generic `ctx.tasks` runtime and controlled through `task_output`, `task_list`, and `task_kill` from `@deepseek-ai/dsh-tool-tasks`. Requires a loaded executor implementation (e.g. `@deepseek-ai/dsh-bash-local`); the plugin stays pending until `ctx.bash` exists (`inject: ['tools', 'bash', 'systemPrompt']`). diff --git a/packages/bash/tool-bash/README.zh.md b/packages/bash/tool-bash/README.zh.md new file mode 100644 index 0000000000..60be5c5ca5 --- /dev/null +++ b/packages/bash/tool-bash/README.zh.md @@ -0,0 +1,158 @@ +# @deepseek-ai/dsh-tool-bash + +[English](README.md) | 中文 + +模型侧 `bash` 工具,注册在 `ctx.bash` 执行器 seam 上。前台执行始终位于该 seam 之后;后台进程句柄会注册到通用 `ctx.tasks` 运行时,并通过 `task_output`、`task_list` 和 `task_kill` 控制;这些工具由 `@deepseek-ai/dsh-tool-tasks` 提供。 + +需要加载执行器实现(例如 `@deepseek-ai/dsh-bash-local`);在 `ctx.bash` 可用之前,插件会保持等待状态(`inject: ['tools', 'bash', 'systemPrompt']`)。 + +包(package)根只公开 Cordis 插件契约(`name`、`inject`、`Config`、`apply`);结果渲染和后台进程适配仍是实现细节,由同包测试覆盖。 + +插件还会提供 `tool:bash` 提示词段落(顺序 105):检查每个结果中的 `[exit code: N]` 标记,发现失败时先调查原因再继续。 + +## 工具 + +### `bash` + +| 参数 | 类型 | 说明 | +|---|---|---| +| `command` | string(必填) | 通过 `bash -c` 运行。调用之间不保留状态;请使用 `workdir`,不要使用 `cd`。 | +| `description` | string(必填) | 用一行主动语态概述命令(5~10 个词),仅用于 UI/日志显示,不影响执行。 | +| `timeoutMs` | number | 以毫秒为单位覆盖超时时间。执行器会应用其配置的默认值和上限。 | +| `workdir` | string | 本次调用的工作目录。默认为调用方 agent(智能体)会话 cwd 的文件系统标识(`session.header.cwd`),使每个会话都在自己的工作区中运行;相对 `workdir` 也以同一标识为基准解析。 | +| `run_in_background` | boolean | 立即返回 task id;不应用超时。 | +| `sandbox_permissions` | string enum | 仅当已挂载的执行器启用沙箱时才会公开(`ctx.bash.sandboxMode` 报告一个具有限制作用的默认值):被拒命令所需的更宽模式,取自封闭的目标词汇 `workspace-write`/`danger-full-access`(绝不能缩减为执行器默认值;有效模式按会话确定,执行时会基于它检查是否严格拓宽,未拓宽的请求直接失败,不会向任何人发起提示)。 | +| `justification` | string | 必须与 `sandbox_permissions` 一同提供(缺少任一项都会产生验证错误):用一句话向用户解释此命令为何需要这项更宽权限。 | + +执行前,`command`、`workdir` 和 `timeoutMs` 会通过 `ctx.bash.resolve()` 依据执行器配置默认值完成解析,因此执行器 seam(`BashExecSpec`)收到显式的 `workdir`/`timeoutMs` 值。工具层会根据调用方 agent 的 `session.header.cwd` 应用工作目录默认值,然后才调用 `resolve()`:由于 N 个会话共享一个执行器,逐会话 cwd 必须来自 `exec.agent`;只有无法取得会话 cwd 时,执行器才回退到自身配置/`process.cwd()`。存在沙箱策略时,工具会复用已经规范化的 `workspaceRoot` 作为工作目录基准,防止限制逻辑与进程启动过程对同一个会话路径拼写产生不同解析结果。 + +### 托管 shell 环境 + +每次模型发起的前台或后台 bash 调用都会收到新收集的一组可信 `DSH_*` 环境变量。`DSH_HOME` 是由 [`@deepseek-ai/dsh-paths`](../../util/paths/README.md) 解析出的 Harness home 绝对路径(依次采用 `dshHome` 配置、环境中的 `$DSH_HOME`、`~/.dsh`),`DSH_SHELL=1` 则标识受托管的子进程。Agent 调用还会收到 `DSH_SESSION_ID=agent.session.header.id`;当活跃的持久化 seam 找到 JSONL 产物时,也会收到 `DSH_SESSION_JSONL=`。JSONL 路径只是位置提示:首次 flush 前它可能尚不存在,也可能不包含当前缓冲的轮次,并且它不是授权凭据。 + +`ctx.bashEnv` 持有收集过程。其他插件可以注册具有 effect 作用域的贡献方,提供稳定名称、已声明的键/说明以及 `resolve(execution: ToolExecution)`;重复持有或运行时返回未声明的键会快速失败,而 `list()` 无需执行提供方即可列举声明。Harness 内置项保留 `DSH_HOME`、`DSH_SHELL` 和 `DSH_SESSION_ID`;tool-bash 的持久化转换器持有 `DSH_SESSION_JSONL`,其值来自后端无关的 `sessionPersistence.locate()` seam。 + +```ts +import type { Context } from 'cordis' +import type {} from '@deepseek-ai/dsh-tool-bash' + +export const inject = ['bashEnv'] + +export function apply(ctx: Context): void { + ctx.bashEnv.register({ + name: 'deployment-region', + variables: { DSH_DEPLOYMENT_REGION: { description: 'Current deployment region.' } }, + resolve: execution => execution.agent === undefined ? {} : { DSH_DEPLOYMENT_REGION: 'cn-north' }, + }) +} +``` + +overlay 根据当前 `ToolExecution` 计算,并通过专用的 `BashExecRequest.dshEnv` 通道传递。本地执行器会先删除继承的所有 `DSH_*`,再合并该快照,因此嵌套 harness 和并发的父/子 agent 不会泄漏陈旧身份。它绝不会修改 `process.env`。工具说明只教授通用 `$DSH_*` 约定,不会点名持久化专用变量,也不会添加永久的系统提示词段落。 + +结果文本依次包含 stdout、可选的 `[stderr]` 段落和适用的沙箱拒绝、超时、信号、退出代码及截断标记。超时与最终退出状态分别报告;非零退出仍是由模型解释的结果,不会成为 `isError`。截断结果会链接安全的完整 spill 文件,或报告文件不可用。只有 spawn 错误和中止等基础设施故障才会产生 `isError`。 + +已完成前台进程的规范成功值为 `{ kind: 'foreground', ...BashRunResult }`,已发布任务则为 `{ kind: 'background', taskId }`。Native renderer 保留上述文本,包括精确的 `started background task `;程序化消费方使用带类型字段,无需解析这些字符串。执行器的流上限仍是 `BashRunResult` 的采集限制,并携带其 spill 路径。 + +当 `run_in_background` 为 true 时,此插件会在 spawn 前预检 `ctx.tasks.start()`,把调用方 agent 注册为持有者,并将返回的 `BashProcess` 句柄适配为通用的取消/完成/增量输出钩子。任务运行时持有 id、跨会话隔离、完成通知、等待和 dispose(资源释放)清理;此插件只把 bash 退出/沙箱事实映射为任务输出和结果详情。`enableRunInBackground: false` 会移除该参数,并在执行时拒绝强制后台调用。 + +## UI 展示 + +工具持有自己的 `presentCall`/`presentResult` 渲染意图。前台调用是终端卡片,包含命令、说明、cwd、原始输出和解析后的退出状态。后台启动只返回 task id,因此使用通用执行卡片;通用 `task_*` 工具持有各自的卡片。这些 presenter 是纯函数,可安全回放。 + +## 工具仅使用具名参数构建请求 + +`BashExecRequest` seam 携带可选的 `stdoutMaxBytes`、`stdin`、普通 `env` 和托管 `dshEnv`,供可信进程内插件及此工具的环境注册表使用。模型侧工具不公开 `stdoutMaxBytes`、`stdin` 或 `env`:它使用具名的命令/工作目录/超时/信号/沙箱字段,加上从注册表收集的 `dshEnv` 来构建请求。额外模型键会被忽略,无法替换托管值。Shell 语法可以提供等价的命令级行为,而本地执行器会清除环境中的凭据和陈旧 `DSH_*` 值。参见 [stdin/env Agent Note(agent 决策记录)](../../../.agents/notes/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md)。 + +## 权限与升权 + +除非启用沙箱的执行器([`dsh-bash-sandbox`](../bash-sandbox/))限制命令,否则命令以执行器的完整权限运行。仅拒绝型沙箱会把拒绝作为结果事实报告,并在此渲染为拒绝标记;逐调用的允许/拒绝/询问策略由 `tools/pre-execute` waterfall(瀑布式事件)负责(参见 docs/architecture.md)。 + +需要升权的 bash 调用会在执行前解析 `ctx.approval`。`allowed-once` 只对该次调用应用请求模式;审批被拒、取消、不可用或缺少审批上下文时,命令完全不会执行,并返回不同的错误。发生真实拒绝后,模型可以在同一轮次中使用满足需要的最窄模式和理由重试同一命令一次;审批提示本身就是征求同意的步骤。升权绝不能预先推测,禁用或拒绝审批即为最终结果。其理由由 [沙箱 Agent Note](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md) 持有。 + +## 逐会话模式切换 + +对于启用沙箱的执行器,每次调用依次按单次升权、会话覆盖、执行器默认值解析模式。未启用沙箱以及没有 agent 的调用不携带会话覆盖。提示词和切换通知均不公布当前常驻模式;拒绝结果会在边界相关时报告有效模式。参见 [`dsh-bash` 整合](../bash/README.md)和[沙箱切换契约](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md)。 + +## 模型体验 + +### 系统提示词 + +#### 模型看到的内容 + +此插件注册作用域内的每个请求都包含下方 bash 指引。启用沙箱的执行器不会添加模式声明或切换通知。作用域工具限制可以隐藏 schema,但不会移除这个独立注册的段落。 + +##### Bash 指引 + +```markdown +Check the [exit code: N] marker on every bash result; investigate failures before moving on. +``` + +#### Token 影响 + +插件活跃期间,每个请求都会产生少量固定输入开销,不受沙箱模式或模式切换影响。 + +#### KV Cache 影响 + +只要注册作用域和提示词文本不变,前缀即可稳定复用。插件激活或 dispose 可能从此提示词段落开始使复用失效;沙箱模式切换不会。 + +### 工具 schema + +#### 模型看到的内容 + +模型会看到生成的 [`bash` schema](../../../docs/tool-catalog.md#deepseek-aidsh-tool-bash)。仅当此生产方启用 `run_in_background` 时,该字段才会出现;仅当已挂载执行器声明支持沙箱时,`sandbox_permissions` 和 `justification` 才会出现。Agent 作用域的工具限制可以移除该 agent 的定义。 + +#### Token 影响 + +工具可见的每个请求都会产生固定 schema 开销;沙箱支持会增加升权字段及其条件说明段落。 + +#### KV Cache 影响 + +只要可见性、后台支持和执行器沙箱功能保持不变,前缀即可稳定复用。限制、配置或执行器发生变化时,可能从首个变化的工具定义开始使复用失效。 + +### 前台结果 + +#### 模型看到的内容 + +renderer 先输出依数据而定的 stdout 尾部,再输出可选的 `[stderr]` 和 stderr 尾部。没有输出时,它会精确输出 `(no output)`。条件行精确为 `[output truncated; full output: ]`、`[sandbox: file access denied under mode]`、`[timed out after ms]`、`[killed by signal: ]` 和 `[exit code: ]`;沙箱升权与 runner 故障行原文列于 [`dsh-bash-sandbox`](../bash-sandbox/README.md)。 + +#### Token 影响 + +调用前结果 token 为零。每条流的输出有界,每个已输出行则会保留在历史中,直至压缩(compaction)。 + +#### KV Cache 影响 + +仅追加;新可见内容位于可复用请求前缀之后,不会使现有 KV-cache 条目失效。 + +### 后台任务上下文与结果 + +#### 模型看到的内容 + +启动会精确返回 `started background task `。此生产方会向通用任务运行时提供增量进程输出、可选的 `[some output was dropped from memory; full output: ]`、沙箱事实,以及 `exit code: ` 或 `signal: ` 等终止详情。[`dsh-tool-tasks`](../../tasks/tool-tasks/README.md) 持有模型可见的状态行、完成通知、列表和取消响应。 + +#### Token 影响 + +启动确认很短并会保留;收集到的输出依数据而定,并受执行器流缓冲区限制。消费式读取不会重复先前输出。 + +#### KV Cache 影响 + +仅追加;新可见内容位于可复用请求前缀之后,不会使现有 KV-cache 条目失效。 + +### 工具错误 + +#### 模型看到的内容 + +验证和策略失败统一为 `Error: `。此包的稳定消息包括 `invalid command: expected a non-empty string`、`invalid description: expected a non-empty string`、`invalid timeoutMs: expected a positive number, got `、`invalid escalation: sandbox_permissions requires a justification`、`invalid escalation: justification is only valid together with sandbox_permissions`、`invalid justification: expected a non-empty sentence`、`background execution is disabled for this bash tool`、`background tasks unavailable: load @deepseek-ai/dsh-tasks and @deepseek-ai/dsh-tool-tasks`、`sandbox_permissions is not available in this composition (no sandboxing executor to escalate)`、`sandbox escalation to "" is not strictly wider than this call's current "" mode`、审批不可用/拒绝/取消变体,以及 `command aborted`。 + +#### Token 影响 + +只有失败调用会增加这些保留 token;升权被拒时命令不会运行,因此不会添加命令输出。 + +#### KV Cache 影响 + +仅追加;新可见内容位于可复用请求前缀之后,不会使现有 KV-cache 条目失效。 + +## 已知限制与延期工作 + +- **回放退出状态 pill 从结果文本解析**:如果输出最后一行恰好精确为 `[exit code: N]` / `[killed by signal: …]`,会话回放将显示错误的 pill;这是仅影响展示的已知残留问题。 +- **`bash` 工具不采用 `timeout-policy` 预算**:根据[工具调用 timeout-policy Agent Note](../../../.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md),它保留由执行器持有的 `BASH_TIMEOUT` 路径。 +- **后台进程没有执行器超时**:工作不再需要时,调用方必须使用 `task_kill`,或依赖持有者/服务的 dispose。 diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml new file mode 100644 index 0000000000..0dd8860d65 --- /dev/null +++ b/packages/client/connection/README.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 +README.md: 80228a180faba0c556ff720e999b29b5bb1635b6 +README.zh.md: f4b857886bfafa891ceb1bd6b79b27e1fb725819 diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index 569670c274..80228a180f 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-client-connection +English | [中文](README.zh.md) + Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared api client + single-consumer stream-loop starter); the export face carries the wire contract types, the `AbstractApiClient` seam, and the loop's sink/config types. The platform subclasses (WebApiClient/FixtureApiClient), the ConnectionController loop, and the fixture data source are package-internal — apply selects and drives them; tests reach them via src. Contract: api-contracts v3 §3. ## Keyless fixture diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md new file mode 100644 index 0000000000..f4b857886b --- /dev/null +++ b/packages/client/connection/README.zh.md @@ -0,0 +1,22 @@ +# @deepseek-ai/dsh-client-connection + +[English](README.md) | 中文 + +协议消费层:客户端插件的 apply 会挂载 `ctx.connection`(共享 API 客户端 + 单消费方流循环启动器);导出表层携带协议契约类型、`AbstractApiClient` seam,以及循环的 sink/配置类型。平台子类(WebApiClient/FixtureApiClient)、ConnectionController 循环和 fixture 数据源都属于包内部:apply 负责选择并驱动它们,测试则通过 src 访问。契约:api-contracts v3 §3。 + +## 无密钥 fixture + +任何 `fixture` 查询参数都会选择内存载体。`fixture=empty` 启动时不含 Workspace 或 Session;`fixturePrompt=reject` 在接受前拒绝提示词;`fixtureAttach=fail` 发布 Session 但拒绝将其附加到 Workspace;`fixtureSessionCreate=drop-response` 在丢弃创建响应前发布 Session 并为其发出帧;`fixtureFrames=workspace-first` 则反转默认的 Session 优先创建帧顺序。按名称/路径创建 Workspace 以及由调用方预先分配 SessionId,均具有足够的确定性,组装后的 Web 测试可以据此协调列表与帧的到达。 + +## 模型体验 + +无。协议消费层只在浏览器与主机之间搬运已经组合好的消息;这里没有任何内容进入模型请求。 + +#### KV Cache 影响 + +无;该包既不组装也不发送提供方请求。 + +## 已知限制与暂缓事项 + +- **history 的隐式恢复存在争议**:在未附加的会话上打开 history,会在主机侧拉起 agent;纯持久化读取的替代方案记录在 rt-core 协调账本中,P-I 不作改变。该包的消费方会在首次打开时感受到这段延迟。 +- **计划移除 `ToolEventView`/`ToolCallView`/`ToolResultView` 的重新导出**:当 toolview 迁移删除主机 `viewFor` 行时,它们会一并移除(呈现属于客户端);在此之前,fixture 保留一份局部 `viewFor` 镜像。 diff --git a/packages/client/hmr/README.i18n.yaml b/packages/client/hmr/README.i18n.yaml new file mode 100644 index 0000000000..ce05fdae22 --- /dev/null +++ b/packages/client/hmr/README.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 +README.md: 2b2f63c25cbf3a46babef78a4dfb52f859156887 +README.zh.md: 6d94ca4a5e91f390e58575aa4ddf64fc18a509de diff --git a/packages/client/hmr/README.md b/packages/client/hmr/README.md index fc262bb086..2b2f63c25c 100644 --- a/packages/client/hmr/README.md +++ b/packages/client/hmr/README.md @@ -1,5 +1,7 @@ # @deepseek-ai/dsh-client-hmr +English | [中文](README.zh.md) + Hot reload for fetch-arrival client plugins. A static-arrival entry composed only into `--dev` graphs (`dsh web --dev`); production graphs omit the row, so the shell-bundled code stays inert. The browser half subscribes to the system SSE channel (`GET /plugins/events`) and reloads one plugin per `rebuilt` frame, serialized through a queue (the bundle handoff slot is single). The sequence per frame — `prefetch` (fetch the new bundle before touching anything), `invalidate`, `registry.delete` (before the fiber: a bare fiber dispose trips the vendored Loader's self-dispose branch, which would mark the entry disabled), drain the old fiber, delete `entry.fiber`, remove owned `