diff --git a/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.i18n.yaml index 5be7e083a3..7c9a3757f4 100644 --- a/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.i18n.yaml @@ -33,8 +33,8 @@ en: a244f6a88fdabf3d zh: e4feedb7297f4865 /agent-note-typert-gateway-targeted-method-calls/three-artifact-kinds-and-two-typescript-programs: - en: 6ea4bddcf35a834d - zh: 4af474c6818b1cf0 + en: c5bcd6eb76bf3d42 + zh: 9df2fbb364643186 /agent-note-typert-gateway-targeted-method-calls/the-remote-package-entry: en: 75e977fe0fb71d59 zh: 00760c79da173cb7 diff --git a/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md b/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md index 58135ff56e..f8eb1a8f42 100644 --- a/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md +++ b/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md @@ -215,7 +215,7 @@ Host lib build → Vite 构建 Web ``` -The existing top-level `build` still runs `build:lib` before `build:web`, but `build:lib` must complete the Host and Remote artifacts before starting Client TypeScript compilation. A clean build must not depend on stale `.d.ts` files from an earlier build. +The top-level `build` runs the step graph in `scripts/build.ts`, which completes the Host bundle and the Remote artifacts before starting Client TypeScript compilation. `build:lib` remains the complete serial lib build for `build:bench`, and its Host half `build:lib:host` serves the vendor release workflows. `typecheck` writes the Remote artifacts through `scripts/generate-typert.ts`, beside Host compilation, before Client TypeScript compilation. A clean build must not depend on stale `.d.ts` files from an earlier build. Compiler-backed repository gates that resolve the consumer surface have the same prerequisite even when their primary inputs are source files. The public `typecheck`, `lint`, and `doc-typecheck` commands run the Host contract pass first. The gate scheduler may use their `*:contracts-ready` variants only after an explicit Typert-contract or complete-build dependency, so parallel lanes neither read missing declarations nor run concurrent generators against the same outputs. diff --git a/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md b/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md index 21d51800ae..53edd345a7 100644 --- a/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md @@ -215,7 +215,7 @@ Host lib build → Vite 构建 Web ``` -现有顶层 `build` 仍表现为先 `build:lib`、再 `build:web`,但 `build:lib` 内部必须先完成 Host 与 Remote artifact,再启动 Client TypeScript 编译。一次干净构建不能依赖上次残留的 `.d.ts`。 +顶层 `build` 运行 `scripts/build.ts` 中的步骤图,先完成 Host bundle 与 Remote artifact,再启动 Client TypeScript 编译。`build:lib` 仍是 `build:bench` 使用的完整串行 lib 构建,其 Host 部分 `build:lib:host` 供 vendor 发布 workflow 使用。`typecheck` 与 Host 编译并行,经 `scripts/generate-typert.ts` 写出 Remote artifact,再启动 Client TypeScript 编译。一次干净构建不能依赖上次残留的 `.d.ts`。 即使主要输入是源文件,需要通过编译器解析消费方 surface 的仓库门禁也有相同的前置条件。公共 `typecheck`、`lint` 和 `doc-typecheck` 命令会先执行 Host 约定 pass。门禁调度器仅可在显式的 Typert 约定依赖或完整构建依赖完成后使用对应的 `*:contracts-ready` 变体,使并行 lane 既不会读取缺失的声明,也不会针对同一输出并发运行多个生成器。 diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml index bf89beeba0..e70e858963 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.i18n.yaml @@ -9,11 +9,11 @@ en: 9f34c53e647c69ca zh: 551776c7cc9618b5 /agent-note-client-derived-presentation-from-raw-session-tool-events/decision: - en: bdbb99c01b4c4db0 - zh: 570040471ad1f7f4 + en: 5fcc5a3de9f757cd + zh: a693cefdb82784ee /agent-note-client-derived-presentation-from-raw-session-tool-events/decision/goals-and-non-goals: - en: 7e7a937dc4fe1b18 - zh: 530f508b7e17b607 + en: 40aceb58d71303b5 + zh: 6954e41ae2fd1efd /agent-note-client-derived-presentation-from-raw-session-tool-events/terminology: en: 021106dd41176715 zh: 131caff7bd37251b @@ -72,11 +72,11 @@ en: f40f0a8ee8c055c0 zh: 6957b7372956113c /agent-note-client-derived-presentation-from-raw-session-tool-events/client-card-model-design/generic-tool-row: - en: 20ff82b092325c5c - zh: 1afd5441a9816117 + en: d336c77d1b09f349 + zh: 6e613f9c9108058f /agent-note-client-derived-presentation-from-raw-session-tool-events/client-card-model-design/terminal-card: - en: eab7f366df331b6e - zh: d82499e2a982206f + en: 492669c2134169b2 + zh: 0247a38df2dd8a83 /agent-note-client-derived-presentation-from-raw-session-tool-events/client-card-model-design/diff-card: en: ea384415c94f82da zh: 5f146c6cb534e1db @@ -99,8 +99,8 @@ en: e5b42aa311079bd7 zh: ec4cf97037ece7e0 /agent-note-client-derived-presentation-from-raw-session-tool-events/presentation-equivalence-matrix: - en: 30915c26728eeafe - zh: eea04dea7b4604a5 + en: 7974f20a6ac687ac + zh: cb4c350325a6da67 /agent-note-client-derived-presentation-from-raw-session-tool-events/client-extension-contract: en: 96619dfd5ef299cf zh: 253df98eb42ad75e diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md index ee1b54f6ee..8a0c4ea6fc 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.md @@ -22,7 +22,7 @@ The required result is one raw Session journal and one Client presentation owner ## Decision -The visual-equivalence requirements below exclude the separately approved [nested terminal-card fix](../../../../packages/client/ui-tool/README.md) and [recorded tool details](../../../../packages/client/ui-tool/README.md); all other presentation and ownership constraints remain. +The visual-equivalence requirements below exclude the separately approved [nested terminal-card fix](../../../../packages/client/ui-tool/README.md), [recorded tool details](../../../../packages/client/ui-tool/README.md), and [background Shell command display](../bug-fix/2026-10-10-background-shell-command-display.md); all other presentation and ownership constraints remain. The Session Remote journal sends only raw, validated, persistable Session events. `session.page` and `session.follow` do not parse tool arguments, query the Tools registry, restore a presenter scope, execute `presentCall` or `presentResult`, or construct or clone any tool view. @@ -51,7 +51,7 @@ The Host `ToolDefinition.presentCall`, `ToolDefinition.presentResult`, `ToolCall | Retained | the Session log format, Remote journal lifecycle, and Conversation identity/topology | | Retained | the existing keyed slot, Generic fallback, and Chat, Details, and Trajectory structure | | Forbidden | a new Client presenter service, parallel registry, or wire renderer id | -| Forbidden | new cards, visual redesign, interaction redesign, or PTC dispatch rich-card enhancements except the [nested terminal-card exception](../../../../packages/client/ui-tool/README.md) and [recorded tool details](../../../../packages/client/ui-tool/README.md) | +| Forbidden | new cards, visual redesign, interaction redesign, or PTC dispatch rich-card enhancements except the [nested terminal-card exception](../../../../packages/client/ui-tool/README.md), [recorded tool details](../../../../packages/client/ui-tool/README.md), and [background Shell command display](../bug-fix/2026-10-10-background-shell-command-display.md) | | Forbidden | compatibility dual-writing, version negotiation, or retention of the old `view` field | ## Terminology @@ -294,15 +294,16 @@ Unknown tools continue to use `GenericToolCard` with the name, raw arguments, re The title, kind, rawInput, content, and locations from Generic Host `presentCall` do not currently drive an ordinary Web row. Generic `presentResult.content` also does not drive Web output, so the Client need not copy these unconsumed values. + ### Terminal card -The Client terminal model derives existing `TerminalBlock` props from the tool name, call arguments, result content, error, and Session cwd, independently of `parentCallId`. +The Client terminal model derives existing `TerminalBlock` props from the tool name, call arguments, result content, error, and Session cwd, independently of `parentCallId`. [Background Shell command display](../bug-fix/2026-10-10-background-shell-command-display.md) governs explicit background `bash`/`pwsh` launches; the remaining ownership and fallback rules below stay in force. | Input | Preserved result | |---|---| | running standard `bash`/`pwsh` foreground call | terminal prompt, description, cwd, and running state | | successful standard foreground call | terminal output, exit code/signal, and settled state presentation | -| `run_in_background:true` | Generic row and raw result | +| explicit background standard `bash`/`pwsh` | original `background` flag with call `running` at Start; acknowledgement clears `running` and retains a static command without output or job status | | tool execution error | Generic IN/OUT and error summary | | running persistent `bash`/`pwsh` | terminal prompt | | settled persistent `bash`/`pwsh` | Generic flattened result, with no new exit card | @@ -310,7 +311,7 @@ The Client terminal model derives existing `TerminalBlock` props from the tool n | background/error `terminal_send` | Generic result | | PTC dispatch child | same terminal eligibility and fallback rules as a root call | -Standard shell results parse trailing `[exit code: N]` and `[killed by signal: X]` markers. A final recognized spill-policy notice selects Generic output instead: expandable in shell rows and raw in Details, because the exit marker may be displaced or omitted. A parsed marker is removed from the terminal body; timeout, sandbox denial, and markers without a pill remain in the body. +Foreground standard shell results parse trailing `[exit code: N]` and `[killed by signal: X]` markers; explicit background launch acknowledgements do not enter output or exit-status parsing. A final recognized spill-policy notice selects Generic output instead: expandable in shell rows and raw in Details, because the exit marker may be displaced or omitted. A parsed marker is removed from the terminal body; timeout, sandbox denial, and markers without a pill remain in the body. Call `description` remains above the card and overrides the collapsed summary. Workdir continues handling absolute, relative, and missing values. Relative paths resolve against the Session cwd while preserving normalization for `.`, `..`, drive letters, and UNC roots. @@ -318,7 +319,7 @@ For `terminal_send`, non-empty input and the session id remain verbatim tool dat Standard and persistent providers sharing the same tool name are a special compatibility point. The Client uses currently valid argument and result features to preserve their delivered differences. Input that cannot be identified unambiguously uses a Generic settled result rather than gaining new presentation. -`TerminalBlock` ANSI handling, cursor replay, wide characters, line limits, expansion, copying, and assistive text remain unchanged. +Outside the explicit background command-only presentation, `TerminalBlock` ANSI handling, cursor replay, wide characters, line limits, expansion, copying, and assistive text remain unchanged. ### Diff card @@ -412,7 +413,7 @@ The scenario does not import Host tool packages to compute page presentation and | orphan result | callId title and Generic output | | interrupted call | warning/stopped state | | foreground bash/pwsh | current terminal prompt, body, cwd, and state | -| background/error bash/pwsh | current Generic IN/OUT | +| explicit background bash/pwsh | terminal Start and static command-only acknowledgement; launch errors retain Generic IN/OUT | | persistent shell | current running terminal and settled Generic form | | terminal_send | current foreground terminal and background/error Generic form | | write/edit | current intended/applied diff and error fallback | diff --git a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md index 332c30df9b..2dd4ad8bc9 100644 --- a/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-23-client-derived-tool-presentation.zh.md @@ -22,7 +22,7 @@ Host presenter 与 Client keyed renderer 分担展示会形成对同一事件的 ## Decision -下述展示对等要求不包含已独立批准的[嵌套 terminal 卡片修复](../../../../packages/client/ui-tool/README.zh.md)和[记录结果的工具详情](../../../../packages/client/ui-tool/README.zh.md);其他展示与所有权约束全部保留。 +下述展示对等要求不包含已独立批准的[嵌套 terminal 卡片修复](../../../../packages/client/ui-tool/README.zh.md)、[记录结果的工具详情](../../../../packages/client/ui-tool/README.zh.md)和[后台 Shell 命令展示](../bug-fix/2026-10-10-background-shell-command-display.zh.md);其他展示与所有权约束全部保留。 Session Remote journal 只下发原始、已验证、可持久化的 Session event。`session.page` 和 `session.follow` 不解析工具参数,不查询 Tools registry,不恢复 presenter scope,不执行 `presentCall`/`presentResult`,也不构造或克隆任何 tool view。 @@ -51,7 +51,7 @@ Host 的 `ToolDefinition.presentCall`、`ToolDefinition.presentResult`、`ToolCa | 保留 | Session 日志格式、Remote journal 生命周期与 Conversation identity/topology | | 保留 | 现有 keyed slot、Generic fallback、Chat、Details 与 Trajectory 结构 | | 禁止 | 新 Client presenter service、平行 registry 或 wire renderer id | -| 禁止 | 新卡片、视觉改版、交互改版或 PTC dispatch rich-card 增强,[嵌套 terminal 卡片例外](../../../../packages/client/ui-tool/README.zh.md)和[记录结果的工具详情](../../../../packages/client/ui-tool/README.zh.md)除外 | +| 禁止 | 新卡片、视觉改版、交互改版或 PTC dispatch rich-card 增强,[嵌套 terminal 卡片例外](../../../../packages/client/ui-tool/README.zh.md)、[记录结果的工具详情](../../../../packages/client/ui-tool/README.zh.md)和[后台 Shell 命令展示](../bug-fix/2026-10-10-background-shell-command-display.zh.md)除外 | | 禁止 | 为兼容保留双写、版本协商或旧 `view` 字段 | ## 术语 @@ -294,15 +294,16 @@ Chat 与 Details 通过纯 helper 复用同一 block 的解析。未来缓存必 Generic Host `presentCall` 的 title、kind、rawInput、content 与 locations 当前并不驱动普通 Web 行;Generic `presentResult.content` 也不驱动 Web 输出,因此无需把这些未消费值复制到 Client。 + ### Terminal 卡片 -Client terminal model 从工具名称、调用参数、结果 content、error 与 Session cwd 派生现有 `TerminalBlock` props,不依赖 `parentCallId`。 +Client terminal model 从工具名称、调用参数、结果 content、error 与 Session cwd 派生现有 `TerminalBlock` props,不依赖 `parentCallId`。[后台 Shell 命令展示](../bug-fix/2026-10-10-background-shell-command-display.zh.md)拥有主动后台 `bash`/`pwsh` 启动的展示决定;下述其余所有权和 fallback 规则继续有效。 | 输入 | 保持的结果 | |---|---| | 标准 `bash`/`pwsh` 前台 running | terminal prompt、description、cwd、running 状态 | | 标准前台 success | terminal output、exit code/signal 与结算状态呈现 | -| `run_in_background:true` | Generic 行与原始结果 | +| 标准 `bash`/`pwsh` 主动后台调用 | Start 使用原 `background` 标志和调用 `running`;回执清除 `running` 后保留静态命令,不显示输出或任务状态 | | 工具执行 error | Generic IN/OUT 与错误摘要 | | persistent `bash`/`pwsh` running | terminal prompt | | persistent `bash`/`pwsh` settled | Generic flattened result,不新增 exit card | @@ -310,7 +311,7 @@ Client terminal model 从工具名称、调用参数、结果 content、error | `terminal_send` background/error | Generic 结果 | | PTC dispatch child | 与根调用相同的 terminal 适用规则与 fallback 规则 | -标准 shell 结果解析末尾 `[exit code: N]` 与 `[killed by signal: X]`。末尾已识别的 spill 策略提示会改用 Generic 输出:在 shell 行中可展开,在 Details 中显示原文,因为退出标记可能被移位或省略。已解析的 marker 从 terminal 正文移除;timeout、sandbox denial 与没有 pill 的 marker 留在正文。 +标准前台 shell 结果解析末尾 `[exit code: N]` 与 `[killed by signal: X]`;主动后台启动回执不进入输出或退出状态解析。末尾已识别的 spill 策略提示会改用 Generic 输出:在 shell 行中可展开,在 Details 中显示原文,因为退出标记可能被移位或省略。已解析的 marker 从 terminal 正文移除;timeout、sandbox denial 与没有 pill 的 marker 留在正文。 调用 `description` 继续显示在 card 上方并覆盖折叠摘要。workdir 继续按绝对、相对和缺失三种情况处理;相对路径基于 Session cwd,且保留 `.`、`..`、盘符与 UNC root 的归一化。 @@ -318,7 +319,7 @@ Client terminal model 从工具名称、调用参数、结果 content、error 同名普通与 persistent provider 是特殊兼容点。Client 使用当前有效参数与结果特征保留已交付差异;不足以无歧义识别的输入选择 Generic settled 结果,不增加新表现。 -TerminalBlock 的 ANSI、光标重放、宽字符、行数上限、展开、复制与辅助技术文本完全不变。 +除主动后台的仅命令展示外,TerminalBlock 的 ANSI、光标重放、宽字符、行数上限、展开、复制与辅助技术文本保持不变。 ### Diff 卡片 @@ -412,7 +413,7 @@ Deliverables Definition 按 callId 观察 root `tool/call` 与成功 `tool/resul | orphan result | callId 标题与 Generic output | | interrupted call | warning/stopped 状态 | | bash/pwsh 前台 | 当前 terminal prompt、正文、cwd 与状态 | -| bash/pwsh background/error | 当前 Generic IN/OUT | +| bash/pwsh 主动后台调用 | terminal Start 与静态仅命令回执展示;启动错误保留 Generic IN/OUT | | persistent shell | 当前 running terminal、settled Generic | | terminal_send | 当前前台 terminal、后台/error Generic | | write/edit | 当前 intended/applied diff 与 error fallback | diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml index 981cb258f7..59f213ad30 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.i18n.yaml @@ -24,8 +24,8 @@ en: e9f140cd22670dfa zh: bf85cfe9c12a0345 /agent-note-package-and-update-the-electron-desktop-application/security-and-release-policy: - en: 97ee608e96fc3602 - zh: 932b98e7d344cd87 + en: 36559f9179764da7 + zh: f1d39a6438ca520c /agent-note-package-and-update-the-electron-desktop-application/implementation: en: 041a6d35ed61b149 zh: 617c6b90a6f4fa4d diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md index 26a6b9ba99..60fd24c8f2 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.md @@ -81,7 +81,7 @@ Test releases require `DOWNLOAD_TEST_RELEASE_ID` from the platform dotenv file. Core dsh and the private Desktop Host come only from the signed application resource tree. Plugin installation forwards package specs to pnpm, including local and remote sources, but never accepts raw pnpm commands. pnpm owns dependency resolution and the profile’s `allowBuilds` policy; the Host loads activated bundles. -Electron release artifacts are signed; macOS artifacts are notarized. Release package and upload commands read release settings from the Git-ignored target `.env.windows` or `.env.macos`; subprocesses receive the fields selected by orchestration. The target file exclusively owns release fields so stale shell or system credentials cannot override local selection, and loading does not mutate the parent environment. Packaging validates the mode-specific application ID, update origin, signing identity, and local files before builds, downloads, or release-record cleanup; macOS also requires one complete notarization strategy. The separate `check:package` command runs the same validation without accessing the token or Apple; actual signing and notarization still verify authentication. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS release packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. The fixed-target installer command uses [isolated App copies for parallel notarization](../process/2026-09-09-parallel-macos-notarization.md): the ZIP contains a stapled App, while the signed DMG carries the ticket covering its unstapled inner App. The DMG artifact-completion hook requires the configured identity, a valid ticket, and Gatekeeper acceptance. Both artifact lanes must succeed before the command promotes their outputs and writes the release completion record; directory-only commands still notarize and staple the App. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. +Electron release artifacts are signed; macOS artifacts are notarized. Release package and upload commands read release settings from the Git-ignored target `.env.windows` or `.env.macos`; subprocesses receive the fields selected by orchestration. Windows packaging can instead select a machine-owned public `presets/.env`, plus `secrets/windows-signing.env` for signed builds; unsigned and preparation-only modes omit the signing file. The selected files exclusively own release fields so stale shell or system credentials cannot override local selection, and loading does not mutate the parent environment. Packaging validates the mode-specific application ID, update origin, signing identity, and local files before builds, downloads, or release-record cleanup; macOS also requires one complete notarization strategy. The separate `check:package` command runs the same validation without accessing the token or Apple; actual signing and notarization still verify authentication. Configuration loading rejects missing or malformed identifiers and incomplete notarization credentials, while macOS release packaging requires signing so certificate discovery cannot silently select another installed identity or emit an unsigned release. Runtime preparation verifies the exact Authority and Team ID plus the timestamp and hardened-runtime flags on every embedded Mach-O file. An after-sign hook performs Apple's deep strict application verification and requires the same leaf Authority and Team ID before artifact creation continues. The fixed-target installer command uses [isolated App copies for parallel notarization](../process/2026-09-09-parallel-macos-notarization.md): the ZIP contains a stapled App, while the signed DMG carries the ticket covering its unstapled inner App. The DMG artifact-completion hook requires the configured identity, a valid ticket, and Gatekeeper acceptance. Both artifact lanes must succeed before the command promotes their outputs and writes the release completion record; directory-only commands still notarize and staple the App. DMG blockmaps are disabled because macOS updates consume the signed ZIP, and stapling would otherwise invalidate an already-generated DMG blockmap. The [pinned osx-sign patch](../../../../patches/@electron__osx-sign@1.3.3.patch) uses `lstat` in both published module builds, so Framework file and directory aliases do not trigger duplicate signing. The patch remains necessary until the selected upstream release skips those aliases. PAK files are resources sealed by the enclosing bundle; individual signatures add serial timestamp requests without additional resource integrity. Desktop preserves all locale files and skips only their standalone signatures. Executable code retains Developer ID signatures, secure timestamps, and hardened runtime. The [signer traversal regression](../../../../apps/desktop/tests/macos-signing-walk.spec.ts) exercises the installed dependency with real Framework aliases; release qualification still requires strict application verification, notarization, and startup. diff --git a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md index 21ef91d0e0..6d1c2b8328 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-electron-desktop-packaging-and-updates.zh.md @@ -81,7 +81,7 @@ Electron 更新只使用一个 `electron-updater` 发布流和签名 `electron-b 核心 dsh 和私有 Desktop Host 只来自签名应用的资源树。插件安装把包规格交给 pnpm,包括本地和远程来源,但不接受原始 pnpm 命令。pnpm 负责依赖解析和 profile 的 `allowBuilds` 策略;Host 加载已启用的 bundle。 -Electron 发布产物必须签名;macOS 产物必须公证。发布打包与上传命令从 Git 忽略的目标 `.env.windows` 或 `.env.macos` 读取发布配置,子进程通过编排器选择的环境字段接收配置。目标文件是发布字段的唯一来源,避免旧的 shell 或系统凭据覆盖本地选择;配置加载不修改父进程环境。打包在构建、下载或清理发布记录前校验该模式必需的应用 ID、更新地址、签名身份及本地文件,macOS 还要求一套完整公证凭据。单独的 `check:package` 执行同一校验而不访问 Token 或 Apple;凭据真实性仍由实际签名与公证验证。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 发布打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。固定目标安装包命令使用[隔离的 App 副本并行公证](../process/2026-09-09-parallel-macos-notarization.zh.md):ZIP 包含已钉票的 App,签名 DMG 则携带覆盖其中未钉票 App 的票据。DMG 的 artifact-completion hook 要求其使用配置的身份、具备有效票据并通过 Gatekeeper。只有两条产物流都成功,命令才会移入其输出并写入发布完成记录;仅生成目录的命令仍会公证 App 并钉票。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。 +Electron 发布产物必须签名;macOS 产物必须公证。发布打包与上传命令从 Git 忽略的目标 `.env.windows` 或 `.env.macos` 读取发布配置,子进程通过编排器选择的环境字段接收配置。Windows 打包也可选择机器管理的公开 `presets/.env`,签名构建另读 `secrets/windows-signing.env`;未签名和仅准备模式不读取签名文件。所选文件是发布字段的唯一来源,避免旧的 shell 或系统凭据覆盖本地选择;配置加载不修改父进程环境。打包在构建、下载或清理发布记录前校验该模式必需的应用 ID、更新地址、签名身份及本地文件,macOS 还要求一套完整公证凭据。单独的 `check:package` 执行同一校验而不访问 Token 或 Apple;凭据真实性仍由实际签名与公证验证。配置加载会拒绝缺失或格式错误的标识符和不完整的公证凭据,macOS 发布打包还会强制签名,避免证书发现过程静默选择其他已安装身份或生成未签名发布。运行时准备会验证每个内嵌 Mach-O 文件的精确 Authority 与 Team ID,以及时间戳和 hardened-runtime 标记。签名后钩子会执行 Apple 的深度严格应用验证,并要求同一叶证书 Authority 与 Team ID 完全匹配,验证通过后才继续生成产物。固定目标安装包命令使用[隔离的 App 副本并行公证](../process/2026-09-09-parallel-macos-notarization.zh.md):ZIP 包含已钉票的 App,签名 DMG 则携带覆盖其中未钉票 App 的票据。DMG 的 artifact-completion hook 要求其使用配置的身份、具备有效票据并通过 Gatekeeper。只有两条产物流都成功,命令才会移入其输出并写入发布完成记录;仅生成目录的命令仍会公证 App 并钉票。macOS 更新使用签名 ZIP,因此 DMG 不生成 blockmap;否则钉票会让已经生成的 DMG blockmap 失效。 [固定版本的 osx-sign 补丁](../../../../patches/@electron__osx-sign@1.3.3.patch)在两种已发布模块构建中使用 `lstat`,因此 Framework 的文件和目录别名不会触发重复签名。选定的上游版本能够跳过这些别名前,仍需保留该补丁。PAK 文件由外层 bundle 签名记录完整性;逐个签名会增加串行时间戳请求,但不会增加资源完整性保护。Desktop 保留全部语言文件,只跳过其单独签名。可执行代码仍使用 Developer ID 签名、安全时间戳和 hardened runtime。[签名器遍历回归测试](../../../../apps/desktop/tests/macos-signing-walk.spec.ts)使用真实 Framework 别名执行已安装依赖;发布验收仍要求严格应用验证、公证和启动。 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml index d83f853c54..d7f60ead90 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.i18n.yaml @@ -9,8 +9,8 @@ en: 66ac3d7ce7eb8e15 zh: abb9d41b71900bbf /agent-note-sandboxed-node-execution-for-ptc/decision: - en: cf072f53de09faca - zh: 9edd5c4a2bfaae5a + en: d6b9c22603a4f933 + zh: f324b91830078d9a /agent-note-sandboxed-node-execution-for-ptc/decision/resolved-inputs-and-policy: en: 3aef37bb4f8a8e53 zh: a7b477324d486ab3 @@ -18,8 +18,8 @@ en: 2c7a694b04951772 zh: 133b95b0477b127f /agent-note-sandboxed-node-execution-for-ptc/decision/resource-limits: - en: 84c73cf3ff33bc03 - zh: a228080683d6252c + en: 3f1d8a30f6d48243 + zh: faa7c01d7c959893 /agent-note-sandboxed-node-execution-for-ptc/alternatives-considered: en: 8ffcc2b32a2243d7 zh: 81d48d38947abc76 diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md index 2104e58e8e..1259a617ad 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.md @@ -12,7 +12,7 @@ The [PTC foundation](../feature/2026-06-15-ptc.md) remains responsible for regis ## Decision -`dsh-ptc-runtime-node` runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains inside this provider. +`dsh-ptc-runtime-node` in its default `per-call` mode runs each program in one fresh Node process. The host resolves execution choices, confines the launch through the same `ctx.sandbox` provider as Bash, and gives process lifetime to `ctx.subprocess`. The child evaluates erasable TypeScript with direct Node APIs, an empty model environment and host-provided asynchronous bindings. No worker or persistent kernel remains after a per-call execution. The host preserves `ELECTRON_RUN_AS_NODE` for child startup; the bootstrap removes it from the native environment before evaluation, and model-visible `process.env` stays empty. Nested Electron launches require their own explicit Node-mode selection. Desktop uses Electron as its Node executable; removing this selector launches Electron's application path instead of the PTC bootstrap. Sandbox permission changes cannot repair that launch mismatch. The macOS Desktop regression uses real Electron to verify binding writes, direct workspace writes, and rejection of writes outside the workspace under restricted policy. It requires an installed Electron binary; ordinary runtime tests cover environment filtering without that dependency. @@ -34,6 +34,8 @@ Program completion, timeout, cancellation and protocol failure all close executi The default elapsed deadline is 120 seconds, capped at 600 seconds by default. Trusted service consumers may request `timeoutMs: null` to disable this timer; [workflow sandbox reuse](2026-09-13-workflow-ptc-sandbox-reuse.md) owns that caller-controlled lifetime. Omitted and numeric requests, including model-facing `run_code`, retain the numeric defaults and caps. An enabled deadline includes runtime setup and nested tool or approval waits. V8 old-generation memory, serialized outer output and control traffic have separate configured bounds. The heap limit excludes native allocations and descendant memory, and elapsed time is not a process-tree CPU budget. +The opt-in [in-memory execution mode](2026-09-23-best-effort-persistent-ptc.md) retains disposable memory under the same file policy; [retained-process permissions](2026-10-08-persistent-ptc-sandbox.md) govern policy changes and temporary escalation. + ## Alternatives considered **Keep the worker and add tool checks.** Tool checks cannot intercept direct Node imports or establish OS confinement. Keeping a worker inside a confined supervisor process preserves worker metering but adds another execution lifetime without supplying a process-tree CPU limit. diff --git a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md index 429351cca2..0074fdf578 100644 --- a/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-11-sandboxed-node-ptc-runtime.zh.md @@ -12,7 +12,7 @@ Node worker 隔离 JavaScript 状态,但不应用调用 Session 的 OS 沙箱 ## 决策 -`dsh-ptc-runtime-node` 在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。本提供方不保留 worker 或持久内核。 +`dsh-ptc-runtime-node` 的默认 `per-call` 模式在一个全新 Node 进程中运行每个程序。Host 解析执行选择,通过与 Bash 相同的 `ctx.sandbox` 提供方约束启动,并将进程生命周期交给 `ctx.subprocess`。子进程以直接 Node API、空模型环境和 Host 提供的异步绑定求值可擦除 TypeScript。逐次执行结束后不保留 worker 或持久内核。 Host 在子进程启动时保留 `ELECTRON_RUN_AS_NODE`;bootstrap 在求值前将其从原生环境中删除,模型可见的 `process.env` 仍为空。嵌套启动 Electron 需要自行显式选择 Node 模式。桌面端使用 Electron 作为 Node 可执行文件;删除此选择变量会启动 Electron 应用路径,而不是 PTC bootstrap。更改沙箱权限无法修复这一启动模式不匹配。macOS 桌面端回归测试使用真实 Electron 验证绑定写入、直接工作区写入以及受限策略对工作区外写入的拒绝。该测试需要已安装的 Electron 二进制文件;普通运行时测试无需此依赖即可覆盖环境过滤。 @@ -34,6 +34,8 @@ Host 在子进程启动时保留 `ELECTRON_RUN_AS_NODE`;bootstrap 在求值前 默认经过时间截止为 120 秒,默认上限为 600 秒。可信服务消费方可以请求 `timeoutMs: null` 来禁用该定时器;[工作流沙箱复用](2026-09-13-workflow-ptc-sandbox-reuse.zh.md)负责这种由调用方控制的生命周期。省略 timeout 或使用数值的请求(包括面向模型的 `run_code`)保留数值默认值与上限。启用的截止包括运行时准备以及嵌套工具或审批等待。V8 老生代内存、序列化外层输出与控制通信具有独立配置的上限。堆限制不包含原生分配和后代内存,经过时间也不是进程树 CPU 预算。 +显式启用的[内存保留执行模式](2026-09-23-best-effort-persistent-ptc.zh.md)在相同文件策略下保留可丢弃内存;[常驻进程权限](2026-10-08-persistent-ptc-sandbox.zh.md)负责策略切换和临时提权。 + ## 考虑过的替代方案 **保留 worker 并增加工具检查。** 工具检查不能拦截直接 Node 导入,也不能建立 OS 约束。在受限监督进程中保留 worker 可以保留 worker 计量,但会增加一层执行生命周期,仍不能提供进程树 CPU 限制。 diff --git a/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.i18n.yaml index ae4cd23658..5441a65985 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.i18n.yaml @@ -9,14 +9,14 @@ en: 837ebb0071a5611b zh: 23d0f0713889ead6 /agent-note-writer-acquisition-for-blank-session-reuse/decision: - en: 7f2676feb224e7ea - zh: babfda5b31dfd0fe + en: a54db0d4a97aa9b8 + zh: a52d257b657fe99b /agent-note-writer-acquisition-for-blank-session-reuse/alternatives-considered: en: 2a67a53f7f396ba8 zh: 6df6ccc071fb0de2 /agent-note-writer-acquisition-for-blank-session-reuse/consequences: - en: 2e1f1894337689a2 - zh: d0cab07cc48083ee + en: 8307612b7476e8f3 + zh: 87fa39e58d33d4f1 /agent-note-writer-acquisition-for-blank-session-reuse/verification: - en: 4680e845e2ab294e - zh: ea5890c5ffb09831 + en: 4367d55ae9dce5c1 + zh: c610626f4e15eb77 diff --git a/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.md b/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.md index c832604dfb..d6be46b3ed 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.md +++ b/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.md @@ -10,7 +10,7 @@ Two Hosts sharing Session storage can select the same blank Session when opening ## Decision -The Session catalog includes persisted blanks. Startup restoration selects the saved blank; ordinary Workspace navigation selects the first eligible unarchived member in catalog order. Explicit-id `session.create` resumes that Session and acquires its writer before opening history. Only `session/writer-held` triggers creation of a new Session. Other errors propagate. Concurrent Workspace connects in one Client share the acquisition and fallback. Later navigation cancels a pending startup selection. +The Session catalog includes persisted blanks. Startup restoration selects the saved blank; ordinary Workspace navigation selects the first eligible unarchived member in catalog order. Explicit-id `session.create` names that Session; the Host resumes it and acquires its writer before opening history, and creates a new Session when another owner holds the writer ([reuse and preset rules](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.md)). Other errors propagate. A Workspace connect in one Client joins the latest in-flight connect to that Workspace only when both request the same preset. Later navigation cancels a pending startup selection. The Agent retains the acquired handle throughout its lifetime. Checking ownership and releasing a probe lock would leave a race before resume. No PID or process identity enters persisted data or the Remote schema. @@ -28,8 +28,8 @@ This decision extends the blank-reuse policy in the [Client Session scope refere ## Consequences -A Host can reuse its own live blank or reclaim an unowned persisted blank with its slash state. Separate Hosts create distinct blanks while existing writers remain held. A held selected blank causes fresh creation even when another blank is free; navigation does not search for another candidate. No cleanup is added. Opening the same established conversation from two Hosts can still encounter writer contention. Unknown projection hints remain visible without cold body scans; automatic reuse requires known blank metadata. A non-contention acquisition failure aborts New Session and is currently reported only to the console; hidden blanks have no recovery action in this flow. +A Host can reuse its own live blank or reclaim an unowned persisted blank with its slash state. Separate Hosts create distinct blanks while existing writers remain held. A held selected blank causes fresh creation even when another blank is free; navigation does not search for another candidate. No cleanup is added. Opening the same established conversation from two Hosts can still encounter writer contention. Unknown projection hints remain visible without cold body scans; automatic reuse requires known blank metadata. A non-contention acquisition failure aborts the navigation; a hero Workspace pick or explicit draft preparation reports it as a notice and startup restoration only to the console, and a hidden blank that fails this way has no recovery action in this flow. ## Verification -Navigation tests cover saved selection, single-candidate contention fallback, non-contention failures, overlapping acquisition, and superseding navigation. A shipped Web-composition test holds a real persistence writer, verifies fresh creation despite another free blank, and reclaims the released selected blank with its plan state. The fresh-round-trip recorded Session scenario reloads its blank before submitting the recorded prompt. +Navigation tests cover saved selection, opening the Session the Host returns for a held candidate, non-contention failures, overlapping acquisition, and superseding navigation. A shipped Web-composition test holds a real persistence writer, verifies fresh creation despite another free blank, and reclaims the released selected blank with its plan state. The fresh-round-trip recorded Session scenario reloads its blank before submitting the recorded prompt. diff --git a/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.zh.md b/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.zh.md index f5d5d58bc6..d477e9770c 100644 --- a/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-17-process-local-blank-sessions.zh.md @@ -10,7 +10,7 @@ Status: implemented ## Decision -Session 列表包含持久化空白会话。启动恢复选择已保存的空白会话;普通 Workspace 导航按列表顺序选择第一个符合条件且未归档的成员。显式 ID 的 `session.create` 会恢复该 Session,并在打开历史前取得写锁。只有 `session/writer-held` 会触发新建 Session。其他错误返回调用方。同一 Client 的并发 Workspace 连接共享获取与回退过程。后续导航会取消尚未完成的启动选择。 +Session 列表包含持久化空白会话。启动恢复选择已保存的空白会话;普通 Workspace 导航按列表顺序选择第一个符合条件且未归档的成员。显式 ID 的 `session.create` 指明该 Session;Host 恢复它并在打开历史前取得写锁,写锁被其他写者持有时改为新建 Session([复用与 preset 规则](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.zh.md))。其他错误返回调用方。同一 Client 中的 Workspace 连接仅在与该 Workspace 最近一次进行中的连接请求相同 preset 时与之合并。后续导航会取消尚未完成的启动选择。 Agent 在整个生命周期内持有取得的句柄。检查占用后释放探测锁,会在恢复前留下竞态。持久化数据与 Remote schema 均不引入 PID 或进程身份。 @@ -28,8 +28,8 @@ Agent 在整个生命周期内持有取得的句柄。检查占用后释放探 ## Consequences -Host 可以复用自己的活动空白会话,也可以接管无人占用的持久化空白会话并保留其 slash 状态。现有写锁被持有时,不同 Host 创建不同的空白会话。所选空白会话被占用时,即使另有空闲空白会话也会新建;导航不再寻找其他候选。不增加清理逻辑。两个 Host 打开同一个已有对话时仍可能遇到写锁争用。未知投影提示仍可见且不扫描冷日志正文;自动复用要求已知的空白元数据。非锁争用的获取错误会中止新建会话,目前只报告到控制台;此流程没有针对隐藏空白会话的恢复操作。 +Host 可以复用自己的活动空白会话,也可以接管无人占用的持久化空白会话并保留其 slash 状态。现有写锁被持有时,不同 Host 创建不同的空白会话。所选空白会话被占用时,即使另有空闲空白会话也会新建;导航不再寻找其他候选。不增加清理逻辑。两个 Host 打开同一个已有对话时仍可能遇到写锁争用。未知投影提示仍可见且不扫描冷日志正文;自动复用要求已知的空白元数据。非锁争用的获取错误会中止该次导航;在 hero 中选择工作区或显式准备草稿时以提示展示该错误,启动恢复只报告到控制台,以此方式失败的隐藏空白会话在此流程中没有恢复操作。 ## Verification -导航测试覆盖已保存选择、单候选锁争用回退、其他错误、重叠获取以及后续导航替代。实际 Web 组合测试持有真实持久化写锁,验证另有空闲空白会话时仍新建,并接管已释放的所选空白会话及其 plan 状态。fresh-round-trip 的录制 Session 场景在提交已录制的提示词前刷新空白会话。 +导航测试覆盖已保存选择、为被占用候选打开 Host 返回的 Session、其他错误、重叠获取以及后续导航替代。实际 Web 组合测试持有真实持久化写锁,验证另有空闲空白会话时仍新建,并接管已释放的所选空白会话及其 plan 状态。fresh-round-trip 的录制 Session 场景在提交已录制的提示词前刷新空白会话。 diff --git a/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.i18n.yaml index 70d50d1b1a..455daa7fff 100644 --- a/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.i18n.yaml @@ -9,8 +9,8 @@ en: 725f773bb350218e zh: dd8fbc09ef48208d /agent-note-declarative-agent-presets-and-retained-revisions/decision: - en: 53fd72bf4bbe4eb3 - zh: 406eee6e4f818e7c + en: 88edb925b556300c + zh: c6f05b641513d768 /agent-note-declarative-agent-presets-and-retained-revisions/alternatives-considered: en: 09f40eab4659e9f6 zh: 7a70da0d0ae6845b diff --git a/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.md b/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.md index fe7df55cde..38fa045ef1 100644 --- a/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.md +++ b/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.md @@ -16,7 +16,7 @@ The registry owns each revision's scope and Loader tree. Agents link their own s The Web editor and `agent_preset` tool accept only child plugin YAML. Saving writes the active profile's user patch, preserving display metadata and unrelated configuration. Revision checks and profile locking prevent overwriting concurrent saves; validation rejects a higher-priority override that would defeat the edit. Persistence and activation outcomes are reported separately. Tool writes require approval or full access because configuration executes in the Host. -Session data continues to record the preset identity. Restart resolves that identity against current configuration and rejects a missing definition. Old executable revisions are process-local, not serialized. New sessions without an explicit preset resolve `selectedDefault`; Client choice filtering and default correction follow [the preset UI policy](../../../../packages/client/ui-agent-preset/README.md). +Session data continues to record the preset identity. Restart resolves that identity against current configuration and rejects a missing definition; reusing a blank Session for a new conversation does not resolve it ([decision](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.md)). Old executable revisions are process-local, not serialized. New sessions without an explicit preset resolve `selectedDefault`; Client choice filtering and default correction follow [the preset UI policy](../../../../packages/client/ui-agent-preset/README.md). ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.zh.md b/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.zh.md index abe1ab27ae..4da53eb366 100644 --- a/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-18-declarative-agent-presets.zh.md @@ -16,7 +16,7 @@ Preset 目录重复承担 Cordis 配置的所有权。独立的发现、元数 Web 编辑器与 `agent_preset` 工具只接受子插件 YAML。保存写入当前 profile 的用户补丁,保留显示元数据和无关配置。版本检查和 profile 锁防止覆盖并发保存;验证拒绝会使编辑失效的更高优先级覆盖。持久化与激活结果分别报告。配置在 Host 中执行,因此工具写入需要批准或完全访问权限。 -会话数据继续记录 preset 标识。重启时根据当前配置解析该标识,定义缺失则拒绝恢复。旧的可执行代际仅保留在进程内,不会序列化。未显式指定 preset 的新会话解析 `selectedDefault`;客户端选项过滤和默认值修正遵循[预设 UI 策略](../../../../packages/client/ui-agent-preset/README.zh.md)。 +会话数据继续记录 preset 标识。重启时根据当前配置解析该标识,定义缺失则拒绝恢复;为新对话复用空白会话时不解析该标识([决策](../bug-fix/2026-09-29-reused-blank-runs-requested-preset.zh.md))。旧的可执行代际仅保留在进程内,不会序列化。未显式指定 preset 的新会话解析 `selectedDefault`;客户端选项过滤和默认值修正遵循[预设 UI 策略](../../../../packages/client/ui-agent-preset/README.zh.md)。 ## Alternatives considered diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml new file mode 100644 index 0000000000..615a8d43cf --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-23-best-effort-persistent-ptc.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md +/agent-note-node-ptc-execution-modes-and-in-memory-state: + en: 078a89753b06cd6a + zh: 4004e5e4bb42f2cc +/agent-note-node-ptc-execution-modes-and-in-memory-state/problem: + en: e42db40b879fdbf4 + zh: 6017da9c4da17835 +/agent-note-node-ptc-execution-modes-and-in-memory-state/decision: + en: d2d08c54c6520f02 + zh: 520a9b3421ff5c65 +/agent-note-node-ptc-execution-modes-and-in-memory-state/alternatives-considered: + en: 396157a9fc293198 + zh: a061f05b4423e26f +/agent-note-node-ptc-execution-modes-and-in-memory-state/consequences: + en: 9b9172f4aafe907f + zh: 022a6bd52d7caf05 diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md new file mode 100644 index 0000000000..153a63b87e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.md @@ -0,0 +1,37 @@ +# Agent Note: Node PTC execution modes and in-memory state + +Status: implemented + +English | [中文](2026-09-23-best-effort-persistent-ptc.zh.md) + +## Problem + +Interactive automation retains application objects, imported modules and helper functions between model calls. Recreating every object for every program prevents consumers from using ordinary JavaScript references across observations and actions. + +## Decision + +The existing `@deepseek-ai/dsh-ptc-runtime-node` plugin selects its execution mode through `executionMode`. The default `per-call` mode starts a fresh process under the configured file policy. Opt-in `persistent-in-memory` mode keeps a Node REPL process per explicit, object-identity state owner. Both modes provide the same `ctx.ptcRuntime` service. PTC uses the live Agent as owner and awaits release during its context disposal. Changing the configuration reloads the provider and releases its processes. The [sandboxed Node decision](2026-09-11-sandboxed-node-ptc-runtime.md) owns per-call confinement; the [PTC foundation](../feature/2026-06-15-ptc.md) owns tool dispatch and logged model requests. + +Mode names describe state retention rather than a process implementation or source syntax. `per-call` retains state for one invocation; `persistent-in-memory` retains it across invocations until the process or owner ends. `durable` names the deferred ability to save and restore execution state across restarts. It is not an accepted configuration value: a future implementation must define its recovery point, recoverable values and external-resource handling before exposing that mode. The [retained-process permission decision](2026-10-08-persistent-ptc-sandbox.md) owns confinement, policy changes and temporary escalation. + +One npm package and one plugin entry keep existing installation and loading paths stable. Communication, binding proxies, JSON encoding and output limits remain package-local modules. The Node provider delegates retained process ownership to an internal execution object, which registers no additional Cordis service. Per-call and in-memory execution keep their distinct lifecycle rules. `programFormat` describes source evaluation independently of retention: a REPL need not retain state. The runtime owns syntax, completion and retention instructions through `executionInstructions`; tools own call arguments, SDK declarations and image attachment. Workflow uses `programFormat` to wrap its program and refuses restricted file policies when the selected runtime cannot enforce them. + +The Session records submitted programs, nested tool calls and returned output. It does not serialize the REPL heap or rerun earlier programs after restart, resume or fork: replaying automation could repeat external side effects. A missing variable is a normal program error, and the model-visible instructions require recreating variables and reacquiring resources. No environment identifier or new durable Session event is required because the provider exposes no unlogged model input. + +Cancellation, deadline expiry, protocol or output-limit failure, owner disposal and process exit discard the environment. Ordinary exceptions retain earlier mutations. A retained function uses the active evaluation's host bindings; asynchronous work from an earlier evaluation cannot acquire a later evaluation's tool authority or output sink. + +## Alternatives considered + +Separate npm providers plus a shared library allow independent distribution, at the cost of another package, dependency declarations and cross-package exports for shared implementation details. The two Node modes have no current need for separate release schedules or independent dependencies. A second plugin subpath permits separate loading but asks deployments to replace plugin entries to select an execution policy. A configuration field expresses that selection while preserving the existing entry. Independent distribution or substantially different dependencies can justify revisiting this choice. + +A new Cordis service for common helpers would require another registration and injected dependency without adding an independently replaceable runtime capability. Internal functions and classes provide the required reuse. A common execution superclass would also couple fresh-process cleanup with owner-retained lifetimes; the provider shares mechanisms without merging those lifecycles. + +Serializing arbitrary JavaScript objects cannot preserve native resources and closures. Replaying prior programs can repeat writes and input actions. Both would imply recovery guarantees that in-memory execution does not offer. + +A realm inside the Harness process shares process lifetime with model code and cannot terminate a synchronous loop independently. A managed child process permits cancellation and resource cleanup while retaining imports and variables during healthy use. Process ownership alone does not provide a file sandbox or multi-tenant isolation. + +## Consequences + +Selecting `persistent-in-memory` retains execution state; the [permission decision](2026-10-08-persistent-ptc-sandbox.md) defines its file restrictions. Nested tools keep their normal authorization and logging. Memory and native handles may disappear without a Harness restart. The model must recover from reference or resource errors; the runtime never retries a program automatically. + +An idle owner retains a process with no expiration timer. Callers release owners explicitly; ownerless service calls use temporary processes. Programs use REPL statements and a final expression rather than top-level return, and calls for one retained owner cannot overlap. Tool schemas and program guidance follow the selected mode. diff --git a/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md new file mode 100644 index 0000000000..a4c4a52828 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-23-best-effort-persistent-ptc.zh.md @@ -0,0 +1,37 @@ +# Agent Note: Node PTC 执行模式与内存状态 + +Status: implemented + +[English](2026-09-23-best-effort-persistent-ptc.md) | 中文 + +## 问题 + +交互式自动化需要在模型调用之间保留应用对象、导入模块和辅助函数。如果每次执行都重新创建对象,消费者就无法在观察与操作之间继续使用普通 JavaScript 引用。 + +## 决策 + +现有 `@deepseek-ai/dsh-ptc-runtime-node` 插件通过 `executionMode` 选择执行模式。默认的 `per-call` 模式按配置的文件策略启动新进程。显式启用的 `persistent-in-memory` 模式为每个以对象身份标识的状态所有者保留一个 Node REPL 进程。两种模式都提供同一个 `ctx.ptcRuntime` 服务。PTC 使用存活的 Agent 作为所有者,在其上下文销毁时等待释放。修改配置会重载提供方并释放其进程。[Node 沙箱决策](2026-09-11-sandboxed-node-ptc-runtime.zh.md)负责逐次执行的文件约束,[PTC 基础决策](../feature/2026-06-15-ptc.zh.md)负责工具分派与模型请求日志。 + +模式名称描述状态保留方式,不绑定进程实现或代码语法。`per-call` 只为一次调用保留状态;`persistent-in-memory` 跨调用保留状态,直到进程或所有者结束。`durable` 用于命名未来跨重启保存与恢复执行状态的能力。它不是可接受的配置值:实现必须先明确恢复点、可恢复的值以及外部资源的处理方式,才能公开这个模式。[常驻进程权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)负责文件约束、权限切换与临时提权。 + +一个 npm 包和一个插件入口保持现有安装与加载路径稳定。通信、绑定代理、JSON 编码和输出限制继续作为包内模块复用。Node 提供方将保留进程的所有权交给内部执行对象,该对象不注册额外的 Cordis 服务。逐次执行和内存保留各自管理不同的生命周期。`programFormat` 描述代码求值形式,与状态保留独立:REPL 不必跨调用保留状态。运行时通过 `executionInstructions` 负责语法、完成值和状态保留指引;工具层负责调用参数、SDK 声明和图片附加。工作流根据 `programFormat` 包装程序;所选运行时无法执行受限文件策略时,工作流拒绝执行。 + +Session 记录提交的程序、嵌套工具调用和返回输出。它不序列化 REPL 堆,也不在重启、恢复或派生后重新执行旧程序,因为重放自动化可能重复外部操作。缺失变量产生普通程序错误,模型指引要求重新创建变量并获取资源。提供方没有引入日志之外的模型输入,因此不需要环境标识或新的持久 Session 事件。 + +取消、截止时间到期、协议失败、输出超限、所有者销毁和进程退出都会丢弃环境。普通异常保留此前发生的修改。保留的函数使用当前执行的宿主绑定;较早执行中的异步任务不能获取后续执行的工具权限或向其输出。 + +## 考虑过的替代方案 + +将提供方拆成独立 npm 包并增加共享库,可以分别分发,但需要维护额外的包、依赖声明和共享实现的跨包导出。两种 Node 模式目前没有不同发布节奏或独立依赖的需求。第二个插件子路径允许独立加载,但要求部署配置通过替换插件入口来选择执行策略。配置字段直接表达这个选择,并保留已有入口。需要独立分发或出现明显不同的依赖时,可以重新评估拆包。 + +为公共辅助代码新增 Cordis 服务,会增加注册和注入依赖,却没有提供独立替换的运行能力。内部函数和类已经能够完成复用。共同的执行基类还会把新进程清理与按所有者保留进程的生命周期耦合起来,因此提供方共用处理机制,各自管理生命周期。 + +序列化任意 JavaScript 对象无法保留原生资源和闭包。重放旧程序可能重复写入和输入操作。这两种做法都会暗示内存保留模式没有提供的恢复保证。 + +Harness 进程内的独立执行上下文与模型代码共享进程生命周期,无法单独终止同步死循环。托管子进程可以在正常使用时保留导入和变量,同时支持取消与资源清理。仅有进程所有权不能提供文件沙箱或多租户隔离。 + +## 影响 + +选择 `persistent-in-memory` 会保留执行状态;[权限决策](2026-10-08-persistent-ptc-sandbox.zh.md)定义其文件限制。嵌套工具仍遵循原有授权和日志规则。即使 Harness 没有重启,内存和原生句柄也可能丢失。模型需要从引用或资源错误中恢复,运行时不会自动重试程序。 + +空闲所有者保留一个没有过期计时器的进程。调用方显式释放所有者,没有所有者的服务调用使用临时进程。程序使用 REPL 语句和末尾表达式,不支持顶层 return;同一保留所有者的调用不能重叠。工具 schema 和程序指引跟随所选模式。 diff --git a/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.i18n.yaml new file mode 100644 index 0000000000..262e03bb22 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-08-persistent-ptc-sandbox.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.md +/agent-note-retained-ptc-processes-follow-file-policy: + en: ef07a82c85e490e1 + zh: b1662d1970d2b83b +/agent-note-retained-ptc-processes-follow-file-policy/problem: + en: b8cb574032d4e6e4 + zh: 6a1a25dec5f96086 +/agent-note-retained-ptc-processes-follow-file-policy/decision: + en: 5109a4bb5be39867 + zh: 2dcc602aba9eae61 +/agent-note-retained-ptc-processes-follow-file-policy/alternatives-considered: + en: 10bebc7f982cf7f4 + zh: 9247a2ba57921a11 +/agent-note-retained-ptc-processes-follow-file-policy/consequences: + en: b3ddf273158d3754 + zh: 916356f4074b3622 diff --git a/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.md b/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.md new file mode 100644 index 0000000000..2c4235fcc3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.md @@ -0,0 +1,31 @@ +# Agent Note: Retained PTC processes follow file policy + +Status: implemented + +English | [中文](2026-10-08-persistent-ptc-sandbox.zh.md) + +## Problem + +Retaining JavaScript variables does not require broader file access. A process that outlives one execution can also outlive a one-time approval or a Session policy change. File-policy changes must invalidate retained environments and begin stopping their file handles and background work. + +## Decision + +`persistent-in-memory` starts its Node process through the same sandbox provider as `per-call`. A retained owner uses one resolved mode, workspace root and Session identity until release. The [memory decision](2026-09-23-best-effort-persistent-ptc.md) owns retained values, failure recovery and package composition; this note owns file authority. + +The [PTC-owned cleanup decision](2026-10-09-ptc-owned-policy-cleanup.md) supersedes this note’s permission-setter completion and cleanup-ownership decision. Permission changes commit synchronously; PTC owns immediate cancellation and waits internally before subsequent execution. The tools package keeps Agent ownership and omits the owner for temporary escalations. + +An approved one-time escalation omits the state owner and receives a fresh temporary environment. Its process is released before the call returns. It cannot access standing variables, and its declarations do not survive. The standing environment keeps its original policy and variables. Nested tools continue to apply their own permissions and approvals. + +## Alternatives considered + +**Unconfined retained execution.** Omitting confinement simplifies a temporary prototype but couples variable retention to full host file access. The existing process sandbox supports long-lived processes, so this grant is unnecessary. + +**Changing the running process policy.** Existing backends apply restrictions at launch. Arbitrary retained objects, open handles and background work cannot be transferred into another policy with the existing interface. Releasing the environment prevents later evaluations from reusing those resources. + +**Coordinating through permission presets.** File-policy changes also have direct callers. PTC observes committed Session mode events from both paths, independently of user-facing preset selection. + +**Keeping an elevated environment.** A one-time approval cannot authorize future programs or idle background work. Omitting the state owner makes the approval lifetime explicit while preserving the standing environment. + +## Consequences + +Normal calls retain variables without changing file permissions. Changing sandbox mode discards variables. Escalated programs must be self-contained. Runtime consumers must release a retained owner before supplying a different policy without a Session mode change; the provider rejects inconsistent reuse. The sandbox inherits the existing backends’ file-effect coverage and platform limitations. diff --git a/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.zh.md b/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.zh.md new file mode 100644 index 0000000000..d841702941 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-08-persistent-ptc-sandbox.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 保留状态的 PTC 进程遵循文件策略 + +Status: implemented + +[English](2026-10-08-persistent-ptc-sandbox.md) | 中文 + +## 问题 + +保留 JavaScript 变量不需要更大的文件访问权限。跨调用存活的进程也可能在单次审批结束或 Session 策略变化后继续运行。文件策略变化必须使保留环境失效,并开始停止其文件句柄和后台工作。 + +## 决策 + +`persistent-in-memory` 与 `per-call` 通过同一个沙箱提供方启动 Node 进程。保留状态的所有者在释放前使用固定的已解析权限模式、工作区根目录和 Session 身份。[内存决策](2026-09-23-best-effort-persistent-ptc.zh.md)负责保留值、失败恢复和包组成;本文负责文件权限。 + +[PTC 自行等待清理的决策](2026-10-09-ptc-owned-policy-cleanup.zh.md)替代本文关于权限设置完成时点和清理归属的决策。权限变化同步提交;PTC 负责立即取消,并在后续执行前内部等待清理。工具包保留 Agent 所有权,在临时提权时省略所有者。 + +单次获准的提权省略状态所有者,使用全新的临时环境。该次调用返回前释放进程,无法访问原环境的变量,也不会保留新声明。原环境保持原权限和变量。嵌套工具继续应用各自的权限和审批规则。 + +## 考虑过的替代方案 + +**不限制保留状态的执行环境。** 省略沙箱能简化临时原型,却把变量保留与完整宿主文件访问权限绑定。现有进程沙箱支持长期运行的进程,因此这项授权没有必要。 + +**修改运行中进程的策略。** 现有后端在启动时应用限制。现有接口无法把任意保留对象、打开的句柄和后台工作转移到另一策略。释放环境可以防止后续执行复用这些资源。 + +**通过权限预设协调清理。** 文件策略也有直接调用方。PTC 观察两类调用方提交的 Session 模式事件,无需依赖面向用户的预设选择。 + +**保留提权环境。** 单次审批不能授权未来程序或空闲期间的后台工作。省略状态所有者明确了审批生效的范围,同时保留原环境。 + +## 影响 + +普通调用保留变量,同时维持原文件权限。切换沙箱模式会丢弃变量。提权程序必须包含执行所需的完整代码。未发生 Session 模式变化时,运行时消费者在传入不同策略前必须释放保留状态的所有者;提供方拒绝策略不一致的复用。沙箱继承现有后端的文件约束范围与平台限制。 diff --git a/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.i18n.yaml new file mode 100644 index 0000000000..ac38c709dc --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-09-message-node-factories-and-delegates.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.md +/agent-note-domain-image-slots-and-a-shared-gallery-factory: + en: bce6358fb4211261 + zh: bfebd3bbdb1affb1 +/agent-note-domain-image-slots-and-a-shared-gallery-factory/problem: + en: ec6ffd7f737a1f56 + zh: 5e368f87ce52e28c +/agent-note-domain-image-slots-and-a-shared-gallery-factory/decision: + en: b807777fd48560eb + zh: e7b1625bd4448ce1 +/agent-note-domain-image-slots-and-a-shared-gallery-factory/alternatives-considered: + en: db14fd6d0e2ce78b + zh: c29a19cde692a1dd +/agent-note-domain-image-slots-and-a-shared-gallery-factory/verification: + en: d82e036edb981e7c + zh: 5a05e9a2e6489d21 +/agent-note-domain-image-slots-and-a-shared-gallery-factory/consequences: + en: ac387ffb5a316920 + zh: ab584aaafe554278 diff --git a/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.md b/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.md new file mode 100644 index 0000000000..054dbe24ac --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.md @@ -0,0 +1,54 @@ +# Agent Note: Domain image Slots and a shared gallery Factory + +Status: implemented + +English | [中文](2026-10-09-message-node-factories-and-delegates.zh.md) + +## Problem + +User messages, assistant output, Trajectory records, and tool results need independently replaceable image presentation. Their official entries can share one gallery, but sharing that implementation must not merge their replacement positions or hide the caller's image-reading authority. + +## Decision + +Each domain declares its own image Slot and supplies the framework's `renderSlot` seat to the component that renders it. The official attachment entries use one reusable Content Factory, following the [Body Slot and Content Factory division](2026-10-09-reasoning-content-slot-factory.md). + +| Entry | Declaration owner and renderer | +| --- | --- | +| `conversation.chat.user.images` Slot | The `conversation.chat.user.content` Factory declares it; `UserContent` renders it for user messages, pending steering, and local echoes. | +| `conversation.chat.message.images` Slot | The Assistant node registration declares it; `AssistantMarkdown` renders consecutive output-image groups. | +| `conversation.trajectory.images` Slot | The Trajectory view registration declares it; record attachments and tool-output blocks render it through the ledger's Slot seat. | +| `tool.call.images` Slot | The `read_image` tool-view registration declares it; `ToolRow` renders the result image. | +| `conversation.images.content` Factory | The attachment plugin registers this root-scoped gallery, implemented by `MessageImagesContent`. | + +The attachment plugin fills all four image Slots with the same `MessageImages` React adapter at priority 100. A smaller priority replaces only the selected domain's entry; disposing that replacement restores the official entry. Each adapter invokes `conversation.images.content` with explicit image references, `loadImage`, and layout parameters. The shared Factory neither declares the domain Slots nor selects a domain from a scene parameter. + +The image callers use their declared Slot directly; no image-entry Factory exists solely to forward one Slot call. User text remains a separate shared `conversation.user.text` Factory with its own keyed node Slot, as specified by the [user-text decision](2026-10-10-user-text-json-nodes.md). + +`AssistantNodeView` passes its Slot seat and `loadImage` to `AssistantMarkdown`. User wrappers pass the loader through `UserStyleBubble` to `UserContent`. Trajectory passes its Slot seat and loader through the ledger. These paths preserve component responsibilities, image order, and keys without custom ReactNode-producing image callbacks. + +Conversation owns read authorization, per-Session URL caching, and cleanup. The shared gallery never searches for a global current Session: persistent reads use the loader supplied by the caller, while submission-echo previews retain their existing browser URLs. Gallery layout, retries, thumbnails, and lightbox behavior remain in the attachment package. + +`ChatView` keeps the existing `MarkdownDelegateProvider` with its wrapped file opener, external-link action, and file-image capabilities. Native-image composition does not replace Markdown image handling or its failure feedback. + +`MessageImagesContentInput` accepts optional complete `MessageImageLabels`. Supplied labels are used unchanged; when omitted, the Content Factory's locale seat supplies the default copy. + +## Alternatives considered + +**One shared image Slot for every caller.** A replacement intended for one domain would also affect the others; shared implementation does not require shared replacement identity. + +**Import the gallery component across feature packages.** This bypasses standard Slot replacement and the reusable Factory entry point. + +**Pass custom image-rendering functions or supply the loader through a private Context.** Framework Slot seats already express rendering authority, while explicit loader props preserve the caller's Session authority. + +## Verification + +- User and output images use separate Slots; replacing either leaves the other and its mounted gallery untouched. +- Each official image entry has priority 100; a priority-0 replacement wins and disposal restores the official gallery. +- All four defaults call the same Content Factory with their original image data, authorized loader, and layout choices. +- Source order, keys, cached previews, failed-load retries, and lightbox interactions retain their existing behavior. +- The Content Factory accepts complete custom labels and resolves default labels when the caller omits them. +- Unloading the attachment implementation removes its entries without removing Slots declared by the owning domains. + +## Consequences + +Independent Slots allow domain-specific presentation without copying the gallery. Domain callers must forward the framework Slot seat to their plain React descendants and must supply an authorized loader at each image call. A Factory and an ordinary Slot have different lifetimes and ownership; a reusable implementation does not own every position where it appears. diff --git a/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.zh.md b/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.zh.md new file mode 100644 index 0000000000..03869f2dbb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-message-node-factories-and-delegates.zh.md @@ -0,0 +1,54 @@ +# Agent Note: 领域图片 Slot 与共享画廊 Factory + +Status: implemented + +[English](2026-10-09-message-node-factories-and-delegates.md) | 中文 + +## 问题 + +用户消息、助手输出、Trajectory 记录和工具结果需要可独立替换的图片展示。官方条目可以共享同一画廊,但共享实现不能合并各自的替换位置,也不能隐藏调用方的图片读取授权。 + +## 决策 + +各领域声明自己的图片 Slot,并把框架 `renderSlot` 席位交给实际渲染它的组件。官方附件条目复用一个 Content Factory,沿用 [Body Slot 与 Content Factory 的分工](2026-10-09-reasoning-content-slot-factory.zh.md)。 + +| 入口 | 声明所有者与渲染组件 | +| --- | --- | +| `conversation.chat.user.images` Slot | `conversation.chat.user.content` Factory 声明,由 `UserContent` 为用户消息、待处理 steering 和本地回显渲染。 | +| `conversation.chat.message.images` Slot | Assistant 节点注册声明,由 `AssistantMarkdown` 渲染连续的输出图片组。 | +| `conversation.trajectory.images` Slot | Trajectory 视图注册声明,记录附件及工具输出块通过账本的 Slot 席位渲染。 | +| `tool.call.images` Slot | `read_image` 工具视图注册声明,由 `ToolRow` 渲染结果图片。 | +| `conversation.images.content` Factory | 附件插件注册此 root 作用域画廊,由 `MessageImagesContent` 实现。 | + +附件插件以优先级 100 为四个图片 Slot 填入同一个 `MessageImages` React 适配组件。较小的优先级只替换选定领域的条目;替换条目释放后恢复官方条目。适配组件显式向 `conversation.images.content` 传入图片引用、`loadImage` 和布局参数。共享 Factory 不声明各领域的 Slot,也不通过场景参数选择领域。 + +图片调用方直接使用其声明的 Slot,不设置仅转发一次 Slot 调用的图片入口 Factory。用户文本仍使用独立共享的 `conversation.user.text` Factory 及其 keyed 节点 Slot,详见[用户文本决策](2026-10-10-user-text-json-nodes.zh.md)。 + +`AssistantNodeView` 将 Slot 席位与 `loadImage` 传给 `AssistantMarkdown`。用户包装层通过 `UserStyleBubble` 将 loader 传给 `UserContent`。Trajectory 通过账本传递自己的 Slot 席位与 loader。这些路径保持组件职责、图片顺序和 key,不使用自制的 ReactNode 图片渲染回调。 + +Conversation 拥有读取授权、逐 Session URL 缓存与回收。共享画廊不查找全局当前 Session:持久图片使用调用方提供的 loader 读取,本地提交回显预览保留已有浏览器 URL。画廊布局、重试、缩略图和灯箱行为仍由附件包负责。 + +`ChatView` 保留既有 `MarkdownDelegateProvider` 及其包装后的文件打开动作、外链动作和文件图片能力。原生图片组合不替代 Markdown 图片处理及失败反馈。 + +`MessageImagesContentInput` 接受可选的完整 `MessageImageLabels`。提供 labels 时原样使用,省略时由 Content Factory 的 locale 席位提供默认文案。 + +## 考虑过的替代方案 + +**所有调用方共用一个图片 Slot。** 面向某个领域的替换也会影响其他领域;共享实现不要求共享替换身份。 + +**跨功能包导入画廊组件。** 绕过标准 Slot 替换机制和可复用的 Factory 入口。 + +**传递自制图片渲染函数,或通过私有 Context 供应 loader。** 框架 Slot 席位已经表达渲染权限,显式 loader props 则保留调用方的 Session 授权。 + +## 验证 + +- 用户与输出图片使用独立 Slot;替换任意一方时,另一方及其已挂载画廊不受影响。 +- 各官方图片条目优先级为 100;优先级 0 的替换条目胜出,释放后恢复官方画廊。 +- 四个默认条目携带原有图片数据、授权 loader 和布局选项调用同一个 Content Factory。 +- 来源顺序、key、缓存预览、读取失败重试及灯箱交互保持既有行为。 +- Content Factory 接受完整自定义 labels,调用方省略时解析默认 labels。 +- 卸载附件实现会移除其条目,但不移除各领域声明的 Slot。 + +## 影响 + +独立 Slot 支持各领域定制展示而无需复制画廊。领域调用方需要将框架 Slot 席位传给普通 React 后代组件,并在每次图片调用中提供授权 loader。Factory 与普通 Slot 的生命周期和所有权不同;可复用实现不拥有它出现的所有位置。 diff --git a/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.i18n.yaml new file mode 100644 index 0000000000..da9d7f6c81 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-09-ptc-owned-policy-cleanup.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.md +/agent-note-ptc-owns-policy-change-cleanup-waits: + en: dfe28bee0ab79ff6 + zh: dd68c51b4cbfbc3f +/agent-note-ptc-owns-policy-change-cleanup-waits/problem: + en: 5620ff525d762114 + zh: ddef3a3624cab79b +/agent-note-ptc-owns-policy-change-cleanup-waits/decision: + en: 4389c330d95f1588 + zh: 97e4b9cf8b69f48e +/agent-note-ptc-owns-policy-change-cleanup-waits/alternatives-considered: + en: a51d7f5c5b8fd7dc + zh: 4480107a4d8cff70 +/agent-note-ptc-owns-policy-change-cleanup-waits/consequences: + en: f83009b6406bafa1 + zh: c774eb1895bf37e1 diff --git a/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.md b/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.md new file mode 100644 index 0000000000..470568cc3f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.md @@ -0,0 +1,27 @@ +# Agent Note: PTC owns policy-change cleanup waits + +Status: implemented + +English | [中文](2026-10-09-ptc-owned-policy-cleanup.zh.md) + +## Problem + +Stopping a retained Node process and its nested tools can take longer than recording a new file policy. Making permission setters await that cleanup spreads PTC lifecycle requirements into unrelated callers, including Webhook Session creation, and adds cancellation windows to those callers. + +## Decision + +Permission setters commit synchronously. Success means the selected policy is recorded; it does not guarantee that operations admitted under the old policy have completely stopped. This replaces the completion requirement and cleanup ownership in the [retained-process sandbox decision](2026-10-08-persistent-ptc-sandbox.md), whose confinement and one-time escalation rules still apply. + +PTC observes committed Session mode changes. The tool bridge immediately cancels affected complete calls, including pending approvals and nested tools. A later PTC call waits for canceled predecessors to settle before resolving the latest standing policy. The Node provider immediately invalidates affected processes, including idle environments, starts cleanup, and retains the cleanup Promise internally. A later program waits for that cleanup; failed cleanup remains retryable and prevents process reuse. Unchanged modes preserve environments. Tool-registry and provider unload remove their observers and await owned work. + +## Alternatives considered + +**Wait in permission setters.** This provides a definite completion point for old-authority work, but no current permission consumer requires that guarantee. It introduces a general resource registry and asynchronous API migration for PTC-specific cleanup. The completion guarantee belongs to PTC execution and disposal instead. + +**Clean up only on the next PTC call.** An idle environment can retain background work indefinitely when no further call occurs. Policy changes begin cancellation immediately; only waiting is deferred. + +**Reconfigure an existing process.** The sandbox applies restrictions at launch. Open handles, retained objects and background work require releasing the old environment before another policy can execute there. + +## Consequences + +Permission changes return without process-cleanup latency. Old operations may remain active while cancellation finishes, and cleanup failure does not roll back the recorded policy. Subsequent PTC execution waits for cleanup and uses the latest policy. Webhook creation keeps its synchronous permission step, so that step adds no cancellation window before prompt admission. Regression coverage holds cleanup with explicit barriers, changes policy again while a call waits, checks idle cancellation without another call, and verifies cleanup retry and owner unload. diff --git a/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.zh.md b/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.zh.md new file mode 100644 index 0000000000..9d852a0eb6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-09-ptc-owned-policy-cleanup.zh.md @@ -0,0 +1,27 @@ +# Agent Note: PTC 自行等待策略变化后的清理 + +Status: implemented + +[English](2026-10-09-ptc-owned-policy-cleanup.md) | 中文 + +## 问题 + +停止保留的 Node 进程及其嵌套工具,可能比记录新文件策略耗时更长。让权限设置等待这些清理,会把 PTC 生命周期要求传给 Webhook Session 创建等无关调用方,并为这些调用方增加取消窗口。 + +## 决策 + +权限设置同步提交。成功表示所选策略已经记录,不保证按旧策略接纳的操作已完全停止。这替代[保留进程沙箱决策](2026-10-08-persistent-ptc-sandbox.zh.md)中的完成要求和清理归属;其中的沙箱限制与单次提权规则继续适用。 + +PTC 观察已提交的 Session 模式变化。工具桥接立即取消受影响的完整调用,包括等待中的审批和嵌套工具。后续 PTC 调用先等待已取消的调用结束,再解析最新常设策略。Node 提供方立即使受影响的进程失效,包括空闲环境,开始清理并在内部保留清理 Promise。后续程序等待清理完成;清理失败可重试,且阻止复用进程。模式不变时保留环境。工具注册表和提供方卸载时移除各自监听器,并等待所拥有的工作结束。 + +## 考虑过的替代方案 + +**在权限设置中等待。** 这可以明确旧权限下的工作完成时点,但当前权限调用方不需要该保证。为此增加通用资源登记和异步 API 迁移,会扩大 PTC 清理的影响范围。完成保证由 PTC 执行和销毁负责。 + +**等下次 PTC 调用再清理。** 没有后续调用时,空闲环境的后台工作可能一直存在。策略变化立即开始取消,只有等待被推迟。 + +**重新配置已有进程。** 沙箱在启动时应用限制。打开的句柄、保留对象和后台工作要求先释放旧环境,才能在其中按另一策略执行。 + +## 影响 + +权限变化返回时无需等待进程清理。取消完成前,旧操作可能仍在运行;清理失败不会回滚已记录的策略。后续 PTC 执行等待清理并使用最新策略。Webhook 创建保留同步权限步骤,该步骤不会在提交任务前增加取消窗口。回归测试通过显式信号阻塞清理,覆盖等待期间再次改变策略、没有后续调用时取消空闲环境、清理重试及所有者卸载。 diff --git a/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.i18n.yaml new file mode 100644 index 0000000000..41d9dfe377 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.i18n.yaml @@ -0,0 +1,40 @@ +# Bilingual-pair consistency record for 2026-10-10-user-text-json-nodes.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh: + en: 6185ac67a459beba + zh: 994bf90f05c0fd5a +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/problem: + en: 42e3752efebedde5 + zh: 75e23c5762efbb1f +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/decision: + en: 71f5b33f58cd2066 + zh: 8365506795c0b158 +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/decision/rule-roles-and-original-coordinates: + en: ed0fa9306f0605cb + zh: 7240e135f6d1b46b +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/decision/one-reconciliation-loop: + en: acaeb2dccfac3f07 + zh: 2170ec2b858627fc +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/decision/query-cache-and-traversal: + en: 55dee64de32bef9a + zh: 69eb625451f55268 +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/decision/actual-facts-dependencies: + en: 11bc718324d22c03 + zh: 371576c1b2a90d62 +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/decision/facts-text-and-registration-refresh: + en: 47bc3f32b9aa22de + zh: 59ffd06c800c00af +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/decision/output-ownership-and-publication: + en: e076cb57a1fdcfc1 + zh: 988c02c6cf751f16 +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/verification-requirements: + en: 78127c1f18eacf8a + zh: fcc2ad5db1279356 +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/alternatives-considered: + en: 439e5ecff6701938 + zh: 9861805f2a19439c +/agent-note-user-text-candidate-scheduling-and-facts-driven-refresh/consequences: + en: 13bd26532d0353fa + zh: d6a4997b51af09d5 diff --git a/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md b/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md new file mode 100644 index 0000000000..3b01c313f0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md @@ -0,0 +1,91 @@ +# Agent Note: User-text candidate scheduling and Facts-driven refresh + +Status: implemented + +English | [中文](<2026-10-10-user-text-json-nodes.zh.md>) + +## Problem + +User text contains references owned by independent businesses. Recognition must follow original-text positions, resolve collisions deterministically, and reuse unaffected matching work when Facts change. The evaluator must expose its scheduling behavior to pure logic tests without depending on React, browser timing, or elapsed-time benchmarks. + +## Decision + +The composition is business registration, lazy candidate matching, a single reconciliation loop, readonly JSON nodes, and business-owned keyed renderers. Initialization and Facts refresh use the same algorithm; they differ only in which query caches remain valid. + +### Rule roles and original coordinates + +Every rule provides an ID, finite order, and synchronous `match(text, from, context)`. Each call returns its nearest eligible node with `start >= from`, or no candidate anywhere in the remaining original text. It returns one node, not all matches or a replacement document. The original string and UTF-16 offsets remain intact: a search cursor does not create a new word, line, or quoted-token boundary. Matching depends only on original text and Facts, not previously selected node payloads. + +Each matcher resolves its own alternative spellings by earliest start and then its documented same-start choice; Session labels choose the longer match. A matcher cannot replace a consumed prefix with the remainder of an overlapping candidate. Each business owns its grammar, payload, and renderer; the generic evaluator has no Session, file, skill, or command branches. + +There is one rule type and one candidate protocol. A candidate contains either a business node using the rule ID or a Text node preserving the original substring with an optional `data.display`. Text-producing rules compete by the same start, order, and stable ID as business rules. Order only breaks same-start ties; no rule gets precedence over an earlier position. + +### One reconciliation loop + +The evaluator keeps original text, the previous successful segmentation, registered definitions, per-rule Facts reads, and query results. Nonempty text initially has one Text covering `[0, text.length)`; empty text has no nodes. Initialization makes every rule invalid, including rules that read no Facts. + +Each reconciliation starts its result cursor at zero. Every matcher obtains one candidate through the same cache-aware query operation. The evaluator selects the smallest candidate start, breaks same-start ties by ascending rule order and stable ID, emits the preceding raw Text gap, emits the winner, and advances the cursor to the winner's end. No candidate means the remaining raw text is emitted and recognition ends. + +Only a consumed candidate or a candidate whose start is before the new cursor needs another query. A cached candidate beginning at or after the cursor remains eligible. A no-candidate result remains eligible as the cursor advances. All ranges are nonempty half-open original-text ranges; candidates cannot move the cursor backward or exceed the original string. + +Previously accepted nodes are reusable output, not a complete list of possible matches: a losing candidate can become visible when an earlier winner disappears. The evaluator retains queries for this purpose instead of treating an old Text node or the absence of a business node as unconditional evidence of no match. + +### Query cache and traversal + +A query record contains its original `from` offset and either the next candidate, no candidate, or a failure. If a query from `q` returned a candidate starting at `s`, its result is valid for any requested cursor `c` with `q <= c <= s`. A no-candidate result is valid for every `c >= q`. Neither result proves anything before `q`. A failed query is reusable only at the same requested offset while its dependencies remain valid. + +During a reconciliation, each matcher has one active candidate. The evaluator also retains the sorted query records already produced for that matcher across reconciliations; it does not enumerate all possible matches eagerly. Forward cursors walk these records monotonically. Queries generated in newly exposed gaps are merged with retained records in source order, with one record per query offset. Unsearched intervals require matching rather than an invented negative result. + +The result cursor and matcher search cursors are distinct. Starting result reconciliation at zero does not require unchanged matchers to scan from zero again: their recorded queries answer valid requests. Each matcher must implement a forward search rather than repeatedly materializing every match in the remaining text. Internal scans, candidate selection, and result comparison still have costs; the scheduling guarantees concern actual matcher calls, not a claim that arbitrary regular expressions are linear. + +### Actual Facts dependencies + +`context.read(key)` returns the borrowed readonly value from the current Facts snapshot and records the read, including `undefined`. The reader is valid only during its owning synchronous call and cannot be retained. Businesses receive neither a whole Facts object, a manual `dependsOn` list, nor previous-output/cache objects. + +A matcher's dependency set is the union of reads for the queries retained in its current cache generation, including losing candidates, no-match queries, and failed calls. Changed fields are detected with `Object.is` at field granularity. A new outer Facts object alone does not invalidate matching. When a rule is invalidated, its old queries and read set are discarded; subsequent calls establish the replacement read set, so obsolete conditional dependencies do not remain permanently attached. + +Text-producing rules use the same query cache and dependency generation as every other rule. Updating a whitespace switch invalidates only its readers; it does not trigger an unconditional pass over the completed nodes. + +### Facts, text, and registration refresh + +A Facts update invalidates only rules that read changed fields. Their first query starts at original offset zero; all other rules retain their query records. The same reconciliation loop then compares fresh candidates with reusable ones. Refreshing a rule does not give it priority, and a new first candidate does not hide the removal of an earlier old winner. + +A fresh candidate confined to previously plain text can split that Text without invoking unrelated matchers whose cached queries still cover the new cursors. A fresh candidate that loses to an earlier unchanged winner is discarded without invalidating that winner. When a fresh winner covers another candidate, only expired heads advance. When a winner disappears or shrinks, cached losing candidates can compete again; any previously unsearched interval causes a query at the newly exposed cursor. All changes use the same cursor loop and query-coverage rules. + +Several changed Facts fields form one snapshot and one invalidation set. All affected matchers participate in the same reconciliation; one update is not committed before processing the next. Equivalent refreshed results reuse previous nodes and, when all elements remain identical, the entire result array. Reconciliation settles the complete document before publishing its result. + +Original-text changes discard all query caches and supply one full-range Text as the previous segmentation. New or replaced rule definitions start with empty caches; unchanged definitions retain their independent queries. Removed rules lose their dependencies and candidates. Reconciliation after additions, removals, or order changes uses the same selection logic and can expose formerly blocked candidates. + +### Output, ownership, and publication + +Nodes retain `{ id, start, end, data }`. Business nodes use their matcher's ID; Text retains the exact source substring in `data.text` and optional display text in `data.display`. Output is ordered, nonoverlapping, and completely covers the original text. JSON compatibility and readonly ownership are TypeScript obligations: the evaluator neither freezes borrowed objects nor deep-copies Facts or payloads for isolation. + +The document evaluator owns all caches; the registry retains neither evaluators nor document subscriptions. Separate text instances do not share state through a global cache. Only fully successful evaluation publishes a new result. A matcher failure carries the rule ID and cause and publishes no partial segmentation; its actual reads remain available for dependency-driven retry. Reentrant evaluation and escaped synchronous read contexts are rejected. + +`conversation.user.text` remains a session-scoped Factory owning `conversation.user.text.node`, a keyed inline Slot. React consumes final nodes and forwards `raw` and `interactive` to the business renderer. Session, skill, file/folder, and command matching remain owned by their respective plugins, and actions remain in each renderer's Injection. No matching work or cache subscription moves into React. + +`collapseWhitespace` and `trimWhitespace` each control one ordinary matcher and default to off. Collapse offers whitespace runs as Text candidates with display `" "`; trim offers original leading/trailing whitespace runs with display `""`. Trim has lower order than collapse, so it wins their same-start edge collisions. An earlier reference candidate consumes its whole range and naturally excludes internal whitespace candidates. Every Text candidate retains its exact raw substring; emoji and spaces between references remain intact. `interactive` and CSS `ellipsis` remain React Props, not matching Facts. Queue uses full original text with CSS ellipsis; native attachments remain in their existing cards and image Slots, outside text recognition. + +## Verification requirements + +Pure logic tests assert both the final nodes and each matcher's ordered calls with their `from` offsets. They use deterministic input and spies rather than clocks or performance thresholds. + +- Initialization calls every matcher, including Facts-free and no-match rules; empty input has explicit terminal-query behavior. +- Earlier starts beat stronger order values; same-start ties use order and stable ID, and each matcher preserves its own longest-match choice. +- A future candidate and a no-match answer are not requested again during forward traversal; only the winner and overlapping heads advance. +- Unread Facts changes and new outer Facts objects with unchanged field values cause no matcher calls. +- One or several changed fields rerun exactly their readers; missing fields, losing candidates, no-match results, failures, and conditional read-set replacement remain covered. +- Equivalent refreshes preserve node/array identity and do not invoke unrelated matchers; payload-only changes preserve unaffected nodes. +- Insertions in plain text, losing new candidates, same-start winner changes, extending/shrinking matches, and removal of an early winner assert the exact affected query offsets and counts. +- Removing or shrinking a winner exposes cached losers and unsearched gaps; an old tail no-match result cannot answer a query before its recorded origin. +- Batched Facts updates equal a fresh evaluation under the same snapshot and do not give the first refreshed matcher precedence. +- Text and rule-definition changes, registration/disposal, range validation, synchronous failure containment, Context lifetime, and independent evaluator state have deterministic tests. +- Real Session/file/skill/command combinations preserve full quoted references, original word boundaries, and same-start precedence; whitespace candidates use exactly the same scheduling and cache rules. + +## Alternatives considered + +**Ordered whole-document business transforms.** A business can consume later text before an earlier reference from another business is considered, so fixed type order does not express leftmost recognition. + +## Consequences + +Field-level invalidation can require a matcher to traverse the document again; it does not promise per-element Facts invalidation. Query history consumes memory proportional to the distinct recorded search positions for the current text and definitions. Reconciliation and JSON identity alignment can still traverse output without invoking matchers. The performance evidence is the exact scheduling count and query offsets, while semantic evidence compares refreshed output with a fresh evaluator. This mechanism requires no browser end-to-end or elapsed-time benchmark tests. diff --git a/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.zh.md b/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.zh.md new file mode 100644 index 0000000000..c689d56cc9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.zh.md @@ -0,0 +1,91 @@ +# Agent Note: 用户文本候选调度与 Facts 驱动刷新 + +Status: implemented + +[English](<2026-10-10-user-text-json-nodes.md>) | 中文 + +## 问题 + +用户文本包含独立业务拥有的引用。识别必须按原文位置推进,确定性地处理冲突,并在 Facts 变化时复用无关匹配工作。计算器必须能通过纯逻辑测试展示调度行为,不依赖 React、浏览器时序或耗时基准。 + +## 决策 + +采用业务注册、按需候选匹配、单一协调循环、只读 JSON 节点和业务拥有的 keyed renderer。初始化与 Facts 刷新使用同一个算法,只在查询缓存的有效性上存在差别。 + +### 规则职责与原始坐标 + +所有规则都提供 ID、有限的 order 和同步 `match(text, from, context)`。每次调用返回 `start >= from` 的最近有效节点,或确认剩余原文中没有候选。它返回一个节点,不返回全部匹配或整份替换文档。原始字符串及 UTF-16 坐标保持不变:搜索游标不创造新的词首、行首或带引号词元边界。匹配只依赖原文和 Facts,不依赖先前选中节点的 payload。 + +每个匹配器先按最早起点处理自身不同写法,再按该语法规定处理同起点选择;Session 标签选择较长匹配。匹配器不能把被消费前缀之后的半截重叠候选变成新匹配。语法、payload 和 renderer 均归对应业务所有,通用计算器不包含 Session、文件、skill 或命令分支。 + +只有一种规则类型和一个候选协议。候选既可以包含使用规则 ID 的业务节点,也可以包含保留原文子串、携带可选 `data.display` 的 Text 节点。产生 Text 的规则与业务规则按相同的起点、order 和稳定 ID 竞争。Order 仅裁定同起点冲突,任何规则都不优先于更早的位置。 + +### 单一协调循环 + +计算器保留原文、上一次成功分段、注册定义、逐规则 Facts 读取记录和查询结果。非空原文最初对应一个覆盖 `[0, text.length)` 的 Text,空原文没有节点。初始化使所有规则失效,包括不读取 Facts 的规则。 + +每次协调都从结果游标零开始,各匹配器通过同一个带缓存的查询操作获取一个候选。计算器选择起点最小的候选,同起点按规则 order 升序和稳定 ID 裁定,输出前面的原文 Text 空隙,输出赢家,再将游标推进到赢家末尾。全部没有候选时,输出剩余原文并结束识别。 + +只有被消费的候选或起点早于新游标的候选需要再次查询。缓存候选从新游标或其后开始时仍然有效;无候选结论在游标前进时保持有效。所有范围均是原文中的非空半开区间;候选不能使游标倒退或超出原文。 + +先前采纳的节点是可复用输出,不是所有可能匹配的完整清单;更早的赢家消失后,落败候选可能重新可见。计算器为此保留查询,而不能将旧 Text 节点或缺少某类业务节点无条件解释为没有匹配。 + +### 查询缓存与遍历 + +查询记录包含原始 `from` 偏移,以及下一个候选、无候选或失败。若从 `q` 查询得到起点为 `s` 的候选,则在请求游标 `c` 满足 `q <= c <= s` 时可以复用;无候选结论可用于所有 `c >= q`。两者都不能证明 `q` 之前的情况。失败查询只在请求偏移相同且依赖仍有效时复用。 + +一次协调过程中,每个匹配器只有一个活动候选。计算器同时保留该匹配器跨次协调已经产生的有序查询记录,不预先枚举所有可能匹配。前进游标单调遍历这些记录;新暴露空隙中的查询按原文顺序与旧记录合并,每个查询偏移只保留一条记录。未搜索区间必须执行匹配,不能虚构无匹配结论。 + +结果游标与匹配器搜索游标不同。结果协调从零开始,不代表无变化的匹配器需要从零重新扫描,它们的查询记录可以回答有效请求。各匹配器必须实现向前搜索,不能每次调用都重新收集剩余文本中的全部匹配。内部扫描、候选选择及结果比较仍有成本;调度保证针对实际匹配器调用,不宣称任意正则表达式都是线性的。 + +### 实际 Facts 依赖 + +`context.read(key)` 返回本次 Facts 快照中借用的只读值,并记录读取,包括 `undefined`。读取器仅在所属同步调用期间有效,不得保留。业务既不获得完整 Facts 对象,也不维护手工 `dependsOn` 列表或接收上一轮输出/缓存对象。 + +匹配器依赖集合是当前缓存代次所保留查询读取字段的并集,包括落败候选、无匹配查询和失败调用。字段变化按 `Object.is` 比较,外层 Facts 对象换引用不单独使匹配失效。规则失效时丢弃旧查询及读取集合,后续调用建立新的集合,因此已经不再读取的条件依赖不会永久残留。 + +产生 Text 的规则与其他规则共用查询缓存和依赖代次。空白开关更新只使它的读取者失效,不触发对已完成节点的无条件遍历。 + +### Facts、原文与注册刷新 + +Facts 更新只使实际读取变化字段的规则失效。它们的首次查询从原文零开始,其他规则保留查询记录;随后由同一个协调循环比较新候选和可复用候选。规则刷新不赋予额外优先权,新首个候选也不能掩盖更早旧赢家的消失。 + +新候选完全位于原有普通文字内时,可以拆分该 Text;无关匹配器的缓存仍覆盖新游标时,不调用它们。新候选输给更早的有效旧赢家时,丢弃新候选,不使旧赢家失效。新赢家覆盖其他候选时,只推进过期的候选头。赢家消失或缩短时,缓存的落败候选可以重新竞争;此前未搜索的区间在新暴露游标处触发查询。所有变化都使用同一个游标循环和查询覆盖规则。 + +多个 Facts 字段变化形成同一份快照和一个失效集合,所有受影响匹配器共同参与一次协调,不先提交某个更新再处理另一个。刷新结果等价时复用旧节点,所有元素相同则复用整个结果数组。协调在整份文档确定后发布结果。 + +原文变化会丢弃全部查询缓存,并以覆盖全文的 Text 作为上一版分段。新增或替换的规则定义从空缓存开始,无变化定义保留各自独立查询。规则移除时删除其依赖和候选。新增、移除或顺序变化后的协调仍使用相同选择逻辑,并可暴露此前被遮挡的候选。 + +### 输出、所有权与发布 + +节点保留 `{ id, start, end, data }`。业务节点使用所属匹配器 ID;Text 的 `data.text` 保留准确原文子串,`data.display` 可保存显示文字。输出有序、非重叠并完整覆盖原文。JSON 兼容性与只读所有权由 TypeScript 协议约束;计算器既不冻结借用对象,也不为隔离而深拷贝 Facts 或 payload。 + +文档计算器拥有全部缓存;注册表不持有计算器或文档订阅,不同文本实例不通过全局缓存共享状态。只有完整成功的求值才能发布新结果。匹配器失败时保留规则 ID 与 cause,不发布部分分段;实际读取仍参与依赖驱动的重试。禁止重入求值以及逃逸的同步读取 Context。 + +`conversation.user.text` 保持 session 作用域 Factory,拥有 keyed inline Slot `conversation.user.text.node`。React 消费最终节点,将 `raw` 和 `interactive` 交给业务 renderer。Session、skill、文件/目录和命令匹配仍归各插件所有,动作仍由各 renderer 的 Injection 提供,匹配与缓存订阅不进入 React。 + +`collapseWhitespace` 与 `trimWhitespace` 分别控制一个普通匹配器,缺省均关闭。Collapse 将空白串作为显示值为 `" "` 的 Text 候选;trim 将原文开头/末尾的空白串作为显示值为 `""` 的候选。Trim 的 order 小于 collapse,因此在同起点的边缘空白冲突中胜出。更早的引用候选消费自身完整范围,自然排除内部空白候选。每个 Text 候选保留准确的原文子串,emoji 及引用之间的空格保持不变。`interactive` 和 CSS `ellipsis` 仍为 React Props,不是匹配 Facts。Queue 使用完整原文和 CSS 省略,原生附件保留既有卡片及图片 Slot,不进入文本识别。 + +## 验证要求 + +纯逻辑测试同时断言最终节点,以及每个匹配器有序的调用和 `from` 偏移。使用确定性输入与 spy,不依赖时钟或性能阈值。 + +- 初始化调用所有匹配器,包括不读 Facts 和始终无匹配的规则;空输入具有明确的终止查询行为。 +- 较早起点胜过更强 order;同起点按 order 和稳定 ID 裁定,各匹配器保留自身最长匹配选择。 +- 向前遍历不重复查询未来候选及无匹配结论,只推进赢家和重叠候选头。 +- 未读取 Facts 字段变化,或字段值不变而外层 Facts 对象换引用,不调用匹配器。 +- 一个或多个字段变化只重跑实际读取者;覆盖缺失字段、落败候选、无匹配结果、失败和条件依赖集合替换。 +- 等价刷新保留节点/数组引用且不调用无关匹配器;仅 payload 变化保留无关节点。 +- 普通文字中插入、落败的新候选、同起点换赢家、匹配扩张/缩短、较早赢家移除,均断言准确的受影响查询偏移与次数。 +- 赢家移除或缩短后暴露缓存落败者及未搜索空隙;旧尾部的无匹配结论不能回答其查询起点之前的问题。 +- 批量 Facts 更新等于相同快照下的新建计算器结果,不赋予先刷新匹配器额外优先权。 +- 原文及规则定义变化、注册/注销、范围校验、同步失败隔离、Context 生命周期和计算器状态独立均有确定性测试。 +- 真实 Session/文件/skill/命令组合保留完整带引号引用、原始词边界和同起点优先关系;空白候选使用完全相同的调度和缓存规则。 + +## 备选方案 + +**按顺序处理整篇文档的业务变换。** 某业务可能在另一业务更早的引用获得考虑前消费后面的文本,因此固定类型顺序不能表达最左优先识别。 + +## 影响 + +字段级失效仍可能要求某个匹配器重新遍历文档,不承诺 Facts 字段内部逐元素失效。查询历史的内存量与当前原文、定义下记录的不同搜索位置成正比。协调及 JSON 引用对齐可能遍历输出而不调用匹配器。性能证据是准确的调度次数和查询偏移,语义证据是刷新结果与全新计算器的等价性。本机制不需要浏览器端到端测试或耗时基准测试。 diff --git a/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.i18n.yaml new file mode 100644 index 0000000000..3087777feb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for 2026-10-11-chat-group-tree-exchanges.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.md +/agent-note-chat-group-tree-positions-and-exchanges: + en: b26212eda152d6c6 + zh: a801a75ee0c07911 +/agent-note-chat-group-tree-positions-and-exchanges/problem: + en: 84858bc0e1e268ab + zh: 39ebb2979968d6cc +/agent-note-chat-group-tree-positions-and-exchanges/decision: + en: c8c4091863dec269 + zh: 57a0f26683867350 +/agent-note-chat-group-tree-positions-and-exchanges/why-mark-the-opening-rather-than-the-notice: + en: db8d77cd773ad646 + zh: ab2f03b8fc58e952 +/agent-note-chat-group-tree-positions-and-exchanges/alternatives-considered: + en: 635ddcb04fefe8e2 + zh: 360c171ccb613ed5 +/agent-note-chat-group-tree-positions-and-exchanges/consequences: + en: c8cfdc3009b19b12 + zh: 36c541cd9692057d +/agent-note-chat-group-tree-positions-and-exchanges/testing: + en: 0d7f5281e66b0c39 + zh: 5be221de46e9e0f7 diff --git a/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.md b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.md new file mode 100644 index 0000000000..6c3a9f0df1 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.md @@ -0,0 +1,51 @@ +# Agent Note: Chat group-tree positions and exchanges + +Status: implemented + +English | [中文](2026-10-11-chat-group-tree-exchanges.zh.md) + +## Problem + +On next message folding kept only the last Turn of the loaded timeline expanded. A Turn woken by a notice (a settled subagent, goal round, schedule, or background job) is not submitted by this Client, yet its arrival made the preceding Turn historical and folded it. No own-input driver computed the exact remaining room for that fold, so the scroll layer reserved generic bottom space and a reader following the tail saw blank space. In the recorded Session the notice woke the next Turn 13–15 ms after the previous Turn ended; the minimal reproduction left 596 px blank that had not recovered after five seconds. + +## Decision + +A notice is neither body text nor a user message: folding and bottom advancement ignore it. The bottom changes from the last Turn to the latest exchange. + +- **Group-tree positions.** `ChatConversationViewNode.groupTree` declares a Node's position in the group tree, typed `ChatGroupTree = 'exchange' | 'turn' | 'process'` and ordered outermost first; a Node at a position also stands outside every inner grouping. `isAtOrOutside(node, position)` is the single reader of that order. Only `exchange` is read today; `turn` and `process` are reserved for migrating the `TURN_PROCESS_INDEPENDENT_KINDS` and process-group `INDEPENDENT` kind lists later without changing what `exchange` means. +- **Exchanges.** A Turn holding an `exchange` Node opens an exchange, which lasts until the next opening Turn. The business message Definition marks only human input claimed in Step 1 (`user` or `steering`) as `exchange`; notices and later steering carry no position. +- **Mechanism.** `GroupTreeSegments(position)` splits the loaded Turns at the Turns holding a Node at that position. The latest segment starts at the last opening Turn, or at the first loaded Turn when the window holds none. It counts per Turn incrementally without scanning loaded Nodes, and a start move returns only the Turns that entered or left the latest segment. The Chat Builder's `bottomSource` is "the Node is visible and belongs to the latest exchange". + +As a result, a notice-woken Turn no longer folds earlier Turns, so no room is reserved; the human's next ordinary message folds the whole exchange through the own-input path. + +## Why mark the opening rather than the notice + +The host claims the waking input right after `turn/start`, assembles the system prompt, and only then logs `step/start` and `user/message`; the recorded Session spent 187 ms in that gap. Marking only the notice leaves the new Turn untagged during the gap, so the bottom still advances and the previous Turn folds and then reopens. Marking the human opening and letting unmarked Turns continue the exchange keeps the gap inert. + +## Alternatives considered + +**Tag the notice as a continuation.** The 187 ms gap above makes it fold and reopen, and a claim that mixes a notice with human input needs extra classification. + +**Name opening kinds in a list (`user`, `steering`).** A kind cannot separate Step 1 steering from mid-Turn steering, so a human steering into a notice-woken Turn would wrongly fold the previous exchange. + +**Publish Turn-level Location data.** Only one Context may publish a key for a Turn, while opening input comes from several message Contexts; aggregating per Turn would repeat the inbox claim classification in a new Definition and read every Turn on each update. + +**Declare a business role (`input`, `notice`) on Nodes.** That places business semantics in the grouping mechanism; group-tree positions describe structure only, and each business Definition chooses its position. + +**Correct the scroll room for folds not caused by own input.** Notices should not fold at all, and correcting the room would not remove that unnecessary fold; it remains a residual issue for human input from another tab. + +**Migrate both kind lists now.** That reaches well beyond this defect; the type reserves the positions and the migration is separate work. + +## Consequences + +- Notice-woken Turns no longer cause a fold, reserved room, or blank space, and the grouping mechanism reads declared positions instead of naming kinds. +- Under On next message, a long run of notice-woken Turns (up to 31 goal-mode Turns in sampled Sessions) stays expanded until the human types again. +- When the loaded window holds no opening Turn, every loaded Turn belongs to the latest exchange. +- Human input from another tab folds when its `user/message` arrives, about 200 ms later than the former `turn/start` fold; that fold still uses generic room and is unchanged here. + +## Testing + +- `packages/client/ui-chat/tests/group-tree-segments.client.spec.ts`: position order, segmentation, count fallback, and the empty window. +- `packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts`: latest-exchange membership and notification scope. +- `packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts`: a real assembler across an opening Turn, mid-Turn steering, the pre-Step gap, a notice wake, and an idle steer. +- `apps/web/tests/notice-wake-tail.e2e.ts`: after a long Turn a notice wakes the next Turn; the long Turn stays expanded through the pre-Step gap and after the notice reply, and a following reader sees the notice and the reply. diff --git a/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md new file mode 100644 index 0000000000..170a82fb92 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md @@ -0,0 +1,51 @@ +# Agent Note: Chat 分组树位置与交互段 + +Status: implemented + +[English](2026-10-11-chat-group-tree-exchanges.md) | 中文 + +## Problem + +「下次发送时收起」原本只让已加载时间线的最后一个 Turn 保持展开。由通知唤醒的 Turn(子 agent 完成、Goal Round、定时任务、后台作业)不是本客户端提交的,它一出现,上一轮就被当作历史折叠。这次折叠没有自己输入的驱动来计算精确的剩余补白,滚动层只能按通用规则预留底部空间,正在跟尾的读者因此看到一片空白。录制的真实 Session 中,通知在上一轮结束后 13–15 ms 唤醒新轮次;最小复现里空白高 596 px,五秒后仍未恢复。 + +## Decision + +通知不算正文,也不算用户消息:折叠和推进底部时都忽略它。底部从"最后一个 Turn"改为"最新交互段"。 + +- **分组树位置。** `ChatConversationViewNode.groupTree` 声明节点在分组树中的位置,类型为 `ChatGroupTree = 'exchange' | 'turn' | 'process'`,由外到内有序;站在某个位置的节点同时也站在所有内层分组之外。`isAtOrOutside(node, position)` 是读取这一顺序的唯一入口。目前只读取 `exchange`;`turn` 和 `process` 预留给以后把 `TURN_PROCESS_INDEPENDENT_KINDS` 与过程组 `INDEPENDENT` 两份 kind 名单迁移过来,届时不改变 `exchange` 的含义。 +- **交互段。** 含 `exchange` 节点的 Turn 开启一个交互段,交互段持续到下一个开启 Turn。业务层的 message Definition 只给 Step 1 中被认领的真人输入(`user` 或 `steering`)标 `exchange`;通知和之后的 steering 不标。 +- **机制。** `GroupTreeSegments(position)` 按含该位置节点的 Turn 切分已加载的 Turn,最新一段从最后一个开启 Turn 开始,窗口中没有开启 Turn 时从第一个已加载 Turn 开始。它按 Turn 增量计数,不扫描已加载节点;起点移动时只返回进入或离开最新一段的 Turn。Chat Builder 的 `bottomSource` 为"节点可见且属于最新交互段"。 + +结果是:通知唤醒的 Turn 不再折叠前面的 Turn,没有折叠就没有补白;真人下一次普通输入时,整个交互段经由自己输入的路径一起折叠。 + +## 为什么标开头而不是标通知 + +Host 在 `turn/start` 之后立即认领唤醒输入,然后组装系统提示,再写 `step/start` 和 `user/message`。录制的 Session 中这段间隔为 187 ms。只给通知打标的话,这段时间新 Turn 还没有标签,底部照样推进,上一轮会先折叠再展开。把标签放在真人开头上、未标的 Turn 默认续接,空白间隔里什么都不会发生。 + +## Alternatives considered + +**给通知打"续接"标签。** 上面那 187 ms 的间隔会让它先折后展;同一次认领里通知和真人输入并存时还要额外判断。 + +**按 kind 写一张开启名单(`user`、`steering`)。** kind 区分不了 Step 1 的 steering 与 Turn 中途的 steering,真人往通知唤醒的 Turn 里插话时会错误地折叠前一个交互段。 + +**发布到 Turn 级 Location data。** 同一 Turn 的同一个 key 只允许一个 Context 发布,而开启输入来自多个消息 Context;改成按 Turn 汇总就得在新的 Definition 里重复 inbox 认领分类,并且每次都要读取所有 Turn。 + +**节点声明业务角色(`input`、`notice`)。** 这会把业务语义放进分组机制;分组树位置只描述结构,业务 Definition 自行决定位置。 + +**修正非自身输入折叠时的滚动补白。** 通知本来就不应触发折叠,修补白不能消除这次不必要的折叠;它仍是另一个标签页里真人输入的残留问题。 + +**这次就迁移两份 kind 名单。** 改动面明显超出这次缺陷;类型先预留位置,迁移另做。 + +## Consequences + +- 通知唤醒的 Turn 不再产生折叠、补白和空白;分组机制读取节点声明的位置,而不是点名 kind。 +- 「下次发送时收起」下,一长串通知唤醒的 Turn(抽样会话中 Goal 模式最长 31 轮)会一直展开,直到真人再次输入。 +- 已加载窗口里没有开启 Turn 时,所有已加载 Turn 都属于最新交互段。 +- 另一个标签页里的真人输入在它的 `user/message` 到达时才折叠,比原来在 `turn/start` 时晚约 200 ms;这类折叠仍使用通用补白,本次没有修改。 + +## Testing + +- `packages/client/ui-chat/tests/group-tree-segments.client.spec.ts`:位置顺序、切分、计数回退与空窗口。 +- `packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts`:最新交互段的成员与通知范围。 +- `packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts`:真实 assembler 下的开轮、中途 steering、Step 1 前的间隔、通知唤醒与空闲 steer。 +- `apps/web/tests/notice-wake-tail.e2e.ts`:长 Turn 之后由通知唤醒,在 Step 1 前的间隔和通知回复之后,上一轮都保持展开,跟尾读者看到通知与回复。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.i18n.yaml new file mode 100644 index 0000000000..56ecd753a6 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-09-29-reused-blank-runs-requested-preset.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.md +/agent-note-a-reused-blank-session-runs-the-requested-preset: + en: 06173bc82e1d9f59 + zh: 637352fd92142310 +/agent-note-a-reused-blank-session-runs-the-requested-preset/problem: + en: 7514025504dc2ddd + zh: 96249d3472005023 +/agent-note-a-reused-blank-session-runs-the-requested-preset/decision: + en: e396c291f742a5f3 + zh: c67be0fd305215fe +/agent-note-a-reused-blank-session-runs-the-requested-preset/alternatives-considered: + en: ae99345e8df800e4 + zh: a4d0c257c4216337 +/agent-note-a-reused-blank-session-runs-the-requested-preset/consequences: + en: bc7dda06670b4d96 + zh: 24f381b8cb6ed3f8 +/agent-note-a-reused-blank-session-runs-the-requested-preset/testing: + en: 1aefca569f5dce81 + zh: 527c9aacf5a2f6b8 diff --git a/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.md b/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.md new file mode 100644 index 0000000000..0ebcb569a2 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.md @@ -0,0 +1,37 @@ +# Agent Note: A reused blank Session runs the requested preset + +Status: implemented + +English | [中文](2026-09-29-reused-blank-runs-requested-preset.zh.md) + +## Problem + +Web New Session, Workspace navigation, and startup restoration reused a blank Session by naming it in `session.create`. The Host resumed that Session under the preset its log recorded, so a new conversation inherited the preset the blank had been created or switched under. When that preset was no longer declared, such as a removed or renamed definition or a legacy `$DSH_HOME/.agent-presets//` directory that nothing reads any more, every New Session in that Workspace and every startup restoration of that draft failed with `agent-preset/not-found` although the default preset was valid (issue #2566). A blank created under an earlier default silently kept that default. The client retried only `session/writer-held`, so the stale blank stayed first in line. + +## Decision + +`session.create` returns a Session for a new conversation. A named `sessionId` is a reuse candidate that the Host verifies: it must not have started a turn, must belong to the requested directory, must be an unarchived member of the requested Workspace, and must not be written by another owner. For a persisted candidate the Host repeats the started check under the writer it acquires. Requests naming one identity run in arrival order, including their preset resolution, and the directory and ownership checks precede that resolution. The reused Session runs the requested `agentPreset`, or the configured default when the request names none; the Host does not resolve the recorded preset for reuse. When the target differs, a live Session switches through the preset registry's `select`, and a persisted Session mounts the target in its unpublished resume setup and appends `agent-preset/selected` there, so the log names the composition before the Agent is published. A candidate that has started, fails placement, or is written by another owner stays unchanged, and the Host creates a new Session; the response names the Session used. An explicit request for an undeclared preset still fails with `agent-preset/not-found`, and resuming a started Session still resolves its recorded identity. + +The Web client names the first eligible blank when it connects a Workspace or prepares an explicit draft, and passes the preset a flow knows before it starts, such as the creator entry's `cordis`; a plain New Session creates a fresh Session instead. Startup restoration names the saved blank with the preset its log recorded, reloading the Session's projections first because listed values are cached hints that can lag the log after an unclean Host exit, so a draft keeps its selection; after `agent-preset/not-found` or `agent-preset/invalid` it asks again without a preset, and the draft continues under the default. When the Host declines a named blank, the client reloads that Session's projections, because stale cached list metadata can still mark a started conversation blank and hide it from the Session tree. + +## Alternatives considered + +**Fall back to the default only when the recorded preset is missing.** This removes the failure but keeps an inherited preset whenever it still resolves, so a New Session after a default change runs the old default. + +**Retry `agent-preset/not-found` in the client.** The stale blank stays the first reuse candidate, so later New Sessions fail once before creating another Session, and startup restoration and other callers still fail. + +**Skip blanks whose preset is missing from the roster.** Navigation would need the roster, stale Sessions would never be repaired, and other callers would still fail. + +**Let the Host choose the blank.** The Host would scan the catalog on every request, while the client already holds the ordered catalog; verification under the writer covers a stale client view. + +**Keep a restored draft's preset on the Host when it resolves.** A request that names a blank without a preset would then mean "keep" for restoration and "default" for New Session. Passing the recorded preset gives each request one meaning. + +## Consequences + +A reused blank runs the default or the preset its flow names, including after the default changes or a definition disappears. A preset picked on a draft survives a page reload but not a later Workspace connection or draft preparation that reuses the draft, and reusing a draft that another tab shows changes that tab's preset too. Writer contention no longer reaches the client: the Host creates the replacement Session. A blank whose first prompt was accepted but whose turn has not started still counts as blank, as it does for `select`. A declined stale blank is corrected only in the client that named it, until the Session is next activated. The preset registry's `select` leaves a blank Session that records the requested preset and runs its current revision unchanged, so a client that also selects that preset after the creation request adds no second record. + +This note replaces the client-side contention fallback of [Writer acquisition for blank Session reuse](../architecture/2026-09-17-process-local-blank-sessions.md); writer acquisition and candidate order remain as decided there. + +## Testing + +Session Controller tests cover live and persisted reuse, a recorded preset that is no longer declared, named presets, started and overtaken Sessions, writer contention, Workspace placement, storage failures, arrival order when an earlier preset resolves later, and directory checks before preset resolution. Workspace navigation tests cover restoration with and without a usable recorded preset, restoration when the listed preset lags the log, connection coalescing that a different preset request supersedes, and the projection reload for a declined blank; the preset plugin tests cover the creator entry, and the registry tests cover a repeated selection with and without a replaced definition. The shipped Web composition test reuses a blank recorded under an undeclared preset under the default when startup connects its Workspace and when startup restores it, keeps a restored draft's declared preset, and checks the durable `agent-preset/selected` record; the stale blank cache scenario checks that startup opens a new Session and still lists the declined conversation. diff --git a/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.zh.md b/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.zh.md new file mode 100644 index 0000000000..28c717f958 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-09-29-reused-blank-runs-requested-preset.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 被复用的空白会话运行请求的 preset + +Status: implemented + +[English](2026-09-29-reused-blank-runs-requested-preset.md) | 中文 + +## Problem + +Web 的新建会话、工作区导航与启动恢复过去通过在 `session.create` 中指明空白会话来复用它。Host 过去按日志记录的 preset 恢复该会话,因此新对话继承了空白会话创建时或切换后的 preset。当该 preset 已不再声明时,例如定义被删除或改名,或是如今已无人读取的旧版 `$DSH_HOME/.agent-presets//` 目录,即使默认 preset 有效,该工作区中的每次新建会话以及该草稿的每次启动恢复都会以 `agent-preset/not-found` 失败(issue #2566)。在更早默认值下创建的空白会话则会静默保留那个旧默认值。客户端只对 `session/writer-held` 重试,因此过期的空白会话始终排在复用候选首位。 + +## Decision + +`session.create` 返回一个用于新对话的会话。请求指明的 `sessionId` 是由 Host 核实的复用候选:它必须尚未开始任何轮次、属于请求的目录、是请求的工作区中未归档的成员,且未被其他写者占用。对于持久化候选,Host 会在取得写锁后再次检查它是否已开始。指明同一标识的请求按到达顺序执行,preset 解析也包含在内,且目录与归属检查先于该解析。被复用的会话运行请求的 `agentPreset`,请求未指明时运行配置的默认 preset;Host 复用时不解析记录的 preset。目标与当前不同时,活动会话通过 preset 注册表的 `select` 切换;持久化会话在尚未发布的恢复 setup 中挂载目标 preset,并在同一处追加 `agent-preset/selected`,使日志在 Agent 发布前就写明其组成。已开始、不满足归属或被其他写者占用的候选保持不变,Host 改为新建会话;响应指明实际使用的会话。显式请求未声明的 preset 仍以 `agent-preset/not-found` 失败,恢复已开始的会话仍解析其记录的标识。 + +Web 客户端在连接工作区或显式准备草稿时指明第一个符合条件的空白会话,并传入流程在开始前已确定的 preset,例如创造模式入口的 `cordis`;普通新建会话则直接新建 Session。启动恢复指明已保存的空白会话及其日志记录的 preset,并先重新加载该会话的投影,因为列表中的值是缓存提示,Host 非正常退出后可能落后于日志,从而使草稿保留其选择;遇到 `agent-preset/not-found` 或 `agent-preset/invalid` 后改为不带 preset 再请求一次,草稿在默认 preset 下继续。Host 拒绝复用某个指明的空白会话时,客户端会重新读取该会话的投影,因为过期的列表缓存元数据可能仍把已开始的对话标为空白,并把它从会话树中隐藏。 + +## Alternatives considered + +**只在记录的 preset 缺失时回退到默认值。** 这能消除失败,但只要继承的 preset 仍可解析就会保留它,因此默认值变更后的新建会话仍运行旧默认值。 + +**在客户端重试 `agent-preset/not-found`。** 过期的空白会话仍是第一个复用候选,之后每次新建会话都会先失败一次再新建,启动恢复和其他调用方仍会失败。 + +**跳过 preset 不在列表中的空白会话。** 导航需要读取 preset 列表,过期会话永远得不到修复,其他调用方仍会失败。 + +**由 Host 选择空白会话。** Host 每次请求都要扫描会话列表,而客户端已持有排好序的列表;在写锁下的核实足以覆盖客户端视图过期的情况。 + +**恢复草稿时由 Host 在记录的 preset 可解析时保留它。** 这样一个指明空白会话但未带 preset 的请求,在恢复时表示「保留」,在新建会话时表示「默认」。传入记录的 preset 让每个请求只有一种含义。 + +## Consequences + +被复用的空白会话运行默认 preset 或其流程指明的 preset,默认值变更或定义消失之后也是如此。在草稿上选择的 preset 在刷新页面后仍保留,但之后复用该草稿的工作区连接或草稿准备不会保留它;复用另一个标签页正在显示的草稿也会改变那个标签页的 preset。写锁争用不再到达客户端:由 Host 新建替代会话。首条提示词已被接受但轮次尚未开始的空白会话仍算空白,与 `select` 一致。被拒绝复用的过期空白会话只在指明它的客户端中得到纠正,直到该会话下次被激活。若空白会话已记录所请求的 preset 且正运行其当前版本,preset 注册表的 `select` 不做改动,因此客户端在创建请求之后再选择同一 preset 也不会追加第二条记录。 + +本注记取代 [复用空白 Session 时获取写锁](../architecture/2026-09-17-process-local-blank-sessions.zh.md) 中的客户端锁争用回退;写锁获取与候选顺序仍按该决策执行。 + +## Testing + +Session Controller 测试覆盖活动会话与持久化会话的复用、记录的 preset 已不再声明、指明的 preset、已开始与被抢先开始的会话、写锁争用、工作区归属、存储失败、较早请求的 preset 解析较慢时仍按到达顺序执行,以及目录检查先于 preset 解析。工作区导航测试覆盖记录的 preset 可用与不可用时的恢复、列表中的 preset 落后于日志时的恢复、被不同 preset 请求取代的连接不再合并,以及被拒绝的空白会话的投影重读;preset 插件测试覆盖创造模式入口,注册表测试覆盖定义未替换与已替换时的重复选择。实际 Web 组合测试在启动连接工作区与启动恢复时,把记录了未声明 preset 的空白会话复用到默认 preset 下,验证恢复的草稿保留已声明的 preset,并检查持久化的 `agent-preset/selected` 记录;过期空白缓存场景验证启动时打开新会话,并仍列出被拒绝复用的对话。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.i18n.yaml new file mode 100644 index 0000000000..edb4886429 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-10-background-shell-command-display.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md +/agent-note-separate-background-shell-command-display-from-job-state: + en: c531a4b2eb444a12 + zh: 7c216f829d2e5168 +/agent-note-separate-background-shell-command-display-from-job-state/problem: + en: 116454bc385c0cc3 + zh: 241905c37c22cb45 +/agent-note-separate-background-shell-command-display-from-job-state/decision: + en: ca05afff8b542979 + zh: ccb19c8709718ca0 +/agent-note-separate-background-shell-command-display-from-job-state/alternatives-considered: + en: 573a8d2e99de14e6 + zh: 1e7767c951672b42 +/agent-note-separate-background-shell-command-display-from-job-state/consequences: + en: 15b6456f87cfeaa2 + zh: 5fec862a0180dc55 diff --git a/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md b/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md new file mode 100644 index 0000000000..156aae0ae8 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md @@ -0,0 +1,33 @@ +# Agent Note: Separate background Shell command display from job state + +Status: implemented + +English | [中文](2026-10-10-background-shell-command-display.zh.md) + +## Problem + +An explicit background Shell call already carries its complete command and working directory at Start, but the Tool card shows generic argument JSON rather than the ordinary Shell command area. The original call returns a launch acknowledgement; the background result arrives through a separate completion notice or `job_output` call. Those messages do not directly carry the original Bash callId, so the acknowledgement cannot establish execution completion, and the original call's state cannot represent the job's live state. + +## Decision + +Valid explicit background `bash`/`pwsh` calls reuse the existing terminal command presentation. Before Start returns, the card indicates only that the launch call is in progress. After a normal launch acknowledgement, the same Tool card retains its command, working directory, wrapping, and disclosure state, and becomes a static command-only display without a run-state dot, exit code, empty-output placeholder, or continuing running animation. Launch failures retain the existing raw-argument and error-result presentation; Inspect still exposes the complete arguments and launch acknowledgement. + +The terminal component receives the original call's `background` flag from Start and combines it with the call's `running` value: `background=true` and `running=true` mean that the launch call is still in progress. When the acknowledgement arrives, `background` stays unchanged and `running=false` leaves a static command; it does not describe the background job's running state. This introduces no derived presentation parameter or job state, and does not keep `running=true` indefinitely to pretend that the command is still executing. Ordinary foreground calls, persistent Shell calls, and `terminal_send` retain their default behavior; the existing Copy button's output-copy semantics do not change. + +This decision covers explicit background launches only, not timeout promotion. It adds no job subscription, polling, output assembly, or callId/jobId index. Later completion notices and `job_output` keep their independent presentation, while the header's job panel owns live job information. The Tool card does not receive the final output, and Host interfaces, execution, and the Session log remain unchanged. + +The [Client tool-presentation decision](../architecture/2026-08-23-client-derived-tool-presentation.md#terminal-card) still governs raw-event derivation and business ownership. This note supersedes only its generic-body rule for explicit background Shell calls, not background `terminal_send`. + +## Alternatives considered + +**Parse the launch acknowledgement as an ordinary completed-command result.** The acknowledgement contains no command exit result and can therefore produce a false success indicator. + +**Retain Start's running state indefinitely.** The original Tool call has returned, and without a job subscription the card cannot establish that the background job is still running. + +**Match subsequent job output back to the original Tool.** This requires a reliable jobId-to-callId association and rules for incremental reads, missing history, and duplicate presentation. None is a prerequisite for displaying the existing command, so they remain outside this decision. + +**Keep generic argument JSON as the only presentation.** The data remains available, but the card does not reuse the familiar Shell command presentation and retains an unnecessary difference between foreground and background calls. + +## Consequences + +Users can inspect the launch command in its original Tool card but cannot infer whether the background job is currently running, successful, or failed. Final state and output remain in the job panel, completion notices, and independent read calls. Component and assembly regressions cover disclosure preservation from Start to acknowledgement, absence of false state and empty output, launch failures, root/child calls, and unchanged foreground and `terminal_send` behavior; assembly-regression event cases use explicitly identified constructed data. diff --git a/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.zh.md b/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.zh.md new file mode 100644 index 0000000000..19090614e3 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 主动后台 Shell 的命令展示与任务状态分离 + +Status: implemented + +[English](2026-10-10-background-shell-command-display.md) | 中文 + +## Problem + +主动后台 Shell 在 Start 时已经具有完整 command 和工作目录,但 Tool 卡片使用通用参数 JSON,而不是普通 Shell 的命令区域。原调用返回的是启动回执,后台最终结果通过另一条完成通知或 `job_output` 调用出现;这些消息没有直接携带原 Bash callId,不能把启动回执当成执行完成,也不能用原调用状态代表任务实时状态。 + +## Decision + +合法的主动后台 `bash`/`pwsh` 复用现有终端命令展示。Start 尚未返回时只表达启动调用正在进行;正常启动回执到达后,同一 Tool 卡片保留 command、工作目录、软换行及展开状态,切换为静态的仅命令展示,不显示执行状态点、退出码、空输出提示或持续运行动画。启动错误继续使用现有原始参数和错误结果展示;完整参数与启动回执仍可通过 Inspect 查看。 + +终端组件从 Start 起接收原调用的 `background` 标志,并结合调用的 `running` 决定展示:`background=true`、`running=true` 表示启动调用尚在进行;回执到达后 `background` 不变、`running=false`,只保留静态命令,不代表后台任务的运行状态。不新增派生展示参数或任务状态,也不以永久 `running=true` 伪造命令仍在执行。普通前台、持久 Shell 和 `terminal_send` 的默认行为不变;不改变原有 Copy 按钮的输出复制语义。 + +本次只处理主动后台启动,不修改超时转后台。没有 job 订阅、轮询、结果拼接或 callId/jobId 索引;后续完成通知和 `job_output` 保持原来的独立展示,标题栏任务面板继续拥有实时任务信息。Tool 卡片不回填最终输出,不修改 Host 接口、执行器或 Session 日志。 + +[Client 工具展示决策](../architecture/2026-08-23-client-derived-tool-presentation.zh.md#terminal-card)的原始事件派生与业务归属保持有效;本文仅替代其主动后台 Shell 使用通用正文的条目,不改变后台 `terminal_send`。 + +## Alternatives considered + +**直接按普通已结束命令解析启动回执。** 回执没有命令退出结果,容易显示虚假的成功状态。 + +**永久保留 Start 的 running 状态。** 原 Tool 调用已返回,且不订阅任务状态,无法保证后台任务仍在运行。 + +**将后续 job 输出匹配回原 Tool。** 需要可靠的 jobId 与原 callId 关联,还要定义分次读取、缺失历史和重复展示的处理;这些不是展示已有 command 的前提,本次不做。 + +**继续只展示通用参数 JSON。** 数据虽然存在,但没有复用用户熟悉的 Shell 命令展示,保留了后台与前台的不必要差异。 + +## Consequences + +用户能在原 Tool 卡片查看启动命令,但不能据此判断后台任务当前成功、失败或运行中。最终状态和输出仍在任务面板、完成通知及独立读取调用中查看。组件与装配回归覆盖 Start→回执的展开保持、无虚假状态与空输出、启动失败、root/child、普通前台及 `terminal_send` 不变;装配回归的事件用例使用明确标识的构造数据。 diff --git a/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.i18n.yaml new file mode 100644 index 0000000000..f9ff8a3881 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-10-11-process-specific-prompt-values-in-runtime-context.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.md +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context: + en: 711ce3e3afb1f905 + zh: 2d4e4aea44043c4a +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/problem: + en: f4e050c7dbf645da + zh: 722bcdc409d09bec +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/decision: + en: 5222f00fd05d3801 + zh: fcfa430a0fa5588c +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/decision/ownership: + en: c23d5c27f1f160f0 + zh: 5c2464666f1e6c29 +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/decision/new-sessions: + en: 1ee144c39905bb89 + zh: a6669d7ad394e41c +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/decision/earlier-format-sessions: + en: 27c11e7ced286898 + zh: 944d051494b1498d +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/alternatives-considered: + en: c324412be4034c40 + zh: 923ad612fc884be1 +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/consequences: + en: 8aa41ff08b848916 + zh: bc1c1647ca0eb86a +/agent-note-process-specific-checkout-path-and-web-url-move-to-runtime-context/testing: + en: 9667d1749bdf1547 + zh: 598dc39120c91228 diff --git a/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.md b/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.md new file mode 100644 index 0000000000..86bda9b2a6 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.md @@ -0,0 +1,95 @@ +# Agent Note: Process-specific checkout path and Web URL move to runtime context + +Status: implemented + +English | [中文](2026-10-11-process-specific-prompt-values-in-runtime-context.zh.md) + +## Problem + +`dsh web` wrote two process-specific values directly into the system prompt: the implementation checkout path in the `harness:source` section (four directories above the web-app module) and the Web GUI URL in the `app:web-surface` section (the bound port or `publicUrl`). These operations change them without the user perceiving a system-prompt change: + +| Operation | Changed value | +|---|---| +| Every Desktop launch (`--port 0` picks a random port) | Web URL | +| A different `--port`, or alternating A/B checkouts | Web URL, checkout path | +| npm and Desktop installations sharing one `DSH_HOME` | Checkout path | + +On resume the loop renders the prompt again. On a route without `systemPromptUpdate: 'in-history'`, such as a hand-declared pi-ai `anthropic-messages` route, the changed prompt rewrites the surface head node. Claude binds historical thinking-block signatures to the conversation prefix, system prompt included, so the upstream answers 400 (`Invalid signature … bound to a different conversation`) and the Session cannot continue until the environment is restored. In-history routes do not fail, but every change appends a complete prompt. + +## Decision + +Both values become runtime context and the system prompt keeps only value-free guidance; a Session whose log already holds the earlier format keeps its logged paragraphs. + +### Ownership + +| Package | Responsibility | +|---|---| +| `@deepseek-ai/dsh-harness-dev-context` (`packages/context/harness-dev-context`) | Both sections, both contexts, and the earlier-format projection; all module-private, exporting only the plugin protocol (`name`, `inject`, `apply`) | +| `@deepseek-ai/dsh-host-webserver` | `WebServer.getOrigin()` (the bind address's URL form with protocol and bound port) and `bindUrlHost(host)` | +| `@deepseek-ai/dsh-web-app` | The `web-runtime` row provides `webApp`, whose `getAdvertisedUrl()` returns the configured `publicUrl`, otherwise the listener origin, the same value as `DSH_WEB_URL` and the startup URL; the bundle patch mounts the `harness-dev-context` row | +| `@deepseek-ai/dsh-system-prompt` | `CONTEXT_ORDERS.HARNESS_SOURCE = 200` and `WEB_SURFACE = 210` | + +The plugin injects `systemPrompt`, `sessionProjections`, and `webApp` and reads those services in code; its patch row carries no configuration expression. The checkout path is four directories above this package's source or built entry, the same depth as the former web-app location, so source, npm, and Desktop installations resolve the same root. The URL is `webApp.getAdvertisedUrl()`, so a profile that overrides the `web-runtime` row's `publicUrl` reaches the model as well. The plugin reaches the `webApp` type through `import type {} from '@deepseek-ai/dsh-web-app'`; the import is erased at runtime, so the web-app bundle's dependency on this package remains the only runtime edge. + +### New Sessions + +| Registration | Content | +|---|---| +| Section `harness:source` (the `HARNESS_SOURCE` slot) | `The runtime context names the DeepSeek Harness implementation checkout. …`, the remaining guidance unchanged | +| Context `harness:source` (`CONTEXT_ORDERS.HARNESS_SOURCE = 200`) | `Current DeepSeek Harness implementation checkout: "".` | +| Section `app:web-surface` (the `WEB_SURFACE` slot) | `You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. …`, the remaining guidance unchanged | +| Context `app:web-surface` (`CONTEXT_ORDERS.WEB_SURFACE = 210`) | `Current DeepSeek Harness Web GUI URL: "".` | + +Both contexts are optional (no `required`). The only complete persona, web-app's minimal preset, also disables optional runtime context, so it still sees neither value. Runtime context follows the existing mechanism: an unchanged value emits no snapshot, a change appends a complete snapshot before the step's user message, and resume compares against the latest logged snapshot, never rewriting a committed message. + +### Earlier-format Sessions + +The plugin registers the host-only session projection `harnessDevLegacyPrompt`, folding every nonempty `system/message` in event order into `{ source, web }`: the paragraphs of that prompt that match an earlier template verbatim, or `null`. + +| Earlier template | Matching rule | +|---|---| +| `harness:source` | Starts with `The DeepSeek Harness implementation checkout is at `, ends with the earlier fixed guidance, no line break between | +| `app:web-surface` | Starts with `You are interacting with the user through the DeepSeek Harness Web GUI at `, ends with `. ` plus the guidance as earlier releases rendered it, frozen as a literal, no line break between | + +Both section text providers read the projection state of `AssembleContext.agent.session`: with an earlier paragraph they return it verbatim (`interpolate: false`), otherwise the current guidance. Diagnostic assemblies without an agent use the current guidance. `sessionProjections` is a required injection and the plugin registers its own unit, so the state is readable whenever an agent exists. + +An earlier-format Session therefore satisfies both requirements: + +| Scenario | System prompt | Runtime context | +|---|---|---| +| First resume after upgrading, same port | Byte-identical to the log; the loop emits no `system/message` | Appends a snapshot with both current values | +| Port, slot, or installation change after upgrading | Still the logged earlier paragraphs | Appends a snapshot with the new values | + +The projection computes only on each committed `system/message`, adding no synchronous read of historical events; its state persists with projection checkpoints. When compaction or a new request series rewrites the head, the rendering still contains the same earlier paragraphs, so the projection state does not change. + +## Alternatives considered + +**Move both values to runtime context without keeping earlier paragraphs.** The upgrade itself changes the prompt text, so every existing Claude Session rewrites its head and fails with 400 on its first turn after the upgrade. + +**Offer `supportsMidConvoSystemMessages` on hand-declared Anthropic routes.** The upstream accepts mid-conversation system messages in a live probe, but the pi-ai catalog already supplies that capability for named Anthropic routes and hand-declared routes withhold catalog fields by convention; in-history routes would still append a complete prompt on every value change. + +**Ask the upstream to drop mismatched thinking blocks (`prefix_mismatch_behavior: "drop_block"`).** It silently loses historical reasoning and covers one vendor. + +**Freeze the whole system prompt per Session.** Legitimate prompt changes such as plan mode, skills, and tool guidance would also be frozen and never reach the model. + +**Keep the implementation in web-app and app-boot.** Development-facing context and earlier-format compatibility would enlarge the public API of two core packages; app-boot's `addHarnessSourceSection` had web-app as its only caller. + +**Read `webStartup.publicUrl`.** It carries only the `--public-url` flag, so a profile override of the `web-runtime` row's `publicUrl` would reach `DSH_WEB_URL` but not the model; the effective value exists only inside web-app, which now provides it as `webApp`. + +**Read the head node text from Session history directly.** The synchronous arbitrary-history read APIs are deprecated and new calls are prohibited; a projection is the established way to obtain that state after resume. + +## Consequences + +- A new Session's system prompt no longer changes with the port, slot, or installation; both current values arrive as runtime-context snapshots, and a change appends a few lines. +- An earlier-format Session keeps the old values of its earlier paragraphs for its whole lifetime; the later `Current …` runtime context in the same request gives the current values. +- Only these two paragraphs are protected. When other prompt text changes between releases, routes without in-history updates still rewrite the head. +- A release without this fix rewrites the head of a new-format Session with the earlier template on resume; both A/B checkouts need this fix before they alternate. +- app-boot no longer exports `addHarnessSourceSection` or `HARNESS_SOURCE_SECTION`; web-app's `surfaceContext` controls only `DSH_WEB_URL`, and disabling the `harness-dev-context` row turns both contexts off. +- Runtime context in recorded Web e2e Sessions gains two lines; the test scaffold normalizes the URL and checkout path to placeholders. + +## Testing + +- `packages/context/harness-dev-context/tests/harness-dev-context.spec.ts`: on a production AgentLoop, an earlier-format Session resumed on another port emits no `system/message`, the request's system prompt is byte-identical to the log, and runtime context carries the current URL; a second port change keeps this; replace-only and in-history routes each run. When a series consolidation only empties a later version, the next turn keeps the earlier paragraphs. Similar text without the fixed ending or broken across lines receives the current guidance. A new Session keeps its system prompt across a port change and only appends a runtime-context snapshot. Sections carry no values, the context carries the advertised URL, and disposing the plugin fiber removes every registration. +- `packages/host/webserver/tests/webserver.spec.ts`: `bindUrlHost` across address forms; `getOrigin()` on HTTP and HTTPS listeners, and its errors before binding and for a zoned non-loopback address. +- `packages/bundle/web-app/tests/web-app.spec.ts`: `webApp.getAdvertisedUrl()` returns the listener origin, or the row's configured `publicUrl`. +- `packages/core/system-prompt/tests/system-prompt.spec.ts`: the added context positions are unique integers. diff --git a/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.zh.md b/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.zh.md new file mode 100644 index 0000000000..b37e09e6bb --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.zh.md @@ -0,0 +1,95 @@ +# Agent Note: 进程相关的 checkout 路径与 Web URL 改走运行时上下文 + +Status: implemented + +[English](2026-10-11-process-specific-prompt-values-in-runtime-context.md) | 中文 + +## 问题 + +`dsh web` 曾把两项随进程变化的值直接写进 system prompt:`harness:source` 段里的实现 checkout 路径(web-app 模块位置上溯四层),以及 `app:web-surface` 段里的 Web GUI URL(实际监听端口或 `publicUrl`)。下列操作都会改变它们,而用户感知不到 system prompt 变了: + +| 操作 | 变化的值 | +|---|---| +| Desktop 每次启动(`--port 0` 取随机端口) | Web URL | +| 换 `--port`、A/B 两个 checkout 交替运行 | Web URL、checkout 路径 | +| npm 安装与 Desktop 安装共用同一个 `DSH_HOME` | checkout 路径 | + +会话恢复时 loop 重新渲染 prompt。对不声明 `systemPromptUpdate: 'in-history'` 的路由(例如手写的 pi-ai `anthropic-messages` 路由),变化的 prompt 会改写 surface 头节点。Claude 的历史 thinking 块签名绑定包括 system prompt 在内的对话前缀,前缀一变上游返回 400(`Invalid signature … bound to a different conversation`),会话在环境恢复原样之前无法继续。声明 in-history 的路由不报错,但每次变化都追加一份完整 prompt。 + +## 决定 + +两项值改为运行时上下文,system prompt 只保留不含值的说明;已经按旧格式写入日志的会话继续沿用日志里的旧段落。 + +### 归属 + +| 包 | 职责 | +|---|---| +| `@deepseek-ai/dsh-harness-dev-context`(`packages/context/harness-dev-context`) | 两个 section、两个 context、旧格式投影;全部模块私有,只导出插件协议(`name`、`inject`、`apply`) | +| `@deepseek-ai/dsh-host-webserver` | `WebServer.getOrigin()`(绑定地址的 URL 形式加协议与实际端口)与 `bindUrlHost(host)` | +| `@deepseek-ai/dsh-web-app` | `web-runtime` 行提供 `webApp`,其 `getAdvertisedUrl()` 返回配置的 `publicUrl`,否则返回监听器 origin,与 `DSH_WEB_URL` 和启动 URL 同值;bundle patch 挂载 `harness-dev-context` 行 | +| `@deepseek-ai/dsh-system-prompt` | `CONTEXT_ORDERS.HARNESS_SOURCE = 200`、`WEB_SURFACE = 210` | + +插件 `inject` 为 `systemPrompt`、`sessionProjections`、`webApp`,在代码里直接读取这些服务;patch 行不写任何配置表达式。checkout 路径取本包源码或构建入口上溯四层,与原 web-app 位置同深度,源码、npm 与 Desktop 安装下结果不变。URL 取 `webApp.getAdvertisedUrl()`,因此 profile 覆盖 `web-runtime` 行的 `publicUrl` 时模型也能看到。插件通过 `import type {} from '@deepseek-ai/dsh-web-app'` 取得 `webApp` 类型;该导入在运行时被擦除,因此 web-app bundle 对本包的依赖仍是唯一的运行时依赖。 + +### 新会话 + +| 注册 | 内容 | +|---|---| +| section `harness:source`(`HARNESS_SOURCE` 位) | `The runtime context names the DeepSeek Harness implementation checkout. …`,其余说明不变 | +| context `harness:source`(`CONTEXT_ORDERS.HARNESS_SOURCE = 200`) | `Current DeepSeek Harness implementation checkout: "".` | +| section `app:web-surface`(`WEB_SURFACE` 位) | `You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. …`,其余说明不变 | +| context `app:web-surface`(`CONTEXT_ORDERS.WEB_SURFACE = 210`) | `Current DeepSeek Harness Web GUI URL: "".` | + +两个 context 都是可选项(不设 `required`)。唯一的 complete persona(web-app 的 minimal 预设)同时关闭了可选运行时上下文,因此它仍然看不到这两项。运行时上下文按既有机制工作:值不变不发新快照,变化时在本轮 user 消息前追加完整快照,恢复时从会话日志取上一份快照比较,不改写任何已提交消息。 + +### 旧格式会话 + +插件注册仅限宿主的会话投影 `harnessDevLegacyPrompt`,按事件顺序折叠每个非空 `system/message`,状态为 `{ source, web }`:该 prompt 中按旧模板逐字匹配到的段落,未匹配为 `null`。 + +| 旧模板 | 匹配规则 | +|---|---| +| `harness:source` | `The DeepSeek Harness implementation checkout is at ` 开头、旧版固定说明结尾、中间不含换行 | +| `app:web-surface` | `You are interacting with the user through the DeepSeek Harness Web GUI at ` 开头、`. ` 加早期版本渲染的说明结尾(冻结为字面量)、中间不含换行 | + +两个 section 的文本提供函数读取 `AssembleContext.agent.session` 的投影状态:有旧段落时原样返回该段落(`interpolate: false`),否则返回新说明。没有 agent 的诊断性组装使用新说明。`sessionProjections` 是插件的必需注入,投影单元由插件自己注册,因此存在 agent 时状态必然可读。 + +旧会话因此满足两点: + +| 场景 | system prompt | 运行时上下文 | +|---|---|---| +| 升级后首次恢复,端口不变 | 与日志逐字相同,loop 不产生 `system/message` | 追加含两项当前值的快照 | +| 升级后换端口、slot 或安装位置 | 仍是日志里的旧段落 | 追加新值快照 | + +投影只在每次提交的 `system/message` 上计算,不新增同步读取历史事件的调用;状态随投影检查点持久化。压缩或新请求序列重写头节点时,渲染结果仍含同一旧段落,投影状态不变。 + +## 备选方案 + +**只把两项值移到运行时上下文,不保留旧段落。** 升级本身会改变 prompt 文本,所有既有 Claude 会话在升级后第一轮改写头节点并报 400。 + +**为手写 Anthropic 路由开放 `supportsMidConvoSystemMessages`。** 上游实测接受对话中途的 system 消息,但 pi-ai 目录已为具名 Anthropic 路由提供该能力,手写路由按既有约定不开放目录字段;而且 in-history 路由每次值变化仍追加一份完整 prompt。 + +**请求上游丢弃不匹配的 thinking 块(`prefix_mismatch_behavior: "drop_block"`)。** 会静默丢失历史推理,且只覆盖一个供应商。 + +**会话内冻结整份 system prompt。** plan 模式、技能和工具说明等合法的 prompt 变化也会被冻结,无法到达模型。 + +**留在 web-app 与 app-boot 中实现。** 面向开发的上下文与旧格式兼容逻辑会扩大两个核心包的公开 API;app-boot 的 `addHarnessSourceSection` 当时只有 web-app 一个调用方。 + +**读取 `webStartup.publicUrl`。** 它只携带 `--public-url` 参数,profile 覆盖 `web-runtime` 行的 `publicUrl` 时只会影响 `DSH_WEB_URL`,到不了模型;生效值只存在于 web-app 内部,现在由它以 `webApp` 提供。 + +**直接读取会话历史中的头节点文本。** 同步读取任意历史事件的 API 已弃用,新调用被禁止;投影是恢复后取得该状态的既定方式。 + +## 后果 + +- 新会话的 system prompt 不再随端口、slot 或安装位置变化;两项当前值以运行时上下文快照送达,变化时只追加几行。 +- 旧会话在整个生命周期内保留旧段落中的旧值;同一请求里更晚的 `Current …` 运行时上下文给出当前值。 +- 只保护这两段。其他提示文本在版本之间变化时,不支持 in-history 的路由仍会改写头节点。 +- 不含本修复的旧版本恢复新格式会话时会按旧模板改写头节点;A/B 两个 checkout 都需包含本修复后再交替运行。 +- app-boot 不再导出 `addHarnessSourceSection` 与 `HARNESS_SOURCE_SECTION`;web-app 的 `surfaceContext` 只控制 `DSH_WEB_URL`,关闭这两项上下文改为禁用 `harness-dev-context` 行。 +- Web e2e 录制会话里的运行时上下文多出两行;测试脚手架把 URL 与 checkout 路径规范化为占位符。 + +## 测试 + +- `packages/context/harness-dev-context/tests/harness-dev-context.spec.ts`:真实 AgentLoop 上,旧格式会话在另一端口恢复时不产生 `system/message`、请求中的 system prompt 与日志逐字相同、运行时上下文携带当前 URL;再换一次端口仍成立;不支持与支持 in-history 的路由各跑一遍。series 合并只清空后续版本时,下一轮仍沿用旧段落。缺少固定结尾或跨行的相似文本得到新说明。新会话换端口后 system prompt 不变、只追加运行时上下文快照。section 不含值、context 携带公告 URL,销毁插件 fiber 后全部注册消失。 +- `packages/host/webserver/tests/webserver.spec.ts`:`bindUrlHost` 各地址形式;`getOrigin()` 在 HTTP 与 HTTPS 监听上的值,绑定前与带 zone 的非回环地址抛错。 +- `packages/bundle/web-app/tests/web-app.spec.ts`:`webApp.getAdvertisedUrl()` 返回监听器 origin,或该行配置的 `publicUrl`。 +- `packages/core/system-prompt/tests/system-prompt.spec.ts`:新增的 context 位置唯一且为整数。 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml index 38cc4a8bf5..e3bd9b93f5 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.i18n.yaml @@ -39,8 +39,8 @@ en: 761eb6c1aeb7af18 zh: 5434456a3d0a1b65 /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/testing: - en: f5d287f610962a48 - zh: 88368e1df517b087 + en: 6e637b0970682265 + zh: 7fed6e98f87b5f1a /agent-note-ptc-mode-the-model-writes-typescript-against-the-tool-registry/alternatives-considered: en: e78530994a88d14f zh: 49f64c7f1421f507 diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.md b/.agents/notes/implemented/feature/2026-06-15-ptc.md index c49b21ecee..97fc5b04db 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.md @@ -101,6 +101,8 @@ Deployments switching to `'ptc'` must update any native-only `toolOrder`. Assemb - **With-key e2e:** A real model composes two bash calls in one program; another discovers nested workspace instructions through a PTC mode fs dispatch. The tests verify collapsed request headers, correlated dispatch events, resulting files, deferred context, and model behavior. - **Snapshot:** The `ptc-turn`, `both-mode-turn`, and `ptc-workspace-context` fixtures pin SDK text, header tool lists, dispatch events, deferred context, and result cards. The TypeScript SDK PTC scenario mounts its Node runtime through an explicit test-owned profile patch and pins Session events and JSON-RPC notifications; its expected response and completed-turn checks run before refresh writes. +The optional [Node in-memory execution mode](../architecture/2026-09-23-best-effort-persistent-ptc.md) permits disposable cross-call memory without restoring objects or replaying programs after restart; the default execution mode stays stateless. + ## Alternatives considered **An add-on consumer plugin with zero core changes.** Rejected because `agent/request` is call-config-only under [reconstructable requests](../architecture/2026-07-05-reconstructable-requests.md), while transforming an assembled tool list would have to undo `toolOrder` canonicalization without owning its config and would depend on listener order. Which tools the model is offered, and in which representation, is the registry's single concern: native schemas and the SDK are two projections of one visible store. diff --git a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md index 669a63e991..381448d354 100644 --- a/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md +++ b/.agents/notes/implemented/feature/2026-06-15-ptc.zh.md @@ -101,6 +101,8 @@ SDK 指示模型编写一个所加载运行时语言的异步函数体(默认 - **带密钥 e2e:** 真实模型在一个程序中组合两次 bash 调用;另一个模型通过 PTC mode fs 分发发现嵌套的工作区指令。测试验证折叠的请求头、关联的分发事件、结果文件、延后上下文和模型行为。 - **快照:** `ptc-turn`、`both-mode-turn` 和 `ptc-workspace-context` fixture(测试前置数据)固定 SDK 文本、请求头工具列表、分发事件、延后上下文和结果卡片。TypeScript SDK PTC 场景通过测试拥有的显式 profile patch 挂载 Node 运行时,并固定 Session 事件与 JSON-RPC 通知;预期回复和完成轮次检查在 refresh 写入前执行。 +可选的[Node 内存保留执行模式](../architecture/2026-09-23-best-effort-persistent-ptc.zh.md)允许跨调用保留可丢失的内存,不在重启后恢复对象或回放程序;默认执行模式保持无状态。 + ## 曾考虑的替代方案 **一个零核心改动的附加消费方插件。** 否决,因为 `agent/request` 在[可重建请求](../architecture/2026-07-05-reconstructable-requests.zh.md)下仅限 call-config,而变换已组装的工具列表需要在不拥有其配置的情况下撤销 `toolOrder` 规范化,并依赖监听器顺序。向模型提供哪些工具、以何种表示形式提供,是注册表的单一关注点:原生 schema 和 SDK 是同一个可见存储的两种投影。 diff --git a/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.i18n.yaml b/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.i18n.yaml index 67d1d90e9b..83ef4ebea0 100644 --- a/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.i18n.yaml +++ b/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.i18n.yaml @@ -9,14 +9,14 @@ en: e6929494e60041a2 zh: 15bec8e8baabcab2 /agent-note-generated-third-party-notices/decision: - en: 11f3362b0f45debb - zh: 5953b0848b940b67 + en: e0a339aa86f13898 + zh: 9ab0c7de7bb185b5 /agent-note-generated-third-party-notices/testing: en: 194f87f780991068 zh: 58096d2339576d20 /agent-note-generated-third-party-notices/alternatives-considered: - en: 093ddc027e296bf0 - zh: 6b9e64d99dcefa11 + en: 7e9d8d7864503e46 + zh: 5b93a1130cfab260 /agent-note-generated-third-party-notices/consequences: - en: 860b806c5d393c98 - zh: 51b4ca11e2d3802a + en: ed2210ac6c133e6c + zh: 7957cb33da842642 diff --git a/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.md b/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.md index 0ebd540939..d233fd1eb4 100644 --- a/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.md +++ b/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.md @@ -14,9 +14,7 @@ A hand-written inventory answers none of those durably. Roughly a hundred rows o [`THIRD_PARTY_NOTICES.md`](../../../../THIRD_PARTY_NOTICES.md) is generated by [`scripts/gen-third-party-notices.ts`](../../../../scripts/gen-third-party-notices.ts) from the workspace manifests, `vendor/README.md`, the `pyproject.toml` files, `pnpm-workspace.yaml`, and the [shared runtime lock](../../../../scripts/primary-runtime/lock.json). The root README pair links the file from its License section. -**Freshness is maintained, not merely enforced.** A pre-commit job regenerates the file and stages it whenever a generator input is staged — any manifest, a workspace declaration, the root or shared runtime lock file, `vendor/README.md`, a `pyproject.toml`, the generator itself, or the script holding the build-time pin — so an unrelated dependency edit never has to come back and rerun a generator. The committed bytes are then asserted inside [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts), which the test lane already runs — the check adds no gate process, no scheduler slot, and no separate CI step. `pnpm run verify-third-party-notices` remains available for a standalone check. - -One trigger gap is accepted rather than worked around: lefthook inspects only files present on disk, so **deleting** a manifest runs no job, and removing a package reaches the assertion in the test lane instead. Reconstructing the staged file list to include deletions does not work — lefthook filters the list against the working tree either way. The assertion is the backstop for exactly this case. +**The test lane enforces freshness.** The committed bytes are asserted inside [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts), which the test lane already runs, including the required `node 24 / coverage` pull-request lane — the check adds no gate process, no scheduler slot, and no separate CI step. A contributor who changes a generator input — any manifest, a workspace declaration, the root or shared runtime lock file, `vendor/README.md`, a `pyproject.toml`, the generator itself, or the script holding the build-time pin — runs `pnpm run gen-third-party-notices`; `pnpm run verify-third-party-notices` remains available for a standalone check. No Git hook regenerates the file: browser inputs make every package source file a generator input, so a hook would run the 16-second generator on nearly every commit, while few commits change the output. The file discloses **direct** dependencies by default; complete npm and Python SDK closures remain in their lock files. Two separately distributed payload sets receive explicit entries: the official Claude executable packages declared by `@anthropic-ai/claude-agent-sdk`, and every distribution in the shared runtime lock's `pythonPackages`. Bundled entries include normalized names, exact versions, and recorded license metadata; missing metadata, duplicate normalized names and conflicting normalized versions fail generation. The shared wheel set is independent of the `python/` manifests, so scanning only those manifests would omit the packaged Office libraries. Bundled distributions also pass the runtime license check, including the permissive `MIT-CMU` and `PSF-2.0` identifiers declared by Pillow and typing-extensions. @@ -38,7 +36,7 @@ The Claude distribution tests prove that only the exact direct SDK identity bypa **Keep the hand-written file and review it at release time.** Reviewing a hundred derived rows by eye is exactly the work a generator does correctly, and the file's own claim — that it lists every direct dependency — would be unverified between releases. -**Verify through a dedicated `doc-sync` gate.** That is how every other generated artifact here is checked, and it was the first shape of this change. It costs a gate process and a scheduler slot in a matrix that is already long, and — worse — its only failure mode is telling a contributor, minutes after they pushed an unrelated dependency bump, to go rerun a generator. Regenerating at commit time removes the interruption, and the assertion inside a spec the test lane already runs keeps the guarantee at no additional CI cost. +**Verify through a dedicated `doc-sync` gate.** That is how every other generated artifact here is checked, and it was the first shape of this change. It costs a gate process and a scheduler slot in a matrix that is already long, while the assertion inside a spec the test lane already runs reports the same staleness at no additional CI cost. **Enumerate the full transitive closure.** The closure is thousands of packages, already recorded in the lock files with exact versions, and would bury the direct dependencies that a reader actually evaluates. The file points at the lock files and the `pnpm licenses list` renderer instead. @@ -52,7 +50,7 @@ The Claude distribution tests prove that only the exact direct SDK identity bypa ## Consequences -A dependency edit now carries a regenerated notices file into the same commit. Contributors pay one generator run — about a second — on commits that touch a manifest, and nothing on any other commit. Committing with hooks disabled defers the cost to a test-lane failure that names the command. +Commits pay no generator run. A dependency or browser-import edit that leaves the notices stale fails the test lane with an error that names the regeneration command. The generator needs an installed tree, which makes it heavier than a pure-source generator, and a new package with unusable published metadata needs an `OVERRIDES` entry rather than silently rendering a blank license. Both failures are loud and name the remedy. diff --git a/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.zh.md b/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.zh.md index 323ad8ea15..b229c16396 100644 --- a/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.zh.md +++ b/.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.zh.md @@ -14,9 +14,7 @@ Status: implemented [`THIRD_PARTY_NOTICES.md`](../../../../THIRD_PARTY_NOTICES.md) 由 [`scripts/gen-third-party-notices.ts`](../../../../scripts/gen-third-party-notices.ts) 依据各工作区 manifest、`vendor/README.md`、`pyproject.toml`、`pnpm-workspace.yaml` 与 [共享运行时锁文件](../../../../scripts/primary-runtime/lock.json)生成。根 README 双语两侧都从「许可证」一节链到该文件。 -**新鲜度会得到维护,而非仅靠校验。** 只要暂存了生成器的任一输入——任何 manifest、工作区声明、根锁文件或共享运行时锁文件、`vendor/README.md`、某个 `pyproject.toml`、生成器自身,或持有构建期 pin 的脚本——pre-commit 任务就会重新生成该文件并将其暂存,改依赖的人不必事后再折返跑一次生成器。已提交的字节随后由 [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) 断言,而测试 lane 本就会跑这个文件——这项校验不增加门禁进程、不占调度位、也不新增 CI 步骤。需要单独校验时,`pnpm run verify-third-party-notices` 仍然可用。 - -有一处触发缺口是接受而非绕过的:lefthook 只检视磁盘上存在的文件,因此**删除** manifest 不会触发任何任务,移除一个包会落到测试 lane 的断言上。重构暂存文件列表以纳入删除的做法不成立——无论怎么给列表,lefthook 都会拿工作树过滤一遍。这个场景正由断言兜底。 +**新鲜度由测试 lane 保证。** 已提交的字节由 [`scripts/gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) 断言,而测试 lane 本就会跑这个文件,其中包括 PR 必过的 `node 24 / coverage` lane——这项校验不增加门禁进程、不占调度位、也不新增 CI 步骤。改动生成器任一输入——任何 manifest、工作区声明、根锁文件或共享运行时锁文件、`vendor/README.md`、某个 `pyproject.toml`、生成器自身,或持有构建期 pin 的脚本——的贡献者运行 `pnpm run gen-third-party-notices`;需要单独校验时,`pnpm run verify-third-party-notices` 仍然可用。没有 Git 钩子重新生成该文件:浏览器输入使每个包源码文件都成为生成器输入,钩子会让几乎每个提交都运行约 16 秒的生成器,而改变输出的提交很少。 文件默认只披露**直接**依赖;完整的 npm 与 Python SDK 闭包保留在各自锁文件中。两组独立分发的载荷会明确列出:`@anthropic-ai/claude-agent-sdk` 声明的官方 Claude 可执行包,以及共享运行时锁文件 `pythonPackages` 中的每个分发包。内置条目包含归一化名称、精确版本和已记录的许可证元数据;元数据缺失、归一化后名称重复或版本冲突都会使生成失败。共享 wheel 集合独立于 `python/` 下的 manifest,仅扫描后者会遗漏已打包的 Office 库。内置分发包同样通过运行时许可证检查,其中包括 Pillow 与 typing-extensions 声明的宽松许可证标识 `MIT-CMU` 和 `PSF-2.0`。 @@ -38,7 +36,7 @@ Claude 分发测试证明:只有精确匹配的直接 SDK 身份会绕过通 **保留手写文件,发版时人工过一遍。** 用肉眼审阅上百行推导数据,恰恰是生成器能做对的活;而且在两次发版之间,文件自称「列出全部直接依赖」这句话无人验证。 -**用专门的 `doc-sync`(文档同步门禁)校验。** 仓库里其他生成产物都是这么把关的,本次改动最初也是这个形态。但它要在本已冗长的矩阵里再占一个门禁进程和一个调度位;更糟的是,它唯一的失败方式,就是在别人推完一个无关的依赖升级几分钟后,通知对方回去重跑一次生成器。改为提交时重新生成消除了这次打断,而把断言放进测试 lane 本就会跑的 spec 里,则以零额外 CI 成本保住了这项保证。 +**用专门的 `doc-sync`(文档同步门禁)校验。** 仓库里其他生成产物都是这么把关的,本次改动最初也是这个形态。但它要在本已冗长的矩阵里再占一个门禁进程和一个调度位,而测试 lane 本就会跑的 spec 里的断言能以零额外 CI 成本报告同样的过期。 **列出完整传递闭包。** 闭包有数千个包,锁文件里已带精确版本,铺开只会淹没读者真正要评估的直接依赖。文件转而指向锁文件与 `pnpm licenses list`。 @@ -52,7 +50,7 @@ Claude 分发测试证明:只有精确匹配的直接 SDK 身份会绕过通 ## 后果 -此后改动依赖时,重新生成的披露文件会随同一个提交入库。触及 manifest 的提交多付一次生成器运行——约一秒;其余提交不受影响。若禁用钩子提交,代价推迟为一次测试 lane 失败,其报错会指明补救命令。 +提交不运行生成器。改动依赖或浏览器侧 import 却未更新披露文件时,测试 lane 会失败,其报错会指明重新生成的命令。 生成器需要已安装的依赖树,因此比纯源码生成器更重;发布元数据不可用的新包需要补一条 `OVERRIDES`,而不是默默渲染出空白许可证。这两类失败都会明确报错并指出补救方式。 diff --git a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml index 79f3339e71..192e40c2d2 100644 --- a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml +++ b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.i18n.yaml @@ -9,8 +9,8 @@ en: e5c984fa32cc5e69 zh: 25d5742b2106d830 /agent-note-pr-artifact-builds-and-aggregate-typescript-checks/decision: - en: 6e84bceaba4573ca - zh: 25a37c147a675643 + en: af93d8849bb8831a + zh: 53e15e801ab844da /agent-note-pr-artifact-builds-and-aggregate-typescript-checks/alternatives-considered: en: f61da066f9ddcd62 zh: 816fd6e0063017cd diff --git a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md index 7577a7c06e..6c422a612d 100644 --- a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md +++ b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md @@ -12,13 +12,13 @@ PR jobs need the same compiled packages for benchmarks, compatibility, packaging Required Linux consumer and native Windows build jobs retain normal builds, including both complete aggregate programs. Public `build` and `typecheck` keep the same checks. [Node version ownership](2026-07-06-node-engine-floor.md) and [native Windows ownership](2026-08-08-native-windows-pull-request-ci.md) remain in force. -Checked PR artifact builds compile every existing project reference from each compiler face with one serial `tsc -b` process, then run the ordinary Typert, bundling, Desktop, and Web stages. The helper reads the existing Host and Client aggregates rather than maintaining another package list. It omits only each root's additional test and script program; package diagnostics, emitted outputs, and Host-before-Client ordering remain required. Non-PR release and real-API workflow builds retain their normal checks. +Checked PR artifact builds compile every existing project reference from each compiler face with one serial `tsc -b` process, then run the ordinary Typert, bundling, Desktop, and Web stages. The helper reads the existing Host and Client aggregates rather than maintaining another package list. It omits only each root's additional test and script program; package diagnostics, emitted outputs, and Host-before-Client ordering remain required. Non-PR release and real-API workflow builds retain their normal checks. That artifact build is `pnpm run build:artifacts`; [the build split](2026-10-11-build-artifacts-check-split.md) owns its steps and scheduling. Only the CI benchmark helper selects `tsc -b --noCheck` for package emission. Benchmarks consume JavaScript and Typert runtime metadata; their declaration and build-information files are disposable and never published. Typert analyzes source types independently, while required complete builds own semantic diagnostics. Syntax and configuration failures still reject benchmark preparation. TypeScript records pending checks so a later ordinary incremental build diagnoses the same source without deleting caches or forcing a rebuild. Public benchmark scripts and every release, Python, preview, compatibility, and normal artifact builder keep their checked defaults. -The Python executable builder selects artifact compilation with `--artifacts-only` after verifying its runtime closure. Invalid closure inputs fail before compilation, deployment, or packing; the default complete build and prebuilt `--skip-build` mode keep their existing stages. +The Python executable builder selects `build:artifacts` artifact compilation with `--build-artifacts` after verifying its runtime closure. Invalid closure inputs fail before compilation, deployment, or packing; the default complete build and prebuilt `--skip-build` mode keep their existing stages. -CI invokes the internal build helpers directly and keeps the root package manifest unchanged. Root manifest edits activate the separate native-addon platform matrix even when only build aliases change; avoiding that trigger preserves the existing workflow set and concurrent-job ceiling without weakening native validation. +PR artifact builds in CI invoke the root manifest's `build:artifacts`; a PR that edits these root manifest scripts activates the separate native-addon platform matrix, a trade-off [the build split](2026-10-11-build-artifacts-check-split.md) records. The vendor rehearsal and benchmark lanes invoke the internal build helpers directly. Job inventory, runner selectors, and benchmark sample counts stay fixed; gate and worker ceilings do not increase. The three compatibility cases run one job at a time; the two-target Python runtime matrix starts after the keyless Python SDK job succeeds. Four Linux lanes, the Python SDK, three Windows lanes, and one compatibility job permit at most nine worker jobs initially. Once the SDK job finishes, the remaining seven independent lanes, one compatibility job, and two runtime targets permit at most ten. The runtime plan and wheel stages precede those targets and each use one job. This permits runtime validation to overlap the Node 22 build within the original ten-job ceiling. Coverage partitions reuse compact file-cost metadata within their platform and runner pool. Parallel release packing uses pnpm's existing bounded scheduler; serial publication keeps family order. diff --git a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md index c0b3c1bcf4..9f25366401 100644 --- a/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md +++ b/.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md @@ -12,13 +12,13 @@ PR job 需要相同的编译包来运行 benchmark、兼容性、打包和运行 必需的 Linux consumer 与原生 Windows build job 保留普通构建,包括两个完整 aggregate program。公开的 `build` 和 `typecheck` 保留相同检查。[Node 版本职责](2026-07-06-node-engine-floor.zh.md)与[原生 Windows 职责](2026-08-08-native-windows-pull-request-ci.zh.md)仍然有效。 -带检查的 PR 产物构建通过一个串行 `tsc -b` 进程编译各 compiler face 的全部现有 project reference,然后运行普通 Typert、bundling、Desktop 和 Web 阶段。helper 读取现有 Host 与 Client aggregate,而不维护另一份包清单。它只省略各 root 附加的测试和脚本 program;包诊断、emit 输出及 Host 先于 Client 的顺序仍然必需。非 PR 的 release 和真实 API 工作流构建保留普通检查。 +带检查的 PR 产物构建通过一个串行 `tsc -b` 进程编译各 compiler face 的全部现有 project reference,然后运行普通 Typert、bundling、Desktop 和 Web 阶段。helper 读取现有 Host 与 Client aggregate,而不维护另一份包清单。它只省略各 root 附加的测试和脚本 program;包诊断、emit 输出及 Host 先于 Client 的顺序仍然必需。非 PR 的 release 和真实 API 工作流构建保留普通检查。该产物构建即 `pnpm run build:artifacts`,其步骤与调度见[构建拆分](2026-10-11-build-artifacts-check-split.zh.md)。 只有 CI benchmark helper 选择 `tsc -b --noCheck` 来 emit 包。benchmark 消费 JavaScript 和 Typert 运行时元数据;其声明与 build-information 文件是临时产物,不会发布。Typert 独立分析源码类型,语义诊断由必需的完整构建负责。语法与配置错误仍会拒绝 benchmark 准备。TypeScript 记录待检查状态,使后续普通增量构建无需删除缓存或强制重建,就能诊断相同源码。公开 benchmark script,以及所有 release、Python、preview、compatibility 和普通产物 builder,均保留带检查的默认行为。 -Python executable builder 在验证 runtime closure 后,通过 `--artifacts-only` 选择产物编译。无效 closure 在编译、部署或打包前失败;默认完整构建和复用预构建产物的 `--skip-build` 模式保留原有阶段。 +Python executable builder 在验证 runtime closure 后,通过 `--build-artifacts` 选择 `build:artifacts` 产物编译。无效 closure 在编译、部署或打包前失败;默认完整构建和复用预构建产物的 `--skip-build` 模式保留原有阶段。 -CI 直接调用内部 build helper,并保持 root package manifest 不变。即使只修改 build alias,root manifest 改动也会激活独立的 native-addon 平台矩阵;避免这一触发条件,可以在不削弱 native 验证的情况下保留现有 workflow 集合与并发 job 上限。 +CI 的 PR 产物构建调用 root manifest 中的 `build:artifacts`;修改 root manifest 中这些 script 的 PR 会激活独立的 native-addon 平台矩阵,[构建拆分](2026-10-11-build-artifacts-check-split.zh.md)记录这一取舍。vendor 演练与 benchmark lane 直接调用内部 build helper。 job 清单、runner 选择和 benchmark sample 数量保持固定;gate 与 worker 上限不提高。三个 compatibility case 每次运行一个 job;双目标 Python runtime 矩阵在 keyless Python SDK job 成功后启动。四个 Linux lane、Python SDK、三个 Windows lane 和一个 compatibility job,初始最多占用九个 worker job。SDK job 完成后,剩余七个独立 lane、一个 compatibility job 和两个 runtime target,最多占用十个 job。runtime plan 与 wheel 阶段先于这些 target,各占一个 job。这允许 runtime 验证与 Node 22 构建重叠,同时保持原有十个 job 的上限。覆盖率分区在各自的平台和 runner pool 内复用精简的文件成本元数据。并行 release 打包使用 pnpm 现有的有界调度器;串行发布保持 family 顺序。 diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml new file mode 100644 index 0000000000..84099cc7a6 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.i18n.yaml @@ -0,0 +1,40 @@ +# Bilingual-pair consistency record for 2026-10-11-build-artifacts-check-split.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently: + en: b1a98fdd8008dce1 + zh: 15bdc2f2c2584226 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/problem: + en: bc382ad1f1e71352 + zh: 44189bf0f69a0bf7 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision: + en: a15c7c13f167e5ac + zh: 63bcc2ef60c2f344 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/commands: + en: 174241330463841d + zh: 7fe361c07e634053 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/steps-and-dependencies: + en: 43e78e255306cd43 + zh: a741d5ef1c7379f3 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/scheduling-failure-and-output: + en: 4b324f92307d3691 + zh: e0cf4411a747f7e5 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/callers: + en: 55c55eea07fdb459 + zh: ab78cdfa4d04a5e7 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/measurements: + en: b3a753ac2aab6073 + zh: 19cbd0e32751896f +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/completeness-and-lossless-evidence: + en: 3cd40e0db9a2c89a + zh: 3f708be239779d0a +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/decision/intentional-trade-offs-not-lossless: + en: 14370bc5b54e1278 + zh: 7ac933092d3e9954 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/alternatives-considered: + en: 54905b912d17c74e + zh: 86a298004c8024e3 +/agent-note-split-build-artifacts-and-build-check-with-build-running-both-concurrently/consequences: + en: 083467f68d0f03ed + zh: 93400e9994b8c645 diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md new file mode 100644 index 0000000000..4476424af5 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.md @@ -0,0 +1,157 @@ +# Agent Note: Split build:artifacts and build:check, with build running both concurrently + +Status: implemented + +English | [中文](2026-10-11-build-artifacts-check-split.zh.md) + +## Problem + +`pnpm run build` runs the native addon, the package-library build (Host `tsc -b tsconfig.host.json` → Host tsdown → Desktop bundle → Client `tsc -b tsconfig.client.json` → Client tsdown), and the Web build serially. Besides referencing package projects, the Host and Client aggregates each carry a `noEmit` root program covering tests, scripts, benchmarks, and website. These two root programs emit no files and feed no later artifact step, yet sit on the serial critical path: timed alone, the Host root program takes 68.5 s and the Client root program 36.0 s, while the serial package-library build takes about 249 s (median of 2). + +Development iterations need only artifacts; test and script type checks are needed before work is declared complete. The only way to skip the two root programs is the CI-oriented `pnpm run build --artifacts-only`, which has no local development command name and no counterpart that runs only those two checks. Meanwhile, `pnpm run build` must stay complete and detect every type error. + +## Decision + +### Commands + +Each command does only its own job. + +| Command | Responsibility | Steps | Scheduling | Client build record | +|---|---|---|---|---| +| `pnpm run build:artifacts` | Produces every artifact of `build`; package projects are fully type-checked as usual, the two aggregate root programs are not checked | native → host-src → host-bundle → desktop-bundle → client-src → client-bundle → web | One linear chain | Deleted at start, written after every step passes | +| `pnpm run build:check` | Type-checks only the two aggregate root programs | host-check, client-check | Both steps concurrent, no prerequisite steps | Neither read nor written | +| `pnpm run build` | Every step of `build:artifacts` and `build:check` | The dependency graph below | Concurrent through the run-gates scheduler | Deleted at start, written after every step passes | + +`build:check` neither detects, rebuilds, nor validates `build:artifacts` outputs; when prerequisite outputs are missing or stale, the compiler's own diagnostics (for example TS6305 and TS2307) report it, and no command adds prerequisite checks, guards, or fallbacks. `build:artifacts` produces the same artifacts and record as `build` and replaces `--artifacts-only`; that flag and the `libraries` mode of `compile-referenced-projects.ts` are removed, and the Python executable builder uses `--build-artifacts`. `build:official` remains `tsx scripts/build.ts --profile official` and runs the complete `build`. + +### Steps and dependencies + +| Step | Command | `needs` in `build` | +|---|---|---| +| native | `pnpm run build:native-system` | — | +| host-src | `node --max-old-space-size=4096 -b ` | native | +| host-bundle | `tsdown --config-loader native --env.DSH_BUILD_FACE host` (runs Typert) | host-src | +| desktop-bundle | `pnpm --filter @deepseek-ai/dsh-desktop run bundle` | host-bundle | +| client-src | ` -b ` | desktop-bundle | +| client-bundle | `tsdown --config-loader native --env.DSH_BUILD_FACE client` | client-src | +| web | `pnpm run build:web` | client-bundle | +| host-check | `node --max-old-space-size=4096 -p tsconfig.host.json` | host-src | +| client-check | ` -p tsconfig.client.json` | client-src | + +```text +native → host-src ─┬─ host-check ───────────────────────────────────────────────────────┐ + └─ host-bundle → desktop-bundle → client-src ─┬─ client-check ───────┤ → record + └─ client-bundle → web ┘ +``` + +- client-src must follow host-bundle: Client packages import `@deepseek-ai/dsh-*/remote`, whose types `lib/typert.remote-client.d.ts` Typert writes, inside Host tsdown in these scopes and through `scripts/generate-typert.ts` in the typecheck scope. host-check reads no Typert output; clean serial builds have always finished the Host aggregate check before Host tsdown. +- The artifact chain keeps the two non-data edges native → host-src and desktop-bundle → client-src; only the two check steps attach to the chain in parallel. +- [`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts) owns the package-library step list `libraryBuildSteps`, the references argument construction `referencedProjectsCompilerArgs` (relative paths keep the command below Windows' command-line limit), and the aggregate-check arguments `aggregateCheckArgs`. The vendor release rehearsal (`host-libraries`) and CI benchmarks (`--noCheck`) run the same step list serially. +- The check steps use project mode (`tsc -p`): it reads the declarations that references already emitted and compiles no reference, writing incremental state to the aggregates' existing `tsconfig.{host,client}.tsbuildinfo`. `build` and `build:check` run the same command, so their diagnostics are identical. + +### Scheduling, failure, and output + +- [`scripts/build.ts`](../../../../scripts/build.ts) owns the step table and the three scopes and executes them through `runAggregate` from [`scripts/run-gates.ts`](../../../../scripts/run-gates.ts): each step is a gate with `needs`, and shell-free spawning, per-step buffered output, fail-fast process-tree termination, Windows `taskkill`, and host signal forwarding come from the run-gates implementation. `build:artifacts` is `tsx scripts/build.ts --scope artifacts`, `build:check` is `--scope check`, and `build` omits `--scope` and runs both as one graph; `--profile` applies only to artifact scopes, and combining it with `--scope check` fails argument parsing. +- The concurrency limit is `DSH_GATE_CONCURRENCY`, defaulting to the available CPU count; the dependency graph is at most 3 wide (client-check and client-bundle can start while host-check is still running). Master serial reference lanes set `DSH_GATE_CONCURRENCY=1`, so `build` runs serially in topological order there, consistent with the [serial reference decision](2026-07-21-serial-cross-platform-ci-reference.md) and without workflow edits. +- By default (locally), every dependent of a failed step is recorded as skipped, while running steps and steps unrelated to the failure run to completion; the executed set depends only on step outcomes, so one run reports every independent type error. With `DSH_GATE_FAIL_FAST=1` (set in every building PR lane), the first failure terminates the process trees of the other running steps and records every unfinished step as skipped. +- A failed step prints `== FAILED ==`, its command, the exit reason, and the step's complete buffered output, and the final summary lists failed and skipped steps; a passing step prints only its PASS line, and `DSH_GATE_VERBOSE=1` prints all output. The exit code is 1 when any step failed or was skipped, and the client build record is not written. Every step inherits the public Client environment selected by `clientBuildProcessEnvironment`. +- In CI, `build` itself is one gate of an outer run-gates aggregate; outer fail-fast termination propagates to the inner scheduler. `check:node-compat` and `check:ci:lint:contracts-ready` already nest the same way. + +### Callers + +| Caller | Command | Aggregate root-program checks | +|---|---|---| +| `build`, `build:official`, `Makefile` `build`, `scripts/publish-npm-baseline.ts`, `apps/desktop/scripts/package-target.ts`, `scripts/dev-bundle-registry.ts`, `release-publish.yml`, `sandbox.yml`, and the non-PR branches of `e2e.yml` and `release.yml` | `build` / `build:official` | Yes | +| `test:web`, `test:web:refresh`, `test:web:perf`, `test:web:stress`, `apps/desktop` `test:updates:local`, `test:bench` / `build:bench` | `build`; `build:bench` runs `build:native-system`, `build:lib`, and the benchmark tsdown | Yes | +| `typecheck` (run by the pre-push hook) | `build.ts --scope typecheck`: host-src beside host-typert (the bundle-free, source-only Typert pass `generate-typert.ts`) → client-src, with `tsc -b tsconfig.{host,client}.json` after each face's package compilation; no bundle | Yes | +| `dev:web` ([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts)), `dev:desktop` (`apps/desktop/scripts/dev.ts`) | `build:artifacts` | None before launch; after `dev:web` launches, its `tsc -b tsconfig.client.json --watch` keeps checking the Client aggregate root program | +| Prerequisite step of `lint`, `lint:fix`, `doc-typecheck`, and the CI Typert contracts gate | Host package compilation beside the bundle-free Typert pass (`compile-referenced-projects.ts host-contracts`), without any bundle | None | +| CI node 24 / snapshots and artifacts (`check:ci:consumers`), windows node 24 / build & observational (`check:ci:windows-blocking`) | `build` | Yes, the two required lanes | +| CI node-compat 22.19 | `build:artifacts` (through run-gates) | None | +| CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | None | +| PR rehearsals in `e2e.yml` and `release.yml` | `pnpm run build:artifacts --profile official` | None | +| `build-preview-cloudflare.yml` | `pnpm run build:artifacts` | None | +| CI node 24 / benchmarks | `run-ci-bench.ts` (`tsc -b --noCheck`) | None | +| PR rehearsal in `release-vendor.yml` | `compile-referenced-projects.ts host-libraries` | None | +| Non-PR branch of `release-vendor.yml`, `release-vendor-publish.yml` | `build:lib:host` | Host aggregate root program only | + +`lint`, `lint:fix`, `doc-typecheck`, and the Typert contracts gate read only Typert outputs and package declarations: both aggregates are `noEmit`, oxlint builds its own programs, `doc-typecheck` references only package projects, and none of them reads a bundle. Their prerequisite step therefore skips the Host aggregate check and every bundle; skipping the Host aggregate check and the Desktop bundle alone took it from 159.8 s to 90.9 s (see the measurements below). + +The consumers lane's HMR Web test starts `dev:web` and therefore uses `build:artifacts` inside that lane; the same lane's `build` gate still runs both aggregate checks. CI does not call `build:check` separately: the two required lanes already get the same checks through `build`. The [PR artifact build decision](2026-10-05-pr-artifact-typechecks.md) keeps its required complete builds, benchmark `--noCheck`, job and worker ceilings, serial node-compat Vitest, coverage weights, and pnpm packing checks; its PR artifact build is `build:artifacts`. + +### Measurements + +Prototype conditions: a shared 256 vCPU Linux host (load average 23–70), Node v24.18.0, TypeScript 6.0.3, React type packages hoisted to the root, without the Typert changes of [the lossless speed-ups note](2026-10-11-lossless-build-speedups.md); scope is the package-library build (excluding native and web). Every round starts from `pnpm run clean`, running once each in the order serial, concurrent, `build:lib`, `build:lib`, concurrent, serial; `/usr/bin/time -v` times each step, and summed process-tree RSS is sampled every 250 ms. The prototype runs the aggregate checks as `tsc -b tsconfig.{host,client}.json` once references are up to date, when build mode builds only the aggregate root program. + +| Mode (medians of 2) | Wall (s) | CPU user+sys (s) | Process-tree RSS peak (GiB) | +|---|---|---|---| +| Serial `pnpm run build:lib` | 249.4 | 378.0 | 5.95 | +| Each step run separately in sequence | 255.1 | 373.8 | 5.82 | +| Concurrent by dependency graph | 172.1 | 392.1 | 8.00 | + +Median wall falls from 249.4 s to 172.1 s (−77.3 s, −31%). The two runs of each step separately differ by 28 s, so the overhead of running the steps as separate processes is not resolvable. CPU grows by about 14 s (+3.7%), mostly Host aggregate check user time under contention; the RSS peak grows by about 2.1 GiB where the Host aggregate check (about 4 GiB) overlaps Host tsdown (about 5.7 GiB). The concurrent critical path is host-src → host-bundle → desktop-bundle → client-src → client-check; host-check finishes about 33 s before the end and client-bundle about 21 s before. + +Final measurements: master (the merge base) and this branch run interleaved, each from clean, in a 64-core cgroup; values are medians of 2 samples unless marked n=1. + +| Scenario | master | This branch | CPU user+sys (master → branch) | Process-tree RSS peak (master → branch) | +|---|---|---|---|---| +| Complete build `pnpm run build` | 317.1 s | 169.1 s (−46.7%) | 423.1 → 374.4 s (−11.5%) | 6.11 → 7.53 GiB (+1.42) | +| Serial branch build `DSH_GATE_CONCURRENCY=1 pnpm run build` (n=1) | — | 266.7 s | 389.5 s | 6.27 GiB | +| Artifact build: master `build --artifacts-only`, branch `build:artifacts` | 185.8 s | 153.6 s (−17.3%) | 256.2 → 231.2 s | 6.58 → 6.18 GiB | +| Development iteration: master `build`, branch `build:artifacts` | 317.1 s | 153.6 s (−51.6%) | 423.1 → 231.2 s (−45.4%) | 6.11 → 6.18 GiB | +| `pnpm run build:check` after `build:artifacts` | — | 67.7 s | 144.6 s | 5.33 GiB | +| `pnpm run build:check` no-op rerun | — | 19.4 s | 33.1 s | Not measured | +| Prerequisite of `lint` and `doc-typecheck`: master `build:lib:host`, branch `host-libraries` (since replaced by `host-contracts`, see [local gate speed-ups](2026-10-12-local-gate-speedups.md)) | 159.8 s | 90.9 s (−43.2%) | 234.7 → 136.0 s | Not measured | + +The serial branch sample overlapped other work on the host (742 s of foreign CPU), so its wall likely overstates the serial cost. In the serial build segments (master → branch, one sample each), Host tsdown falls from 22.5 to 11.7 s, Client package compilation from 55.6 to 48.7 s, the Client aggregate check from 68.2 to 35.9 s, and Client tsdown from 13.9 to 10.5 s; the segments sum to 308.5 s and 254.9 s. Those reductions come from [the lossless speed-ups note](2026-10-11-lossless-build-speedups.md); the further reduction from 254.9 s of serial segments to the 169.1 s concurrent build comes from this note's scheduling, which takes the Host aggregate check (about 66 s) off the critical path. In the concurrent build, the critical path is native → host-src → host-bundle → desktop-bundle → client-src → client-check, and host-check ends about 30 s before the last step (one earlier sample). `build:check` runs the Host and Client aggregate checks concurrently, so its wall is the Host check's (about 65 s). + +### Completeness and lossless evidence + +`build` runs the same set of compiler programs as the serial build: host-src and client-src compile every package project of both faces, and host-check and client-check check both aggregate root programs with the same commands as `build:check`. Across the prototype's six rounds, the 11,580 files of `{packages,apps,vendor,native}/**/lib/**` (excluding `*.tsbuildinfo`) are byte-identical between serial and concurrent runs, and after every round `tsc -b --dry tsconfig.host.json tsconfig.client.json` reports no out-of-date project. tsbuildinfo writers are host-src (292), client-src (76, exactly the client-only projects), and one per aggregate check; client-src rewrites no tsbuildinfo or declaration that host-check reads, so the graph has no write race. The fixture tests `checks only the aggregate program in project mode` and `reports missing package declarations without compiling references` show that `tsc -b --dry` treats the tsbuildinfo written by `tsc -p` as up to date and that project mode compiles no reference. In this implementation, the concurrent `build` and `DSH_GATE_CONCURRENCY=1 pnpm run build` produce byte-identical `lib/` (11,584 files), `apps/web/dist` (156 files), and client build record; afterwards `tsc -b --dry` reports all 372 projects of both aggregates up to date, with none to build. + +| Error | `build:artifacts` | `build:check` | `build` | `typecheck` | Required CI lanes | +|---|---|---|---|---|---| +| Package source type error | host-src / client-src | Not reported (reads existing declarations) | host-src / client-src | Reported | Reported | +| Type error only in an aggregate root program's tests, scripts, benchmarks, or website | Not reported | host-check / client-check | host-check / client-check | Reported | consumers, windows-build | +| Package tsconfig configuration error | host-src / client-src | Not reported (`tsc -p` does not validate referenced projects' tsconfig options or syntax) | host-src / client-src | Reported | Reported | +| Typert analysis error | host-bundle | Not reported | host-bundle | Reported (through host-typert) | Reported | +| Missing prerequisite output | — | Compiler diagnostic (TS6305, TS2307) | — | — | — | + +Negative controls: after a type error (TS2322) is added to `scripts/pnpm-invocation.spec.ts`, which only the Host aggregate root program contains, `build:artifacts` exits 0; `build:check` exits 1 with the Host aggregate check failing and the Client aggregate check passing; `build` exits 1 with 8 of 9 steps passing and 1 failing, and writes no client build record. In a scratch fixture whose referenced project's tsconfig has an invalid `target`, a JSON syntax error, or an unknown compiler option, `tsc -p` exits 0, while `tsc -b` reports TS6046, TS5092 with TS1012, and TS5023 respectively and exits 1; when the referenced project lacks `composite`, both report TS6306. + +CI evidence: on PR #6005 both required lanes that run the concurrent `pnpm run build` passed, `node 24 / snapshots and artifacts` (`check:ci:consumers` on `blacksmith-16vcpu-ubuntu-2404`) and `windows node 24 / build & observational` (`check:ci:windows-blocking` on `blacksmith-16vcpu-windows-2025`); the GitHub-hosted 4 vCPU benchmarks lane does not run `build`. The inner concurrency follows `DSH_GATE_CONCURRENCY`: master serial lanes set 1, the consumers lane sets 10 under self-hosted failover, and an unset value selects the available CPU count, capped at the 9 steps. + +### Intentional trade-offs (not lossless) + +- **Some commands skip the aggregate checks:** `build:artifacts`, the launch builds of `dev:web` and `dev:desktop`, and the prerequisite steps of `lint`, `lint:fix`, `doc-typecheck`, and the Typert contracts gate do not type-check the two aggregate root programs, and these prerequisite steps produce declarations and Typert outputs but no bundle. `build`, `build:check`, `typecheck` (pre-push hook), and the two required CI lanes own completeness; `dev:web` and `dev:desktop` do not refuse to launch because of test type errors. +- **`build:check` does not check freshness:** When sources change after `build:artifacts`, `build:check` checks against stale declarations, including Typert Remote declarations; rerun `build:artifacts` first. The complete `build` is unaffected. +- **Concurrent `build` raises the memory peak:** This branch's complete `build` peaks at 7.53 GiB of process-tree RSS against 6.11 GiB for the master serial build (+1.42 GiB, medians of 2) and 6.27 GiB for the branch's serial build (n=1); CPU meanwhile falls from 423.1 s to 374.4 s because [the lossless speed-ups note](2026-10-11-lossless-build-speedups.md) removes more work than concurrent contention adds. In the prototype (without the Typert changes), concurrent scheduling alone raises the RSS peak by about 2.1 GiB (5.9 → 8.0 GiB) and CPU by about 3.7%. `DSH_GATE_CONCURRENCY` bounds it; under memory pressure use `DSH_GATE_CONCURRENCY=1 pnpm run build`, or run `build:artifacts` and `build:check` separately. In the windows-build lane, `build` runs concurrently with `docs:build`. +- **Passing steps' output is hidden by default:** Only failed steps print their complete output. +- **`tsc -p` does not skip an up-to-date root program:** An immediate rerun of `build:check` without changes still takes 19.4 s and 33.1 s of CPU because both programs are parsed again; `tsc -b` skips an up-to-date root. +- **On many-core cold builds `build:artifacts` is only 15.5 s faster than `build`:** This branch's cold `build` takes 169.1 s and `build:artifacts` 153.6 s (medians of 2), because host-check is off the critical path and client-check is only about 16 s longer than client-bundle plus web. The rest of `build:artifacts`'s saving is CPU and memory: 374.4 → 231.2 s of CPU and 7.53 → 6.18 GiB of peak RSS; on few-core machines and in incremental rebuilds this also turns into wall time. +- **CI invokes public commands in the root manifest:** PR artifact builds invoke `build:artifacts` rather than an internal helper flag; a PR that edits these root manifest scripts activates the separate Node Addon System platform matrix. + +## Alternatives considered + +- **Keep the aggregate checks only in `typecheck`:** `pnpm run build` must stay complete and detect every error. +- **Keep `--artifacts-only` and add a `build:artifacts` alias:** One operation would have two names. +- **Name the commands `build:src` and `build:test`:** `build:artifacts` produces every artifact, including the tsdown bundles, the Desktop bundle, and Web, not only compiled sources; `build:check` checks scripts, benchmarks, and website code as well as tests. +- **Name the commands after compiler terms (`build:b`/`build:p`, `build:project`, `build:emit`) or `build:dist`:** tsc runs in only two artifact steps, and `-p` is an implementation choice for the check steps; TypeScript calls the `tsc -p` side the project; `emit` reads as the emit-only `--noCheck` mode although package projects stay fully checked; package outputs live under `lib/`, and `dist` suggests release packaging. +- **`build:check` runs `tsc -b `:** Build mode compiles out-of-date references, doing `build:artifacts`'s work. +- **`build:check` first completes or validates prerequisite outputs:** It violates each command doing only its own job and adds prerequisite logic; compiler diagnostics already name missing outputs. +- **A new scheduler (shell `&`/`wait`, `concurrently`, turbo/nx):** It duplicates run-gates' failure summary, process-tree termination, and Windows handling. +- **Expand `build` into several gates in CI's run-gates:** `pnpm run build` must be a complete command usable directly locally and by release workflows, and it writes the record. +- **Relax the non-data edges in the artifact chain (native ∥ host-src, desktop-bundle ∥ client-src):** Not measured; the Desktop bundle itself takes only 4.0–4.5 s. +- **Move tests into a new tsconfig:** The existing aggregates already separate package references from the root program. +- **Split the aggregate root programs into sub-programs:** Each sub-program must inject the 242 files carrying module augmentations, CPU grows by 9–57%, and only wall falls (see [the lossless speed-ups note](2026-10-11-lossless-build-speedups.md)). +- **Run `build:check` separately in CI:** The required lanes already get the same checks through `build`; a separate run repeats the work. + +## Consequences + +Development iterations can skip the two aggregate root programs with `build:artifacts` (51.6% faster cold than master's `build`) and complete the checks with `build:check` or `build` before declaring work complete. `build` stays complete: the Host aggregate check is off the critical path, the Client aggregate check runs alongside the Client bundle and web, and a cold build is 46.7% faster than master (including the lossless speed-ups note's changes; medians of 2). The costs are a higher memory peak, a little extra CPU from concurrent contention, less passing output by default, and several development and prerequisite commands that do not check test types (see the trade-offs above). + +Removing or changing `build` in the two required lanes, consumers and windows-build, requires first transferring both aggregate checks to another blocking owner. The typecheck scope and the lint prerequisites generate Typert contracts without bundling ([local gate speed-ups](2026-10-12-local-gate-speedups.md)); the artifact scopes keep generating them inside Host tsdown. + +client-src's dependency on host-bundle guarantees the "Host and Remote artifacts complete before Client compilation" ordering that [Typert Remote method calls](../architecture/2026-08-02-typert-remote-method-calls.md) describes. + +Verification: `scripts/build.spec.ts` covers the type-stripping check, rejection of the removed flag and invalid scopes, the conflict between `--profile` and `--scope check`, scope selection, step dependencies, and the environment; `compile-referenced-projects.spec.ts` covers project mode checking only the aggregate program, the diagnostic for missing declarations, and `tsc -b --dry` accepting the tsbuildinfo that `tsc -p` writes; failure propagation, output buffering, and process-tree termination come from the run-gates scheduler and its tests; `run-gates.spec.ts`, `ci-workflow.spec.ts`, `preview-workflow.spec.ts`, `build-exe-for-python-sdk.spec.ts`, `dev-web.spec.ts`, and `tests/ci-release-selfhosted.spec.ts` pin each caller's command. diff --git a/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md new file mode 100644 index 0000000000..4929e28574 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-11-build-artifacts-check-split.zh.md @@ -0,0 +1,157 @@ +# Agent Note: 拆分 build:artifacts 与 build:check,build 并发执行两者 + +Status: implemented + +[English](2026-10-11-build-artifacts-check-split.md) | 中文 + +## 问题 + +`pnpm run build` 串行执行 native addon、包库构建(Host `tsc -b tsconfig.host.json` → Host tsdown → Desktop bundle → Client `tsc -b tsconfig.client.json` → Client tsdown)和 Web 构建。Host 与 Client 聚合配置除了引用各包 project,还各自带有一个 `noEmit` 根程序,覆盖 tests、scripts、benchmarks 与 website。这两个根程序不产出任何文件,也不是后续产物步骤的输入,却位于串行关键路径上:单独计时时 Host 根程序为 68.5 s、Client 根程序为 36.0 s,串行包库构建约为 249 s(2 个样本的中位数)。 + +开发迭代只需要产物,测试与脚本的类型检查在声明完成前才需要。能跳过两个根程序的只有面向 CI 的 `pnpm run build --artifacts-only`;它没有本地开发命令名,也没有只做这两项检查的对应命令。同时,`pnpm run build` 必须保持完整,能检测出所有类型错误。 + +## 决策 + +### 命令 + +每个命令只做自己的工作。 + +| 命令 | 职责 | 步骤 | 调度 | client build record | +|---|---|---|---|---| +| `pnpm run build:artifacts` | 产出 `build` 的全部产物;包 project 照常完整类型检查,不检查两个聚合根程序 | native → host-src → host-bundle → desktop-bundle → client-src → client-bundle → web | 一条线性链 | 开始时删除,全部通过后写入 | +| `pnpm run build:check` | 只类型检查两个聚合根程序 | host-check、client-check | 两步并发,无前置步骤 | 不读写 | +| `pnpm run build` | `build:artifacts` 与 `build:check` 的全部步骤 | 下文依赖图 | run-gates 调度器并发执行 | 开始时删除,全部通过后写入 | + +`build:check` 不检测、不重建、也不校验 `build:artifacts` 的产物;前置产物缺失或过期时,由编译器自身的诊断(例如 TS6305、TS2307)报告,任何命令都不增加前置检查、守卫或回退逻辑。`build:artifacts` 产出的产物与 record 和 `build` 相同,并取代 `--artifacts-only`;该参数与 `compile-referenced-projects.ts` 的 `libraries` 模式已删除,Python executable builder 使用 `--build-artifacts`。`build:official` 仍是 `tsx scripts/build.ts --profile official`,执行完整的 `build`。 + +### 步骤与依赖 + +| 步骤 | 命令 | `build` 中的 `needs` | +|---|---|---| +| native | `pnpm run build:native-system` | — | +| host-src | `node --max-old-space-size=4096 -b ` | native | +| host-bundle | `tsdown --config-loader native --env.DSH_BUILD_FACE host`(运行 Typert) | host-src | +| desktop-bundle | `pnpm --filter @deepseek-ai/dsh-desktop run bundle` | host-bundle | +| client-src | ` -b ` | desktop-bundle | +| client-bundle | `tsdown --config-loader native --env.DSH_BUILD_FACE client` | client-src | +| web | `pnpm run build:web` | client-bundle | +| host-check | `node --max-old-space-size=4096 -p tsconfig.host.json` | host-src | +| client-check | ` -p tsconfig.client.json` | client-src | + +```text +native → host-src ─┬─ host-check ───────────────────────────────────────────────────────┐ + └─ host-bundle → desktop-bundle → client-src ─┬─ client-check ───────┤ → record + └─ client-bundle → web ┘ +``` + +- client-src 必须在 host-bundle 之后:Client 包导入 `@deepseek-ai/dsh-*/remote`,其类型 `lib/typert.remote-client.d.ts` 由 Typert 写出:这些 scope 在 Host tsdown 中生成,typecheck scope 经 `scripts/generate-typert.ts` 生成。host-check 不读取 Typert 输出,干净的串行构建一直在 Host tsdown 之前完成 Host 聚合检查。 +- 产物链保留 native → host-src 与 desktop-bundle → client-src 这两条非数据依赖;只有两个 check 步骤并行挂接到链上。 +- [`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts) 拥有包库步骤列表 `libraryBuildSteps`、references 参数构造 `referencedProjectsCompilerArgs`(相对路径传参,避开 Windows 命令行长度上限)与聚合检查参数 `aggregateCheckArgs`。vendor 发布演练(`host-libraries`)与 CI benchmark(`--noCheck`)串行执行同一步骤列表。 +- check 步骤使用 project mode(`tsc -p`):它读取 references 已有的声明而不编译任何 reference,incremental 状态写入聚合配置已有的 `tsconfig.{host,client}.tsbuildinfo`。`build` 与 `build:check` 使用同一条命令,因此诊断相同。 + +### 调度、失败与输出 + +- [`scripts/build.ts`](../../../../scripts/build.ts) 拥有步骤表与三个范围,执行复用 [`scripts/run-gates.ts`](../../../../scripts/run-gates.ts) 的 `runAggregate`:每个步骤是一个带 `needs` 的 gate,shell-free 启动、按步骤缓冲输出、fail-fast 进程树终止、Windows `taskkill` 与宿主信号转发都沿用 run-gates 的实现。`build:artifacts` 为 `tsx scripts/build.ts --scope artifacts`,`build:check` 为 `--scope check`,`build` 不带 `--scope`,把两者作为一张图执行;`--profile` 只适用于产生产物的范围,与 `--scope check` 同用时参数解析失败。 +- 并发上限取 `DSH_GATE_CONCURRENCY`,未设置时为可用 CPU 数;依赖图宽度最多为 3(host-check 尚未结束时,client-check 与 client-bundle 可能已开始)。master 串行参考 lane 设置 `DSH_GATE_CONCURRENCY=1`,`build` 在那里按拓扑顺序串行执行,符合[串行参考决策](2026-07-21-serial-cross-platform-ci-reference.zh.md),无需修改 workflow。 +- 缺省(本地)时,失败步骤的所有依赖方记为 skipped,正在运行的步骤和与失败无关的步骤继续运行到结束;执行集合只取决于各步骤的结果,因此一次运行报告所有相互独立的类型错误。`DSH_GATE_FAIL_FAST=1`(所有构建型 PR lane 已设置)时,第一个失败终止其余正在运行步骤的进程树,所有未完成步骤记为 skipped。 +- 失败步骤打印 `== FAILED <步骤> ==`、命令、退出原因与该步骤完整的缓冲输出,结尾汇总列出 failed 与 skipped 步骤;成功步骤只打印 PASS 行,`DSH_GATE_VERBOSE=1` 打印全部输出。任一步骤 failed 或 skipped 时退出码为 1,且不写 client build record。所有步骤继承 `clientBuildProcessEnvironment` 选定的公开 Client 环境。 +- CI 中 `build` 本身是外层 run-gates 的一个 gate;外层 fail-fast 终止会转发到内层调度。`check:node-compat` 与 `check:ci:lint:contracts-ready` 已使用同样的嵌套。 + +### 调用方 + +| 调用方 | 命令 | 聚合根程序检查 | +|---|---|---| +| `build`、`build:official`、`Makefile` `build`、`scripts/publish-npm-baseline.ts`、`apps/desktop/scripts/package-target.ts`、`scripts/dev-bundle-registry.ts`、`release-publish.yml`、`sandbox.yml`、`e2e.yml` 与 `release.yml` 的非 PR 分支 | `build` / `build:official` | 有 | +| `test:web`、`test:web:refresh`、`test:web:perf`、`test:web:stress`、`apps/desktop` `test:updates:local`、`test:bench` / `build:bench` | `build`;`build:bench` 运行 `build:native-system`、`build:lib` 与 benchmark tsdown | 有 | +| `typecheck`(pre-push hook 运行它) | `build.ts --scope typecheck`:host-src 与 host-typert(不打包、只读源码的 Typert 生成 `generate-typert.ts`)并行 → client-src,各 face 包编译后运行 `tsc -b tsconfig.{host,client}.json`;不含任何 bundle | 有 | +| `dev:web`([`scripts/dev-web.ts`](../../../../scripts/dev-web.ts))、`dev:desktop`(`apps/desktop/scripts/dev.ts`) | `build:artifacts` | 启动前无;`dev:web` 启动后的 `tsc -b tsconfig.client.json --watch` 持续检查 Client 聚合根程序 | +| `lint`、`lint:fix`、`doc-typecheck` 与 CI 的 Typert contracts gate 的前置步骤 | Host 包编译与不打包的 Typert 生成并行(`compile-referenced-projects.ts host-contracts`),不含任何 bundle | 无 | +| CI node 24 / snapshots and artifacts(`check:ci:consumers`)、windows node 24 / build & observational(`check:ci:windows-blocking`) | `build` | 有,两个必需 lane | +| CI node-compat 22.19 | `build:artifacts`(经 run-gates) | 无 | +| CI python runtime | `build-exe-for-python-sdk.ts --build-artifacts` | 无 | +| `e2e.yml`、`release.yml` 的 PR 演练 | `pnpm run build:artifacts --profile official` | 无 | +| `build-preview-cloudflare.yml` | `pnpm run build:artifacts` | 无 | +| CI node 24 / benchmarks | `run-ci-bench.ts`(`tsc -b --noCheck`) | 无 | +| `release-vendor.yml` 的 PR 演练 | `compile-referenced-projects.ts host-libraries` | 无 | +| `release-vendor.yml` 的非 PR 分支、`release-vendor-publish.yml` | `build:lib:host` | 仅 Host 聚合根程序 | + +`lint`、`lint:fix`、`doc-typecheck` 与 Typert contracts gate 只读取 Typert 输出与包声明:两个聚合配置都是 `noEmit`,oxlint 自行构建程序,`doc-typecheck` 只引用包 project,它们都不读取 bundle。它们的前置步骤因此跳过 Host 聚合检查与所有 bundle;仅跳过 Host 聚合检查与 Desktop bundle 就使耗时从 159.8 s 降到 90.9 s(见下文测量)。 + +consumers lane 的 HMR Web 测试启动 `dev:web`,因此在该 lane 内使用 `build:artifacts`;同一 lane 的 `build` gate 仍运行两个聚合检查。CI 不单独调用 `build:check`:两个必需 lane 已通过 `build` 获得同一组检查。[PR 产物构建决策](2026-10-05-pr-artifact-typechecks.zh.md)的必需完整构建、benchmark `--noCheck`、job 与 worker 上限、node-compat 串行 Vitest、覆盖率权重与 pnpm 打包检查仍然有效;其中的 PR 产物构建由 `build:artifacts` 执行。 + +### 测量 + +原型测量的条件:256 vCPU 共享 Linux 主机(load average 23–70),Node v24.18.0、TypeScript 6.0.3,React 类型包已提升到根,不含[无损提速 Note](2026-10-11-lossless-build-speedups.zh.md) 的 Typert 改动;范围是包库构建(不含 native 与 web)。每轮从 `pnpm run clean` 开始,按 串行、并发、`build:lib`、`build:lib`、并发、串行 的顺序各运行一次;每个步骤由 `/usr/bin/time -v` 计时,进程树 RSS 每 250 ms 采样求和。原型中的聚合检查以 `tsc -b tsconfig.{host,client}.json` 在 references 已是最新时运行,此时 build mode 只构建聚合根程序。 + +| 方式(2 个样本的中位数) | wall(s) | CPU user+sys(s) | 进程树 RSS 峰值(GiB) | +|---|---|---|---| +| 串行 `pnpm run build:lib` | 249.4 | 378.0 | 5.95 | +| 各步骤依次单独运行 | 255.1 | 373.8 | 5.82 | +| 按依赖图并发 | 172.1 | 392.1 | 8.00 | + +wall 中位数从 249.4 s 降到 172.1 s(−77.3 s,−31%)。各步骤单独运行的两次样本相差 28 s,因此把步骤拆成独立进程的开销无法分辨。CPU 增加约 14 s(+3.7%),主要是争用下 Host 聚合检查增加的 user 时间;RSS 峰值增加约 2.1 GiB,出现在 Host 聚合检查(约 4 GiB)与 Host tsdown(约 5.7 GiB)重叠时。并发时的关键路径是 host-src → host-bundle → desktop-bundle → client-src → client-check;host-check 在结束前约 33 s 完成,client-bundle 在结束前约 21 s 完成。 + +最终测量:master(合并基点)与本分支交替运行,每次均从 clean 开始,在 64 核 cgroup 中运行;除标注 n=1 者外,数值均为 2 个样本的中位数。 + +| 场景 | master | 本分支 | CPU user+sys(master → 本分支) | 进程树 RSS 峰值(master → 本分支) | +|---|---|---|---|---| +| 完整构建 `pnpm run build` | 317.1 s | 169.1 s(−46.7%) | 423.1 → 374.4 s(−11.5%) | 6.11 → 7.53 GiB(+1.42) | +| 本分支串行构建 `DSH_GATE_CONCURRENCY=1 pnpm run build`(n=1) | — | 266.7 s | 389.5 s | 6.27 GiB | +| 产物构建:master `build --artifacts-only`,本分支 `build:artifacts` | 185.8 s | 153.6 s(−17.3%) | 256.2 → 231.2 s | 6.58 → 6.18 GiB | +| 开发迭代:master `build`,本分支 `build:artifacts` | 317.1 s | 153.6 s(−51.6%) | 423.1 → 231.2 s(−45.4%) | 6.11 → 6.18 GiB | +| `pnpm run build:check`(`build:artifacts` 之后) | — | 67.7 s | 144.6 s | 5.33 GiB | +| `pnpm run build:check` 无改动重跑 | — | 19.4 s | 33.1 s | 未测量 | +| `lint` 与 `doc-typecheck` 的前置步骤:master `build:lib:host`,本分支 `host-libraries`(后由 `host-contracts` 取代,见[本地门禁提速](2026-10-12-local-gate-speedups.zh.md)) | 159.8 s | 90.9 s(−43.2%) | 234.7 → 136.0 s | 未测量 | + +本分支串行样本运行时主机上有其他工作(外来 CPU 742 s),因此它的 wall 可能高估串行成本。串行构建的各段中(master → 本分支,各一个样本),Host tsdown 从 22.5 s 降到 11.7 s,Client 包编译从 55.6 s 降到 48.7 s,Client 聚合检查从 68.2 s 降到 35.9 s,Client tsdown 从 13.9 s 降到 10.5 s;各段合计分别为 308.5 s 与 254.9 s。这些缩短来自[无损提速 Note](2026-10-11-lossless-build-speedups.zh.md);从 254.9 s 的串行各段合计到 169.1 s 的并发构建,其余缩短来自本 Note 的调度,它把 Host 聚合检查(约 66 s)移出关键路径。并发构建的关键路径是 native → host-src → host-bundle → desktop-bundle → client-src → client-check,host-check 在最后一步结束前约 30 s 完成(取自更早的一个样本)。`build:check` 并发运行 Host 与 Client 聚合检查,因此其 wall 等于 Host 聚合检查的 wall(约 65 s)。 + +### 完整性与无损依据 + +`build` 运行的编译器程序集合与串行构建相同:host-src 与 client-src 编译两个 face 的全部包 project,host-check 与 client-check 检查两个聚合根程序,且使用与 `build:check` 相同的命令。原型的 6 轮运行中,`{packages,apps,vendor,native}/**/lib/**`(排除 `*.tsbuildinfo`)的 11,580 个文件在串行与并发之间逐字节一致,每轮之后 `tsc -b --dry tsconfig.host.json tsconfig.client.json` 报告没有过期 project。tsbuildinfo 写入方归属为:host-src 292 个,client-src 76 个(恰好是 client-only project),两个聚合检查各 1 个;client-src 不改写 host-check 读取的任何 tsbuildinfo 或声明,因此该依赖图中不存在写入竞争。fixture 测试 `checks only the aggregate program in project mode` 表明 `tsc -p` 写出的 tsbuildinfo 被 `tsc -b --dry` 视为最新,`reports missing package declarations without compiling references` 表明 project mode 不编译 references。本实现中,并发 `build` 与 `DSH_GATE_CONCURRENCY=1 pnpm run build` 产出逐字节一致的 `lib/`(11,584 个文件)、`apps/web/dist`(156 个文件)与 client build record;之后 `tsc -b --dry` 对两个聚合配置报告 372 个 project 全部为最新,没有需要构建的 project。 + +| 错误 | `build:artifacts` | `build:check` | `build` | `typecheck` | 必需 CI lane | +|---|---|---|---|---|---| +| 包源码类型错误 | host-src / client-src | 不报告(读取已有声明) | host-src / client-src | 报告 | 报告 | +| 只属于聚合根程序的测试、脚本、benchmark、website 类型错误 | 不报告 | host-check / client-check | host-check / client-check | 报告 | consumers、windows-build | +| 包 tsconfig 配置错误 | host-src / client-src | 不报告(`tsc -p` 不校验被引用 project 的 tsconfig 选项与语法) | host-src / client-src | 报告 | 报告 | +| Typert 分析错误 | host-bundle | 不报告 | host-bundle | 报告(经 host-typert) | 报告 | +| 前置产物缺失 | — | 编译器诊断(TS6305、TS2307) | — | — | — | + +负对照:在只属于 Host 聚合根程序的 `scripts/pnpm-invocation.spec.ts` 中加入类型错误(TS2322)后,`build:artifacts` 以 0 退出;`build:check` 以 1 退出,其中 Host 聚合检查失败、Client 聚合检查通过;`build` 以 1 退出,9 个步骤中 8 个通过、1 个失败,且不写 client build record。在临时 fixture 中,被引用 project 的 tsconfig 含无效 `target`、JSON 语法错误或未知编译选项时,`tsc -p` 以 0 退出,`tsc -b` 分别报告 TS6046、TS5092 与 TS1012、TS5023 并以 1 退出;被引用 project 缺少 `composite` 时,两者都报告 TS6306。 + +CI 证据:PR #6005 上,两个运行并发 `pnpm run build` 的必需 lane 均通过:`node 24 / snapshots and artifacts`(`check:ci:consumers`,运行于 `blacksmith-16vcpu-ubuntu-2404`)与 `windows node 24 / build & observational`(`check:ci:windows-blocking`,运行于 `blacksmith-16vcpu-windows-2025`);GitHub 托管的 4 vCPU benchmarks lane 不运行 `build`。内层并发取 `DSH_GATE_CONCURRENCY`:master 串行 lane 设为 1,consumers lane 在 self-hosted failover 时设为 10,未设置时取可用 CPU 数,且不超过 9 个步骤。 + +### 有意的取舍(非无损) + +- **部分命令跳过聚合检查:** `build:artifacts`、`dev:web` 与 `dev:desktop` 的启动构建,以及 `lint`、`lint:fix`、`doc-typecheck` 与 Typert contracts gate 的前置步骤,都不类型检查两个聚合根程序,这些前置步骤只产出声明与 Typert 输出,不打包。完整性由 `build`、`build:check`、`typecheck`(pre-push hook)与两个必需 CI lane 负责;`dev:web` 与 `dev:desktop` 不会因测试类型错误而拒绝启动。 +- **`build:check` 不检查新鲜度:** 在 `build:artifacts` 之后修改源码时,`build:check` 基于旧声明(包括 Typert Remote 声明)检查;需要先重跑 `build:artifacts`。完整 `build` 不受影响。 +- **并发 `build` 提高内存峰值:** 本分支完整 `build` 的进程树 RSS 峰值为 7.53 GiB,master 串行构建为 6.11 GiB(+1.42 GiB,2 个样本的中位数),本分支串行构建为 6.27 GiB(n=1);同时 CPU 从 423.1 s 降到 374.4 s,因为[无损提速 Note](2026-10-11-lossless-build-speedups.zh.md) 省去的工作多于并发争用增加的工作。原型(不含 Typert 改动)中,单独的并发调度使 RSS 峰值增加约 2.1 GiB(5.9 → 8.0 GiB)、CPU 增加约 3.7%。上限由 `DSH_GATE_CONCURRENCY` 控制;内存紧张时使用 `DSH_GATE_CONCURRENCY=1 pnpm run build`,或分别运行 `build:artifacts` 与 `build:check`。windows-build lane 中 `build` 与 `docs:build` 同时运行。 +- **成功步骤的输出默认不显示:** 只有失败步骤打印完整输出。 +- **`tsc -p` 不跳过已是最新的根程序:** 无改动时立即重跑 `build:check` 仍需 19.4 s 与 33.1 s CPU,因为两个程序都要重新解析;`tsc -b` 会跳过已是最新的根。 +- **多核冷启动时 `build:artifacts` 只比 `build` 快 15.5 s:** 本分支冷启动 `build` 为 169.1 s,`build:artifacts` 为 153.6 s(2 个样本的中位数),因为 host-check 不在关键路径上,client-check 只比 client-bundle 与 web 之和长约 16 s。`build:artifacts` 的其余收益是 CPU 与内存:CPU 从 374.4 s 降到 231.2 s,RSS 峰值从 7.53 GiB 降到 6.18 GiB;在少核机器与增量重建中,这部分也转化为 wall。 +- **CI 调用根 manifest 中的公开命令:** PR 产物构建调用 `build:artifacts`,而不是内部 helper 参数;修改根 manifest 中这些 script 的 PR 会激活独立的 Node Addon System 平台矩阵。 + +## 考虑过的替代方案 + +- **只在 `typecheck` 中保留聚合检查:** `pnpm run build` 必须完整,能检测出所有错误。 +- **保留 `--artifacts-only` 并新增 `build:artifacts` 别名:** 同一件事有两个名字。 +- **命名为 `build:src` 与 `build:test`:** `build:artifacts` 产出全部产物,包括 tsdown bundle、Desktop bundle 与 Web,而不只是编译后的源码;`build:check` 除测试外还检查脚本、benchmarks 与 website 代码。 +- **按编译器术语命名(`build:b`/`build:p`、`build:project`、`build:emit`)或命名为 `build:dist`:** tsc 只出现在两个产物步骤中,`-p` 只是 check 步骤的实现选择;TypeScript 把 `tsc -p` 一侧称为 project;`emit` 容易被理解为只 emit 的 `--noCheck` 模式,而包 project 仍完整检查;包产物位于 `lib/`,`dist` 则让人联想到发布打包。 +- **`build:check` 使用 `tsc -b `:** build mode 会编译过期的 references,即执行 `build:artifacts` 的工作。 +- **`build:check` 先补齐或校验前置产物:** 违背每个命令只做自己的工作,并增加前置逻辑;编译器诊断已经指明缺失的输出。 +- **新的调度实现(shell `&`/`wait`、`concurrently`、turbo/nx):** 重复 run-gates 已有的失败汇总、进程树终止与 Windows 处理。 +- **在 CI 的 run-gates 中把 `build` 展开为多个 gate:** `pnpm run build` 必须是本地与 release workflow 可直接使用的完整命令,record 也由它写入。 +- **放宽产物链内的非数据依赖(native ∥ host-src、desktop-bundle ∥ client-src):** 未测量;Desktop bundle 本身只占 4.0–4.5 s。 +- **把测试移入新的 tsconfig:** 现有聚合配置已经把包 references 与根程序分开。 +- **把聚合根程序拆成多个子程序:** 每个子程序都要注入 242 个含模块增强的文件,CPU 增加 9–57%,只降低 wall(见[无损提速 Note](2026-10-11-lossless-build-speedups.zh.md))。 +- **CI 单独运行 `build:check`:** 必需 lane 已通过 `build` 获得同一组检查,再单独运行是重复工作。 + +## 后果 + +开发迭代可以用 `build:artifacts` 跳过两个聚合根程序(冷启动比 master 的 `build` 快 51.6%),在声明完成前用 `build:check` 或 `build` 补齐检查。`build` 保持完整:Host 聚合检查不在关键路径上,Client 聚合检查与 Client bundle、web 并行,冷启动比 master 快 46.7%(含无损提速 Note 的改动,2 个样本的中位数)。代价是更高的内存峰值、并发争用带来的少量额外 CPU、默认更少的成功输出,以及多个开发与前置命令不检查测试类型(见上文取舍)。 + +删除或改变 consumers 与 windows-build 两个必需 lane 的 `build`,必须先把两个聚合检查转交另一处阻塞型 owner。typecheck scope 与 lint 类前置步骤不打包即生成 Typert 约定([本地门禁提速](2026-10-12-local-gate-speedups.zh.md));产物 scope 仍在 Host tsdown 中生成。 + +[Typert Remote 方法调用](../architecture/2026-08-02-typert-remote-method-calls.zh.md)描述的“Client 编译前先完成 Host 与 Remote 产物”由 client-src 对 host-bundle 的依赖保证。 + +验证:`scripts/build.spec.ts` 覆盖类型剥离检查、已删除参数与非法范围的拒绝、`--profile` 与 `--scope check` 的冲突、范围选择、步骤依赖与环境;`compile-referenced-projects.spec.ts` 覆盖 project mode 只检查聚合程序、缺失声明的诊断,以及 `tsc -b --dry` 接受 `tsc -p` 写出的 tsbuildinfo;失败传播、输出缓冲与进程树终止沿用 run-gates 的调度实现及其测试;`run-gates.spec.ts`、`ci-workflow.spec.ts`、`preview-workflow.spec.ts`、`build-exe-for-python-sdk.spec.ts`、`dev-web.spec.ts` 与 `tests/ci-release-selfhosted.spec.ts` 固定各调用方的命令。 diff --git a/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.i18n.yaml b/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.i18n.yaml new file mode 100644 index 0000000000..41ef49d183 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.i18n.yaml @@ -0,0 +1,46 @@ +# Bilingual-pair consistency record for 2026-10-11-lossless-build-speedups.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-10-11-lossless-build-speedups.md +/agent-note-build-speed-ups-that-keep-outputs-unchanged: + en: 48682b646b8f993a + zh: 4c26cb4aab5cd08c +/agent-note-build-speed-ups-that-keep-outputs-unchanged/problem: + en: 46551eb7e33c40ca + zh: f8c1fc063fa77062 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision: + en: 3948d6fc3fabf32e + zh: c3b8dcdfe8168275 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/measurement-conditions: + en: 2ab844073ec7c336 + zh: b25e39f2f80b0d7e +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/1-only-the-root-manifest-declares-react-type-packages: + en: 1101c94d04f9c7e9 + zh: 413b7b15f98a5f62 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/2-typert-selects-packages-by-manifest-first: + en: 1ae4b65792db0975 + zh: a11c0d90842a3b55 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/3-typert-does-not-expand-aggregate-include: + en: 0c8ab2d412113914 + zh: 01ba4f5042422d77 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/4-typert-parses-package-tsconfigs-lazily: + en: cd6e05c61a7cc495 + zh: 480d2d85d78d2d7f +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/5-the-typert-workspace-root-also-requires-packages: + en: 8b89436df201141c + zh: 2fab82419c8ba704 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/6-typert-generates-in-a-worker-thread: + en: 0362483a79c07881 + zh: d84a2390b49c4012 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/7-the-typert-transform-hook-filters-by-module-id: + en: b5ad6b5506c150d5 + zh: 25f09e4ab74696ad +/agent-note-build-speed-ups-that-keep-outputs-unchanged/decision/8-client-tsdown-presets-read-the-manifest-from-the-package-directory: + en: 80c2ddc5fdff0b5f + zh: f5ce309a2e88ff4f +/agent-note-build-speed-ups-that-keep-outputs-unchanged/alternatives-considered: + en: 4372c82ef0c944dd + zh: 5fb70d499baadea7 +/agent-note-build-speed-ups-that-keep-outputs-unchanged/consequences: + en: 93a96d3ed398f348 + zh: 93b7c7405be981a6 diff --git a/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.md b/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.md new file mode 100644 index 0000000000..021fe5b241 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.md @@ -0,0 +1,136 @@ +# Agent Note: Build speed-ups that keep outputs unchanged + +Status: implemented + +English | [中文](2026-10-11-lossless-build-speedups.zh.md) + +## Problem + +A cold build carries three fixed costs that do not affect output contents: + +- **JSX signatures in the Client test aggregate program.** The Check phase of `tsc -p tsconfig.client.json` takes 59.1 s, more than half of it computing the `@types/react` module specifier for every JSX file that imports React. TypeScript's `computeModuleSpecifiers` visits every symlink location of that declaration file and scans all 491 tsconfig `paths` entries at each location. pnpm creates one `node_modules/@types/react` link for each workspace package that declares `@types/react` itself; 66 manifests declare it, so the Client test aggregate program sees 65 locations. Counters measured 88 JSX files × 2 modules (`index.d.ts`, `jsx-runtime.d.ts`) × 65 locations: 11,457 `tryGetModuleNameFromPaths` calls and 5,623,782 entry scans, 32.6 s in total. A dose-response run at five truncation levels of the visible location count N (N = 1 to 65; Check 26.92 s to 58.40 s) fits Check ≈ 26.9 + 0.494·N s. +- **Typert inside the Host tsdown pass.** The Host tsdown pass takes about 21.6–22.6 s. Typert discovers and generates artifacts synchronously inside the first `writeBundle`; the CPU profile shows it blocking the tsdown main thread for about 12.4 s while every package build waits. Discovery takes 8.06 s: it parses all 362 package tsconfigs referenced by the two face aggregates (about 3.8 s), expands the Host aggregate's 2,064 literal `include` entries on every parse (1.6 s; the analyzer never reads those file names), and walks the public-export surface of 322 registrations (2.7–3.2 s). Only the 28 packages that declare a Typert export produce Host artifacts. +- **Manifest lookup in the Client tsdown pass.** The Client tsdown pass takes about 11.7 s with a saturated main thread (7.1% idle); 34.5% of it (3.95 s) is `workspaceManifest`: every package config runs `globSync('packages/*/*/package.json')` for its package name and parses manifests until the name matches. The module-level cache has no effect because tsdown's native config loader imports every package config through `import-without-cache`, creating a fresh module instance per config. Each glob takes 40–125 ms and runs inside the `neverBundle`/`alwaysBundle` callbacks of `tsdown:deps`, blocking every build. + +#5849 merged Host fixture type narrowing and Typert memoization; this note's baseline is the master that follows it. + +## Decision + +The following eight speed-ups change neither the bytes of `lib/` and `apps/web/dist` outputs nor the set of type diagnostics that repository builds report. The only change in diagnostic ownership comes from item 4: Typert does not validate tsconfigs of packages it does not analyze, and only `tsc -b` reports those errors. [The build split note](2026-10-11-build-artifacts-check-split.md) records the command split and concurrent scheduling. + +| # | Decision | Affected stage | Measured median | Outputs and diagnostics | Intended behavior difference | +|---|---|---|---|---|---| +| 1 | Only the root manifest declares React type packages | Client type checking | Test aggregate Check 59.1 → 26.3 s | Program file count and diagnostics unchanged | Package manifests do not list React type packages | +| 2 | Typert selects packages by manifest first | Host tsdown | 22.62 → 19.94 s | Byte-identical | None | +| 3 | Typert does not expand aggregate `include` | Host tsdown | 19.94 → 16.99 s | Byte-identical; registration inventory identical | None | +| 4 | Typert parses package tsconfigs lazily | Host tsdown | 16.99 → 16.25 s (within noise); Typert discovery 5.9–7.1 → 0.36–0.40 s | Byte-identical; registration inventory identical | Only `tsc -b` reports tsconfig errors in unanalyzed packages | +| 5 | The Typert workspace root also requires `packages/` | Host tsdown | Within noise | Byte-identical | Dual-face packages get artifacts in `package` mode | +| 6 | Typert generates in a Worker Thread | Host tsdown | 15.39 → 10.25 s | Byte-identical; failures still fail tsdown | Host tsdown max RSS about +0.6 GiB | +| 7 | The Typert `transform` hook filters by module id | Host tsdown | Within noise; hook calls 1,566 → 195 | Byte-identical | None | +| 8 | Client tsdown presets read the manifest from the package directory | Client tsdown | 12.78 → 8.73 s | Byte-identical; external decisions identical | The presets' first argument is the package directory | + +The published `./tsdown` export `typertPlugin()` changes with items 5–7 (`transform` as `{ filter, handler }`, an asynchronous `writeBundle`, and a workspace root that must contain `packages/`); rolldown and tsdown consumers accept both hook forms, and the analyzer already required `/packages`, so no external workspace that worked before stops working. + +### Measurement conditions + +All numbers come from one shared Linux host (256 vCPU, 4 TB memory, load average 23–111 during runs) with Node v24.18.0, TypeScript 6.0.3, and tsdown 0.22.2 (rolldown 1.1.1). + +- **Host tsdown:** `node node_modules/tsdown/dist/run.mjs --config-loader native --env.DSH_BUILD_FACE host`, deleting every `lib/typert.*` before each run; variants run interleaved and sequentially, 3–4 samples per group. Items 2–4 come from the first round (starting from the baseline) and items 5–7 from the second round (starting from the code with items 2–4). Output comparison covers SHA-256 of the 743 top-level files of `packages/*/*/lib`, `apps/*/lib`, and `vendor/*/lib` (140 of them Typert artifacts). Medians of two groups running identical code differ by 0–0.11 s; samples within a group spread by up to 2.5 s. +- **Client test aggregate:** `tsc -p tsconfig.client.json --extendedDiagnostics` with prebuilt references and a fresh tsBuildInfo file; six samples of identical code spread by 3.8 s in Check (about 6%). +- **Client tsdown:** `node node_modules/tsdown/dist/run.mjs --config-loader native --env.DSH_BUILD_FACE client` on a built tree. The item 8 prototype ran three rounds in rotated order with a baseline spread of 1.56 s; the final implementation and the original ran interleaved, three samples each. Output comparison covers every file of `{packages,apps,vendor,native}/**/lib/**`, excluding `*.tsbuildinfo`. + +### 1. Only the root manifest declares React type packages + +- **Purpose:** Reduce the number N of `@types/react` locations that the Client test aggregate program sees from 65 to 1, removing module-specifier work that grows linearly with N. +- **Change:** The root `package.json` declares `@types/react` `~18.3.1` and `@types/react-dom` `~18.3.0` in `devDependencies`, the ranges every package used before; manifests under `apps/*`, `packages/*/*`, and `vendor/*` declare neither in any dependency section. TypeScript resolves the root `node_modules/@types/react` from every package. Packages still declare runtime `react` and `react-dom` under the [Client dependency declaration rules](../../../../packages/client/AGENTS.md#dependency-declaration); `packages/client/ui-slots`, which references React only through `import type`, declares `react` in `devDependencies`. pnpm `dedupeDirectDeps` stays off. Lockfile changes are confined to the importers section, plus one reordered `papaparse` entry with the same integrity. +- **Regression guard:** [`verify-package-dependencies`](../../../../scripts/verify-package-dependencies.ts) runs in `hygiene` and CI. It requires the root manifest's `devDependencies` to declare both packages and rejects either one in the `dependencies`, `devDependencies`, `optionalDependencies`, or `peerDependencies` of any manifest under `apps/*`, `packages/*/*`, or `vendor/*`; the diagnostic names the entry to delete and links Client dependency declaration rule 8. The rule matches only these two exact names; other `@types/*` packages remain DefinitelyTyped type providers. Dependency-section inference does not treat these two packages as type providers for `react`/`react-dom`: when a package lacks a `react` declaration, the verifier reports `react` as missing and `--fix` refuses to repair it until a version range is declared; `--fix` never writes back or deletes the two packages. [`verify-package-dependencies.spec.ts`](../../../../scripts/verify-package-dependencies.spec.ts) covers rejection in each dependency section, a root manifest missing the declarations, the accepted layout, and the type-provider exclusion. +- **Performance:** + + | Measurement | Per-package declarations (N = 65) | Root manifest declaration (N = 1) | + |---|---|---| + | Client test aggregate Check | 59.08 s (median of 3) | 26.28 s (median of 5), −56% | + | Client test aggregate wall | 68–71 s | 33.6–34.9 s | + | Client test aggregate user CPU | 79–83 s | 44.5–45.3 s | + | Check sum of the 76 client-only package projects | 34.6 s (median of 2) | 26.5 s (median of 2), −23% | + | Wall of the 76 client-only package projects | 55.7 s (median of 2) | 44.5 s (median of 2) | + +- **Why it is lossless:** The 66 package-level links and the root link share one realpath (`.pnpm/@types+react@18.3.31`), so the program reads the same declarations; the program keeps 2,613 files, and `tsc -b --force tsconfig.client.json` exits 0 without diagnostics. `devDependencies` are not installed with published packages, so the [published dependency faces](2026-08-26-published-dependency-faces.md) conclusion that independent TypeScript consumers install referenced type packages themselves is unchanged; runtime resolution never reads `@types/*`. +- **Trade-off:** Package manifests do not list their own React type dependency, and every workspace package shares one React types version; a package that needs a different version requires a new Agent Note overturning this item. The check covers only `apps/*`, `packages/*/*`, and `vendor/*`; other pnpm members such as `website`, `benchmarks`, `native/system`, and `python/sdk-runtime` are out of scope, and none of them currently declares React type packages. + +### 2. Typert selects packages by manifest first + +- **Purpose:** Workspace mode generates artifacts only for packages that declare a Typert export, so it skips the surface walk for every other candidate. +- **Change:** `WorkspaceAnalyzer.discoverPackages(includeManifest?)` and `WorkspaceTypertGenerator.discover(faces?, includeManifest?)` accept an optional `package.json` predicate applied before the surface walk; a rejected package has neither its sources read nor its project config parsed. `WorkspaceTypertGenerator.generateContributors(faces?)` passes `hasTypertExport` (`exports` contains `./typert`, `./client/typert`, or `./remote`). Callers that pass no predicate (the Cordis catalog, `generate()` without packages) behave as before. +- **Performance:** Host tsdown 22.62 s → 19.94 s (medians of 3). +- **Why it is lossless:** The predicate is the filter previously applied after discovery, and a package it rejects never produced artifacts; the 743 output files are byte-identical except the Typert generator's own `lib/index.js`, whose source is this change. + +### 3. Typert does not expand aggregate `include` + +- **Purpose:** The analyzer reads only an aggregate's compiler options and project references; expanding `include` only fills `fileNames`, which it never uses. +- **Change:** `WorkspaceCaches.aggregate(path)` returns and caches `AggregateConfig { path, options, projectReferences }`. An aggregate that declares its own `references` is parsed with a `ParseConfigHost` whose `readDirectory` returns an empty list; an aggregate without `references` is expanded as usual. +- **Performance:** Host tsdown 19.94 s → 16.99 s (medians of 3). +- **Why it is lossless:** TypeScript reports TS18003 (no inputs) only for a config with neither `files` nor `references`, so an aggregate that declares `references` yields the same diagnostics, options, and references without expansion. The registration inventory dumped after forcing every lazy config (408 registrations, including `fileNames` and options, plus the aggregates' options and references) is byte-identical to the baseline, and the outputs are byte-identical. The tests `reads aggregate options and references without expanding include patterns` and `reports an aggregate without references or inputs` pin both kinds of config. + +### 4. Typert parses package tsconfigs lazily + +- **Purpose:** Parse only the tsconfigs of packages selected for analysis, not every package that an aggregate references. +- **Change:** `PackageRegistration.config` is a getter over `caches.config(configPath)` that parses on first read. The registration inventory keeps its order, faces, names, roots, and export subpaths. +- **Performance:** Host tsdown 16.99 s → 16.25 s (medians of 3), within the 2.5 s within-group spread. Together, items 2–4 reduce Typert discovery in an isolated benchmark from 5.9–7.1 s to 0.36–0.40 s, tsconfig parses from 362 to 28, surface walks from 322 to 28, and total Typert time from 9.7–11.8 s to 4.4–4.5 s. +- **Why it is lossless:** The inventory comparison is the one in item 3 (byte-identical), and the outputs are byte-identical. The test `reads only the project configs of manifests selected for discovery` pins that only selected configs are parsed. +- **Trade-off (not lossless):** Typert does not parse tsconfigs of packages it does not analyze, so a syntax or configuration error in such a tsconfig does not fail Typert. In the same build, the Host package compilation `tsc -b` that runs before the Host bundle and the Client package compilation `tsc -b` parse every referenced tsconfig and reject those errors; the `PackageRegistration.config` JSDoc and the [Typert generator README](../../../../packages/typert/generator/README.md) state this ownership. A consumer that runs Typert without `tsc -b` does not receive those diagnostics. + +### 5. The Typert workspace root also requires `packages/` + +- **Purpose:** Correct workspace-root resolution. 24 dual-face packages carry their own `tsconfig.host.json` leaf; searching upward for `tsconfig.host.json` alone took each of them as a root, so workspace mode ran one empty discovery per such package per build, and `package` mode silently produced no artifacts for dual-face packages. +- **Change:** The workspace root is the nearest ancestor of the bundle output that contains both `tsconfig.host.json` and `packages/`. +- **Performance:** Host tsdown 14.82 s → 15.39 s (medians of 3), within noise. +- **Why it is lossless:** The repository root [`tsdown.config.ts`](../../../../tsdown.config.ts) uses only workspace mode, and the 743 output files are byte-identical. The test `resolves the workspace root above a dual-face package leaf` pins the rule. +- **Behavior difference:** A `package`-mode consumer building a dual-face package receives that package's Typert artifacts; repository builds do not use `package` mode. + +### 6. Typert generates in a Worker Thread + +- **Purpose:** Overlap Typert analysis with bundling on the tsdown main thread instead of blocking every package build inside the first `writeBundle`. +- **Change:** [`src/worker.ts`](../../../../packages/typert/generator/src/worker.ts) is the Worker Thread entry; it runs `generateContributors(faces)` and posts one `artifacts` or `failure` message. In workspace mode, the build's first `buildStart` locates the workspace root from `options.cwd` and starts generation; `writeBundle` is asynchronous, the first finishing bundle claims emission and awaits the result, and later bundles return immediately. An analysis error, a worker crash or early exit, a malformed or undeserializable response, or a worker that cannot be terminated fails the claiming bundle with a `TypertWorkerError` naming the workspace and cause, which fails the whole tsdown pass; the worker is terminated before the outcome settles, and an unclaimed outcome never becomes an unhandled rejection. Built output starts the worker from `./worker.js`; source runs (tests) load `worker.ts` through `tsx/esm/api`. `package` mode still generates on the main thread. +- **Performance:** Host tsdown 15.39 s → 10.25 s (medians of 3). Profile of the final configuration (items 2–7): main thread 10.1 s, first `buildStart` at 4.18 s (tsdown config resolution), `writeBundle` on the main thread only 0.37 s; worker 5.0 s (module load about 0.4 s, discovery 0.28 s, generation 3.88 s including `createProgram` 2.21 s), ending at about 9.3 s. Host tsdown wall is about max(bundling, 4.2 s + Typert). +- **Why it is lossless:** All 54 second-round runs exit 0, and each run's 743 output files match the baseline except the generator's own `lib/index.js`. The test `writes the artifacts in-process generation produces` compares worker and in-process artifacts; in a scratch workspace with one package's `files` broken, tsdown exits 1 within 2.4 s, reporting `TypertWorkerError` with the worker's `TypertAnalysisError`, and writes no artifacts. The `typertPlugin workspace mode` test group covers each failure path. +- **Trade-off:** The worker heap is about 300–420 MiB; the final configuration's median Host tsdown max RSS is 6,296–6,408 MiB against 5,676 MiB at baseline. Under heavy shared-host load the worker can land on the critical path: one sample took 21.91 s with the artifact-owning package build waiting about 14 s for the worker, not reproduced in 10 later samples; at load average about 100, two runs took 17.86 s and 14.3 s. The worker also completes under a 1,024 MiB heap limit, so GC pressure is not the cause; attribution to host contention is unproven. + +### 7. The Typert `transform` hook filters by module id + +- **Purpose:** Stop every module from crossing from rolldown into the JavaScript `transform` hook only to be rejected by an extension check. +- **Change:** `transform` declares `filter: { id: /^[^?]*\.[cm]?tsx?(?:\?|$)/ }`, and its handler still checks the id with the same regular expression. +- **Performance:** Hook calls per Host build fall from 1,566 to 195 (195 TypeScript modules, 4 of them with decorators). Wall medians are 11.07 s (3 samples) and 9.98 s (4 samples) against 10.25 s for item 6, while the identical-code control groups give 11.07 s and 9.87 s; the difference is within noise. +- **Why it is lossless:** The regular expression uses only ASCII constructs and matches the same id set in rolldown's Rust regex engine and in JavaScript; the handler applies the same check, so hosts that ignore filters behave the same. Outputs are byte-identical; the test `filters transform calls to TypeScript module ids` pins the filter. + +### 8. Client tsdown presets read the manifest from the package directory + +- **Purpose:** Each package config reads only its own `package.json`, removing the glob over every manifest by package name. +- **Change:** The first argument of `clientBundle`, `staticLinked`, and `clientLibrary` in [`packages/client/tsdown.client.ts`](../../../../packages/client/tsdown.client.ts) is the package directory, normally the config file's `import.meta.dirname`; the preset reads `/package.json` once and uses its `name` as the plugin id and diagnostic name; when that manifest is missing, unreadable, or has no `name`, config loading fails with an error naming the path and cause. 82 package configs call these presets. The presets keep no module-level manifest cache; the Node half's production-dependency external list is computed from that manifest on first resolve and cached in that config's closure. +- **Performance:** Client tsdown falls from 12.78 s to 8.73 s (medians of 3), −4.05 s (−31.7%), with disjoint sample ranges; user CPU falls from 26.1 s to 25.2 s and sys from 5.9 s to 4.9 s, so the saving comes mainly from unblocking the main thread rather than from less total CPU. The prototype (one glob building a name index) measured 11.72 s → 7.46 s (−36%). In Host tsdown only 5 `hostPhase` packages reach the lookup; one sample pair measured 11.92 s → 10.71 s, with low confidence. +- **Why it is lossless:** The 11,566 lib files are byte-identical across 11 runs. After the 82 call sites switched to package directories, no resolved package name differs from the name previously written at the call site. An in-process comparison of the external decisions for 82 configs × 3 faces × 1,600 specifiers matches the original implementation exactly; a negative control with one extra external changes 75 decisions. `client-bundle-purity.spec.ts` covers these manifest errors. +- **Behavior difference:** The presets' calling convention changes from a package name to a package directory. + +## Alternatives considered + +- **Enable pnpm `dedupeDirectDeps` (item 1):** It applies to every direct dependency and changes the link layout of every workspace package, a global side effect. +- **Patch TypeScript (item 1):** An upstream-style patch (precomputed candidate endings and cached normalized `paths` patterns) lowers Check by 31.9 s, comparable to the hoist; on the hoisted tree it adds nothing (references Check 25.76 s against 26.47 s) and must be maintained across every TypeScript upgrade. +- **Alias `react` in tsconfig `paths` (item 1):** tsx, vitest, and vite also read `paths`, so the alias changes their resolution of runtime `react`. +- **Narrow `paths` to each face's reference closure (item 1):** The 328-entry version that keeps wildcard keys checks in 55.73 s against 59.08 s (one sample), within noise; the version without wildcard keys produces 18 diagnostics. +- **Split the Client test aggregate program (item 1):** Every sub-program must inject the 242 files carrying module augmentations to pass, and the visible location count stays at 33–49; splitting into 2, 4, or 8 groups leaves the Check sum nearly flat while user CPU rises by 9%, 30%, and 57%, lowering only wall, and the 4- and 8-group splits each produce 1–2 diagnostics. +- **Cache resolution results and make the discovery queue O(1) (Typert):** After items 2–4 only 28 surface walks remain, about 0.18 s, below noise. +- **Move Typert into a separate build step in artifact builds (Typert):** After item 6 the worker already overlaps bundling, leaving at most about 1 s. Type checks, which need no bundle, run a source-only generation step ([local gate speed-ups](2026-10-12-local-gate-speedups.md)). +- **Filter `transform` by code content (item 7):** rolldown interprets `^` and `\s` with Rust regex semantics, which differ from JavaScript on lone CR, U+2028, and BOM, so a decorated module could be missed. +- **Build a process-wide manifest index on `globalThis` (item 8):** The prototype saves about as much time as item 8, but it is process-global state without an owner, violating the shared-state ownership rule in the [package rules](../../../../packages/AGENTS.md). +- **Disable tsdown's gzip report (item 8):** `--no-report` lowers Client tsdown by 0.95 s, within the 1.56 s baseline spread. +- **Add rolldown filters to DSH `resolveId`/`load` hooks (item 8):** Lowers it by 1.16 s, within noise. +- **Memoize the input-isolation check per module id (item 8):** Lowers it by 0.93 s, within noise; on top of the manifest index it saves only another 0.18 s. + +## Consequences + +Client type checking spends substantially less CPU and wall time, and the Host and Client tsdown passes take substantially less wall time, without changing runtime resolution, published installation semantics, or any output byte. In the serial build segments (master → branch, one sample each), Host tsdown falls from 22.5 to 11.7 s, Client package compilation from 55.6 to 48.7 s, the Client aggregate check from 68.2 to 35.9 s, and Client tsdown from 13.9 to 10.5 s; the serial segments sum to 308.5 s on master and 254.9 s on the branch (see [the build split note](2026-10-11-build-artifacts-check-split.md)). Host tsdown lies on the critical path of both `build` and `build:artifacts`, Client tsdown on that of `build:artifacts`, and the Client aggregate check is the last step of the `build` critical path. + +Costs: every workspace package shares one React types version; Typert does not validate tsconfigs of packages it does not analyze, and `tsc -b` owns those errors; Host tsdown max RSS grows by about 0.6 GiB, and under heavy shared-host load the worker can become Host tsdown's critical path. + +Reevaluation conditions: remeasure item 1 when migrating to TypeScript 7, and reconsider per-package declarations if the location count no longer affects Check time. tsdown's own config loading still takes 1.8–2.3 s per Client build (one uncached module instance per config) and needs an upstream change. The first `buildStart` arrives about 4.2 s into the Host build; starting the worker at plugin construction with an explicit root would start Typert earlier. + +Verification: the Typert generator's `tsdown-plugin.spec.ts`, `tsdown-plugin-worker.spec.ts`, and `type-model.spec.ts` pin the behavior of items 2–7; the generator tests report 209 passed and 28 skipped, and `tsc -b tsconfig.host.json` exits 0. The repository coverage gate excludes `packages/typert/*/src/**`; under a scratch coverage config, `tsdown-plugin.ts` reaches 100% statements, branches, functions, and lines. Five negative controls (the old root rule, eager package configs, an expanded aggregate, no emission claim, a skipped worker termination) each fail the test that guards them; the real tsdown failure path exits 1 within 2.4 s and reports `TypertWorkerError`. Item 1: `verify-package-dependencies` exits 0 (74 packages), its spec passes 47/47, `verify-client-packages` exits 0, `tsc -b tsconfig.client.json` reports no diagnostics, and the Client aggregate Check takes 26.48 s. Item 8: all 72 focused specs pass. diff --git a/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.zh.md b/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.zh.md new file mode 100644 index 0000000000..7ccfe2d3c9 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.zh.md @@ -0,0 +1,136 @@ +# Agent Note: 不改变产物的构建提速 + +Status: implemented + +[English](2026-10-11-lossless-build-speedups.md) | 中文 + +## 问题 + +冷启动构建中有三处与产物内容无关的固定开销: + +- **Client 测试聚合程序的 JSX 签名。** `tsc -p tsconfig.client.json` 的 Check 阶段为 59.1 s,其中一半以上用于为每个导入 React 的 JSX 文件计算 `@types/react` 的 module specifier。TypeScript 的 `computeModuleSpecifiers` 遍历该声明文件的每个符号链接位置,并在每个位置扫描全部 491 条 tsconfig `paths`。pnpm 为每个自行声明 `@types/react` 的 workspace 包创建一个 `node_modules/@types/react` 链接;66 个 manifest 声明了它,Client 测试聚合程序因此看到 65 个位置。计数器测得 88 个 JSX 文件 × 2 个模块(`index.d.ts`、`jsx-runtime.d.ts`)× 65 个位置,共 11,457 次 `tryGetModuleNameFromPaths` 调用、5,623,782 次条目扫描,合计 32.6 s。按可见位置数 N 截断的剂量实验在五个截断级别(N 从 1 到 65,Check 从 26.92 s 到 58.40 s)上拟合出 Check ≈ 26.9 + 0.494·N s。 +- **Host tsdown 阶段中的 Typert。** Host tsdown 阶段约 21.6–22.6 s。Typert 在第一个 `writeBundle` 中同步发现并生成产物,CPU profile 显示它阻塞 tsdown 主线程约 12.4 s,期间所有包构建都在等待。发现阶段占 8.06 s:它解析两个 face 聚合配置所引用的 362 个包 tsconfig(约 3.8 s),每次解析 Host 聚合配置都展开 2,064 条字面 `include`(1.6 s,分析器从不读取这些文件名),并对 322 个注册项做公开导出表面遍历(2.7–3.2 s);最终只有 28 个声明 Typert 导出的包产生 Host 产物。 +- **Client tsdown 阶段的 manifest 查找。** Client tsdown 阶段约 11.7 s,主线程饱和(空闲仅 7.1%),其中 34.5%(3.95 s)在 `workspaceManifest`:每个包配置按包名 `globSync('packages/*/*/package.json')` 并逐个解析 manifest,直到名字匹配。模块级缓存无效,因为 tsdown 的 native 配置加载器通过 `import-without-cache` 为每个包配置创建新的模块实例;每次 glob 耗时 40–125 ms,且发生在 `tsdown:deps` 的 `neverBundle`/`alwaysBundle` 回调中,阻塞全部构建。 + +#5849 已合并 Host fixture 类型收窄与 Typert memoization;本 Note 的基线是其后的 master。 + +## 决策 + +以下八项提速不改变 `lib/`、`apps/web/dist` 的产物字节,也不改变仓库构建报告的类型诊断集合。唯一的诊断归属变化来自第 4 项:Typert 不校验它不分析的包 tsconfig,这些错误只由 `tsc -b` 报告。命令拆分与并发调度由[构建拆分 Note](2026-10-11-build-artifacts-check-split.zh.md)记录。 + +| # | 决策 | 受影响阶段 | 实测中位数 | 产物与诊断 | 有意的行为差异 | +|---|---|---|---|---|---| +| 1 | React 类型包只由根 manifest 声明 | Client 类型检查 | 测试聚合 Check 59.1 → 26.3 s | 程序文件数与诊断不变 | 包 manifest 不列出 React 类型包 | +| 2 | Typert 先按 manifest 选择包 | Host tsdown | 22.62 → 19.94 s | 逐字节一致 | 无 | +| 3 | Typert 不展开聚合配置的 `include` | Host tsdown | 19.94 → 16.99 s | 逐字节一致;注册清单一致 | 无 | +| 4 | Typert 惰性解析包 tsconfig | Host tsdown | 16.99 → 16.25 s(噪声内);Typert 发现 5.9–7.1 → 0.36–0.40 s | 逐字节一致;注册清单一致 | 未分析包的 tsconfig 错误只由 `tsc -b` 报告 | +| 5 | Typert 工作区根目录同时要求 `packages/` | Host tsdown | 噪声内 | 逐字节一致 | `package` 模式下双 face 包获得产物 | +| 6 | Typert 在 Worker Thread 中生成 | Host tsdown | 15.39 → 10.25 s | 逐字节一致;失败仍使 tsdown 失败 | Host tsdown 最大 RSS 约 +0.6 GiB | +| 7 | Typert `transform` 钩子按模块 id 过滤 | Host tsdown | 噪声内;钩子调用 1,566 → 195 | 逐字节一致 | 无 | +| 8 | Client tsdown 预设按包目录读取 manifest | Client tsdown | 12.78 → 8.73 s | 逐字节一致;external 判定一致 | 预设第一个参数是包目录 | + +第 5–7 项改变了发布的 `./tsdown` 导出 `typertPlugin()`(`transform` 为 `{ filter, handler }`、`writeBundle` 为异步、工作区根目录必须包含 `packages/`);rolldown 与 tsdown 的使用方接受两种钩子形式,分析器本来就要求 `/packages`,因此此前可用的外部工作区都不会失效。 + +### 测量条件 + +所有数字取自同一台共享 Linux 主机(256 vCPU、4 TB 内存,运行期间 load average 23–111),Node v24.18.0、TypeScript 6.0.3、tsdown 0.22.2(rolldown 1.1.1)。 + +- **Host tsdown:** `node node_modules/tsdown/dist/run.mjs --config-loader native --env.DSH_BUILD_FACE host`,每次运行前删除全部 `lib/typert.*`;各变体交替顺序运行,每组 3–4 个样本。第 2–4 项取自第一轮测量(起点为基线),第 5–7 项取自第二轮测量(起点为第 2–4 项合入后的代码)。产物比较覆盖 `packages/*/*/lib`、`apps/*/lib`、`vendor/*/lib` 顶层的 743 个文件(含 140 个 Typert 产物)的 SHA-256。相同代码的两组中位数相差 0–0.11 s,组内样本跨度最大 2.5 s。 +- **Client 测试聚合:** references 预先构建后运行 `tsc -p tsconfig.client.json --extendedDiagnostics`,使用全新的 tsBuildInfo 文件;相同代码 6 个样本的 Check 跨度为 3.8 s(约 6%)。 +- **Client tsdown:** 已构建的树上运行 `node node_modules/tsdown/dist/run.mjs --config-loader native --env.DSH_BUILD_FACE client`。第 8 项的原型 3 轮轮换顺序,基线跨度 1.56 s;最终实现与原实现交替运行,各 3 个样本。产物比较覆盖 `{packages,apps,vendor,native}/**/lib/**`(排除 `*.tsbuildinfo`)的全部文件。 + +### 1. React 类型包只由根 manifest 声明 + +- **目的:** 把 Client 测试聚合程序看到的 `@types/react` 位置数 N 从 65 降到 1,消除随 N 线性增长的 module specifier 计算。 +- **改动:** 根 `package.json` 的 `devDependencies` 声明 `@types/react` `~18.3.1` 与 `@types/react-dom` `~18.3.0`,沿用各包原先统一的版本范围;`apps/*`、`packages/*/*` 与 `vendor/*` 的 manifest 在任何依赖区段都不声明它们。TypeScript 从任一包向上查找时都解析到根 `node_modules/@types/react`。runtime `react` 与 `react-dom` 仍按 [Client 依赖声明规则](../../../../packages/client/AGENTS.md#dependency-declaration)由各包声明;只通过 `import type` 引用 React 的 `packages/client/ui-slots` 在 `devDependencies` 中声明 `react`。pnpm `dedupeDirectDeps` 保持关闭。lockfile 的变化集中在 importers 区段(另有一条 integrity 相同的 `papaparse` 条目重排)。 +- **防回退:** [`verify-package-dependencies`](../../../../scripts/verify-package-dependencies.ts) 在 `hygiene` 与 CI 中要求根 manifest 的 `devDependencies` 声明这两个包,并拒绝 `apps/*`、`packages/*/*`、`vendor/*` 中任一 manifest 在 `dependencies`、`devDependencies`、`optionalDependencies` 或 `peerDependencies` 中声明它们;诊断指明要删除的条目,并链接 Client 依赖声明规则第 8 条。规则只匹配这两个精确包名,其他 `@types/*` 包仍按 DefinitelyTyped 类型提供方处理。依赖区段推导不把这两个包视为 `react`/`react-dom` 的类型提供方:包缺少 `react` 声明时,验证器报告 `react` 缺失,`--fix` 拒绝修复并要求先声明版本范围;`--fix` 也不写回或删除这两个包。[`verify-package-dependencies.spec.ts`](../../../../scripts/verify-package-dependencies.spec.ts) 覆盖各依赖区段的拒绝、根 manifest 缺失声明、被接受的布局,以及类型提供方排除。 +- **性能:** + + | 测量项 | 各包自声明(N = 65) | 根 manifest 声明(N = 1) | + |---|---|---| + | Client 测试聚合 Check | 59.08 s(3 个样本的中位数) | 26.28 s(5 个样本的中位数),−56% | + | Client 测试聚合 wall | 68–71 s | 33.6–34.9 s | + | Client 测试聚合 user CPU | 79–83 s | 44.5–45.3 s | + | 76 个 client-only 包项目的 Check 总和 | 34.6 s(2 个样本的中位数) | 26.5 s(2 个样本的中位数),−23% | + | 76 个 client-only 包项目的 wall | 55.7 s(2 个样本的中位数) | 44.5 s(2 个样本的中位数) | + +- **无损依据:** 66 个包级链接与根链接指向同一个 realpath(`.pnpm/@types+react@18.3.31`),因此程序读取的声明内容相同;程序文件数保持 2,613,`tsc -b --force tsconfig.client.json` 以 0 退出且无诊断。`devDependencies` 不随已发布的包安装,[发布依赖面](2026-08-26-published-dependency-faces.zh.md)中独立 TypeScript 消费者自行安装所引用类型包的结论不变;runtime 解析不读取 `@types/*`。 +- **取舍:** 包 manifest 不列出自己的 React 类型依赖,所有 workspace 包共用同一个 React 类型版本;某个包需要不同版本时,需要新的 Agent Note 推翻本项。检查只覆盖 `apps/*`、`packages/*/*` 与 `vendor/*`;`website`、`benchmarks`、`native/system` 与 `python/sdk-runtime` 等其他 pnpm 成员不在范围内,目前它们都不声明 React 类型包。 + +### 2. Typert 先按 manifest 选择包 + +- **目的:** workspace 模式只为声明 Typert 导出的包生成产物,避免对其余候选包做表面遍历。 +- **改动:** `WorkspaceAnalyzer.discoverPackages(includeManifest?)` 与 `WorkspaceTypertGenerator.discover(faces?, includeManifest?)` 接受可选的 `package.json` 谓词,在表面遍历之前应用;被拒绝的包既不读取源码,也不解析项目配置。`WorkspaceTypertGenerator.generateContributors(faces?)` 以 `hasTypertExport`(`exports` 含 `./typert`、`./client/typert` 或 `./remote`)为谓词。不传谓词的调用方(Cordis 目录、不指定包的 `generate()`)行为不变。 +- **性能:** Host tsdown 22.62 s → 19.94 s(各 3 个样本的中位数)。 +- **无损依据:** 谓词就是原先在发现之后应用的同一过滤条件,被它拒绝的包本来就不产生产物;743 个产物文件逐字节一致(Typert generator 自身的 `lib/index.js` 除外,其源码即本项改动)。 + +### 3. Typert 不展开聚合配置的 `include` + +- **目的:** 分析器只读取聚合配置的编译选项与 project references,展开 `include` 只为填充从不使用的 `fileNames`。 +- **改动:** `WorkspaceCaches.aggregate(path)` 返回并缓存 `AggregateConfig { path, options, projectReferences }`。解析自身声明 `references` 的聚合配置时,使用 `readDirectory` 返回空列表的 `ParseConfigHost`;不声明 `references` 的聚合配置照常展开。 +- **性能:** Host tsdown 19.94 s → 16.99 s(各 3 个样本的中位数)。 +- **无损依据:** TypeScript 只对既无 `files` 也无 `references` 的配置报告 TS18003(无输入),因此声明 `references` 的聚合配置在不展开时得到相同的诊断、选项与 references。强制读取每个惰性配置后导出的注册清单(408 个注册项,含 `fileNames` 与选项,以及聚合配置的选项和 references)与基线逐字节一致;产物逐字节一致。测试 `reads aggregate options and references without expanding include patterns` 与 `reports an aggregate without references or inputs` 固定这两种配置的行为。 + +### 4. Typert 惰性解析包 tsconfig + +- **目的:** 只解析被选中分析的包的 tsconfig,而不是聚合配置引用的全部包。 +- **改动:** `PackageRegistration.config` 是 `caches.config(configPath)` 的 getter,首次读取时解析。注册清单的顺序、face、包名、根目录与导出子路径不变。 +- **性能:** Host tsdown 16.99 s → 16.25 s(各 3 个样本的中位数),在 2.5 s 的组内跨度以内。第 2–4 项合计在隔离基准中把 Typert 发现从 5.9–7.1 s 降到 0.36–0.40 s,tsconfig 解析从 362 次降到 28 次,表面遍历从 322 次降到 28 次,Typert 总耗时从 9.7–11.8 s 降到 4.4–4.5 s。 +- **无损依据:** 注册清单比较与第 3 项相同(逐字节一致),产物逐字节一致。测试 `reads only the project configs of manifests selected for discovery` 固定只解析所选包的配置。 +- **取舍(非无损):** Typert 不解析它不分析的包的 tsconfig,因此这类 tsconfig 的语法或配置错误不会使 Typert 失败。同一构建中,先于 Host bundle 运行的 Host 包编译 `tsc -b` 与 Client 包编译 `tsc -b` 解析每个被引用的 tsconfig,并拒绝其中的错误;`PackageRegistration.config` 的 JSDoc 与 [Typert generator README](../../../../packages/typert/generator/README.zh.md) 写明这一归属。单独调用 Typert 而不运行 `tsc -b` 的使用方不会得到这些诊断。 + +### 5. Typert 工作区根目录同时要求 `packages/` + +- **目的:** 修正工作区根目录的判定。24 个双 face 包带有自己的 `tsconfig.host.json` 叶子配置;只按 `tsconfig.host.json` 向上查找时,每个这样的包都被当作根目录,workspace 模式每次构建为它们各做一次空发现,`package` 模式下双 face 包得不到产物且没有报错。 +- **改动:** 工作区根目录是打包输出最近的、同时包含 `tsconfig.host.json` 与 `packages/` 的祖先目录。 +- **性能:** Host tsdown 14.82 s → 15.39 s(各 3 个样本的中位数),在噪声内。 +- **无损依据:** 仓库根 [`tsdown.config.ts`](../../../../tsdown.config.ts) 只使用 workspace 模式,743 个产物文件逐字节一致。测试 `resolves the workspace root above a dual-face package leaf` 固定该判定。 +- **行为差异:** `package` 模式的使用方构建双 face 包时得到该包的 Typert 产物;仓库构建不使用 `package` 模式。 + +### 6. Typert 在 Worker Thread 中生成 + +- **目的:** 让 Typert 分析与 tsdown 主线程上的打包重叠,而不是在第一个 `writeBundle` 中阻塞全部包构建。 +- **改动:** [`src/worker.ts`](../../../../packages/typert/generator/src/worker.ts) 是 Worker Thread 入口,运行 `generateContributors(faces)` 并回传一条 `artifacts` 或 `failure` 消息。workspace 模式下,本次构建的第一个 `buildStart` 以 `options.cwd` 定位工作区根目录并启动生成;`writeBundle` 是异步的,第一个完成的打包认领写入并等待结果,之后的打包立即返回。分析错误、worker 崩溃或提前退出、格式错误或无法反序列化的响应、worker 无法终止,都以指明工作区与原因的 `TypertWorkerError` 使认领写入的打包失败,从而使整个 tsdown 阶段失败;结果敲定前 worker 已终止,未被认领的结果不会成为未处理的 rejection。构建产物从 `./worker.js` 启动 worker;源码运行(测试)通过 `tsx/esm/api` 加载 `worker.ts`。`package` 模式仍在主线程中生成。 +- **性能:** Host tsdown 15.39 s → 10.25 s(各 3 个样本的中位数)。最终配置(第 2–7 项)的 profile:主线程 10.1 s,第一个 `buildStart` 出现在 4.18 s(tsdown 配置解析),主线程上的 `writeBundle` 只占 0.37 s;worker 5.0 s(模块加载约 0.4 s、发现 0.28 s、生成 3.88 s,其中 `createProgram` 2.21 s),约在 9.3 s 结束。Host tsdown 的 wall 约为 max(打包, 4.2 s + Typert)。 +- **无损依据:** 第二轮的 54 次运行全部以 0 退出,每次的 743 个产物文件均与基线一致(generator 自身的 `lib/index.js` 除外)。测试 `writes the artifacts in-process generation produces` 比较 worker 与进程内生成的产物;在临时工作区中把一个包的 `files` 改坏后,tsdown 在 2.4 s 内以 1 退出,报告 `TypertWorkerError` 及 worker 内的 `TypertAnalysisError`,不写入任何产物。各失败路径由 `typertPlugin workspace mode` 测试组覆盖。 +- **取舍:** worker 堆约 300–420 MiB;最终配置的 Host tsdown 最大 RSS 中位数为 6,296–6,408 MiB,基线为 5,676 MiB。共享主机高负载时 worker 可能落在关键路径上:一次样本为 21.91 s,拥有产物的包构建等待 worker 约 14 s,其后 10 个样本未复现;load average 约 100 时两次运行为 17.86 s 与 14.3 s。worker 在 1,024 MiB 堆上限下也能完成,因此不是 GC 压力;归因于主机争用尚未证实。 + +### 7. Typert `transform` 钩子按模块 id 过滤 + +- **目的:** 避免每个模块都从 rolldown 进入 JavaScript `transform` 钩子,只为被扩展名检查拒绝。 +- **改动:** `transform` 声明 `filter: { id: /^[^?]*\.[cm]?tsx?(?:\?|$)/ }`,处理函数仍以同一正则检查 id。 +- **性能:** 每次 Host 构建的钩子调用从 1,566 次降到 195 次(195 个 TypeScript 模块,其中 4 个含装饰器)。wall 中位数为 11.07 s(3 个样本)与 9.98 s(4 个样本),第 6 项为 10.25 s,相同代码的对照组为 11.07 s 与 9.87 s,差异在噪声内。 +- **无损依据:** 该正则只含 ASCII 构造,在 rolldown 的 Rust 正则与 JavaScript 中匹配相同的 id 集合;处理函数应用同一检查,因此不读取过滤器的宿主行为相同。产物逐字节一致;测试 `filters transform calls to TypeScript module ids` 固定过滤器。 + +### 8. Client tsdown 预设按包目录读取 manifest + +- **目的:** 每个包配置只读取自己的 `package.json`,消除按包名遍历全部 manifest 的 glob。 +- **改动:** [`packages/client/tsdown.client.ts`](../../../../packages/client/tsdown.client.ts) 的 `clientBundle`、`staticLinked` 与 `clientLibrary` 的第一个参数是包目录(通常为配置文件的 `import.meta.dirname`),预设读取一次 `/package.json`,以其中的 `name` 作为插件 id 与诊断名称;该 manifest 缺失、不可读或缺少 `name` 时,配置加载以指明路径与原因的错误失败。82 个包配置调用这些预设。预设不保留模块级 manifest 缓存;Node 半边的生产依赖 external 列表在首次 resolve 时由该 manifest 计算,并缓存在该配置的闭包中。 +- **性能:** Client tsdown 从 12.78 s 降到 8.73 s(各 3 个样本的中位数),−4.05 s(−31.7%),两组样本区间不重叠;user CPU 从 26.1 s 降到 25.2 s,sys 从 5.9 s 降到 4.9 s,因此收益主要来自解除主线程阻塞,而不是减少 CPU 总量。原型(一次 glob 建立按包名索引)为 11.72 s → 7.46 s(−36%)。Host tsdown 中只有 5 个 `hostPhase` 包经过该查找,一对样本为 11.92 s → 10.71 s,置信度低。 +- **无损依据:** 11 次运行的 11,566 个 lib 文件逐字节一致。82 个调用处改为传入包目录后,没有一个解析出的包名与原先手写的包名不同。进程内比较 82 个配置 × 3 个 face × 1,600 个 specifier 的 external 判定,结果与原实现完全一致;负对照(多加一个 external)使 75 个判定不同。`client-bundle-purity.spec.ts` 覆盖这些 manifest 错误。 +- **行为差异:** 预设的调用约定从包名改为包目录。 + +## 考虑过的替代方案 + +- **开启 pnpm `dedupeDirectDeps`(第 1 项):** 作用于所有直接依赖,改变每个 workspace 包的链接布局,副作用是全局的。 +- **给 TypeScript 打补丁(第 1 项):** 上游式补丁(预先计算候选扩展名并缓存规范化的 `paths` 模式)使 Check 降低 31.9 s,与提升相当;在已提升的树上不再带来收益(refs Check 25.76 s 对 26.47 s),且需随每次 TypeScript 升级维护。 +- **在 tsconfig `paths` 中为 `react` 加别名(第 1 项):** tsx、vitest 与 vite 也读取 `paths`,别名会改变它们对 runtime `react` 的解析。 +- **把 `paths` 收窄为各 face 的 reference closure(第 1 项):** 保留通配键的 328 条版本 Check 为 55.73 s 对 59.08 s(1 个样本),在噪声内;去掉通配键的版本产生 18 个诊断。 +- **拆分 Client 测试聚合程序(第 1 项):** 每个子程序都必须注入 242 个含模块增强的文件才能通过检查,可见位置数仍为 33–49;拆成 2、4、8 组时 Check 总和基本不变,user CPU 分别增加 9%、30%、57%,只降低 wall,且 4 组与 8 组各出现 1–2 个诊断。 +- **缓存解析结果并把发现队列改为 O(1)(Typert):** 第 2–4 项之后只剩 28 次表面遍历,约 0.18 s,低于噪声。 +- **在产物构建中把 Typert 移到独立构建步骤(Typert):** 第 6 项之后 worker 已与打包重叠,剩余收益不超过约 1 s。不需要 bundle 的类型检查运行只读源码的生成步骤([本地门禁提速](2026-10-12-local-gate-speedups.zh.md))。 +- **按代码内容过滤 `transform`(第 7 项):** rolldown 以 Rust 正则语义解释 `^` 与 `\s`,在孤立 CR、U+2028 与 BOM 上与 JavaScript 不同,可能漏掉含装饰器的模块。 +- **在 `globalThis` 上建立进程级 manifest 索引(第 8 项):** 原型收益与第 8 项相当,但它是没有 owner 的进程全局状态,违反[包规则](../../../../packages/AGENTS.md)中的共享状态归属要求。 +- **关闭 tsdown 的 gzip 报告(第 8 项):** `--no-report` 使 Client tsdown 降低 0.95 s,在 1.56 s 的基线跨度内。 +- **为 DSH 的 `resolveId`/`load` 钩子加 rolldown 过滤器(第 8 项):** 降低 1.16 s,在噪声内。 +- **按模块 id 缓存输入隔离检查(第 8 项):** 降低 0.93 s,在噪声内;叠加在 manifest 索引之上只再降低 0.18 s。 + +## 后果 + +Client 类型检查的 CPU 与 wall 时间、Host tsdown 与 Client tsdown 的 wall 时间都明显下降,且不改变 runtime 解析、发布安装语义或任何产物字节。串行构建的各段中(master → 本分支,各一个样本),Host tsdown 从 22.5 s 降到 11.7 s,Client 包编译从 55.6 s 降到 48.7 s,Client 聚合检查从 68.2 s 降到 35.9 s,Client tsdown 从 13.9 s 降到 10.5 s;串行各段合计在 master 上为 308.5 s,在本分支上为 254.9 s(见[构建拆分 Note](2026-10-11-build-artifacts-check-split.zh.md))。Host tsdown 位于 `build` 与 `build:artifacts` 的关键路径上,Client tsdown 位于 `build:artifacts` 的关键路径上,Client 聚合检查是 `build` 关键路径的最后一步。 + +代价:所有 workspace 包共用一个 React 类型版本;Typert 不校验它不分析的包 tsconfig,这些错误由 `tsc -b` 负责;Host tsdown 的最大 RSS 约增加 0.6 GiB,共享主机高负载时 worker 可能成为 Host tsdown 的关键路径。 + +重新评估条件:迁移到 TypeScript 7 时重新测量第 1 项,若位置数不再影响 Check 时间,可以重新评估包级声明。tsdown 的配置加载本身每次 Client 构建仍占 1.8–2.3 s(每个配置一个无缓存的模块实例),需要上游改动。第一个 `buildStart` 在 Host 构建开始约 4.2 s 后才出现;在插件构造时以显式根目录启动 worker 可以进一步提前 Typert。 + +验证:Typert generator 的 `tsdown-plugin.spec.ts`、`tsdown-plugin-worker.spec.ts` 与 `type-model.spec.ts` 固定第 2–7 项的行为;generator 测试 209 个通过、28 个跳过,`tsc -b tsconfig.host.json` 以 0 退出。仓库覆盖率 gate 不包含 `packages/typert/*/src/**`,在临时覆盖率配置下 `tsdown-plugin.ts` 的 statements、branches、functions 与 lines 均为 100%。五个负对照(旧根目录规则、立即解析包配置、展开聚合配置、不认领写入、跳过 worker 终止)各自使守护它的测试失败;真实 tsdown 失败路径在 2.4 s 内以 1 退出并报告 `TypertWorkerError`。第 1 项:`verify-package-dependencies` 以 0 退出(74 个包),其 spec 47/47 通过,`verify-client-packages` 以 0 退出,`tsc -b tsconfig.client.json` 无诊断,Client 聚合 Check 为 26.48 s。第 8 项:72 个相关 spec 全部通过。 diff --git a/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.i18n.yaml b/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.i18n.yaml new file mode 100644 index 0000000000..80284ccdd5 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.i18n.yaml @@ -0,0 +1,49 @@ +# Bilingual-pair consistency record for 2026-10-12-local-gate-speedups.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-10-12-local-gate-speedups.md +/agent-note-local-gate-hook-and-test-speed-ups: + en: d8edb2c26730e9af + zh: fb69bf2e7b602d4c +/agent-note-local-gate-hook-and-test-speed-ups/problem: + en: 1e2163ec378c44ff + zh: d93cb5970896fccb +/agent-note-local-gate-hook-and-test-speed-ups/decision: + en: 9984b4ad646bfaf2 + zh: 753287ae67e29605 +/agent-note-local-gate-hook-and-test-speed-ups/decision/measurement-conditions: + en: 7430353afba96352 + zh: 6d2a09619a67ecba +/agent-note-local-gate-hook-and-test-speed-ups/decision/1-type-checks-generate-typert-declarations-without-bundling: + en: 4dc48e24a3323b7d + zh: 7c88325160a41d12 +/agent-note-local-gate-hook-and-test-speed-ups/decision/2-the-pre-commit-hook-does-not-regenerate-third-party-notices: + en: e2e344f184621172 + zh: 97d8785aaf9105bf +/agent-note-local-gate-hook-and-test-speed-ups/decision/3-local-default-worker-budget: + en: e9649c40d67e26e0 + zh: c99f22a41c4fc4af +/agent-note-local-gate-hook-and-test-speed-ups/decision/4-repository-reference-candidates-resolve-against-one-object-listing: + en: 2c945250337c88cf + zh: d4bfa34cc858782b +/agent-note-local-gate-hook-and-test-speed-ups/decision/5-documentation-gates-parse-each-document-once: + en: c22d38399a2bb87f + zh: 9ae97e5a6e3fbf48 +/agent-note-local-gate-hook-and-test-speed-ups/decision/6-repository-file-walks-list-each-directory-once: + en: 2f0d35b0a688c938 + zh: 7184fd260c066a01 +/agent-note-local-gate-hook-and-test-speed-ups/decision/7-cli-help-reads-run-concurrently-doc-graph-probes-are-memoized: + en: 965503ba8a31c039 + zh: fe02a394a677d018 +/agent-note-local-gate-hook-and-test-speed-ups/decision/8-type-model-spec-ts-runs-against-an-in-memory-workspace: + en: d519ec362903aa2f + zh: f49ee6547cb954f6 +/agent-note-local-gate-hook-and-test-speed-ups/decision/repository-wide-comparison: + en: 7c9388dc859e0f93 + zh: 5df1fc58eb7a46e8 +/agent-note-local-gate-hook-and-test-speed-ups/alternatives-considered: + en: 763d94734b8967cf + zh: abe980d486e1d7da +/agent-note-local-gate-hook-and-test-speed-ups/consequences: + en: ca00b04567d09408 + zh: 97011043c60f4bc9 diff --git a/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.md b/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.md new file mode 100644 index 0000000000..22144834ef --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.md @@ -0,0 +1,158 @@ +# Agent Note: Local gate, hook, and test speed-ups + +Status: implemented + +English | [中文](2026-10-12-local-gate-speedups.zh.md) + +## Problem + +On the baseline, master at the merge of #6013, local runs of the Git hooks, `pnpm run test`, `test:docs`, and `doc-sync` spend most of their wall time on work that their results do not depend on: + +- **Typert declarations from the bundler.** `typecheck`, the command the pre-push hook runs, executes `build:lib:host` (Host `tsc -b tsconfig.host.json`, the Host tsdown pass, and the Desktop bundle) before `tsc -b tsconfig.client.json`. The prerequisite of `lint`, `lint:fix`, `doc-typecheck`, and the CI `typert-contracts` gate runs Host package compilation and then the Host tsdown pass (`compile-referenced-projects.ts host-libraries`). Type checks read only package declarations and Typert declarations, yet `typecheck` with nothing to recheck takes 34.1/35.0 s and the prerequisite takes 52.2/29.6 s. +- **Third-party notices on every commit.** The pre-commit hook regenerates `THIRD_PARTY_NOTICES.md` whenever a staged file is a generator input. To find browser-side third-party imports, the generator test-bundles 75 Client packages and runs one Vite build, so every package source file is an input; on a commit that stages one file under a package `src/` subdirectory, the hooks take 16.5/17.8 s, of which the notices job takes 12.4/13.4 s. +- **Host CPUs as the local worker count.** `os.availableParallelism()` reports the host's CPUs (256 on the measurement host) rather than the container's CPU quota (64). With that default, `pnpm run test` starts 255 Vitest forks, peaks at 55.3 GiB RSS, and fails 12 additional files (14 timeouts) intermittently, while `doc-sync`, `test:docs`, `hygiene`, and `check:all` run at most 4 gates concurrently. +- **One Git prefix lookup per candidate.** `verify-repository-references` resolves each of about 26,000 abbreviated hexadecimal candidates with a Git prefix lookup through `git cat-file --batch-check`; the lookups take 135.7 s of the gate's 166.8 s. +- **Repeated Markdown parsing.** markdown links parses each anchor target twice more and probes target existence without a cache; translation pairing globs four times and parses each document again after link normalization; the package README model-experience and limitations checks each parse every README three times; type equivalence parses all 1,835 documents; Session format references parses each pair four times. +- **Repeated directory reads.** `uniqueRepoFiles`, the walker behind markdown wrap, doc refs, and package paths, reads each directory once per pattern and `**` level and resolves every matched file with `realpath`. +- **Serial help launches and repeated compiler probes.** `gen-cli-help` launches its 12 top-level source-mode `dsh … --help` processes one after another, each waiting mostly on profile boot I/O (49.9/53.9 s); `gen-doc-graphs` builds several compiler hosts and programs that repeat the same `ts.sys` file-system probes (48.7/44.7 s). +- **A test file bound by file-system probes.** Each of the 61 cases of the Typert generator's `type-model.spec.ts` copies its fixture to disk and runs a full analysis whose four TypeScript programs each load the DOM library, `@types/node`, and zod v4, about 22,000 stat calls per analysis. The file takes 316.3/329.1 s and is the long tail of `pnpm run test`. + +## Decision + +The eight decisions below shorten those runs. Each item states the evidence that its outputs and diagnostics stay the same, or the intended difference it accepts. + +| # | Decision | Affected commands | Measured wall | Outputs and diagnostics | Intended behavior difference | +|---|---|---|---|---|---| +| 1 | Type checks generate Typert declarations without bundling | `typecheck`, `lint`, `lint:fix`, `doc-typecheck`, CI `typert-contracts` | `typecheck` 34.1/35.0 → 21.9/20.0 s; prerequisite 52.2/29.6 → 12.5/11.3 s | 140 Typert files byte-identical; the same programs are checked | No runnable bundle and no client build record | +| 2 | The pre-commit hook does not regenerate third-party notices | `pre-commit` | 16.5/17.8 → 4.3/4.5 s | Freshness asserted in the test lane | Stale notices fail in the test lane, not at commit | +| 3 | Local default worker budget | run-gates aggregates, `build`, `typecheck`, `pnpm run test`, Oxlint, publint | `test` at 255 workers: 243.7 s, 55.3 GiB; `test:docs` 74.7 → 50.9 s | Same checks | Local defaults ignore CPUs above 12 or 48 | +| 4 | Repository-reference candidates resolve against one object listing | `verify-repository-references` | 166.8 → 15.7 s | 0 classification differences over 27,050 candidates | None | +| 5 | Documentation gates parse each document once | markdown links, translation pairing, README model experience and limitations, type equivalence, Session format references | markdown links 53.4/51.6 → 25.9/25.1 s; type equivalence 23.0/22.5 → 6.0/5.5 s | Byte-identical gate output | None | +| 6 | Repository file walks list each directory once | markdown wrap, doc refs, package paths | doc refs 8.8/7.0 → 3.2/3.4 s | Identical file lists | doc refs does not read nested `lib` directories | +| 7 | CLI help reads run concurrently; doc-graph probes are memoized | `verify-cli-help`, `verify-doc-graphs` | 49.9/53.9 → 6.9/7.2 s; 48.7/44.7 → 32.7/34.2 s | Byte-identical pages | CLI help uses about 3.6 GB at peak | +| 8 | `type-model.spec.ts` runs against an in-memory workspace | `pnpm run test` | 316.3/329.1 → 14.65/15.04 s | Same 61 cases and assertions; one snapshot line differs | Stubs replace zod, `@types/node`, and the DOM library outside the Emitter case | + +### Measurement conditions + +All numbers are wall times from one shared Linux container with a 64-CPU quota on a host that reports 256 CPUs, at a one-minute load average of 20–150, so samples carry noise. The working tree lives on a network filesystem, where each file-system probe costs more than on a local disk. `a/b` lists two samples, and `x → y` compares the baseline with this implementation. + +### 1. Type checks generate Typert declarations without bundling + +- **Purpose:** Give `typecheck` and the prerequisite of `lint`, `lint:fix`, `doc-typecheck`, and the CI `typert-contracts` gate the declarations they read, package declarations from `tsc` and Typert declarations, without the Host tsdown pass or the Desktop bundle. +- **Change:** `typecheck` is `tsx scripts/build.ts --scope typecheck`, which runs the steps below through the run-gates scheduler ([`scripts/build.ts`](../../../../scripts/build.ts)). The scope builds no native addon, tsdown bundle, Desktop bundle, or Web output, writes no client build record, and leaves runnable `lib/` output as the last `build:artifacts` left it; run `build:artifacts` before launching or testing built output. The prerequisite of `lint`, `lint:fix`, `doc-typecheck`, and `typert-contracts` is `compile-referenced-projects.ts host-contracts`, which runs host-src beside host-typert ([`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts)). `build`, `build:artifacts`, benchmark builds, and the PR rehearsal in `release-vendor.yml` run Typert inside the Host tsdown pass. + +| Step | Command | `needs` | +|---|---|---| +| host-src | `node --max-old-space-size=4096 -b ` | — | +| host-typert | `node --import tsx/esm scripts/generate-typert.ts` | — | +| client-src | ` -b ` | host-src, host-typert | +| host-check | `node --max-old-space-size=4096 -b tsconfig.host.json` | host-src | +| client-check | ` -b tsconfig.client.json` | client-src | + +- **Shared generation:** [`scripts/generate-typert.ts`](../../../../scripts/generate-typert.ts) calls `WorkspaceTypertGenerator.generateContributors()` for `WORKSPACE_TYPERT_FACES` ([`scripts/typert-faces.ts`](../../../../scripts/typert-faces.ts)), the faces the Host tsdown plugin also generates, and writes the result with `writeWorkspaceArtifacts()` from [`artifact-files.ts`](../../../../packages/typert/generator/src/artifact-files.ts), the writer the plugin uses. Like the plugin, it skips TypeScript diagnostics, which Host package compilation reports; a Typert analysis error fails host-typert as it fails the Host bundle in `build`. host-typert runs under Node with tsx's ESM hook rather than through `pnpm exec`, whose startup would lengthen the path to Client compilation. +- **Aggregate checks in build mode:** host-check and client-check start after their own face's package compilation, so build mode finds every reference up to date, checks only the aggregate root program, and skips a root program whose tsbuildinfo is current. +- **Source-only analysis:** host-typert can run beside host-src because its Host program reads no workspace build output. `tsconfig.base.json` maps `@deepseek-ai/dsh-client-file-upload/types` to source; without that alias the specifier resolves through package `exports` to `lib/types/types.d.ts`. With it, the Host program loads 1,289 files, none of them under a workspace package's `lib/`. `generate-typert.ts` enables `rejectBuildOutputs`: [`build-output-guard.ts`](../../../../packages/typert/generator/src/build-output-guard.ts) fails analysis with a `TypertAnalysisError` when a face program loads a file from a workspace package's `lib/` directory, or cannot resolve an import of a workspace package, as on a tree whose packages are not yet compiled, naming each such import specifier and the `paths` entry that maps it to source. Either way a missing alias fails generation whether or not host-src has run. The tsdown plugin leaves the option off because in `build` Typert always runs after Host package compilation. The [Typert generator README](../../../../packages/typert/generator/README.md) documents the writers and the option. +- **Why it is lossless:** No workspace tsconfig sets `allowJs`, every `exports` `types` condition points into `lib/types/` or at `lib/typert.*`, and every tsdown config sets `dts: false`, so no type check reads tsdown output. The 140 Typert files (28 packages × 5 outputs) are byte-identical across the baseline tsdown pass, the current tsdown pass, `generate-typert.ts` after every Typert output is deleted, and `generate-typert.ts` with all 344 `lib/types` directories hidden; with one Remote method temporarily added to `packages/goal/goal`, the tsdown pass and `generate-typert.ts` also write identical files. `typecheck` checks every package project of both faces and both aggregate root programs, the programs that `build` checks. +- **Performance:** `typecheck` with nothing to recheck takes 34.1/35.0 → 21.9/20.0 s. When both aggregate root programs must be rechecked, it takes 83.5 → 76.0/72.1 s, and its critical path is the Host aggregate check at about 66–70 s. The prerequisite of `lint` and `doc-typecheck` takes 52.2/29.6 → 12.5/11.3 s. +- **Trade-off:** `typecheck`, `lint`, `lint:fix`, `doc-typecheck`, and `typert-contracts` write Typert declarations but no bundle, so runnable `lib/` JavaScript can lag behind those declarations until the next `build:artifacts`. +- **Relation to the build:** [The lossless build speed-ups note](2026-10-11-lossless-build-speedups.md) rejects moving Typert out of the Host tsdown pass for builds, where its Worker Thread already overlaps bundling and a separate step saves at most about 1 s. Type-check commands run no bundler, so generating without one removes the whole Host tsdown pass and the Desktop bundle from their critical path. [The build split note](2026-10-11-build-artifacts-check-split.md) lists every caller and its command. +- **Known gap:** Incremental `tsc -b` does not record `lib/typert.remote-client.d.ts`, which Client sources reach through package `exports`, as an input of the consuming project; when a Remote signature changes and no Client source does, an incremental check does not recheck the consumers. The gap is independent of which pass writes the declarations; Issue #6022 tracks it. + +### 2. The pre-commit hook does not regenerate third-party notices + +- **Change:** The `pre-commit` hook in [`lefthook.yml`](../../../../lefthook.yml) has no third-party notices job. [`gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) asserts the committed bytes of `THIRD_PARTY_NOTICES.md` in the test lane, including the required `node 24 / coverage` lane, and names `pnpm run gen-third-party-notices` when they are stale. [The generated third-party notices note](2026-07-30-generated-third-party-notices.md) owns this freshness decision. +- **Performance:** A commit that stages one file under a package `src/` subdirectory spends 4.3/4.5 s in the hooks instead of 16.5/17.8 s, of which the notices job took 12.4/13.4 s. +- **Trade-off:** A commit that leaves the notices stale fails in the test lane after push rather than being corrected at commit time. + +### 3. Local default worker budget + +- **Purpose:** Size default parallelism for a shared workstation or container, where Node reports host CPUs rather than the CPU quota. +- **Change:** [`scripts/parallelism.ts`](../../../../scripts/parallelism.ts) owns the default. With `CI=true` it is the CPU count Node reports. Otherwise it is capped at 12 (`LOCAL_PARALLELISM_CAP`) for the run-gates scheduler, `build`, `typecheck`, Oxlint, and publint, and at 48 (`LOCAL_TEST_PARALLELISM_CAP`) for Vitest forks and the local coverage budget. `doc-sync`, `test:docs`, `hygiene`, and `check:all`, whose gates each build a full `ts.Program`, run at most 8 gates concurrently, in CI as well. Explicit `DSH_GATE_CONCURRENCY`, `DSH_OXLINT_THREADS`, `DSH_COVERAGE_MAX_WORKERS`, and Vitest `--maxWorkers` take precedence; in CI, Vitest and Oxlint keep their own defaults unless the run-gates CI environment sets these variables. The [development guide](../../../../docs/development.md) states the defaults for contributors. + +`pnpm run test` at four fork counts, with the disk-backed `type-model.spec.ts` that item 8 replaces, which sets the wall of the 32-worker run: + +| Vitest workers | Wall | Peak RSS | Additional intermittent failures | Every file except the slowest finished at | +|---|---|---|---|---| +| 255 (the reported CPU count) | 243.7 s | 55.3 GiB | 12 files, 14 timeouts | about 135–170 s | +| 32 | 310.4 s | 15.7 GiB | 4 files, 4 timeouts | 193 s | +| 24 | 337.2 s | 13.2 GiB | 5 files, 5 timeouts | 233 s | +| 12 | 410.5 s | 8.4 GiB | 2 files, 3 timeouts | 406 s | + +- **Oxlint:** Oxlint's own default is 64 threads, read from the cgroup quota; at 12 threads its wall stays about 87–90 s with about 15% less CPU, and at 8 threads it takes about 4 s longer. +- **Documentation aggregates:** `test:docs` takes 50.9 s at 8 concurrent gates against 74.7 s at 4. `doc-sync`, measured without item 4, takes 341.8, 295.0, and 253.2 s at 4, 8, and 12 concurrent gates, with peak RSS of 10.0, 13.5, and 16.3 GiB. +- **Trade-off:** A machine whose CPU quota exceeds the caps gets no more default parallelism than 12 or 48 and needs the override variables; a container whose quota is below a cap still oversubscribes, because Node reports host CPUs. At 8 concurrent gates `doc-sync` peaks at 13.5 GiB RSS against 10.0 GiB at 4; 12 concurrent gates finish 41.8 s sooner at 16.3 GiB. The CI documentation workflow also runs `doc-sync` at 8 concurrent gates. + +### 4. Repository-reference candidates resolve against one object listing + +- **Change:** [`verify-repository-references.ts`](../../../../scripts/verify-repository-references.ts) lists every object name once with `git cat-file --batch-all-objects --batch-check=%(objectname)`, about 1.2 million objects in 0.6 s, sorts the list, and binary-searches each lowercase candidate prefix in memory; one `--batch-check=%(objectname) %(objecttype)` call then reads the types of the matched objects. A candidate is a commit reference only when its prefix matches exactly one available object and that object is a commit, the rule Git's own prefix lookup applies; the listing covers unreachable and alternate objects, as Git's lookup does. +- **Performance:** 166.8 → 15.7 s. +- **Why it is lossless:** Git's per-candidate prefix lookup and the in-memory search classify all 27,050 real and synthetic candidates identically, including ambiguous prefixes, blob and tree prefixes, and random strings. +- **Trade-off:** The listing is about 49 MiB of Git output for 1.2 million objects, read under a 1 GiB output limit. + +### 5. Documentation gates parse each document once + +- **Change:** Each gate below parses a Markdown document once and passes the tree to every consumer in that run. + +| Gate | Single-parse mechanism | Wall | +|---|---|---| +| markdown links ([`verify-md-links.ts`](../../../../scripts/verify-md-links.ts)) | One per-run cache parses each file once for its destinations and anchors and probes each resolved target once | 53.4/51.6 → 25.9/25.1 s | +| translation pairing ([`verify-translation-pairing.ts`](../../../../scripts/verify-translation-pairing.ts)) | One glob covers every scope pattern; the record reuses the authored tree under the guard below | 51.0/47.1 → 30.3/29.3 s | +| package README model experience, package README limitations | Each check parses a README once and passes the tree to `markdownProseLines()` and `markdownHeadingLines()` | about 12 → 5.9 s each | +| type equivalence ([`verify-type-equiv.ts`](../../../../scripts/verify-type-equiv.ts)) | A text prefilter skips documents that cannot hold a source-equivalence fence; each manifest TypeScript source is parsed once | 23.0/22.5 → 6.0/5.5 s | +| Session format references | The persistence renderer passes the trees it parses to the pairing record | 10.2 → 5.3 s | + +- **Pairing reuse guard:** `normalizedTopLevelBlocks()` in [`translation-pairing-record.ts`](../../../../scripts/translation-pairing-record.ts) reuses the authored tree for normalized text only when every link-normalization edit replaces a complete, title-free destination that does not start a line, the authored text equals the node's `url`, and both the authored and the replacement text contain only `[A-Za-z0-9._/:#%-]`. Those characters cannot end a destination or start or end another construct, so the normalized text parses to the same nodes with shifted offsets. Any other edit falls back to a full parse of the normalized text. +- **Type-equivalence prefilter:** [`type-equiv-prefilter.ts`](../../../../scripts/type-equiv-prefilter.ts) keeps a document for parsing when it contains `type-equiv` or `public-api`, or when a line containing `` ``` `` or `~~~` also contains `&` or `\`. Parsing changes an info string only by decoding character references and backslash escapes, so `ts type-equiv` and `ts type\-equiv` keep their documents; [`type-equiv-prefilter.spec.ts`](../../../../scripts/type-equiv-prefilter.spec.ts) covers both forms. +- **Why it is lossless:** Every gate's output on the repository is byte-identical, and seeded faults are reported identically. For pairing, the top-level blocks of all 1,886 corpus documents and the records of all 943 pairs match those of a full reparse, as do randomized destinations. + +### 6. Repository file walks list each directory once + +- **Change:** `uniqueRepoFiles()` in [`scripts/repo-files.ts`](../../../../scripts/repo-files.ts) shares one directory-listing cache across all patterns of a call, so each directory is read at most once, and calls `realpath` only for matches reached through a symbolic link; a regular file reached through real directories canonicalizes to the repository's realpath joined with its relative path. Its optional `skipDirectory` predicate keeps the walker out of a directory whose every path the caller excludes; [`verify-doc-refs.ts`](../../../../scripts/verify-doc-refs.ts) skips every `lib` directory below the first path segment, whose files it excludes in any case. +- **Performance:** markdown wrap 25.8/25.0 → 21.3/21.2 s; doc refs 8.8/7.0 → 3.2/3.4 s; package paths 9.9/8.1 → 7.2/5.5 s. +- **Why it is lossless:** All three gates receive identical file lists, and a broken or cyclic symbolic link still fails through `realpath`. +- **Behavior difference:** doc refs does not list a skipped `lib` directory, so an unreadable one does not fail the gate with EACCES. + +### 7. CLI help reads run concurrently; doc-graph probes are memoized + +- **CLI help:** `prefetchHelp()` in [`scripts/gen-cli-help.ts`](../../../../scripts/gen-cli-help.ts) starts the 12 top-level `dsh … --help` reads (the launcher, `plugin`, and each profile's shorthand and `--profile` forms) within the default worker budget, each with its own temporary `DSH_HOME` and `DSH_AGENTS_HOME`, and the in-order traversal consumes them; nested reads share the same limit. A failed read reaches the traversal when it requests that invocation, and `close()` aborts queued and running reads and waits for every started child. The gate takes 49.9/53.9 → 6.9/7.2 s. +- **Doc graphs:** `withMemoizedFileSystemProbes()` in [`scripts/gen-doc-graphs.ts`](../../../../scripts/gen-doc-graphs.ts) memoizes `ts.sys` `fileExists`, `directoryExists`, `realpath`, `readDirectory`, and `getDirectories` while `renderDocs` runs, so every compiler host and config parse in one run shares one view of the file system. The workspace must not change during the run, and the original methods are restored before pages are written. The gate takes 48.7/44.7 → 32.7/34.2 s. +- **Why it is lossless:** Both generators produce byte-identical pages. +- **Trade-off:** The concurrent help processes use about 3.6 GB of memory combined at peak. + +### 8. `type-model.spec.ts` runs against an in-memory workspace + +- **Change:** [`type-model.spec.ts`](../../../../packages/typert/generator/tests/type-model.spec.ts) mocks `node:fs` with `memoryFileSystem()` and the `ts.sys` host from [`type-model-workspace.ts`](../../../../packages/typert/generator/tests/type-model-workspace.ts), so fixture copies, case edits, write-mode annotations, tsconfig expansion, and module resolution under the in-memory root never touch the disk. Each workspace mounts minimal `zod` and `@types/node` declaration stubs; only the Emitter case keeps real zod. The fixture's `tsconfig.base.json` sets `lib: ["ES2024"]`, which excludes the DOM library, and cases that read the unmodified fixture share one deep-frozen analysis. The generator source has no test-specific path. +- **Performance:** The file alone takes 316.3/329.1 → 14.65/15.04 s. +- **Why the behavior coverage stays:** The 61 case names and their assertions are the same. The snapshot differs in one line, the external zod symbol path, which names the stub (`:node_modules/zod/index.d.ts#ZodType`) rather than a pnpm store version. +- **Trade-off:** Outside the Emitter case, the spec does not exercise the analyzer against the real file system, the DOM library, or the real zod and `@types/node` declarations. The memory file system implements only the `node:fs` calls the analyzer makes (`existsSync`, `readFileSync`, `realpathSync`, and `writeFileSync`); another call on an in-memory path reaches the real file system, where the path does not exist. + +### Repository-wide comparison + +Both trees were measured in the same session, alternating baseline and implementation runs of each command after `pnpm run build:artifacts` (`pnpm run test` fails the same environment-dependent files on both trees, 42 on the baseline and a subset of 28 here): + +| Command | Baseline | This implementation | Change | Items | +|---|---|---|---|---| +| `pre-commit` hooks, one staged file under a package `src/` subdirectory | 16.5/17.8 s | 4.3/4.5 s | −75% | 2 | +| `pnpm run typecheck` (pre-push), nothing to recheck | 29.7/23.3 s | 14.2/16.1 s | −43% | 1, 3 | +| `pnpm run lint` | 110.0 s | 106.7 s | −3% | 1 | +| `pnpm run doc-typecheck` | 45.2 s | 36.1 s | −20% | 1 | +| `pnpm run test:docs` | 102.4/104.0 s | 26.8/29.3 s | −73% | 3–6 | +| `pnpm run doc-sync` | 186.8 s | 70.3 s | −62% | 3–7 | +| `pnpm run test` | 222.7 s (255 workers) | 148.1 s (48 workers) | −34% | 3, 8 | + +`lint` time is Oxlint itself; its prerequisite falls as item 1 states. CPU time falls with wall: `typecheck` user time 39.5 → 14.2 s, `test:docs` 212.6 → 126.3 s, `doc-sync` 628.2 → 503.2 s, and `test` 3,417 → 3,014 s. + +## Alternatives considered + +- **Cap every local default at 12, including Vitest forks (item 3):** `pnpm run test` takes 410.5 s at 12 workers against 243.7 s at 255, 68% longer. +- **Use half of the cgroup CPU quota as the local budget (item 3):** Reading the quota is a larger change and helps only inside containers. +- **Parse documents in parallel `worker_threads` (item 5):** It adds more complexity than parsing each document once, which removes the repeated work itself. +- **Regenerate third-party notices in the pre-commit hook (item 2):** Browser inputs make every package source file a generator input, so the hook runs the 16-second generator on nearly every commit while few commits change its output; [the generated third-party notices note](2026-07-30-generated-third-party-notices.md) owns the decision. + +## Consequences + +The pre-push `typecheck` with nothing to recheck takes about 14–22 s, the `lint` and `doc-typecheck` prerequisite about 12 s, and the hooks of a one-file commit about 4 s. `pnpm run test` starts at most 48 forks locally, and `test:docs` and `doc-sync` run up to 8 gates at once. Typert outputs, generated pages, file lists, and reference classifications are byte-identical to the baseline. + +Costs: type-check commands do not refresh runnable bundles; a stale notices file fails in the test lane after push; local defaults ignore CPUs above the caps and still oversubscribe a container whose quota is below them; 8 concurrent documentation gates raise the `doc-sync` RSS peak; CLI help uses about 3.6 GB at peak; doc graphs and markdown links assume the tree does not change during a run; `type-model.spec.ts` exercises stubs rather than real zod, `@types/node`, the DOM library, and disk I/O outside the Emitter case; and incremental `typecheck` inherits the Remote-declaration gap that Issue #6022 tracks. + +Verification: `generate-typert.spec.ts` pins byte-identical files against the workspace-mode plugin, rejection of a Host program that loads a compiled workspace declaration with the missing alias named, and each failure stage; `compile-referenced-projects.spec.ts` pins the `host-contracts` steps and their failure reporting; `build.spec.ts` pins the typecheck scope's steps; `parallelism.spec.ts`, `run-gates.spec.ts`, and `run-oxlint.spec.ts` pin the CI and local budgets and the overrides; `repo-files.spec.ts`, `markdown.spec.ts`, `translation-pairing.spec.ts`, `type-equiv-prefilter.spec.ts`, `verify-md-links.spec.ts`, `gen-cli-help.spec.ts`, and `gen-doc-graphs.spec.ts` pin single directory listing, parse reuse, the pairing guard, the prefilter, the prefetch order and failure path, and probe memoization with restoration. diff --git a/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.zh.md b/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.zh.md new file mode 100644 index 0000000000..faf66b3153 --- /dev/null +++ b/.agents/notes/implemented/process/2026-10-12-local-gate-speedups.zh.md @@ -0,0 +1,158 @@ +# Agent Note: 本地门禁、钩子与测试提速 + +Status: implemented + +[English](2026-10-12-local-gate-speedups.md) | 中文 + +## 问题 + +在基线(合并 #6013 时的 master)上,本地运行 Git 钩子、`pnpm run test`、`test:docs` 与 `doc-sync`(文档同步门禁)时,大部分 wall 时间花在结果并不依赖的工作上: + +- **经打包器获得 Typert 声明。** pre-push 钩子运行的 `typecheck` 先运行 `build:lib:host`(Host `tsc -b tsconfig.host.json`、Host tsdown 阶段与 Desktop bundle),再运行 `tsc -b tsconfig.client.json`。`lint`、`lint:fix`、`doc-typecheck` 与 CI `typert-contracts` 门禁的前置步骤先运行 Host 包编译,再运行 Host tsdown 阶段(`compile-referenced-projects.ts host-libraries`)。类型检查只读取包声明与 Typert 声明,但无需重查时 `typecheck` 仍需 34.1/35.0 s,前置步骤需 52.2/29.6 s。 +- **每次提交都生成第三方声明。** 只要暂存文件是生成器的输入,pre-commit 钩子就重新生成 `THIRD_PARTY_NOTICES.md`。为找出浏览器侧的第三方 import,生成器对 75 个 Client 包试打包并运行一次 Vite 构建,因此每个包源码文件都是它的输入;暂存一个位于包 `src/` 子目录下的文件的提交,钩子合计 16.5/17.8 s,其中第三方声明任务占 12.4/13.4 s。 +- **以宿主 CPU 数作为本地 worker 数。** `os.availableParallelism()` 报告的是宿主 CPU 数(测量主机上为 256),而不是容器的 CPU 配额(64)。按此默认值,`pnpm run test` 启动 255 个 Vitest fork,RSS 峰值 55.3 GiB,并偶发地多失败 12 个文件(14 次超时);同时 `doc-sync`、`test:docs`、`hygiene` 与 `check:all` 最多只并发 4 个门禁。 +- **每个候选一次 Git 前缀查找。** `verify-repository-references` 通过 `git cat-file --batch-check` 对约 26,000 个缩写十六进制候选逐个做 Git 前缀查找;这些查找占该门禁 166.8 s 中的 135.7 s。 +- **重复解析 Markdown。** markdown links 对每个锚点目标再多解析两次,且探测目标是否存在时不缓存;translation pairing 做四次 glob,并在链接归一化后再次解析每个文档;包 README 的 model experience 与 limitations 检查各自把每个 README 解析三次;type equivalence 解析全部 1,835 个文档;Session format references 把每个配对解析四次。 +- **重复读取目录。** markdown wrap、doc refs 与 package paths 背后的遍历器 `uniqueRepoFiles` 对每个 pattern 与每层 `**` 各读取一次每个目录,并对每个匹配文件调用 `realpath`。 +- **串行启动 help 与重复的编译器探测。** `gen-cli-help` 依次启动 12 个顶层源码模式的 `dsh … --help` 进程,每个进程大部分时间在等待 profile 启动的 I/O(49.9/53.9 s);`gen-doc-graphs` 构建多个编译器 host 与 program,重复执行同样的 `ts.sys` 文件系统探测(48.7/44.7 s)。 +- **受文件系统探测拖累的测试文件。** Typert generator 的 `type-model.spec.ts` 的 61 个用例各自把 fixture(测试前置数据)复制到磁盘并运行一次完整分析,分析中的四个 TypeScript program 各自加载 DOM lib、`@types/node` 与 zod v4,每次分析约 22,000 次 stat 调用。该文件耗时 316.3/329.1 s,是 `pnpm run test` 的长尾。 + +## 决策 + +以下八项决策缩短上述运行。每一项都给出其产物与诊断保持不变的依据,或它接受的有意差异。 + +| # | 决策 | 受影响的命令 | 实测 wall | 产物与诊断 | 有意的行为差异 | +|---|---|---|---|---|---| +| 1 | 类型检查不打包地生成 Typert 声明 | `typecheck`、`lint`、`lint:fix`、`doc-typecheck`、CI `typert-contracts` | `typecheck` 34.1/35.0 → 21.9/20.0 s;前置步骤 52.2/29.6 → 12.5/11.3 s | 140 个 Typert 文件逐字节一致;检查的程序相同 | 不产出可运行 bundle,不写 client build record | +| 2 | pre-commit 钩子不重新生成第三方声明 | `pre-commit` | 16.5/17.8 → 4.3/4.5 s | 新鲜度由测试 lane 断言 | 第三方声明过期时在测试 lane 失败,而不是在提交时 | +| 3 | 本地默认 worker 预算 | run-gates 聚合、`build`、`typecheck`、`pnpm run test`、Oxlint、publint | 255 个 worker 时 `test` 为 243.7 s、55.3 GiB;`test:docs` 74.7 → 50.9 s | 检查不变 | 本地默认值不使用超过 12 或 48 的 CPU | +| 4 | 仓库引用候选对照一次对象列表解析 | `verify-repository-references` | 166.8 → 15.7 s | 27,050 个候选的判定 0 差异 | 无 | +| 5 | 文档门禁每个文档只解析一次 | markdown links、translation pairing、README model experience 与 limitations、type equivalence、Session format references | markdown links 53.4/51.6 → 25.9/25.1 s;type equivalence 23.0/22.5 → 6.0/5.5 s | 门禁输出逐字节一致 | 无 | +| 6 | 仓库文件遍历每个目录只列一次 | markdown wrap、doc refs、package paths | doc refs 8.8/7.0 → 3.2/3.4 s | 文件列表一致 | doc refs 不读取嵌套的 `lib` 目录 | +| 7 | CLI(命令行界面)help 读取并发运行;doc graphs 的探测做 memo | `verify-cli-help`、`verify-doc-graphs` | 49.9/53.9 → 6.9/7.2 s;48.7/44.7 → 32.7/34.2 s | 页面逐字节一致 | CLI help 峰值约用 3.6 GB 内存 | +| 8 | `type-model.spec.ts` 在内存工作区上运行 | `pnpm run test` | 316.3/329.1 → 14.65/15.04 s | 61 个用例与断言不变;快照有一行不同 | 除 Emitter 用例外,桩替代 zod、`@types/node` 与 DOM lib | + +### 测量条件 + +所有数字都是 wall 时间,取自同一个共享 Linux 容器:CPU 配额 64 核,宿主报告 256 个 CPU,一分钟 load average 为 20–150,因此样本带有噪声。工作树位于网络文件系统上,每次文件系统探测的代价都高于本地磁盘。`a/b` 表示两个样本,`x → y` 比较基线与本实现。 + +### 1. 类型检查不打包地生成 Typert 声明 + +- **目的:** 让 `typecheck` 以及 `lint`、`lint:fix`、`doc-typecheck` 与 CI `typert-contracts` 门禁的前置步骤得到它们读取的声明,即 `tsc` 产出的包声明与 Typert 声明,而不运行 Host tsdown 阶段或 Desktop bundle。 +- **改动:** `typecheck` 是 `tsx scripts/build.ts --scope typecheck`,它通过 run-gates 调度器运行下表中的步骤([`scripts/build.ts`](../../../../scripts/build.ts))。该 scope 不构建 native addon、tsdown bundle、Desktop bundle 或 Web 产物,不写 client build record,可运行的 `lib/` 产物保持上一次 `build:artifacts` 的状态;启动或测试构建产物之前先运行 `build:artifacts`。`lint`、`lint:fix`、`doc-typecheck` 与 `typert-contracts` 的前置步骤是 `compile-referenced-projects.ts host-contracts`,它让 host-src 与 host-typert 并行([`compile-referenced-projects.ts`](../../../../scripts/compile-referenced-projects.ts))。`build`、`build:artifacts`、benchmark 构建与 `release-vendor.yml` 的 PR(Pull Request)演练在 Host tsdown 阶段内运行 Typert。 + +| 步骤 | 命令 | `needs` | +|---|---|---| +| host-src | `node --max-old-space-size=4096 -b ` | — | +| host-typert | `node --import tsx/esm scripts/generate-typert.ts` | — | +| client-src | ` -b ` | host-src、host-typert | +| host-check | `node --max-old-space-size=4096 -b tsconfig.host.json` | host-src | +| client-check | ` -b tsconfig.client.json` | client-src | + +- **共用生成:** [`scripts/generate-typert.ts`](../../../../scripts/generate-typert.ts) 对 `WORKSPACE_TYPERT_FACES`([`scripts/typert-faces.ts`](../../../../scripts/typert-faces.ts),即 Host tsdown 插件同样生成的 face)调用 `WorkspaceTypertGenerator.generateContributors()`,并用 [`artifact-files.ts`](../../../../packages/typert/generator/src/artifact-files.ts) 中插件同样使用的 `writeWorkspaceArtifacts()` 写出结果。与插件一样,它跳过 TypeScript 诊断,这些诊断由 Host 包编译报告;Typert 分析错误使 host-typert 失败,正如它在 `build` 中使 Host bundle 失败。host-typert 由 Node 加 tsx 的 ESM 钩子运行,而不经 `pnpm exec`,因为后者的启动开销会拉长通往 Client 编译的路径。 +- **以 build mode 运行聚合检查:** host-check 与 client-check 在本侧 face 的包编译之后才开始,因此 build mode 发现所有 references 都是最新的,只检查聚合根程序,并在根程序的 tsbuildinfo 为最新时跳过它。 +- **只读源码的分析:** host-typert 能与 host-src 并行,是因为它的 Host program 不读取任何工作区构建产物。`tsconfig.base.json` 把 `@deepseek-ai/dsh-client-file-upload/types` 映射到源码;没有这条别名时,该说明符经包 `exports` 解析到 `lib/types/types.d.ts`。有了它,Host program 加载 1,289 个文件,其中没有一个位于工作区包的 `lib/` 下。`generate-typert.ts` 开启 `rejectBuildOutputs`:face program 加载工作区包 `lib/` 目录下的文件,或无法解析对工作区包的 import(例如包尚未编译的工作区)时,[`build-output-guard.ts`](../../../../packages/typert/generator/src/build-output-guard.ts) 以 `TypertAnalysisError` 使分析失败,并指出每个这样的 import 说明符,以及把它映射到源码的 `paths` 条目。因此无论 host-src 是否已运行,缺失的别名都会使生成失败。tsdown 插件不开启该选项,因为在 `build` 中 Typert 总在 Host 包编译之后运行。[Typert generator README](../../../../packages/typert/generator/README.zh.md) 记录了这些写入函数与该选项。 +- **无损依据:** 没有任何工作区 tsconfig 设置 `allowJs`,每个 `exports` 的 `types` 条件都指向 `lib/types/` 内或 `lib/typert.*`,每个 tsdown 配置都设置 `dts: false`,因此没有类型检查读取 tsdown 产物。140 个 Typert 文件(28 个包 × 5 个输出)在以下场景中逐字节一致:基线 tsdown 阶段、当前 tsdown 阶段、删除全部 Typert 输出后运行 `generate-typert.ts`、隐藏全部 344 个 `lib/types` 目录后运行 `generate-typert.ts`;临时给 `packages/goal/goal` 加一个 Remote 方法时,tsdown 阶段与 `generate-typert.ts` 写出的文件也相同。`typecheck` 检查两个 face 的全部包 project 与两个聚合根程序,即 `build` 检查的程序。 +- **性能:** 无需重查时 `typecheck` 为 34.1/35.0 → 21.9/20.0 s。两个聚合根程序都需要重查时为 83.5 → 76.0/72.1 s,其关键路径是约 66–70 s 的 Host 聚合检查。`lint` 与 `doc-typecheck` 的前置步骤为 52.2/29.6 → 12.5/11.3 s。 +- **取舍:** `typecheck`、`lint`、`lint:fix`、`doc-typecheck` 与 `typert-contracts` 写出 Typert 声明但不写 bundle,因此在下一次 `build:artifacts` 之前,可运行的 `lib/` JavaScript 可能落后于这些声明。 +- **与构建的关系:** [无损构建提速 Note](2026-10-11-lossless-build-speedups.zh.md) 否决了在构建中把 Typert 移出 Host tsdown 阶段:构建中它的 Worker Thread 已与打包重叠,独立步骤最多只能省约 1 s。类型检查命令不运行打包器,因此不打包地生成会把整个 Host tsdown 阶段与 Desktop bundle 移出它们的关键路径。[构建拆分 Note](2026-10-11-build-artifacts-check-split.zh.md) 列出每个调用方及其命令。 +- **已知缺口:** 增量 `tsc -b` 不把 Client 源码经包 `exports` 访问到的 `lib/typert.remote-client.d.ts` 记为消费方 project 的输入;Remote 签名改变而 Client 源码未变时,增量检查不会重查消费方。这一缺口与由哪一种生成写出声明无关,由 Issue #6022 跟踪。 + +### 2. pre-commit 钩子不重新生成第三方声明 + +- **改动:** [`lefthook.yml`](../../../../lefthook.yml) 中的 `pre-commit` 钩子没有第三方声明任务。[`gen-third-party-notices.spec.ts`](../../../../scripts/gen-third-party-notices.spec.ts) 在测试 lane(包括必过的 `node 24 / coverage` lane)中断言 `THIRD_PARTY_NOTICES.md` 已提交的字节,过期时指出 `pnpm run gen-third-party-notices`。[生成的第三方声明 Note](2026-07-30-generated-third-party-notices.zh.md) 拥有这一新鲜度决策。 +- **性能:** 暂存一个位于包 `src/` 子目录下的文件的提交,钩子耗时由 16.5/17.8 s 降为 4.3/4.5 s,其中第三方声明任务占 12.4/13.4 s。 +- **取舍:** 使第三方声明过期的提交会在推送后于测试 lane 失败,而不是在提交时被修正。 + +### 3. 本地默认 worker 预算 + +- **目的:** 按共享工作站或容器确定默认并行度;在这类环境中 Node 报告的是宿主 CPU 数而不是 CPU 配额。 +- **改动:** [`scripts/parallelism.ts`](../../../../scripts/parallelism.ts) 拥有默认值。`CI=true` 时它是 Node 报告的 CPU 数。否则,run-gates 调度器、`build`、`typecheck`、Oxlint 与 publint 的上限为 12(`LOCAL_PARALLELISM_CAP`),Vitest fork 与本地覆盖率预算的上限为 48(`LOCAL_TEST_PARALLELISM_CAP`)。`doc-sync`、`test:docs`、`hygiene` 与 `check:all` 的每个门禁都构建完整的 `ts.Program`,它们最多并发 8 个门禁,CI 中同样如此。显式的 `DSH_GATE_CONCURRENCY`、`DSH_OXLINT_THREADS`、`DSH_COVERAGE_MAX_WORKERS` 与 Vitest `--maxWorkers` 优先;CI 中,除非 run-gates 的 CI 环境设置了这些变量,Vitest 与 Oxlint 使用各自的默认值。[开发指南](../../../../docs/development.zh.md)向贡献者说明这些默认值。 + +四种 fork 数下的 `pnpm run test`,运行的是第 8 项所替换的落盘版 `type-model.spec.ts`,32 个 worker 那次的 wall 由它决定: + +| Vitest worker 数 | wall | RSS 峰值 | 额外的偶发失败 | 除最慢文件外其余文件完成于 | +|---|---|---|---|---| +| 255(报告的 CPU 数) | 243.7 s | 55.3 GiB | 12 个文件、14 次超时 | 约 135–170 s | +| 32 | 310.4 s | 15.7 GiB | 4 个文件、4 次超时 | 193 s | +| 24 | 337.2 s | 13.2 GiB | 5 个文件、5 次超时 | 233 s | +| 12 | 410.5 s | 8.4 GiB | 2 个文件、3 次超时 | 406 s | + +- **Oxlint:** Oxlint 自身的默认值是 64 线程(读取 cgroup 配额);12 线程时其 wall 保持约 87–90 s,CPU 少约 15%;8 线程时慢约 4 s。 +- **文档聚合:** 并发 8 个门禁时 `test:docs` 为 50.9 s,并发 4 个时为 74.7 s。不含第 4 项时测得的 `doc-sync` 在并发 4、8、12 个门禁时分别为 341.8、295.0、253.2 s,RSS 峰值分别为 10.0、13.5、16.3 GiB。 +- **取舍:** CPU 配额超过上限的机器,默认并行度也不超过 12 或 48,需要使用覆盖变量;配额低于上限的容器仍会超额订阅,因为 Node 报告的是宿主 CPU 数。并发 8 个门禁时 `doc-sync` 的 RSS 峰值为 13.5 GiB,并发 4 个时为 10.0 GiB;并发 12 个门禁快 41.8 s,但峰值为 16.3 GiB。CI 的文档 workflow 运行 `doc-sync` 时同样最多并发 8 个门禁。 + +### 4. 仓库引用候选对照一次对象列表解析 + +- **改动:** [`verify-repository-references.ts`](../../../../scripts/verify-repository-references.ts) 用 `git cat-file --batch-all-objects --batch-check=%(objectname)` 一次列出全部对象名(约 120 万个对象,0.6 s),排序后在内存中对每个小写候选前缀做二分查找;随后一次 `--batch-check=%(objectname) %(objecttype)` 调用读取命中对象的类型。只有当候选前缀恰好匹配一个可用对象且该对象是 commit 时,它才算 commit 引用,这与 Git 自身前缀查找的规则相同;与 Git 的查找一样,该列表也包含不可达对象与 alternate 对象。 +- **性能:** 166.8 → 15.7 s。 +- **无损依据:** 在 27,050 个真实与合成候选上(包括歧义前缀、blob 与 tree 前缀以及随机字符串),Git 的逐候选前缀查找与内存查找的判定完全一致。 +- **取舍:** 120 万个对象的列表约为 49 MiB 的 Git 输出,读取时的输出上限为 1 GiB。 + +### 5. 文档门禁每个文档只解析一次 + +- **改动:** 下表中的每个门禁对一个 Markdown 文档只解析一次,并把语法树传给本次运行中的所有使用方。 + +| 门禁 | 单次解析机制 | wall | +|---|---|---| +| markdown links([`verify-md-links.ts`](../../../../scripts/verify-md-links.ts)) | 一个按运行划分的缓存对每个文件只解析一次,同时取得其 destination 与锚点,并对每个解析后的目标只探测一次 | 53.4/51.6 → 25.9/25.1 s | +| translation pairing([`verify-translation-pairing.ts`](../../../../scripts/verify-translation-pairing.ts)) | 一次 glob 覆盖所有范围 pattern;record 在下述守卫条件下复用原文语法树 | 51.0/47.1 → 30.3/29.3 s | +| package README model experience、package README limitations | 每项检查对一个 README 只解析一次,并把语法树传给 `markdownProseLines()` 与 `markdownHeadingLines()` | 各约 12 → 5.9 s | +| type equivalence([`verify-type-equiv.ts`](../../../../scripts/verify-type-equiv.ts)) | 文本预筛跳过不可能含源码等价围栏的文档;manifest(元数据清单)中的每个 TypeScript 源文件只解析一次 | 23.0/22.5 → 6.0/5.5 s | +| Session format references | persistence 渲染器把它解析出的语法树传给配对 record | 10.2 → 5.3 s | + +- **配对复用守卫:** [`translation-pairing-record.ts`](../../../../scripts/translation-pairing-record.ts) 中的 `normalizedTopLevelBlocks()` 仅在以下条件同时成立时,才为归一化后的文本复用原文语法树:每处链接归一化编辑都替换一个完整、无 title 且不在行首开始的 destination,原文等于该节点的 `url`,且原文与替换文本都只含 `[A-Za-z0-9._/:#%-]`。这些字符既不能结束 destination,也不能开始或结束其他语法结构,因此归一化后的文本解析出相同的节点,只是偏移量随之移动。其他任何编辑都回退为对归一化文本的完整解析。 +- **type equivalence 预筛:** [`type-equiv-prefilter.ts`](../../../../scripts/type-equiv-prefilter.ts) 在文档含 `type-equiv` 或 `public-api`,或者某个含 `` ``` `` 或 `~~~` 的行同时含 `&` 或 `\` 时,保留该文档进行解析。解析只会通过解码字符引用与反斜杠转义改变信息字符串,因此 `ts type-equiv` 与 `ts type\-equiv` 所在的文档都会被保留;[`type-equiv-prefilter.spec.ts`](../../../../scripts/type-equiv-prefilter.spec.ts) 覆盖这两种写法。 +- **无损依据:** 每个门禁在仓库上的输出逐字节一致,人为注入的错误也被同样报告。对配对而言,语料中全部 1,886 个文档的顶层块与全部 943 个配对的 record 都与完整重新解析的结果一致,随机 destination 的结果也一致。 + +### 6. 仓库文件遍历每个目录只列一次 + +- **改动:** [`scripts/repo-files.ts`](../../../../scripts/repo-files.ts) 中的 `uniqueRepoFiles()` 在一次调用的所有 pattern 之间共享一个目录列表缓存,使每个目录最多读取一次,并且只对经符号链接到达的匹配调用 `realpath`;只经真实目录到达的普通文件,规范路径为仓库 realpath 拼接其相对路径。它的可选谓词 `skipDirectory` 让遍历器不进入调用方排除其下全部路径的目录;[`verify-doc-refs.ts`](../../../../scripts/verify-doc-refs.ts) 跳过第一段路径之后的每个 `lib` 目录,其下文件本来就全部被它排除。 +- **性能:** markdown wrap 25.8/25.0 → 21.3/21.2 s;doc refs 8.8/7.0 → 3.2/3.4 s;package paths 9.9/8.1 → 7.2/5.5 s。 +- **无损依据:** 三个门禁得到的文件列表逐项相同,损坏或循环的符号链接仍会经 `realpath` 失败。 +- **行为差异:** doc refs 不列出被跳过的 `lib` 目录,因此不可读的此类目录不会以 EACCES 使门禁失败。 + +### 7. CLI help 读取并发运行;doc graphs 的探测做 memo + +- **CLI help:** [`scripts/gen-cli-help.ts`](../../../../scripts/gen-cli-help.ts) 中的 `prefetchHelp()` 在默认 worker 预算内启动 12 个顶层 `dsh … --help` 读取(启动器、`plugin`,以及每个 profile 的简写与 `--profile` 形式),每个读取使用独立的临时 `DSH_HOME` 与 `DSH_AGENTS_HOME`,并由按原顺序进行的遍历消费;嵌套读取共享同一上限。失败的读取在遍历请求该调用时才交给遍历;`close()` 中止排队与运行中的读取,并等待每个已启动的子进程结束。该门禁为 49.9/53.9 → 6.9/7.2 s。 +- **doc graphs:** [`scripts/gen-doc-graphs.ts`](../../../../scripts/gen-doc-graphs.ts) 中的 `withMemoizedFileSystemProbes()` 在 `renderDocs` 运行期间对 `ts.sys` 的 `fileExists`、`directoryExists`、`realpath`、`readDirectory` 与 `getDirectories` 做 memo,使一次运行中的所有编译器 host 与配置解析共享同一个文件系统视图。运行期间工作区不得改变,写出页面之前恢复原方法。该门禁为 48.7/44.7 → 32.7/34.2 s。 +- **无损依据:** 两个生成器生成的页面逐字节一致。 +- **取舍:** 并发的 help 进程合计峰值约占 3.6 GB 内存。 + +### 8. `type-model.spec.ts` 在内存工作区上运行 + +- **改动:** [`type-model.spec.ts`](../../../../packages/typert/generator/tests/type-model.spec.ts) 用 [`type-model-workspace.ts`](../../../../packages/typert/generator/tests/type-model-workspace.ts) 中的 `memoryFileSystem()` mock `node:fs` 与 `ts.sys` host,使内存根目录下的 fixture 复制、用例编辑、写模式注解、tsconfig 展开与模块解析都不触及磁盘。每个工作区挂载最小的 `zod` 与 `@types/node` 声明桩;只有 Emitter 用例保留真实 zod。fixture 的 `tsconfig.base.json` 设置 `lib: ["ES2024"]`,不含 DOM lib;读取未修改 fixture 的用例共享一份深度冻结的分析结果。generator 源码没有任何测试专用路径。 +- **性能:** 单独运行该文件为 316.3/329.1 → 14.65/15.04 s。 +- **行为覆盖保持不变的依据:** 61 个用例名及其断言相同。快照只有一行不同,即外部 zod 符号路径,它指向桩(`:node_modules/zod/index.d.ts#ZodType`),而不是某个 pnpm store 版本。 +- **取舍:** 除 Emitter 用例外,该 spec 不针对真实文件系统、DOM lib 以及真实 zod 与 `@types/node` 声明检验分析器。内存文件系统只实现分析器使用的 `node:fs` 调用(`existsSync`、`readFileSync`、`realpathSync` 与 `writeFileSync`);对内存路径的其他调用会落到真实文件系统,而该路径并不存在。 + +### 全仓对比 + +两棵树在同一时段测量,每个命令在 `pnpm run build:artifacts` 之后交替运行基线与本实现(`pnpm run test` 在两棵树上失败的都是依赖环境的文件,基线 42 个,本实现是其中的 28 个): + +| 命令 | 基线 | 本实现 | 变化 | 对应项 | +|---|---|---|---|---| +| `pre-commit` 钩子,暂存一个位于包 `src/` 子目录下的文件 | 16.5/17.8 s | 4.3/4.5 s | −75% | 2 | +| `pnpm run typecheck`(pre-push),无需重查 | 29.7/23.3 s | 14.2/16.1 s | −43% | 1、3 | +| `pnpm run lint` | 110.0 s | 106.7 s | −3% | 1 | +| `pnpm run doc-typecheck` | 45.2 s | 36.1 s | −20% | 1 | +| `pnpm run test:docs` | 102.4/104.0 s | 26.8/29.3 s | −73% | 3–6 | +| `pnpm run doc-sync` | 186.8 s | 70.3 s | −62% | 3–7 | +| `pnpm run test` | 222.7 s(255 个 worker) | 148.1 s(48 个 worker) | −34% | 3、8 | + +`lint` 的耗时主要是 Oxlint 本身,其前置步骤的下降见第 1 项。CPU 时间随 wall 一同下降:`typecheck` 的 user 时间 39.5 → 14.2 s,`test:docs` 212.6 → 126.3 s,`doc-sync` 628.2 → 503.2 s,`test` 3,417 → 3,014 s。 + +## 考虑过的替代方案 + +- **所有本地默认值一律以 12 为上限,包括 Vitest fork(第 3 项):** 12 个 worker 时 `pnpm run test` 为 410.5 s,255 个时为 243.7 s,慢 68%。 +- **以 cgroup CPU 配额的一半作为本地预算(第 3 项):** 读取配额的改动更大,且只在容器内有意义。 +- **用 `worker_threads` 并行解析文档(第 5 项):** 它带来的复杂度高于每个文档只解析一次,而后者直接消除了重复工作。 +- **在 pre-commit 钩子中重新生成第三方声明(第 2 项):** 浏览器输入使每个包源码文件都成为生成器输入,钩子会让几乎每次提交都运行约 16 秒的生成器,而改变输出的提交很少;[生成的第三方声明 Note](2026-07-30-generated-third-party-notices.zh.md) 拥有该决策。 + +## 后果 + +无需重查时 pre-push `typecheck` 约 14–22 s,`lint` 与 `doc-typecheck` 的前置步骤约 12 s,改动 1 个文件的提交的钩子约 4 s。`pnpm run test` 在本地最多启动 48 个 fork,`test:docs` 与 `doc-sync` 最多同时运行 8 个门禁。Typert 输出、生成的页面、文件列表与引用判定都与基线逐字节一致。 + +代价:类型检查命令不刷新可运行的 bundle;第三方声明过期时在推送后于测试 lane 失败;本地默认值不使用超过上限的 CPU,而配额低于上限的容器仍会超额订阅;并发 8 个文档门禁抬高 `doc-sync` 的 RSS 峰值;CLI help 峰值约用 3.6 GB 内存;doc graphs 与 markdown links 假定运行期间工作树不变;除 Emitter 用例外,`type-model.spec.ts` 检验的是桩,而不是真实 zod、`@types/node`、DOM lib 与磁盘 I/O;增量 `typecheck` 继承 Issue #6022 跟踪的 Remote 声明缺口。 + +验证:`generate-typert.spec.ts` 固定与 workspace 模式插件逐字节一致的文件、对加载已编译工作区声明的 Host program 的拒绝(并指出缺失的别名),以及每个失败阶段;`compile-referenced-projects.spec.ts` 固定 `host-contracts` 的步骤及其失败报告;`build.spec.ts` 固定 typecheck scope 的步骤;`parallelism.spec.ts`、`run-gates.spec.ts` 与 `run-oxlint.spec.ts` 固定 CI 与本地预算以及覆盖变量;`repo-files.spec.ts`、`markdown.spec.ts`、`translation-pairing.spec.ts`、`type-equiv-prefilter.spec.ts`、`verify-md-links.spec.ts`、`gen-cli-help.spec.ts` 与 `gen-doc-graphs.spec.ts` 固定目录只列一次、语法树复用、配对守卫、预筛、预取顺序与失败路径,以及探测 memo 及其恢复。 diff --git a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.i18n.yaml b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.i18n.yaml new file mode 100644 index 0000000000..7c41c4d039 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-10-11-user-text-credential-matching.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md +/agent-note-linear-credential-matching-and-performance-gates-for-user-text: + en: 4d3e2c3ad91a1a03 + zh: d08dd77dd0bd849c +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/problem: + en: ae449178436337ea + zh: 9eced057b7d9ef3d +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/decision: + en: a15c7c13f167e5ac + zh: ff261e3705c47ff0 +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/decision/algorithm-what-each-part-does-and-costs: + en: aa1d65cd64a2a895 + zh: 4bf32f20d14ce452 +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/decision/memory: + en: b91fc88cdd488ce3 + zh: 318db3f522681cca +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/decision/trade-offs: + en: f07bb6fbbdd01fe4 + zh: 9313a0ef2a22af12 +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/decision/performance-gate: + en: 6a303115f85ed4e8 + zh: e894f3e9d630bf57 +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/alternatives-considered: + en: 1e21f5f9ca959f7e + zh: 401e303071b8d426 +/agent-note-linear-credential-matching-and-performance-gates-for-user-text/consequences: + en: 8f9d25b72d3e7660 + zh: e5c6ae0194905876 diff --git a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md new file mode 100644 index 0000000000..d7995a1f93 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md @@ -0,0 +1,67 @@ +# Agent Note: Linear credential matching and performance gates for user text + +Status: implemented + +English | [中文](2026-10-11-user-text-credential-matching.zh.md) + +## Problem + +[ui-secret-mask](../../../../packages/client/ui-secret-mask/README.md) recognizes credentials in every sent user text. The UserText scheduler queries the matcher again after each accepted node, so a text costs the sum of all its queries. Most text contains no credential, so the first goal is that such text pays as little as possible; second, text with credentials pays in proportion to their number and length; adversarial input must stay linear. Constraints: no regex backtracking, prefix pruning, linear total over all queries of one text, and no allocation before a node is returned. + +## Decision + +### Algorithm: what each part does and costs + +| Part | Method | Cost over all queries of one text | +|---|---|---| +| Finding format starts | All starting literals (`sk-`, `sk_live_` and kin, `AIza`, `ghp_` and kin, `github_pat_`, `glpat-`, `npm_`, `hf_`, `AKIA`/`ASIA`, `LTAI`, `AKID`, `xox?-`, `whsec_`, `eyJ`, `-----BEGIN `, `://`) form one literal-only alternation grouped by shared leading characters, scanned with `test` | Θ(n) native comparisons; no quantifier, so no backtracking; two adjacent queries reread at most one literal | +| Overlapping literals | Where a literal's suffix begins another literal (the `-` of `sk-`, `glpat-`, `xox?-` and `-----BEGIN `), the scan resumes at that suffix; resume offsets are computed from the literal table at module load | At most one character back per hit | +| Identifying the hit | A table keyed by the hit's last two code units; only the three shared endings (`t_`, `e_`, `IA`) are told apart with `startsWith` | O(1) per hit | +| Format checks | Word boundaries, lengths, digit position, and the `.eyJ` separator are numeric comparisons; a private-key label reads at most 52 characters and a scheme at most 16 back; character runs are measured natively with sticky `[class]*` patterns, which stop at the first character outside the class and have nothing after them to backtrack into | O(1) per hit plus run measurement | +| Runs, next digit, next `END` line | Each matcher instance memoizes per text in one `Int32Array`: four slots for `[A-Za-z0-9_-]` (a JWT uses three runs at once), one slot per other class, the next digit, and the next valid `END` line. These are facts of the text, reused across queries and cleared when a query names another text | Each character measured at most once per class | +| Address passwords | When the `://` precedes the query offset and the password follows it, the matcher first confirms that `:`, a nonempty password, and `@` follow the offset, and only then walks back over the user name; an offset inside `://` is checked directly | At most 258 characters back, only where `:password@` follows the offset | +| Joining candidates | Candidates are processed in start order; an address password starts after its `://` and waits until the scan passes its start, and no other `://` can occur before then because user names and passwords exclude `/`; overlapping candidates join the earliest and take its mask; a range that reaches the end of the text ends the scan | O(1) per candidate, no list | +| Masks | A range of prefixed formats only is ASCII without line breaks, so its mask is a slice of its first 8 characters plus a slice of a shared mark string; a private-key body skips ordinary characters natively and takes one slice of a shared "marks plus line break" string per line; address passwords and other mixed ranges count code points character by character | Θ(masked characters + lines), the order of the output | + +### Memory + +- Nothing is allocated before a node is returned: `test` creates no match array, memo slots are a preallocated integer array, loops use indexes instead of iterators, and candidate ranges live in local numbers. +- Each credential allocates only its result: the node, its `data` object, and the mask. A one-line mask is the concatenation of two slices; a multi-line mask adds one slice and one concatenation per line. +- Each instance keeps a reference to the last queried text until a query names another text. + +### Trade-offs + +- **Scanning is native, decisions are JavaScript**: in V8 a per-character JavaScript loop is slower than a native literal scan or native run measurement, so all work proportional to input length (finding starts, measuring runs, skipping key bodies) uses non-backtracking native patterns, and JavaScript makes a constant number of decisions per hit. +- **Pruning depends on the formats only**: starts come from format literals, not from anchors chosen by character frequency in natural text, so text with any character distribution pays the same linear cost. +- **Memo per text, not per query**: a memo inside one query cannot stop later queries from measuring the same characters again; keyed by text and owned by the instance, cleared on a new text, it costs one retained string reference. +- **Masks use shared-string slices**: faster than writing into a buffer and decoding it; a multi-line mask allocates in proportion to its lines, which is part of the output. + +### Performance gate + +[benchmarks/user-text](../../../../benchmarks/user-text/user-text.bench.client.ts) runs in the required `node 24 / benchmarks` lane. Its compiled worker uses the production UserText registry and every shipped matcher (session, file, folder, skill, command, whitespace, credential) under plain Node, in two processes: timing and allocation. + +| Item | Content | +|---|---| +| Workloads | Without credentials: ordinary messages, and long prose, code, base64, Markdown, log, JSON, and shell text. With credentials: messages each carrying one kind (model key, GitHub token, cloud key ID, JWT, address password, private-key block), and batches of `.env` keys. Adversarial: repeated input shaped against each format's prefix, length, and separator rules, at two sizes. All generated from constants; credential samples are assembled at run time | +| Timing | Each sample builds a fresh registry, document, and matcher instance and times evaluation only; each workload is measured with and without the credential matcher, keeping the fastest of several samples and the process CPU time over the same interval | +| Allocation | A separate process with `--expose-gc` and a fixed semi-space larger than any evaluation; after warm-up and GC, the matcher alone answers every query once and the young-generation growth is taken; GC event timestamps confirm no GC ran inside the interval | +| Assertions | Without credentials: absolute budgets and a cap on the with/without time ratio; with credentials: absolute budgets and the time ratio when the key count doubles; adversarial: absolute budgets and doubling ratios; allocation: a floor plus caps per credential, per line break inside masks, and per masked character | +| Excluded | React rendering, browser paint and layout; allocation results are asserted and printed to the console, not added to the HTML report | + +Expectations come from an x64 development machine. CI time budgets are converted with the shared scale and headroom; time ratios, doubling ratios, and allocation budgets do not scale with machine speed. Negative controls: the same benchmark fails when pointed at the regular-expression implementation or at an implementation that rebuilds its memo per query. Equivalence tests compare this implementation with the regular-expression one ([regex-oracle.client.ts](../../../../packages/client/ui-secret-mask/tests/regex-oracle.client.ts)) node by node through the production scheduler and from every query offset. + +## Alternatives considered + +- **One quantified pattern per format, run from every query**: patterns without a hit scan to the end of the text each time, so cost grows quadratically with credentials, and length quantifiers backtrack on failure. +- **One large quantified pattern for all formats**: one scan finds the leftmost match, but branch quantifiers still backtrack on failure. +- **Scanning for rare characters first, then looking back for prefixes**: faster on ordinary text, but cost depends on character distribution, and text dense in `-` or `_` becomes clearly slower. +- **A pure JavaScript Aho–Corasick automaton**: allocation-free, but per-character table lookups carry a state dependency and are slower than the native literal scan, so the most common text, without credentials, gets slower. +- **A memo rebuilt per query**: with accepted tokens between digit-free `sk-` prefixes, every query's digit search reaches the end of the text, which grows quadratically. +- **Building private-key masks in one buffer with `TextDecoder`**: one string per block, but each decode's fixed cost exceeds shared-string slices. +- **`exec` for hits and `for…of` over memo slots**: they allocate match arrays and iterator results. + +## Consequences + +- The added cost on text without credentials is one native scan plus checks at literals; it cannot drop further without depending on character distribution. +- A new format adds its literal and a forward-only check to the format table; resume offsets and the hit table are derived. The literal-pattern unit test rejects quantifiers, and the benchmark rejects superlinear scans and extra allocation. +- The plugin creates and owns the matcher instance in `apply`; tests and the benchmark create one per sample and share no memo. diff --git a/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md new file mode 100644 index 0000000000..4da050e2e4 --- /dev/null +++ b/.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md @@ -0,0 +1,67 @@ +# Agent Note: 用户文本凭据识别的线性匹配与性能门禁 + +Status: implemented + +[English](2026-10-11-user-text-credential-matching.md) | 中文 + +## 问题 + +[ui-secret-mask](../../../../packages/client/ui-secret-mask/README.zh.md) 在每条已发送用户文本上识别凭据。UserText 调度器在每个被采纳的节点之后再查询一次匹配器,一段文本的成本是它全部查询之和。大部分文本不含凭据,所以首要目标是让不含凭据的文本尽量少付成本;其次是含凭据文本的成本只与凭据个数和长度成正比;对抗输入必须保持线性。约束:正则不回溯;按前缀剪枝;一段文本的全部查询合计线性;返回节点之前不分配内存。 + +## 决定 + +### 算法:每部分的做法与复杂度 + +| 部分 | 做法 | 一段文本全部查询的代价 | +|---|---|---| +| 找格式起点 | 所有起始字面量(`sk-`、`sk_live_` 等、`AIza`、`ghp_` 等、`github_pat_`、`glpat-`、`npm_`、`hf_`、`AKIA`/`ASIA`、`LTAI`、`AKID`、`xox?-`、`whsec_`、`eyJ`、`-----BEGIN `、`://`)按共同前缀分组成一个只含字面量的交替正则,用 `test` 扫描 | Θ(n) 次原生比较,没有量词因而不回溯;相邻两次查询至多重读一个字面量 | +| 重叠的字面量 | 字面量的后缀若是另一个字面量的开头(`sk-`、`glpat-`、`xox?-` 的 `-` 与 `-----BEGIN `),扫描从该后缀处继续;续扫位置在模块加载时由字面量表算出 | 每个命中至多回退一个字符 | +| 识别命中的字面量 | 命中末尾两个码元查表;只有共享结尾的三组(`t_`、`e_`、`IA`)再用 `startsWith` 区分 | 每个命中 O(1) | +| 格式校验 | 单词边界、长度、数字位置、`.eyJ` 分隔用数值比较;私钥标签至多读 52 个字符,协议名至多回看 16 个字符;字符段用粘性 `[字符类]*` 原生测量,模式在第一个不属于该类的字符处停止,后面没有内容,不回溯 | 每个命中 O(1) 加字符段测量 | +| 字符段、下一个数字、下一行 `END` | 每个匹配器实例用一个 `Int32Array` 按文本记忆:`[A-Za-z0-9_-]` 四个槽(JWT 同时用三段),其余字符类各一个槽,另记下一个数字和下一行有效 `END` 的位置;这些是文本本身的事实,跨查询复用,查询换成另一段文本时清空 | 每类字符每个字符至多测量一次 | +| 地址密码 | `://` 在查询起点之前、密码在起点之后时,先确认起点后面紧跟 `:`、非空密码和 `@`,才回看用户名找 `://`;起点落在 `://` 中间时直接检查 | 回看至多 258 个字符,且只在 `:密码@` 紧跟起点时发生 | +| 合并候选 | 候选按起点顺序处理;地址密码在其 `://` 之后开始,延后到扫描越过它的起点,此前不会出现另一个 `://`(用户名和密码不含 `/`);重叠的候选并入最早的候选并使用其遮挡方式;范围到文本末尾即停止扫描 | 每个候选 O(1),不建列表 | +| 遮挡串 | 只由前缀格式组成的范围全是 ASCII 且没有换行,遮挡串是前 8 个字符的切片加一个共享星号串的切片;私钥正文用原生模式跳过普通字符,每行取一个"星号加换行"共享串的切片;地址密码和其他混合范围逐字符计数码点 | Θ(遮挡字符数 + 行数),与输出同阶 | + +### 内存 + +- 返回节点之前不分配:`test` 不产生匹配数组,记忆槽是预先分配的整数数组,遍历用下标而不是迭代器,候选范围存在局部数值里。 +- 每个凭据只分配结果:节点、`data` 对象和遮挡串。单行凭据的遮挡串是两个切片的拼接;多行遮挡每行再加一个切片和一次拼接。 +- 每个实例保留最近一次查询的文本引用,直到查询另一段文本。 + +### 取舍 + +- **扫描交给原生正则,判断交给 JavaScript**:V8 中逐字符的 JavaScript 循环比原生字面量扫描和原生字符段测量慢;凡是与输入长度成正比的工作(找起点、量字符段、跳过私钥正文)都用不回溯的原生模式,JavaScript 只做每个命中常数次的判断。 +- **只依赖格式本身的剪枝**:起点由格式字面量决定,不按字符在自然文本中的频率挑锚点,因此任何字符分布的文本都付同样的线性成本。 +- **记忆按文本而不按查询**:一次查询内的记忆不能阻止后续查询重新测量同一段字符;以文本为键、由实例持有,换文本即清空,代价只是保留一个字符串引用。 +- **遮挡串用共享串切片**:比先写入缓冲区再整体解码更快;多行遮挡的分配与行数成正比,仍属于输出本身。 + +### 性能门禁 + +[benchmarks/user-text](../../../../benchmarks/user-text/user-text.bench.client.ts) 在 `node 24 / benchmarks` 必跑 lane 中运行。编译后的 worker 使用生产的 UserText 注册表和全部已发布匹配器(会话、文件、文件夹、skill、命令、空白、凭据),在纯 Node 下分两个进程运行:计时与分配。 + +| 项 | 内容 | +|---|---| +| 负载 | 无凭据:普通消息,以及散文、代码、base64、Markdown、日志、JSON、shell 长文本。含凭据:每条消息含一种凭据(模型密钥、GitHub 令牌、云密钥 ID、JWT、地址密码、私钥块),以及成批的 `.env` 密钥。对抗:针对每种格式的前缀、长度与分隔规则构造的重复输入,两种长度。全部由常量生成,凭据样本运行时拼接 | +| 计时 | 每个样本新建注册表、文档和匹配器实例,只计求值;每个负载分别测有无凭据匹配器,取多个样本中最快的一个,并记录同一区间的进程 CPU 时间 | +| 分配 | 单独进程,`--expose-gc`,semi-space 固定为大于任何一次求值的大小;预热后 GC,再单独驱动匹配器回答全部查询一遍,取新生代增量;用 GC 事件的时间戳确认区间内没有 GC | +| 断言 | 无凭据:绝对预算,以及"有/无凭据匹配器"的耗时比上限;含凭据:绝对预算,密钥数翻倍时的耗时比;对抗:绝对预算与翻倍耗时比;分配:底噪加每个凭据、每个遮挡内换行和每个遮挡字符的上限 | +| 排除 | React 渲染、浏览器绘制与布局;分配结果只用于断言并输出到控制台,不进 HTML 报告 | + +预期值来自 x64 开发机。CI 时间预算按共享比例与余量换算;耗时比、翻倍比和分配预算不随机器缩放。负对照:同一 benchmark 指向正则实现或"每次查询新建记忆"的实现时都会失败。等价性测试经生产调度器逐节点比较本实现与正则实现([regex-oracle.client.ts](../../../../packages/client/ui-secret-mask/tests/regex-oracle.client.ts)),并对每个查询起点单独比较。 + +## 考虑过的替代方案 + +- **每次查询对每个格式各跑一个带量词的正则**:没有命中的正则每次都扫到文末,凭据多时平方增长;长度量词在失败时回溯。 +- **把全部格式合成一个带量词的大正则**:一次扫描能找到最左匹配,但各分支的量词失败时仍回溯。 +- **先找稀有字符再回看前缀**:普通文本扫描更快,但成本取决于字符分布,`-`、`_` 密集的文本明显变慢。 +- **纯 JavaScript 的 Aho–Corasick 自动机**:可以零分配,但逐字符查表有状态依赖,比原生字面量扫描慢,最常见的无凭据文本反而变慢。 +- **每次查询新建记忆**:被接受的 token 之间夹着无数字的 `sk-` 时,每次查询的数字查找都扫到文末,平方增长。 +- **用 `TextDecoder` 从缓冲区一次生成私钥遮挡串**:每块只分配一个字符串,但每次解码的固定开销高于共享串切片。 +- **用 `exec` 取命中、用 `for…of` 遍历记忆槽**:分别分配匹配数组和迭代器结果。 + +## 影响 + +- 无凭据文本的额外成本是一遍原生扫描加字面量处的校验;不依赖字符分布就无法再降。 +- 新增格式要在格式表里加字面量和只向前的校验;续扫位置与命中识别表自动生成。字面量正则的单测拒绝量词,benchmark 拒绝超线性扫描和多余分配。 +- 匹配器实例由插件在 `apply` 中创建并持有;测试和 benchmark 每个样本新建实例,不共享记忆。 diff --git a/.agents/skills/dsh-pre-push-checks/SKILL.md b/.agents/skills/dsh-pre-push-checks/SKILL.md index 6567dde5dc..3d55a9dece 100644 --- a/.agents/skills/dsh-pre-push-checks/SKILL.md +++ b/.agents/skills/dsh-pre-push-checks/SKILL.md @@ -37,6 +37,7 @@ When the outgoing change adds or changes a resource-owning or asynchronous test, - **Expected-output placement:** a test whose selected recorded Session generation is replay input and expected persisted output belongs under top-level `snapshots/`, with `snapshot.yml` naming its shipped `dsh` profile and composition/header pin. Canonical parent files are `session[.vN].jsonl`, children are `session.[.vN].jsonl`, and the harness selects the highest generation per role. ARIA, geometry, generator, CLI, and unit expectations without that Session round trip stay beside their owning test under `tests/expected/`; do not place them in `snapshots/` or give them a `*.snapshot.ts` owner. Use the owning `test:expected`, `test:web`, or `test` lane. - **Profile and configuration placement:** cross-package behavior of a shipped `dsh` profile belongs under `apps/cli/tests/profiles/`; a package-specific Loader composition belongs under that package's `tests/fixtures/`. User-facing optional overlays live under `apps/cli/config/examples/` and pair with a guide under `docs/user/`. - **Package manifests, public exports, build configuration, worker/bin entries, or built runtime paths:** run `pnpm run build`, the relevant hygiene checks, and the owning built-artifact smoke. +- **Repository test and script types:** `pnpm run build:artifacts` checks package projects only. Before claiming completion of TypeScript changes, run `pnpm run build:check` after the latest `build:artifacts`, or run `pnpm run build`; `build:check` reads the existing `build:artifacts` output and never rebuilds it. - **Real provider or agent behavior:** run the relevant `pnpm run test:e2e` target when credentials are available; never print secrets. Do not manually repeat a passing check merely because commit or push follows. In particular, do not run typecheck immediately before pushing solely to duplicate the pre-push hook. diff --git a/.github/workflows/build-exe-for-python-sdk.yml b/.github/workflows/build-exe-for-python-sdk.yml index 9ea51311b6..0c869d008a 100644 --- a/.github/workflows/build-exe-for-python-sdk.yml +++ b/.github/workflows/build-exe-for-python-sdk.yml @@ -153,11 +153,15 @@ jobs: retention-days: 7 # Blacksmith x64 CI builds use 2 vCPU for compilation, bundling, and wheel smokes. + # Release macOS builds use larger GitHub runners; ordinary CI and direct + # builder dispatches retain the standard native target matrix. build: needs: [plan, sdk-wheel] name: ${{ matrix.target }} runs-on: >- - ${{ inputs.ci && !inputs.release && matrix.target == 'node24-linux-x64' + ${{ inputs.release && matrix.target == 'node24-macos-x64' && 'macos-15-large' + || inputs.release && matrix.target == 'node24-macos-arm64' && 'macos-15-xlarge' + || inputs.ci && !inputs.release && matrix.target == 'node24-linux-x64' && vars.DSH_CI_FAILOVER_LINUX == 'blacksmith' && 'blacksmith-2vcpu-ubuntu-2404' || inputs.ci && !inputs.release && matrix.target == 'node24-win-x64' && vars.DSH_CI_FAILOVER_WINDOWS == 'blacksmith' && 'blacksmith-2vcpu-windows-2025' @@ -262,7 +266,7 @@ jobs: DSH_BUILD_CLIENT_PROFILE: official run: >- pnpm exec tsx scripts/build-exe-for-python-sdk.ts --targets=${{ matrix.target }} - ${{ inputs.ci && github.event_name == 'pull_request' && '--artifacts-only' || '' }} + ${{ inputs.ci && github.event_name == 'pull_request' && '--build-artifacts' || '' }} - name: Resolve platform outputs (POSIX) id: runtime-posix diff --git a/.github/workflows/build-preview-cloudflare.yml b/.github/workflows/build-preview-cloudflare.yml index e8ad9bd2ec..c2ff5d3231 100644 --- a/.github/workflows/build-preview-cloudflare.yml +++ b/.github/workflows/build-preview-cloudflare.yml @@ -71,7 +71,7 @@ jobs: # build:preview packs the image through the packer's installed bin # (lib/bin.js), so neither half exists before the artifact build runs. - name: Build workspace - run: pnpm run build --artifacts-only + run: pnpm run build:artifacts - name: Build the preview page and pack the VFS image env: diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 397ac07b45..726bd070a5 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -107,7 +107,7 @@ jobs: # the built artifact under plain Node, resolving plugins through real package # exports — the shape a real consumer runs. That requires a prior build. - name: Build (lib for the e2e example bins) - run: ${{ github.event_name == 'pull_request' && 'pnpm run build --artifacts-only --profile official' || 'pnpm run build:official' }} + run: ${{ github.event_name == 'pull_request' && 'pnpm run build:artifacts --profile official' || 'pnpm run build:official' }} - name: Prepare Office runtime run: pnpm run prepare:primary-runtime --target linux-x64 --output .cache/e2e-office diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7fd8c9ab8a..b9def1dec1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -146,7 +146,7 @@ jobs: run: pnpm run release:verify --family dsh - name: Build - run: ${{ github.event_name == 'pull_request' && 'pnpm run build --artifacts-only --profile official' || 'pnpm run build:official' }} + run: ${{ github.event_name == 'pull_request' && 'pnpm run build:artifacts --profile official' || 'pnpm run build:official' }} # Concurrency here is rehearsal-only: the credentialed publish workflows # invoke release:pack without the flag and keep the strictly serial path. diff --git a/.github/workflows/windows-package.yml b/.github/workflows/windows-package.yml index 56bcb47a96..b07aa91450 100644 --- a/.github/workflows/windows-package.yml +++ b/.github/workflows/windows-package.yml @@ -1,27 +1,25 @@ -name: Windows installer (unsigned) +name: Windows installer on: workflow_dispatch: inputs: - build_version: - description: 'Build version: auto generates a version; otherwise enter a full version' - type: string - default: auto - required: true - deployment: - description: Update policy deployment + preset: + description: 'Machine preset (configured on the packaging runner)' type: choice options: [test, production] default: test required: true - policy_origin: - description: 'Required update policy HTTPS origin (no path)' - type: string + signing: + description: 'unsigned: test installer; signed: use the configured EV hardware token' + type: choice + options: [unsigned, signed] + default: unsigned required: true - login_origins: - description: 'Required for test: comma-separated allowed login HTTPS origins' + build_version: + description: 'Version: auto recommended; or checkout product version / e.g. 0.2.1-alpha.1.20261009.1 (prefix must match checkout)' type: string - required: false + default: auto + required: true permissions: contents: read @@ -39,7 +37,20 @@ jobs: shell: pwsh env: DSH_TELEMETRY_DISABLED: '1' + DSH_PACKAGING_PRESET: ${{ inputs.preset }} + PACKAGE_SIGNING: ${{ inputs.signing }} steps: + - name: Reset packaging checkout + working-directory: ${{ runner.temp }} + run: | + $workspace = [IO.Path]::GetFullPath($env:GITHUB_WORKSPACE) + $parent = [IO.Path]::GetFullPath($env:RUNNER_WORKSPACE) + if ([IO.Path]::GetDirectoryName($workspace) -ne $parent) { throw 'Checkout must be a direct child of RUNNER_WORKSPACE' } + for ($item = [IO.DirectoryInfo]::new($workspace); $null -ne $item; $item = $item.Parent) { + if ($item.Exists -and ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Checkout ancestors cannot be links' } + } + node -e "const fs = require('node:fs'); fs.rmSync(process.argv[1], { recursive: true, force: true, maxRetries: 3 }); fs.mkdirSync(process.argv[1])" $workspace + if ($LASTEXITCODE -ne 0) { throw 'Checkout cleanup failed' } - uses: actions/checkout@v7.0.1 id: checkout with: @@ -55,25 +66,26 @@ jobs: run: | pnpm install --frozen-lockfile exit $LASTEXITCODE - - name: Validate inputs and prepare public package settings + - name: Validate preset and resolve build version id: settings env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} - PACKAGE_DEPLOYMENT: ${{ inputs.deployment }} - PACKAGE_POLICY_ORIGIN: ${{ inputs.policy_origin }} - PACKAGE_LOGIN_ORIGINS: ${{ inputs.login_origins }} run: node apps/desktop/scripts/prepare-windows-ci.mjs - name: Check packaging configuration and toolchain env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} run: | - pnpm run package:desktop:win:x64:unsigned --check --build-version "$env:PACKAGE_VERSION" + $packageArgs = @('run', 'package:desktop:win:x64', '--check', '--build-version', $env:PACKAGE_VERSION) + if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' } + pnpm @packageArgs exit $LASTEXITCODE - name: Build installer and verify packaged runtime env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} run: | - pnpm run package:desktop:win:x64:unsigned --build-version "$env:PACKAGE_VERSION" + $packageArgs = @('run', 'package:desktop:win:x64', '--build-version', $env:PACKAGE_VERSION) + if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' } + pnpm @packageArgs exit $LASTEXITCODE - name: Retain packaging diagnostics if: always() && steps.checkout.outcome == 'success' @@ -84,7 +96,8 @@ jobs: path: apps/desktop/.desktop-build/packaging-runs/ if-no-files-found: warn retention-days: 14 - - name: Retain verified installer + - name: Retain verified unsigned installer + if: success() && inputs.signing == 'unsigned' uses: actions/upload-artifact@v7.0.1 with: name: windows-x64-unsigned-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }} @@ -92,9 +105,12 @@ jobs: path: apps/desktop/.desktop-build/targets/win-x64/unsigned-artifacts/*.exe if-no-files-found: error retention-days: 14 - - name: Remove generated package settings - if: always() && steps.checkout.outcome == 'success' - run: | - if (Test-Path -LiteralPath apps/desktop/.env.windows) { - Remove-Item -LiteralPath apps/desktop/.env.windows - } + - name: Retain verified signed installer + if: success() && inputs.signing == 'signed' + uses: actions/upload-artifact@v7.0.1 + with: + name: windows-x64-signed-${{ steps.settings.outputs.version }}-${{ github.run_id }}-${{ github.run_attempt }} + include-hidden-files: true + path: apps/desktop/.desktop-build/targets/win-x64/artifacts/*.exe + if-no-files-found: error + retention-days: 14 diff --git a/AGENTS.md b/AGENTS.md index f1bfcf9aeb..724faca086 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,9 @@ pnpm run test:snapshot:record # re-record expected outputs (needs key) pnpm run typecheck pnpm run lint pnpm run duplication # cross-file TypeScript clone detection -pnpm run build # tsc emits lib/types, tsdown bundles runtime +pnpm run build # build:artifacts + build:check, concurrently +pnpm run build:artifacts # artifacts: tsc emits lib/types, tsdown bundles runtime, Web +pnpm run build:check # typecheck aggregate tests/scripts against current build:artifacts output pnpm run hygiene # publint + workspace/package/dependency checks + NodeNext consumer check pnpm run check:windows-wine # ONLY when diagnosing a known Windows failure (needs wine); CI owns this signal pnpm run doc-sync # documentation gates (scripts/run-gates.ts) @@ -100,7 +102,7 @@ pnpm run test:docs # quick documentation checks (no build; doc-quick aggreg pnpm run website:build # VitePress build (doubles as dead-link check) pnpm dsh --profile headless "task" # run one task from source (needs DEEPSEEK_API_KEY) pnpm run demo:ptc -- "task" # headless PTC mode run (needs key) -pnpm run dev:web | dev:desktop # build, then launch; Web also rebuilds client bundles on edits. start:web | start:desktop skip the build +pnpm run dev:web | dev:desktop # build:artifacts, then launch; Web also rebuilds client bundles on edits. start:web | start:desktop skip the build make web|dev-web|desktop|dev-desktop|build # the same commands; ARGS='--no-open' forwards options ``` @@ -115,6 +117,7 @@ Before pushing, follow [dsh-pre-push-checks](.agents/skills/dsh-pre-push-checks/ - Match evidence to the surface: focused behavior tests, model/user-output snapshots, `doc-sync` for docs, built smokes for published paths, and real-API e2e for providers. - Never default to the full suite or repeat a passing check for commit or push. CI owns exhaustive coverage and the platform matrix; rehearse all locally only by explicit request, for CI diagnosis, or for an irreducibly repository-wide change. - `test:coverage`, not `test`, is the CI coverage gate ([why](docs/testing.md)). +- Develop with `build:artifacts`; before claiming completion, run `build:check` after the latest `build:artifacts`, or `build` ([layout](docs/development.md#typescript-project-layout)). - **Web browser automation and GIF recording:** launch with `pnpm dsh web --patch apps/web/tests/pin-browse-picker.overlay.yml` to use the [in-page directory picker](apps/web/tests/pin-browse-picker.overlay.yml); omit this override only when testing native picker behavior explicitly. ## Secrets / .env diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index a07a264ca8..3fd65e81a2 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -5,7 +5,7 @@ DeepSeek Harness is licensed under [MIT](LICENSE). It depends on the third-party software listed below. Each project remains under its own license; nothing in this file changes those terms. -This file lists **direct** dependencies declared by the workspace, the explicitly disclosed official Claude Code platform payload closure, and the Bundled Python distributions. It is generated by `scripts/gen-third-party-notices.ts`: a pre-commit hook regenerates it whenever a staged file changes one of its inputs, and `scripts/gen-third-party-notices.spec.ts` asserts in the test lane that the committed bytes match. Deleting a manifest runs no hook, so that case is caught by the assertion instead. Run `pnpm run verify-third-party-notices` for the standalone check. +This file lists **direct** dependencies declared by the workspace, the explicitly disclosed official Claude Code platform payload closure, and the Bundled Python distributions. It is generated by `scripts/gen-third-party-notices.ts`, and `scripts/gen-third-party-notices.spec.ts` asserts in the test lane that the committed bytes match. Run `pnpm run gen-third-party-notices` after changing one of its inputs, or `pnpm run verify-third-party-notices` for the standalone check. The complete npm transitive closure, including the Landlock launcher workspace, is recorded with exact pinned versions in [`pnpm-lock.yaml`](pnpm-lock.yaml) — inspect it with `pnpm licenses list`. The Python SDK closure is recorded separately in [`python/sdk/uv.lock`](python/sdk/uv.lock). diff --git a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts index 806f081a77..764f353345 100644 --- a/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/ptc.e2e.ts @@ -293,9 +293,9 @@ describe('PTC mode typed values: keyless real-process contracts', () => { await ctx.plugin(CordisInspectProviders) await ctx.plugin(ToolCordis) const agent = { + ctx, id: SessionId('ptc-cordis'), session: ctx.sessions.create(SessionId('ptc-cordis'), { meta: { cwd: process.cwd() } }), - ctx, } as Agent const value = completion(await runCode(ctx, ` diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 0327e3dc0e..d314ec717e 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -15,8 +15,8 @@ en: 069fdfd72d2ea26a zh: 76ae549d43c99bb4 /deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies: - en: cc2d4a2d5aecfaa0 - zh: 2a1d612560f6d95d + en: ef26e0055f9401ee + zh: b358a68cf30ed720 /deepseek-harness-desktop/bundled-command-runtime: en: 09f0b75af9f0ed14 zh: 60bbc2e67d5e87a8 @@ -42,8 +42,8 @@ en: 4cd8a8da6977928d zh: 9f624855a2edac37 /deepseek-harness-desktop/package/release-versions: - en: d938302f92fc3a1a - zh: 29df50bc8791baa7 + en: fdc1fadc506d1087 + zh: 46d5cb8a60ddf7cf /deepseek-harness-desktop/package/local-macos-dmg-without-release-signing: en: 57869a5e3885f843 zh: 7cfc01b2dcbebd78 @@ -51,20 +51,20 @@ en: 5f05072ec82cc62d zh: a3d63b58d1ef2db7 /deepseek-harness-desktop/package/runtime-file-selection: - en: 8b4cca1467f0bea6 - zh: fa3487fc56a53fc4 + en: 2f957ee7e7a4e6e2 + zh: a3b01674d54bec6a /deepseek-harness-desktop/package/upload-updates: en: f48baa680e841b0d zh: 25ded1aeaac6dad1 /deepseek-harness-desktop/package/unsigned-windows-test-installer: - en: fb6de542360dbae7 - zh: 0e17d7765fb10c48 + en: 2e30de3155c32344 + zh: be88a9d7f8682e75 /deepseek-harness-desktop/package/windows-installer-interface: en: 1fc1db8f54475c8f zh: dd834ed206070396 /deepseek-harness-desktop/package/windows-ev-signing: - en: 64836513eb7eda6e - zh: 6ebb9184a7aa51de + en: 5c12ccf2f4482606 + zh: efea2cb823bda62f /deepseek-harness-desktop/package/desktop-runtime-preparation: en: 9a71990bee9867a7 zh: 76c5c1fdff6e6908 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 8a542cfd3f..82ad83eec5 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -70,7 +70,7 @@ The payload follows the Desktop release. `runtime.json` records the Desktop vers The private Desktop `runtime/bin` directory is added only to package-installation processes, not the Host PATH inherited by PTC and agent shells. This tool does not change PATH, environment variables or user package-manager configuration. pnpm retains its own defaults and user settings for global packages, executable entries and its store, including native errors when the environment does not support global installation. There is no separate dependency updater. [The primary-runtime decision](../../.agents/notes/implemented/feature/2026-09-14-desktop-primary-runtime.md) records these choices. -Node prepares the bundled interpreters and Python libraries without a system Python or pip. [The download lock](../../scripts/primary-runtime/lock.json) pins interpreter archives, Python distribution versions and target-specific wheel URLs and hashes; the shared builder resolves pnpm from the root development dependency pin. The root package-manager version and the Desktop pin are checked for agreement. Wheel filenames and distribution versions must agree for every target. Preserve key order within the selected target, wheel records and distribution map, plus wheel-entry order; these affect payload identity, while top-level lock key order does not. Library wheels unpack into site-packages, retaining auxiliary files under each wheel's `.data/scripts` directory without generating command wrappers. Other installation schemes are rejected. Native-target checks verify the locked wheel set and versions, permit the interpreter's bundled pip, and check the Python version, Office document read/write operations and dependency completeness without writing bytecode after staging cleanup and again after macOS signing. The standalone Node executable receives the JIT entitlement required by V8; the x64 target also receives `com.apple.security.cs.allow-unsigned-executable-memory` for executable code pages, including under Rosetta. ARM64 Node and Office helpers retain JIT-only permissions. Cross-target execution and signed installation require the target release host. Both `dev:desktop` and `start:desktop` prepare `.desktop-build/targets//runtime/primary-runtime` before launching Electron; first use may download locked dependencies. An unfinished preparation cannot report a successful launcher exit. +Node prepares the bundled interpreters and Python libraries without a system Python or pip. [The download lock](../../scripts/primary-runtime/lock.json) pins interpreter archives, Python distribution versions and target-specific wheel URLs and hashes; the shared builder resolves pnpm from the root development dependency pin. The root package-manager version and the Desktop pin are checked for agreement. Wheel filenames and distribution versions must agree for every target. Preserve key order within the selected target, wheel records and distribution map, plus wheel-entry order; these affect payload identity, while top-level lock key order does not. Library wheels unpack into site-packages, retaining auxiliary files under each wheel's `.data/scripts` directory without generating command wrappers. Other installation schemes are rejected. macOS signs the versioned Python executable once, retaining the [two interpreter aliases](../../packages/skill/tool-workspace-dependencies/README.md) in external resources and installed copies. POSIX native-target checks require relative interpreter aliases. All native-target checks exercise command names, child execution and a pip-enabled venv, verify the locked wheel set and versions, permit the interpreter's bundled pip, and check the Python version, Office document read/write operations and dependency completeness without writing bytecode after staging cleanup and again after macOS signing. The standalone Node executable receives the JIT entitlement required by V8; the x64 target also receives `com.apple.security.cs.allow-unsigned-executable-memory` for executable code pages, including under Rosetta. ARM64 Node and Office helpers retain JIT-only permissions. Cross-target execution and signed installation require the target release host. Both `dev:desktop` and `start:desktop` prepare `.desktop-build/targets//runtime/primary-runtime` before launching Electron; first use may download locked dependencies. An unfinished preparation cannot report a successful launcher exit. The shared Desktop/SDK runtime builder omits directories named `tests` beneath NumPy and pandas before copying or signing the payload, and removes their rows from each distribution’s `RECORD`. It retains `numpy.testing`, `pandas.testing`, `pandas._testing`, native extensions and licenses. Complete upstream suites are unavailable; native checks verify the retained testing APIs, absence of test directories and existence of recorded files. @@ -217,9 +217,9 @@ A production release publishes the product version and takes no `--build-version Version derivation does not change the fixed update channel or `nightly.yml` / `nightly-mac.yml` filenames. SemVer orders `0.1.6-alpha.1 < 0.1.6-alpha.1.20260916.1 < 0.1.6-alpha.2`, and a stable base's test version precedes that stable release. Clients only accept a greater version: replacing a feed cannot move an installed higher version to a lower corrected version. Such clients need manual installation; keep automatic downgrade disabled. The [archived version decision](../../.agents/notes/archived/process/2026-09-16-desktop-release-version-derivation.md) explains why the channel does not supply the prerelease identifier. -Except for local unsigned macOS builds, packaging, upload, and manual macOS signature verification read `apps/desktop/.env.windows` or `.env.macos`, selected by target platform. Copy the [Windows template](.env.windows.example) or [macOS template](.env.macos.example) and fill in the local settings; Git ignores both local files, and packaged artifacts exclude them. Release fields come only from the target file, without fallback to system or shell variables; `PATH`, proxies, and build-tool settings remain inherited. The published version is an argument rather than a release field, and upload reads it from the completion record the packaging run wrote. Files use UTF-8 with optional BOM; relative certificate, SignTool, Apple API key, and keychain paths resolve from `apps/desktop`, values are not shell-expanded, and passwords containing `#` or spaces need quotes. CI also creates the target file before invoking packaging. +Except for Windows packaging with a selected machine preset and local unsigned macOS builds, packaging, upload, and manual macOS signature verification read `apps/desktop/.env.windows` or `.env.macos`, selected by target platform. Copy the [Windows template](.env.windows.example) or [macOS template](.env.macos.example) and fill in the local settings; Git ignores both local files, and packaged artifacts exclude them. Release fields come only from the selected configuration files, without fallback to system or shell variables; `PATH`, proxies, and build-tool settings remain inherited. The published version is an argument rather than a release field, and upload reads it from the completion record the packaging run wrote. Files use UTF-8 with optional BOM; relative certificate, SignTool, Apple API key, and keychain paths resolve from `apps/desktop`, values are not shell-expanded, and passwords containing `#` or spaces need quotes. Windows CI reads machine presets as described below. -Every package command checks the application ID and its mode-specific update and signing configuration before building or downloading, then probes the external tools the run will use: the archive reader, and on a Windows target the installer compiler. macOS checks the identity, Team ID, one complete notarization strategy, readable local `CSC_LINK` p12 file, explicit `CSC_KEY_PASSWORD`, and referenced API key and keychain files; Windows checks the public code-signing certificate, SignTool file, container name, and PIN format. Windows preparation-only builds and explicit unsigned builds on either platform do not require signing credentials. Configuration checks do not authenticate the PIN, log in to the token, unlock a keychain, or contact Apple; actual signing and notarization perform those checks. `--build-version auto` does contact the destination bucket, including under `--check`. Run the same checks separately: +Every package command checks the application ID and its mode-specific update and signing configuration before building or downloading, then probes the external tools the run will use: the archive reader, and on a Windows target the installer compiler. macOS checks the identity, Team ID, one complete notarization strategy, readable local `CSC_LINK` p12 file, explicit `CSC_KEY_PASSWORD`, and referenced API key and keychain files; Windows checks the public code-signing certificate, SignTool file, container name, and PIN format. Windows preparation-only builds and explicit unsigned builds on either platform do not require signing credentials. Configuration checks do not authenticate the PIN, log in to the token, unlock a keychain, or contact Apple; actual signing and notarization perform those checks. Without a Windows machine preset, `--build-version auto` contacts the destination bucket, including under `--check`. Run the same checks separately: ```sh pnpm --dir apps/desktop run check:package @@ -274,7 +274,7 @@ The served `time` is the real packing time, so pnpm 11's default 24-hour `minimu ### Runtime file selection -Desktop packs workspace packages locally and installs external dependencies through the target's bundled Node and pnpm. [Desktop's file policy](scripts/runtime-file-policy.ts) then filters the immutable `resources/app.asar/dsh/node_modules` copy before signing and integrity sealing. It omits TypeScript declarations, recognized JavaScript/CSS/TypeScript source maps, TypeScript build caches, Domino's test directory, selected native compiler outputs, and node-pty prebuilds for other platforms. Non-Windows targets also omit `node-pty/third_party/conpty`; Windows targets retain that directory. It preserves runtime JavaScript, target native modules and their DLL/EXE helpers, WASM, unknown assets, licenses, and notices. Dependency manifests pass through electron-builder's metadata cleanup before integrity sealing, so archiving preserves their recorded bytes. The policy does not alter npm tarballs, the bundled package manager, or user-installed plugin files. +Desktop packs workspace packages locally and installs external dependencies through the target's bundled Node and pnpm. [Desktop's file policy](scripts/runtime-file-policy.ts) then filters the immutable `resources/app.asar/dsh/node_modules` copy before signing and integrity sealing. It omits TypeScript declarations, recognized JavaScript/CSS/TypeScript source maps, TypeScript build caches, Domino's test directory and Yarn development metadata, selected native compiler outputs, and node-pty prebuilds for other platforms. Non-Windows targets also omit `node-pty/third_party/conpty`; Windows targets retain that directory. It preserves runtime JavaScript, target native modules and their DLL/EXE helpers, WASM, unknown assets, licenses, and notices. Dependency manifests pass through electron-builder's metadata cleanup before integrity sealing, so archiving preserves their recorded bytes. The policy does not alter npm tarballs, the bundled package manager, or user-installed plugin files. The [Electron shell file list](scripts/electron-builder-config.mjs) excludes recognized JavaScript/CSS/TypeScript source maps and TypeScript build caches from the separate `resources/app.asar/node_modules` dependency collection. These exclusions preserve runtime code, native modules, WASM, data files (including ordinary `.map` assets), licenses, and notices; [shell archive tests](tests/shell-file-selection.spec.ts) check retained bytes and exclusions. @@ -364,9 +364,15 @@ The command reads `.env.windows` and requires `DSH_DESKTOP_APP_ID` and the [mand Run `pnpm install --frozen-lockfile`, then `pnpm run package:desktop:win:x64:unsigned --check` to validate configuration and tooling before the full command above. Packaging performs its own complete build and isolated runtime smoke without an online model. Stage logs remain under `.desktop-build/packaging-runs/`; a successful build alone does not qualify the installer. Dependency installation and runtime preparation need access to npm, GitHub release assets and nodejs.org; use the existing registry and proxy configuration when the network requires it. Caches and tool locations belong to the build machine, not tracked personal paths. -The [manual Windows workflow](../../.github/workflows/windows-package.yml) selects a self-hosted Windows x64 runner with the dedicated `dsh-win-package-trial` label and calls the same unsigned command. Provision PowerShell 7 and the tools listed above before starting the runner. It requires the policy deployment and HTTPS origin; test deployments also require comma-separated login origins. These public inputs generate a temporary `.env.windows` without signing or upload credentials. `build_version` defaults to `auto`, using the CI identifier described in [Release versions](#release-versions). An explicit version uses the existing product-version validator. The resolved version appears in the run summary before packaging; manifests remain unchanged. +The [manual Windows workflow](../../.github/workflows/windows-package.yml) selects the dedicated Windows x64 runner label `dsh-win-package-trial` and the machine preset `test` or `production`. Choose `unsigned` (default) or `signed`; signed mode uses the existing EV token preflight, signature cache and failure interlock. It does not publish or upload a release. `build_version` defaults to `auto`, using the CI identifier in [Release versions](#release-versions); an explicit value may be the checkout's product version or an extended build version such as `0.2.1-alpha.1.20261009.1` for product `0.2.1-alpha.1`. The version prefix must match the selected checkout; validation errors show its current example. Manifests remain unchanged. -After this workflow reaches the default branch, select it in Actions, choose the source branch, fill the inputs and click Run workflow. It has no push or PR trigger and leaves existing automatic CI unchanged. Packaging logs and successful EXE artifacts are retained for 14 days; installation, signing and publication are separate operations. Run it once from the default branch and inspect the retained logs and installer before relying on Actions packaging. Checkout cleans the runner-owned source directory, including ignored files; never point it at a development checkout. Runs share one concurrency group without cancelling an active build; only one run can remain pending, and a newer dispatch replaces that pending run. Diagnostics are uploaded only after a successful clean checkout, and generated settings are removed even when preparation fails after writing them. +Select the workflow in Actions, choose the source branch, preset, signing mode and version, then click Run workflow. Before merging input changes, test the pushed branch with `gh workflow run windows-package.yml --ref -f preset=test -f signing=unsigned -f build_version=auto`; verify the web form after merging. There is no push or PR trigger. Logs and successful EXEs are retained for 14 days. Inspect the retained logs and installer before relying on packaging; installation is separate. Before checkout, Node removes the runner-owned source directory without following dependency junctions; the workflow validates its location and rejects linked ancestors. Never point it at a development checkout. Runs share one concurrency group without cancelling an active build; only one run remains pending, and a newer dispatch replaces it. Diagnostics upload requires a successful clean checkout. Machine settings stay outside the checkout and are never uploaded as artifacts. + +The shared packaging runner assumes trusted internal-team code and operators. Under this assumption, credential and device isolation are deferred and the residual risk is accepted (tracked in #5973); signed/master-only access is not enforced. Unsigned mode skips signing-file loading but cannot prevent branch code running as the same Windows account from reading those files or accessing the token. SafeNet Single Logon may reuse authentication. Direct device calls can bypass the signing scripts and exhaust PIN retries; the persistent failure interlock only protects calls through those scripts. Cross-account token isolation and remaining retry counts are unverified. Reassess runner/account/device isolation before expanding access, executing untrusted contributions, changing runner sharing, or after suspicious activity. + +Set `DSH_PACKAGING_CONFIG_DIR` to the absolute machine configuration directory and `DSH_PACKAGING_PRESET` to `test` or `production` for local Windows commands. The loader reads `presets/.env`; signed commands additionally read `secrets/windows-signing.env`. Relative certificate and SignTool paths resolve beside the file declaring them. Public presets reject credentials, and the signing file cannot override public settings. Missing configuration fails without falling back to `.env.windows`; commands without a preset retain the existing dotenv behavior. Unsigned and preparation-only presets never read the signing file. Cache maintenance also reads only public preset settings. Test signed packages also require the existing download origin and release ID, but no upload credentials. Local preset commands with `--build-version auto` number from local artifacts only; Actions uses its run number and attempt. + +Run `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Root ` to prepare private `packaging/{presets,secrets,certificates}` and `cache/windows-signatures` directories and copy templates without overwriting existing files. Add `-CheckOnly` to inspect without writes. Fill the [preset templates](config/windows-packaging/test.env.example) and [signing template](config/windows-packaging/windows-signing.env.example) on the machine. Run `start-windows-packaging-runner.ps1 -RunnerRoot -ConfigRoot /packaging -CheckOnly` from the same scripts directory to inspect PowerShell 7.6.6 under the runner's `tools` directory, Node, Python, Git, tar and Visual C++ tools; packaging `--check` performs the remaining toolchain validation. Omit `-CheckOnly` to start the existing runner with an explicit config root and scrubbed inherited environment. Registration and tool installation are separate; these scripts never create tokens, alter system security settings or clear signing failure records. Use the signing cache maintenance command below to migrate existing entries before changing the preset's cache path. @@ -422,7 +428,7 @@ Insert and unlock the token before packaging. The electron-builder hook passes e Timestamp completion retries only a normally exited timestamp command returning failure or warning, at most three times with one- and two-second delays. Each attempt starts from the same verified primary signature. Launch errors, uncertain termination and verification failures stop immediately. SignTool operates on short private paths; publication copies verified bytes to the target volume before atomic replacement. Final Windows trust, certificate, timestamp and normalized full-file equality are required. Exhaustion stops packaging and preserves evidence without another hardware call. See the [signature completion decision](../../.agents/notes/implemented/process/2026-09-17-windows-signature-completion.md). -The PIN cannot contain `]`, a quote, or a line break because those characters delimit the SafeNet `/kc` value or its CMD argument. The CMD disables delayed expansion so a PIN containing `!` reaches SafeNet unchanged. Packaging withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation subprocesses, gives signing preflight, the dedicated runtime signing stages and electron-builder only the four configured inputs, gives the signing CMD only the validated signing fields in an otherwise scrubbed environment, clears those fields before SignTool starts, and redacts SignTool diagnostics. SafeNet still requires the PIN in the SignTool process command line. The local `.env.windows` stores the PIN in plaintext and needs restricted file access; CI uses a temporary file and deletes it after the job. Do not commit or share its contents or print credentials in logs. Configuration checks consume no token PIN attempts; signing still stops the batch on its first failure. +The PIN cannot contain `]`, a quote, or a line break because those characters delimit the SafeNet `/kc` value or its CMD argument. The CMD disables delayed expansion so a PIN containing `!` reaches SafeNet unchanged. Packaging withholds every `DSH_DESKTOP_WINDOWS_*` field from build and runtime-preparation subprocesses, gives signing preflight, the dedicated runtime signing stages and electron-builder only the four configured inputs, gives the signing CMD only the validated signing fields in an otherwise scrubbed environment, clears those fields before SignTool starts, and redacts SignTool diagnostics. SafeNet still requires the PIN in the SignTool process command line. The local `.env.windows` or machine-owned `secrets/windows-signing.env` stores the PIN in plaintext and needs restricted file access. CI reads the machine-owned file outside the checkout and retains it across jobs. Do not commit or share its contents or print credentials in logs. Configuration checks consume no token PIN attempts; signing still stops the batch on its first failure. Create a runnable application directory instead of an installer by using the matching `:dir` command, such as: diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index dbc68adf69..08a216217b 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -72,7 +72,7 @@ Desktop 展示精简的 `office` 路由及可具名调用的创作/操作子 Desktop 私有的 `runtime/bin` 目录仅添加到包安装进程,不进入 PTC 和 agent shell 从 Host 继承的 PATH。该工具不修改 PATH、环境变量或用户包管理器配置。pnpm 的全局包、命令入口和 store 保留自身默认值及用户设置,包括环境不支持全局安装时的原生错误。不提供独立依赖更新器。[第一方 Runtime 决策](../../.agents/notes/implemented/feature/2026-09-14-desktop-primary-runtime.zh.md)记录这些选择。 -Node 准备内置解释器和 Python 库,无需系统 Python 或 pip。[下载锁](../../scripts/primary-runtime/lock.json)固定解释器压缩包、Python 分发包版本及目标平台 wheel 的 URL 和哈希;共享构建器从根开发依赖中解析 pnpm 固定版本。测试检查根 package-manager 版本和 Desktop 固定版本保持一致。每个目标的 wheel 文件名必须与分发包版本一致。所选目标、wheel 记录及分发包映射内部的键顺序,以及 wheel 条目顺序都会影响产物身份,编辑时须保留;锁文件顶层键的顺序不影响该身份。库 wheel 解压到 site-packages,各 wheel 的 `.data/scripts` 目录保留辅助文件,不生成命令行包装器。其他安装方案会被拒绝。本机目标检查在清理暂存目录后以及 macOS 签名后验证锁定 wheel 的集合与版本,允许解释器自带的 pip,并检查 Python 版本、Office 文档读写和依赖完整性,不写入字节码。独立 Node 可执行文件获得 V8 所需的 JIT 权限;x64 目标还获得 `com.apple.security.cs.allow-unsigned-executable-memory`,允许可执行代码页,包括在 Rosetta 下运行时。ARM64 Node 和 Office 辅助程序保留仅 JIT 权限。跨目标执行和签名安装需要对应的发布主机。`dev:desktop` 和 `start:desktop` 都会在启动 Electron 前准备 `.desktop-build/targets//runtime/primary-runtime`;首次准备可能需要下载锁定的依赖。准备未完成时,启动命令不能报告成功退出。 +Node 准备内置解释器和 Python 库,无需系统 Python 或 pip。[下载锁](../../scripts/primary-runtime/lock.json)固定解释器压缩包、Python 分发包版本及目标平台 wheel 的 URL 和哈希;共享构建器从根开发依赖中解析 pnpm 固定版本。测试检查根 package-manager 版本和 Desktop 固定版本保持一致。每个目标的 wheel 文件名必须与分发包版本一致。所选目标、wheel 记录及分发包映射内部的键顺序,以及 wheel 条目顺序都会影响产物身份,编辑时须保留;锁文件顶层键的顺序不影响该身份。库 wheel 解压到 site-packages,各 wheel 的 `.data/scripts` 目录保留辅助文件,不生成命令行包装器。其他安装方案会被拒绝。macOS 只对版本化 Python 可执行文件签名一次,在外部资源及安装副本中保留[两个解释器别名](../../packages/skill/tool-workspace-dependencies/README.zh.md)。POSIX 本机目标检查要求解释器别名为相对链接。所有本机目标检查验证命令名、子进程执行及包含 pip 的 venv,并在清理暂存目录后以及 macOS 签名后验证锁定 wheel 的集合与版本,允许解释器自带的 pip,并检查 Python 版本、Office 文档读写和依赖完整性,不写入字节码。独立 Node 可执行文件获得 V8 所需的 JIT 权限;x64 目标还获得 `com.apple.security.cs.allow-unsigned-executable-memory`,允许可执行代码页,包括在 Rosetta 下运行时。ARM64 Node 和 Office 辅助程序保留仅 JIT 权限。跨目标执行和签名安装需要对应的发布主机。`dev:desktop` 和 `start:desktop` 都会在启动 Electron 前准备 `.desktop-build/targets//runtime/primary-runtime`;首次准备可能需要下载锁定的依赖。准备未完成时,启动命令不能报告成功退出。 Desktop/SDK 共享运行时构建器在复制或签名产物前,裁剪 NumPy 和 pandas 下名为 `tests` 的目录,并移除各分发包 `RECORD` 中对应的记录。它保留 `numpy.testing`、`pandas.testing`、`pandas._testing`、原生扩展和许可证。完整上游测试套件不可用;本机检查验证保留的 testing API、测试目录已移除,以及清单所列文件存在。 @@ -219,9 +219,9 @@ production 发布使用产品版本本身,不传 `--build-version`。其上传 版本派生不改变固定更新通道,也不改变 `nightly.yml` / `nightly-mac.yml` 文件名。SemVer 排序为 `0.1.6-alpha.1 < 0.1.6-alpha.1.20260916.1 < 0.1.6-alpha.2`,稳定基础版本的测试版低于该稳定版。客户端只接受更高版本:替换 feed 无法让已安装的较高版本更新到较低的纠正版。这类客户端需要手动安装;保持自动降级关闭。[已归档的版本决策](../../.agents/notes/archived/process/2026-09-16-desktop-release-version-derivation.md)解释为什么不能用通道名替换预发布标识。 -除本地 macOS 未签名构建外,打包、上传以及手动 macOS 签名检查使用 `apps/desktop/.env.windows` 或 `.env.macos`,由目标平台选择。复制对应的 [Windows 模板](.env.windows.example) 或 [macOS 模板](.env.macos.example),填写本机配置;Git 忽略这两个本地文件,安装产物也不包含它们。发布字段只从目标文件读取,不回退到系统或 shell 中的同名变量;`PATH`、代理和构建工具环境仍保留。发布版本是命令参数而非发布字段,上传从打包写下的完成记录中读取它。文件使用 UTF-8,支持 BOM;相对证书、SignTool、Apple API Key 和钥匙串路径以 `apps/desktop` 为基准,变量值不做 shell 展开,包含 `#` 或空格的密码需要引号。CI 同样在运行前生成目标文件。 +除选择机器 preset 的 Windows 打包和本地 macOS 未签名构建外,打包、上传以及手动 macOS 签名检查使用 `apps/desktop/.env.windows` 或 `.env.macos`,由目标平台选择。复制对应的 [Windows 模板](.env.windows.example) 或 [macOS 模板](.env.macos.example),填写本机配置;Git 忽略这两个本地文件,安装产物也不包含它们。发布字段只从选定的配置文件读取,不回退到系统或 shell 中的同名变量;`PATH`、代理和构建工具环境仍保留。发布版本是命令参数而非发布字段,上传从打包写下的完成记录中读取它。文件使用 UTF-8,支持 BOM;相对证书、SignTool、Apple API Key 和钥匙串路径以 `apps/desktop` 为基准,变量值不做 shell 展开,包含 `#` 或空格的密码需要引号。Windows CI 读取下文说明的机器 preset。 -每条打包命令在构建与下载前检查应用 ID 以及该模式需要的更新与签名配置,随后探测本次运行要用的外部工具:归档读取工具,以及 Windows 目标的安装器编译器。macOS 检查身份、Team ID、一套完整公证凭据、`CSC_LINK` 指定的可读本地 p12 文件、显式配置的 `CSC_KEY_PASSWORD`,以及引用的 API Key 和钥匙串文件;Windows 检查公开代码签名证书、SignTool 文件、容器名称和 PIN 格式。仅准备 Windows 资源以及两个平台上的显式未签名打包均不要求签名凭据。配置检查不验证 PIN 是否正确、Token 是否登录、钥匙串是否解锁或 Apple 是否接受凭据;实际签名与公证负责这些检查。`--build-version auto` 会访问目标 bucket,`--check` 下同样如此。单独运行相同检查: +每条打包命令在构建与下载前检查应用 ID 以及该模式需要的更新与签名配置,随后探测本次运行要用的外部工具:归档读取工具,以及 Windows 目标的安装器编译器。macOS 检查身份、Team ID、一套完整公证凭据、`CSC_LINK` 指定的可读本地 p12 文件、显式配置的 `CSC_KEY_PASSWORD`,以及引用的 API Key 和钥匙串文件;Windows 检查公开代码签名证书、SignTool 文件、容器名称和 PIN 格式。仅准备 Windows 资源以及两个平台上的显式未签名打包均不要求签名凭据。配置检查不验证 PIN 是否正确、Token 是否登录、钥匙串是否解锁或 Apple 是否接受凭据;实际签名与公证负责这些检查。未选择 Windows 机器 preset 时,`--build-version auto` 会访问目标 bucket,`--check` 下同样如此。单独运行相同检查: ```sh pnpm --dir apps/desktop run check:package @@ -276,7 +276,7 @@ pnpm run dev:bundle-registry ### 运行时文件筛选 -Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安装外部依赖。[Desktop 文件策略](scripts/runtime-file-policy.ts)随后在签名和完整性封装前过滤不可变的 `resources/app.asar/dsh/node_modules` 副本。它排除 TypeScript 声明、已识别的 JavaScript/CSS/TypeScript source map、TypeScript 构建缓存、Domino 测试目录、选定的原生编译器输出和其他平台的 node-pty 预构建文件。非 Windows 目标还会排除 `node-pty/third_party/conpty`;Windows 目标保留该目录。它保留运行时 JavaScript、目标平台的原生模块及其 DLL/EXE 辅助文件、WASM、未知资源、许可证和 notices。依赖清单在完整性封装前经过 electron-builder 的元数据清理,确保归档保持已记录的字节。该策略不修改 npm tarball、捆绑的包管理器或用户安装的插件文件。 +Desktop 在本地打包工作区包,并通过目标捆绑的 Node 和 pnpm 安装外部依赖。[Desktop 文件策略](scripts/runtime-file-policy.ts)随后在签名和完整性封装前过滤不可变的 `resources/app.asar/dsh/node_modules` 副本。它排除 TypeScript 声明、已识别的 JavaScript/CSS/TypeScript source map、TypeScript 构建缓存、Domino 测试目录及 Yarn 开发元数据、选定的原生编译器输出和其他平台的 node-pty 预构建文件。非 Windows 目标还会排除 `node-pty/third_party/conpty`;Windows 目标保留该目录。它保留运行时 JavaScript、目标平台的原生模块及其 DLL/EXE 辅助文件、WASM、未知资源、许可证和 notices。依赖清单在完整性封装前经过 electron-builder 的元数据清理,确保归档保持已记录的字节。该策略不修改 npm tarball、捆绑的包管理器或用户安装的插件文件。 [Electron 外壳文件清单](scripts/electron-builder-config.mjs)从单独收集的 `resources/app.asar/node_modules` 依赖中排除已识别的 JavaScript/CSS/TypeScript source map 和 TypeScript 构建缓存。这些排除规则保留运行时代码、原生模块、WASM、数据文件(包括普通 `.map` 资源)、许可证和 notices;[外壳归档测试](tests/shell-file-selection.spec.ts)检查保留文件的字节和排除项。 @@ -366,9 +366,15 @@ pnpm run package:desktop:win:x64:unsigned 先运行 `pnpm install --frozen-lockfile`,再运行 `pnpm run package:desktop:win:x64:unsigned --check` 校验配置和工具,最后执行上面的完整命令。打包自行执行完整构建和隔离的运行时 smoke,不调用在线模型。阶段日志保留在 `.desktop-build/packaging-runs/`;仅构建成功不代表安装包验证通过。依赖安装和运行时准备需要访问 npm、GitHub release 资源和 nodejs.org;网络需要时使用现有 registry 和代理配置。缓存与工具位置属于构建机器配置,不在跟踪文件中固定个人路径。 -[Windows 手动工作流](../../.github/workflows/windows-package.yml) 选择带有专用标签 `dsh-win-package-trial` 的自托管 Windows x64 runner,并调用同一个未签名命令。启动 runner 前需准备 PowerShell 7 和上述工具。必须填写策略部署环境和 HTTPS origin;测试部署还需填写逗号分隔的登录 origin。这些公开输入生成临时 `.env.windows`,不包含签名或上传凭据。`build_version` 默认为 `auto`,使用[发布版本](#release-versions)中说明的 CI 标识。显式版本复用现有产品版本校验器。解析后的版本在打包前显示于运行摘要,manifest 保持不变。 +[Windows 手动工作流](../../.github/workflows/windows-package.yml) 选择专用 Windows x64 runner 标签 `dsh-win-package-trial`,并使用机器 preset `test` 或 `production`。选择 `unsigned`(默认)或 `signed`;签名模式复用现有 EV token 预检、签名缓存与失败 interlock,不发布或上传 release。`build_version` 默认为 `auto`,使用[发布版本](#release-versions)中的 CI 标识;显式值可以是源码产品版本,或扩展构建版本,例如产品 `0.2.1-alpha.1` 对应 `0.2.1-alpha.1.20261009.1`。版本前缀必须匹配所选源码;校验错误显示其当前示例。manifest 保持不变。 -工作流进入默认分支后,在 Actions 中选择它,选择源码分支、填写输入并点击 Run workflow。它不监听 push 或 PR,不改变现有自动 CI。打包日志和成功生成的 EXE 产物保留 14 天;安装、签名和发布是独立操作。依赖 Actions 打包前,先从默认分支运行一次,并检查保留的日志和安装包。Checkout 会清理 runner 专用源码目录,包括被忽略的文件;不得指向日常开发目录。运行共享一个并发组,不取消正在进行的构建;最多保留一个待运行任务,新的手动触发会替换该待运行任务。仅在成功完成干净检出后上传诊断日志;即使配置准备在写入后失败,也会清理生成的配置。 +在 Actions 选择工作流、源码分支、preset、签名模式和版本,再点击 Run workflow。输入变更合并前,用 `gh workflow run windows-package.yml --ref -f preset=test -f signing=unsigned -f build_version=auto` 测试已推送分支;合并后验证网页表单。它不监听 push 或 PR。日志和成功生成的 EXE 保留 14 天。依赖打包流程前检查日志和安装包;安装是独立操作。检出前,Node 删除 runner 专用源码目录,不跟随依赖 junction;工作流校验目标位置并拒绝链接祖先目录。不得指向日常开发目录。运行共享一个并发组,不取消正在进行的构建;最多保留一个待运行任务,新触发会替换它。仅在成功完成干净检出后上传诊断。机器配置位于 checkout 之外,不作为产物上传。 + +共享打包 runner 以内部团队代码和操作人员可信为前提。在此前提下,凭据和设备隔离暂缓实施,剩余风险按已知风险接受(由 #5973 跟踪);尚未强制限制仅 signed/master 可访问。未签名模式跳过签名文件加载,但无法阻止同一 Windows 账户下的分支代码读取这些文件或访问 Token。SafeNet Single Logon 可能复用认证状态。直接调用设备可以绕过签名脚本并耗尽 PIN 重试次数;持久失败 interlock 只保护经过这些脚本的调用。跨账户 Token 隔离和剩余重试次数尚未验证。扩大访问范围、执行不可信贡献、改变 runner 共享方式前,或出现可疑活动后,重新评估 runner、账户和设备隔离。 + +本地 Windows 命令通过 `DSH_PACKAGING_CONFIG_DIR` 指定机器配置绝对目录,通过 `DSH_PACKAGING_PRESET` 选择 `test` 或 `production`。加载器读取 `presets/.env`;签名命令另读 `secrets/windows-signing.env`。相对证书和 SignTool 路径以声明它们的文件所在目录为基准。公开 preset 拒绝凭据,签名文件不能覆盖公开配置。配置缺失立即失败,不回退到 `.env.windows`;不选择 preset 的命令保留原 dotenv 行为。未签名和仅准备 preset 不读取签名文件。缓存维护也只读取公开 preset 配置。签名测试包还需现有下载 origin 和 release ID,但无需上传凭据。本地 preset 命令使用 `--build-version auto` 时仅按本地产物编号;Actions 使用运行编号和重试次数。 + +运行 `pwsh -NoProfile -File apps/desktop/scripts/setup-windows-packaging.ps1 -Root ` 创建私有 `packaging/{presets,secrets,certificates}` 和 `cache/windows-signatures` 目录并复制模板,不覆盖现有文件。添加 `-CheckOnly` 只检查不写入。在机器上填写 [preset 模板](config/windows-packaging/test.env.example)和[签名模板](config/windows-packaging/windows-signing.env.example)。从同一 scripts 目录运行 `start-windows-packaging-runner.ps1 -RunnerRoot -ConfigRoot /packaging -CheckOnly`,检查 runner 的 `tools` 目录下 PowerShell 7.6.6、Node、Python、Git、tar 和 Visual C++ 工具;打包 `--check` 完成其余工具链检查。省略 `-CheckOnly`,以显式配置目录和清理后的继承环境启动现有 runner。注册和工具安装单独进行;这些脚本不创建 token、不改系统安全设置、不清除签名失败记录。修改 preset 缓存路径前,使用下文签名缓存维护命令迁移已有条目。 @@ -424,7 +430,7 @@ pnpm run package:desktop:win:x64 时间戳处理仅对正常退出但返回失败或警告的时间戳命令重试,最多尝试三次,间隔为一秒和两秒。每次均从同一份已验证的主签名开始。启动错误、终止状态不确定或验签失败会立即停止。SignTool 使用短的私有路径;发布时先把已验证字节复制到目标卷,再原子替换。最终必须通过 Windows 信任、证书、时间戳和规范化全文件相等检查。尝试耗尽后停止打包并保留证据,不再次调用硬件。参见[签名完成决策](../../.agents/notes/implemented/process/2026-09-17-windows-signature-completion.zh.md)。 -PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet `/kc` 值或对应的 CMD 参数。CMD 会禁用延迟展开,因此包含 `!` 的 PIN 可以原样到达 SafeNet。打包流程不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程;它只向签名预检、独立的第一方运行时签名阶段与 electron-builder 提供四个配置输入,在其他字段已经清理的环境中只向签名 CMD 提供经过校验的签名字段,在 SignTool 启动前清除这些字段,并遮盖 SignTool 诊断。SafeNet 仍要求 PIN 出现在 SignTool 进程命令行中。本地 `.env.windows` 明文保存 PIN,应限制文件访问权限;CI 使用临时文件并在任务结束后删除。不要提交或分享文件内容,也不要把凭据写入日志。配置检查不会消耗 Token 的 PIN 尝试次数;签名仍在首次失败后停止整批任务。 +PIN 不能包含 `]`、引号或换行,因为这些字符用于分隔 SafeNet `/kc` 值或对应的 CMD 参数。CMD 会禁用延迟展开,因此包含 `!` 的 PIN 可以原样到达 SafeNet。打包流程不会把任何 `DSH_DESKTOP_WINDOWS_*` 字段传给构建与 运行时准备子进程;它只向签名预检、独立的第一方运行时签名阶段与 electron-builder 提供四个配置输入,在其他字段已经清理的环境中只向签名 CMD 提供经过校验的签名字段,在 SignTool 启动前清除这些字段,并遮盖 SignTool 诊断。SafeNet 仍要求 PIN 出现在 SignTool 进程命令行中。本地 `.env.windows` 或机器管理的 `secrets/windows-signing.env` 明文保存 PIN,应限制文件访问权限。CI 读取 checkout 外的机器签名文件,并在任务结束后保留。不要提交或分享文件内容,也不要把凭据写入日志。配置检查不会消耗 Token 的 PIN 尝试次数;签名仍在首次失败后停止整批任务。 使用对应的 `:dir` 命令可以生成可直接运行的应用目录,而不是安装包,例如: diff --git a/apps/desktop/config/windows-packaging/production.env.example b/apps/desktop/config/windows-packaging/production.env.example new file mode 100644 index 0000000000..2e05825590 --- /dev/null +++ b/apps/desktop/config/windows-packaging/production.env.example @@ -0,0 +1,7 @@ +# Copy to production.env in the same machine configuration directory and fill in the values. +DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_AUTO_UPDATE_ENV=production +DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN= +DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{}' +# DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR= +DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY=4 diff --git a/apps/desktop/config/windows-packaging/test.env.example b/apps/desktop/config/windows-packaging/test.env.example new file mode 100644 index 0000000000..718481f13a --- /dev/null +++ b/apps/desktop/config/windows-packaging/test.env.example @@ -0,0 +1,13 @@ +# Copy to test.env in the same machine configuration directory and fill in the values. +# Public test configuration. No PIN or upload credentials belong here. +DSH_DESKTOP_APP_ID=com.deepseek.harness +DSH_DESKTOP_AUTO_UPDATE_ENV=test +DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN= +# Replace login.example.com with the real login origin before packaging. +DSH_DESKTOP_MANDATORY_UPDATE_CONFIG='{"allowedAuthOrigins":["https://login.example.com"]}' +# Required for signed test packages; retain the release ID for an upgrade test batch. +DOWNLOAD_TEST_ORIGIN= +DOWNLOAD_TEST_RELEASE_ID= +# Optional absolute private cache directory. Omit to retain the account default cache. +# DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR= +DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY=4 diff --git a/apps/desktop/config/windows-packaging/windows-signing.env.example b/apps/desktop/config/windows-packaging/windows-signing.env.example new file mode 100644 index 0000000000..d086a84ae7 --- /dev/null +++ b/apps/desktop/config/windows-packaging/windows-signing.env.example @@ -0,0 +1,7 @@ +# Copy to windows-signing.env in the same machine configuration directory and fill in the values. +# Restrict this file to the runner account, SYSTEM and administrators. +# File paths resolve relative to this file; use the same account as local signing. +DSH_DESKTOP_WINDOWS_CER_FILE=../certificates/windows.cer +DSH_DESKTOP_WINDOWS_SIGNTOOL= +DSH_DESKTOP_WINDOWS_KEY_CONTAINER= +DSH_DESKTOP_WINDOWS_TOKEN_PIN= diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 563f60a858..34e859cd20 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -75,8 +75,6 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "react": "^18.2.0", "react-dom": "^18.2.0", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "vite": "^6.4.3", "@deepseek-ai/dsh-client-ui-theme": "workspace:*", "@deepseek-ai/dsh-client-shortcuts": "workspace:*", diff --git a/apps/desktop/scripts/desktop-package-environment.d.mts b/apps/desktop/scripts/desktop-package-environment.d.mts index a49ca46eb9..90659b6e99 100644 --- a/apps/desktop/scripts/desktop-package-environment.d.mts +++ b/apps/desktop/scripts/desktop-package-environment.d.mts @@ -8,16 +8,18 @@ export function localMacOSPackageEnvironment(environment?: NodeJS.ProcessEnv): NodeJS.ProcessEnv /** - * Read the target's required UTF-8 dotenv file; release settings never fall back to ambient values. + * Read a Windows machine preset when selected, otherwise the target's required dotenv; no ambient release fallback. * @param platform Target platform. * @param environment Parent environment, retained only for unrelated build tools. * @param appRoot Desktop application directory; relative credential paths resolve here. + * @param options Unsigned and preparation-only presets never read signing credentials. * @returns Isolated environment with file-owned release settings. */ export function loadDesktopPackageEnvironment( platform: 'win32' | 'darwin', environment?: NodeJS.ProcessEnv, appRoot?: string, + options?: { unsigned?: boolean, prepareOnly?: boolean }, ): NodeJS.ProcessEnv /** diff --git a/apps/desktop/scripts/desktop-package-environment.mjs b/apps/desktop/scripts/desktop-package-environment.mjs index 51b878100a..9c7d52345b 100644 --- a/apps/desktop/scripts/desktop-package-environment.mjs +++ b/apps/desktop/scripts/desktop-package-environment.mjs @@ -1,7 +1,7 @@ /** Select local test defaults or platform release settings without changing the caller's environment. */ import { accessSync, constants, readFileSync, statSync } from 'node:fs' -import { dirname, join, resolve } from 'node:path' +import { dirname, isAbsolute, join, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { parseEnv } from 'node:util' import { resolveDesktopAppId, resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment, resolveNpmRegistry } from './desktop-release-environment.mjs' @@ -33,14 +33,46 @@ export function localMacOSPackageEnvironment(environment = process.env) { } /** - * Read the target's required UTF-8 dotenv file; release settings never fall back to ambient values. + * Read a Windows machine preset when selected, otherwise the target's required dotenv; no ambient release fallback. * @param {'win32' | 'darwin'} platform Target platform. * @param {NodeJS.ProcessEnv} environment Parent environment, retained only for unrelated build tools. * @param {string} appRoot Desktop application directory; relative credential paths resolve here. + * @param {{ unsigned?: boolean, prepareOnly?: boolean }} options Unsigned and preparation-only presets never read signing credentials. * @returns {NodeJS.ProcessEnv} Isolated environment with file-owned release settings. */ -export function loadDesktopPackageEnvironment(platform, environment = process.env, appRoot = APP_ROOT) { - const path = join(appRoot, platform === 'win32' ? '.env.windows' : '.env.macos') +export function loadDesktopPackageEnvironment(platform, environment = process.env, appRoot = APP_ROOT, options = {}) { + const preset = environment.DSH_PACKAGING_PRESET + let path = join(appRoot, platform === 'win32' ? '.env.windows' : '.env.macos') + if (preset !== undefined) { + if (platform !== 'win32') throw new Error('desktop package: presets support Windows only') + if (preset !== 'test' && preset !== 'production') throw new Error('desktop package: preset must be test or production') + const root = environment.DSH_PACKAGING_CONFIG_DIR + if (!root || !isAbsolute(root)) throw new Error('desktop package: DSH_PACKAGING_CONFIG_DIR must be an absolute directory') + path = join(root, 'presets', `${preset}.env`) + } + const platformSetting = platform === 'win32' ? WINDOWS_SETTING : MACOS_SETTING + const settings = readSettings(path, name => preset === undefined + ? SHARED_SETTING.test(name) || platformSetting.test(name) + : /^(?:DSH_DESKTOP_(?:APP_ID|AUTO_UPDATE_ENV|NPM_REGISTRY|MANDATORY_UPDATE_(?:CONFIG|(?:TEST|PROD)_ORIGIN)|WINDOWS_SIGNATURE_CACHE_(?:DIR|CONCURRENCY))|DOWNLOAD_TEST_(?:ORIGIN|RELEASE_ID))$/u.test(name)) + if (preset !== undefined) { + if (settings.DSH_DESKTOP_AUTO_UPDATE_ENV !== preset) throw new Error('desktop package: preset deployment must match its name') + if (!options.unsigned && !options.prepareOnly) Object.assign(settings, readSettings(join(dirname(dirname(path)), 'secrets', 'windows-signing.env'), + name => /^DSH_DESKTOP_WINDOWS_(?:CER_FILE|SIGNTOOL|KEY_CONTAINER|TOKEN_PIN)$/u.test(name))) + } + return { + ...Object.fromEntries(Object.entries(environment).filter(([name]) => !AMBIENT_RELEASE_SETTING.test(name))), + ...settings, + ...(preset === undefined ? {} : { DSH_PACKAGING_PRESET: preset }), + } +} + +/** + * Read an explicitly selected dotenv without exposing credential-bearing parser errors. + * @param {string} path Selected file; relative file settings resolve beside it. + * @param {(name: string) => boolean} accepts Whether this file may declare a setting. + * @returns {NodeJS.ProcessEnv} Validated file settings. + */ +function readSettings(path, accepts) { let contents try { contents = readFileSync(path, 'utf8') @@ -56,9 +88,8 @@ export function loadDesktopPackageEnvironment(platform, environment = process.en // Parser diagnostics can contain credential-bearing input. throw new Error(`desktop package: invalid dotenv syntax in ${path}`) } - const platformSetting = platform === 'win32' ? WINDOWS_SETTING : MACOS_SETTING for (const name of Object.keys(settings)) { - if (!SHARED_SETTING.test(name) && !platformSetting.test(name)) { + if (!accepts(name)) { throw new Error(`desktop package: unsupported setting ${name} in ${path}; use the platform template`) } if (settings[name].includes('\0')) throw new Error(`desktop package: ${name} cannot contain a NUL character`) @@ -66,10 +97,7 @@ export function loadDesktopPackageEnvironment(platform, environment = process.en for (const name of FILE_SETTINGS) { if (settings[name]?.trim()) settings[name] = resolve(dirname(path), settings[name].trim()) } - return { - ...Object.fromEntries(Object.entries(environment).filter(([name]) => !AMBIENT_RELEASE_SETTING.test(name))), - ...settings, - } + return settings } function requireReadableFile(environment, name) { diff --git a/apps/desktop/scripts/dev.ts b/apps/desktop/scripts/dev.ts index 1ae2f3e952..37515c20b0 100644 --- a/apps/desktop/scripts/dev.ts +++ b/apps/desktop/scripts/dev.ts @@ -93,7 +93,7 @@ async function launchElectron(): Promise { async function main(): Promise { const { values } = parseArgs({ options: { 'skip-build': { type: 'boolean', default: false } } }) if (!values['skip-build']) { - await runPackageScript('build', REPOSITORY_ROOT) + await runPackageScript('build:artifacts', REPOSITORY_ROOT) await runPackageScript('build', APP_ROOT) } for (const path of [ diff --git a/apps/desktop/scripts/macos-runtime.ts b/apps/desktop/scripts/macos-runtime.ts index 3d5fabdbed..1d4c27c0d5 100644 --- a/apps/desktop/scripts/macos-runtime.ts +++ b/apps/desktop/scripts/macos-runtime.ts @@ -1,8 +1,9 @@ /** Sign final native runtime files before the enclosing Desktop application is signed. */ import { createHash } from 'node:crypto' -import { closeSync, openSync, readSync } from 'node:fs' -import { join } from 'node:path' +import { closeSync, openSync, readdirSync, readSync } from 'node:fs' +import { join, relative, sep } from 'node:path' +import { primaryRuntimePythonAliases, readPrimaryRuntime } from '../../../packages/skill/tool-workspace-dependencies/src/index.ts' import { inventoryDesktopRuntime } from '../src/runtime-tree.ts' import type { MacOSSigningEnvironment } from './desktop-release-environment.mjs' import { cachedMacOSSignature, pruneMacOSSignatureCache } from './macos-signature-cache.ts' @@ -19,19 +20,34 @@ function magic(path: string): string { } finally { closeSync(descriptor) } } +async function primaryRuntimeFiles(root: string): Promise { + const aliases = await primaryRuntimePythonAliases(root, await readPrimaryRuntime(root)) + const files: string[] = [] + for (const entry of readdirSync(root, { recursive: true, withFileTypes: true })) { + const path = relative(root, join(entry.parentPath, entry.name)).split(sep).join('/') + if (entry.isDirectory() || (entry.isSymbolicLink() && aliases.has(path))) continue + if (!entry.isFile()) throw new Error(`desktop runtime: unsupported filesystem entry ${path}`) + files.push(path) + } + return files.sort() +} + /** * Sign and verify every materialized Mach-O file, awaiting all signers on failure. - * @param root - Self-contained production runtime without symlinks. + * @param root - Self-contained production runtime. * @param appId - Release application identifier. * @param expected - Required signing identity. * @param arch - Target runtime architecture, independent of the signing host. * @param cacheDirectory - Optional content-addressed cache; requires the keychain-owned signing probe. + * @param kind - Primary payloads admit validated Python aliases; Desktop application runtimes reject every link. * @returns Number of signed native files. */ export async function signMacOSRuntime( root: string, appId: string, expected: MacOSSigningEnvironment, arch: 'arm64' | 'x64', cacheDirectory?: string, + kind: 'desktop' | 'primary' = 'desktop', ): Promise { - const files = inventoryDesktopRuntime(root).map(file => file.path).filter(path => MACH_O_MAGICS.has(magic(join(root, path)))) + const inventory = kind === 'primary' ? await primaryRuntimeFiles(root) : inventoryDesktopRuntime(root).map(file => file.path) + const files = inventory.filter(path => MACH_O_MAGICS.has(magic(join(root, path)))) const policy = cacheDirectory === undefined ? undefined : macOSCachePolicy(process.env.DSH_DESKTOP_MACOS_SIGNING_PROBE ?? '') let hits = 0 let misses = 0 diff --git a/apps/desktop/scripts/manage-windows-signature-cache.mjs b/apps/desktop/scripts/manage-windows-signature-cache.mjs index de44540c70..f36aaf5925 100644 --- a/apps/desktop/scripts/manage-windows-signature-cache.mjs +++ b/apps/desktop/scripts/manage-windows-signature-cache.mjs @@ -11,7 +11,7 @@ const { values } = parseArgs({ options: { if ([values.from !== undefined, values.usage === true, values.clear === true].filter(Boolean).length !== 1) { throw new Error('Specify exactly one of --from , --usage or --clear') } -const environment = values.directory === undefined ? loadDesktopPackageEnvironment('win32') +const environment = values.directory === undefined ? loadDesktopPackageEnvironment('win32', process.env, undefined, { unsigned: true }) : { DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR: values.directory } const root = resolveWindowsSignatureCacheDirectory(environment) const record = event => process.stdout.write(`${JSON.stringify(event)}\n`) diff --git a/apps/desktop/scripts/package-target.ts b/apps/desktop/scripts/package-target.ts index a133ccdcf8..505b7c7598 100644 --- a/apps/desktop/scripts/package-target.ts +++ b/apps/desktop/scripts/package-target.ts @@ -322,7 +322,9 @@ async function resolveRequestedBuildVersion( if (requested !== AUTOMATIC_BUILD_VERSION) return validateDesktopBuildVersion(requested, productVersion) const paths = desktopTargetBuildPaths(invocation.target.name) return suggestDesktopBuildVersion({ - productVersion, target: invocation.target.name, environment, + productVersion, target: invocation.target.name, + // Machine presets own packaging, not upload credentials; local auto numbering uses existing artifacts. + environment: environment.DSH_PACKAGING_PRESET === undefined ? environment : {}, // Unsigned builds land beside the signed output, so numbering has to read the directory this run writes. artifactsRoot: invocation.unsigned ? paths.unsignedArtifacts : paths.artifacts, }) @@ -333,9 +335,11 @@ async function main(): Promise { const { target } = invocation const environment = target.platform === 'darwin' && invocation.unsigned ? localMacOSPackageEnvironment() - : loadDesktopPackageEnvironment(target.platform) + : loadDesktopPackageEnvironment(target.platform, process.env, APP_ROOT, { + unsigned: invocation.unsigned, prepareOnly: invocation.prepareOnly, + }) const productVersion = packageVersion(join(APP_ROOT, 'package.json'), 'desktop package') - // Release settings come from the target dotenv file alone, so the version this run publishes is an + // Release settings come from the selected configuration files, so the version this run publishes is an // argument; the environment variable below only carries it to the child processes that build. const buildVersion = await resolveRequestedBuildVersion(invocation, productVersion, environment) environment[DESKTOP_BUILD_VERSION_ENV] = buildVersion diff --git a/apps/desktop/scripts/prepare-dsh.ts b/apps/desktop/scripts/prepare-dsh.ts index 7d290b945a..808b8ae8b5 100644 --- a/apps/desktop/scripts/prepare-dsh.ts +++ b/apps/desktop/scripts/prepare-dsh.ts @@ -158,7 +158,7 @@ async function main(): Promise { } if (process.platform === 'darwin' && process.env.DSH_DESKTOP_UNSIGNED !== '1') { await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:dsh-native', () => signMacOSRuntime(DSH_OUTPUT_ROOT, resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, join(BUILD_PATHS.root, 'signature-cache'))) - await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:primary-native', () => signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, join(BUILD_PATHS.root, 'signature-cache'))) + await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'sign:primary-native', () => signMacOSRuntime(join(RUNTIME_ROOT, 'primary-runtime'), resolveDesktopAppId(process.env), resolveMacOSSigningEnvironment(process.env), target.arch, join(BUILD_PATHS.root, 'signature-cache'), 'primary')) } await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:manifests', () => prepareRuntimeManifests(DSH_OUTPUT_ROOT)) await packagingStep(process.env.DSH_DESKTOP_PACKAGING_RUN_DIR, 'runtime:primary-smoke', async () => smokePrimaryRuntime(join(RUNTIME_ROOT, 'primary-runtime'))) diff --git a/apps/desktop/scripts/prepare-windows-ci.d.mts b/apps/desktop/scripts/prepare-windows-ci.d.mts index 0fa67ecf7f..3b0196dc57 100644 --- a/apps/desktop/scripts/prepare-windows-ci.d.mts +++ b/apps/desktop/scripts/prepare-windows-ci.d.mts @@ -1,14 +1,10 @@ -/** Public settings prepared for a manual Windows package run. */ -export interface WindowsCiSettings { - version: string - settings: string -} +/** Resolve the version used by the manual Windows packaging workflow. */ /** - * Validate manual inputs without local credentials or release storage. - * @param environment Manual inputs and GitHub run identity. + * Resolve an explicit version or a UTC date/run/attempt identifier without release storage access. + * @param environment Manual version and GitHub run identity. * @param productVersion Version declared by the selected checkout. * @param now Time used for the UTC date segment. - * @returns Validated version and public dotenv content. + * @returns Validated build version. */ -export function windowsCiSettings(environment: NodeJS.ProcessEnv, productVersion: string, now?: Date): WindowsCiSettings +export function windowsCiVersion(environment: NodeJS.ProcessEnv, productVersion: string, now?: Date): string diff --git a/apps/desktop/scripts/prepare-windows-ci.mjs b/apps/desktop/scripts/prepare-windows-ci.mjs index c86c303d41..5d00dbd415 100644 --- a/apps/desktop/scripts/prepare-windows-ci.mjs +++ b/apps/desktop/scripts/prepare-windows-ci.mjs @@ -1,54 +1,52 @@ -/** Prepare public Windows packaging settings and a version for a manual GitHub run. */ -import { appendFileSync, readFileSync, writeFileSync } from 'node:fs' +/** Resolve a manual Windows build version and validate the selected machine preset. */ +import { appendFileSync, readFileSync } from 'node:fs' import { resolve } from 'node:path' import { desktopBuildVersionPrefix, validateDesktopBuildVersion } from './desktop-build-version.mjs' -import { resolveDesktopPolicyEnvironment } from './desktop-policy-environment.mjs' +import { loadDesktopPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs' /** - * Validate manual inputs without reading local credentials or querying release storage. - * @param {NodeJS.ProcessEnv} environment Manual inputs and GitHub run identity. + * Resolve an explicit version or a UTC date/run/attempt identifier without release storage access. + * @param {NodeJS.ProcessEnv} environment Manual version and GitHub run identity. * @param {string} productVersion Version declared by the selected checkout. * @param {Date} now Time used for the UTC date segment. - * @returns {{ version: string, settings: string }} Validated version and public dotenv content. + * @returns {string} Validated build version. */ -export function windowsCiSettings(environment, productVersion, now = new Date()) { - const deployment = environment.PACKAGE_DEPLOYMENT - if (deployment !== 'test' && deployment !== 'production') throw new Error('Select test or production deployment') - const loginOrigins = (environment.PACKAGE_LOGIN_ORIGINS ?? '').split(',').map(value => value.trim()).filter(Boolean) - if (deployment === 'production' && loginOrigins.length > 0) throw new Error('Production must not supply login origins') - const originKey = deployment === 'test' ? 'DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN' : 'DSH_DESKTOP_MANDATORY_UPDATE_PROD_ORIGIN' - const config = deployment === 'test' ? { allowedAuthOrigins: loginOrigins } : {} - const policy = resolveDesktopPolicyEnvironment({ - DSH_DESKTOP_AUTO_UPDATE_ENV: deployment, - [originKey]: environment.PACKAGE_POLICY_ORIGIN, - DSH_DESKTOP_MANDATORY_UPDATE_CONFIG: JSON.stringify(config), - }) +export function windowsCiVersion(environment, productVersion, now = new Date()) { const requested = environment.PACKAGE_BUILD_VERSION?.trim() - if (!requested) throw new Error('Build version is required; use auto or a full version') + const date = now.toISOString().slice(0, 10).replaceAll('-', '') + const example = `${desktopBuildVersionPrefix(productVersion)}${date}.1` + if (!requested) throw new Error(`Build version is required: use auto, ${productVersion}, or e.g. ${example}`) let candidate = requested if (requested === 'auto') { for (const name of ['GITHUB_RUN_NUMBER', 'GITHUB_RUN_ATTEMPT']) { if (!/^[1-9]\d*$/u.test(environment[name] ?? '')) throw new Error(`${name} must be a positive integer`) } - const date = now.toISOString().slice(0, 10).replaceAll('-', '') candidate = `${desktopBuildVersionPrefix(productVersion)}${date}.${environment.GITHUB_RUN_NUMBER}.${environment.GITHUB_RUN_ATTEMPT}` } - const version = validateDesktopBuildVersion(candidate, productVersion) - const settings = [ - 'DSH_DESKTOP_APP_ID=com.deepseek.harness', - `DSH_DESKTOP_AUTO_UPDATE_ENV=${deployment}`, - `${originKey}=${policy.origin}`, - `DSH_DESKTOP_MANDATORY_UPDATE_CONFIG=${JSON.stringify(config)}`, - ].join('\n') + '\n' - return { version, settings } + try { + return validateDesktopBuildVersion(candidate, productVersion) + } catch { + throw new Error(`Invalid build version for this checkout: use auto, ${productVersion}, or e.g. ${example}`) + } } if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) { const appRoot = resolve(import.meta.dirname, '..') const product = JSON.parse(readFileSync(resolve(appRoot, 'package.json'), 'utf8')) - const result = windowsCiSettings(process.env, product.version) + const version = windowsCiVersion(process.env, product.version) + const mode = process.env.PACKAGE_SIGNING + if (mode !== 'unsigned' && mode !== 'signed') throw new Error('Select unsigned or signed packaging') + if (!process.env.DSH_PACKAGING_PRESET) throw new Error('Select a machine preset') + const environment = loadDesktopPackageEnvironment('win32', process.env, appRoot, { unsigned: mode === 'unsigned' }) + // Machine-owned secrets are not automatically known to the Actions log masker. + for (const [name, value] of Object.entries(environment)) { + if (/TOKEN|PASSWORD|SECRET/iu.test(name) && value) { + const escaped = value.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A') + process.stdout.write(`::add-mask::${escaped}\n`) + } + } + validateDesktopPackageEnvironment(environment, { platform: 'win32', arch: 'x64' }, { unsigned: mode === 'unsigned' }) if (!process.env.GITHUB_OUTPUT || !process.env.GITHUB_STEP_SUMMARY) throw new Error('Run this adapter from GitHub Actions') - writeFileSync(resolve(appRoot, '.env.windows'), result.settings, { flag: 'wx' }) - appendFileSync(process.env.GITHUB_OUTPUT, `version=${result.version}\n`) - appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Windows x64 unsigned installer\n\nVersion: ${result.version}\n\nCommit: ${process.env.GITHUB_SHA}\n\nDeployment: ${process.env.PACKAGE_DEPLOYMENT}\n`) + appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, `Windows x64 ${mode} installer\n\nVersion: ${version}\n\nCommit: ${process.env.GITHUB_SHA}\n\nPreset: ${process.env.DSH_PACKAGING_PRESET}\n`) } diff --git a/apps/desktop/scripts/runtime-file-policy.ts b/apps/desktop/scripts/runtime-file-policy.ts index a292e7d80f..14b0e2a186 100644 --- a/apps/desktop/scripts/runtime-file-policy.ts +++ b/apps/desktop/scripts/runtime-file-policy.ts @@ -34,6 +34,7 @@ export function desktopRuntimeFileExclusion( return 'fs-ext build configuration' } if (name === '@mixmark-io/domino' && (entry === 'test' || entry.startsWith('test/'))) return 'Domino test fixtures' + if (name === '@mixmark-io/domino' && (entry === '.yarn' || entry.startsWith('.yarn/'))) return 'Domino development tooling' if (name === 'node-pty' && target.platform !== 'win32' && /^third_party\/conpty(?:\/|$)/u.test(entry)) { return 'node-pty Windows ConPTY sources' } diff --git a/apps/desktop/scripts/setup-windows-packaging.ps1 b/apps/desktop/scripts/setup-windows-packaging.ps1 new file mode 100644 index 0000000000..9e686fb2fe --- /dev/null +++ b/apps/desktop/scripts/setup-windows-packaging.ps1 @@ -0,0 +1,49 @@ +# Prepare or inspect machine-owned Windows packaging directories without reading secret values. +[CmdletBinding()] +param( + [Parameter(Mandatory=$true)][string]$Root, + [switch]$CheckOnly +) +$ErrorActionPreference = 'Stop' +if ($Root -notmatch '^[A-Za-z]:[\\/]') { throw 'Root must be an absolute local drive directory' } +$rootPath = [IO.Path]::GetFullPath($Root) +$drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot($rootPath)) +if ($drive.DriveType -ne [IO.DriveType]::Fixed) { throw 'Packaging root requires a fixed local drive' } +for ($ancestor = [IO.DirectoryInfo]::new($rootPath); $null -ne $ancestor; $ancestor = $ancestor.Parent) { + if ($ancestor.Exists -and ($ancestor.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Packaging root cannot contain linked directories' } +} +$identity = [Security.Principal.WindowsIdentity]::GetCurrent().User +$allowed = @($identity.Value, 'S-1-5-18', 'S-1-5-32-544') +foreach ($relative in @('packaging', 'packaging/presets', 'packaging/secrets', 'packaging/certificates', 'cache', 'cache/windows-signatures')) { + $path = Join-Path $rootPath $relative + if (-not (Test-Path -LiteralPath $path)) { + if ($CheckOnly) { throw "Missing directory: $path" } + $null = New-Item -ItemType Directory -Path $path + $acl = [Security.AccessControl.DirectorySecurity]::new() + $acl.SetOwner($identity) + $acl.SetAccessRuleProtection($true, $false) + foreach ($sid in $allowed) { + $rule = [Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid), 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow') + $null = $acl.AddAccessRule($rule) + } + Set-Acl -LiteralPath $path -AclObject $acl + } + $item = Get-Item -LiteralPath $path + if (-not $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw "Not a real directory: $path" } + $acl = Get-Acl -LiteralPath $path + if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $identity.Value) { throw "Directory must belong to current account: $path" } + foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) { + if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $allowed) { throw "Directory permits another account: $path" } + } +} +if (-not $CheckOnly) { + $templates = Join-Path $PSScriptRoot '../config/windows-packaging' + foreach ($name in @('test', 'production')) { + $destination = Join-Path $rootPath "packaging/presets/$name.env.example" + if (-not (Test-Path -LiteralPath $destination)) { Copy-Item -LiteralPath (Join-Path $templates "$name.env.example") -Destination $destination } + } + $destination = Join-Path $rootPath 'packaging/secrets/windows-signing.env.example' + if (-not (Test-Path -LiteralPath $destination)) { Copy-Item -LiteralPath (Join-Path $templates 'windows-signing.env.example') -Destination $destination } +} +Write-Output "Packaging directories verified. Configuration root: $(Join-Path $rootPath 'packaging')" +Write-Output 'Existing configuration, caches, runner registration and signing failure records were not overwritten.' diff --git a/apps/desktop/scripts/start-windows-packaging-runner.ps1 b/apps/desktop/scripts/start-windows-packaging-runner.ps1 new file mode 100644 index 0000000000..13251a110a --- /dev/null +++ b/apps/desktop/scripts/start-windows-packaging-runner.ps1 @@ -0,0 +1,38 @@ +# Start the existing registered runner with explicit machine configuration and a scrubbed environment. +[CmdletBinding()] +param([Parameter(Mandatory=$true)][string]$RunnerRoot, [Parameter(Mandatory=$true)][string]$ConfigRoot, [switch]$CheckOnly) +$ErrorActionPreference='Stop' +$pwshRoot=Join-Path $RunnerRoot 'tools/pwsh-7.6.6' +$runnerPath = $pwshRoot + ';' + [Environment]::GetEnvironmentVariable('Path','Machine') + ';' + [Environment]::GetEnvironmentVariable('Path','User') +$keep=@('SystemRoot','windir','SystemDrive','ComSpec','TEMP','TMP','USERPROFILE','HOMEDRIVE','HOMEPATH','LOCALAPPDATA','APPDATA','ProgramData','ProgramFiles','ProgramFiles(x86)','CommonProgramFiles','CommonProgramFiles(x86)','CommonProgramW6432','ProgramW6432','PROCESSOR_ARCHITECTURE','NUMBER_OF_PROCESSORS','OS','PATHEXT','USERNAME','USERDOMAIN','COMPUTERNAME','PUBLIC','ALLUSERSPROFILE') +foreach($entry in @(Get-ChildItem Env:)) { + if($entry.Name -notin $keep) { [Environment]::SetEnvironmentVariable($entry.Name,$null,'Process') } +} +$env:PATH=$runnerPath +if (-not [IO.Path]::IsPathRooted($ConfigRoot) -or -not (Test-Path -LiteralPath $ConfigRoot -PathType Container)) { throw 'ConfigRoot must identify an existing absolute directory' } +if ($ConfigRoot -notmatch '^[A-Za-z]:[\\/]') { throw 'ConfigRoot requires an absolute local drive directory' } +$drive = [IO.DriveInfo]::new([IO.Path]::GetPathRoot([IO.Path]::GetFullPath($ConfigRoot))) +if ($drive.DriveType -ne [IO.DriveType]::Fixed) { throw 'ConfigRoot requires a fixed local drive' } +$env:DSH_PACKAGING_CONFIG_DIR=[IO.Path]::GetFullPath($ConfigRoot) +$env:DSH_TELEMETRY_DISABLED='1' +$env:POWERSHELL_TELEMETRY_OPTOUT='1' +foreach($tool in @('pwsh','node','git','tar','python')) { + $resolved=Get-Command $tool -CommandType Application -ErrorAction Stop | Select-Object -First 1 + Write-Output ('Tool: '+$tool+' -> '+$resolved.Source) +} +$env:PYTHON=(Get-Command python -CommandType Application | Select-Object -First 1).Source +& pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()' +if($LASTEXITCODE -ne 0){throw 'PowerShell probe failed'} +& node --version +if($LASTEXITCODE -ne 0){throw 'Node probe failed'} +& python --version +if($LASTEXITCODE -ne 0){throw 'Python probe failed'} +$vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe' +$visualStudio=& $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +if($LASTEXITCODE -ne 0 -or -not $visualStudio){throw 'Visual C++ tools unavailable'} +Write-Output 'Visual C++ tools located.' +if($CheckOnly){Write-Output 'Runner environment check passed.'; exit 0} +if(Get-Process -Name Runner.Listener -ErrorAction SilentlyContinue){throw 'A runner listener is already running; inspect before starting another.'} +Set-Location $RunnerRoot +& .\run.cmd +exit $LASTEXITCODE diff --git a/apps/desktop/tests/macos-runtime.spec.ts b/apps/desktop/tests/macos-runtime.spec.ts index fdcb61600a..4ad63e41fd 100644 --- a/apps/desktop/tests/macos-runtime.spec.ts +++ b/apps/desktop/tests/macos-runtime.spec.ts @@ -1,4 +1,4 @@ -import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, readFileSync, readlinkSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, expect, it, vi } from 'vitest' @@ -25,6 +25,41 @@ it('signs Mach-O files in their final locations and verifies each signature', as expect(signMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), expect.stringMatching(/^com\.example\.app\.runtime\.[a-f0-9]{64}$/u), identity, undefined) expect(verifyMacOSRuntimeCode).toHaveBeenCalledWith(join(path, 'addon.node'), identity) }) + +// File symlinks in these macOS fixtures require privileges unavailable to ordinary Windows processes. +it.skipIf(process.platform === 'win32')('signs a shared Python interpreter once and retains both executable aliases', async () => { + const path = root() + const bin = join(path, 'dependencies/python/bin') + mkdirSync(bin, { recursive: true }) + writeFileSync(join(path, 'runtime.json'), JSON.stringify({ desktopVersion: '1', platform: 'darwin', arch: 'arm64', python: '3.12.14', pythonPackages: {} })) + writeFileSync(join(bin, 'python3.12'), Buffer.from('cffaedfe00000000', 'hex')) + for (const name of ['python', 'python3']) symlinkSync('python3.12', join(bin, name)) + await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64', undefined, 'primary')).resolves.toBe(1) + expect(signMacOSRuntimeCode).toHaveBeenCalledExactlyOnceWith(join(bin, 'python3.12'), expect.any(String), identity, undefined) + for (const name of ['python', 'python3']) expect(readlinkSync(join(bin, name))).toBe('python3.12') + await expect(signMacOSRuntime(path, 'com.example.app', identity, 'arm64')).rejects.toThrow('unsupported filesystem entry') +}) + +// The signer must inspect real file symlinks, including dangling and cyclic ones. +it.skipIf(process.platform === 'win32').each(['unknown', 'absolute', 'escaping', 'dangling', 'chained', 'directory'])('rejects a %s runtime link before signing any file', async (kind) => { + const path = root() + const bin = join(path, 'dependencies/python/bin') + mkdirSync(bin, { recursive: true }) + writeFileSync(join(path, 'runtime.json'), JSON.stringify({ desktopVersion: '1', platform: 'darwin', arch: 'arm64', python: '3.12.14', pythonPackages: {} })) + const canonical = join(bin, 'python3.12') + if (kind === 'directory') mkdirSync(canonical) + else if (kind !== 'dangling') writeFileSync(canonical, Buffer.from('cffaedfe00000000', 'hex')) + if (kind === 'chained') { + rmSync(canonical) + symlinkSync('python3', canonical) + } + const target = kind === 'absolute' ? canonical : kind === 'escaping' ? '../outside' : 'python3.12' + symlinkSync(target, join(bin, kind === 'unknown' ? 'unlisted' : 'python3')) + const result = signMacOSRuntime(path, 'com.example.app', identity, 'arm64', undefined, 'primary') + if (kind === 'dangling') await expect(result).rejects.toMatchObject({ code: 'ENOENT', path: canonical }) + else await expect(result).rejects.toThrow(kind === 'unknown' ? 'unsupported filesystem entry' : 'invalid Python alias') + expect(signMacOSRuntimeCode).not.toHaveBeenCalled() +}) it('awaits other signers before rejecting and permitting output cleanup', async () => { const path = root() for (const name of ['a.node', 'b.node']) writeFileSync(join(path, name), Buffer.from('cffaedfe00000000', 'hex')) diff --git a/apps/desktop/tests/prepare-windows-ci.spec.ts b/apps/desktop/tests/prepare-windows-ci.spec.ts index 4633a77a12..67d62bbe19 100644 --- a/apps/desktop/tests/prepare-windows-ci.spec.ts +++ b/apps/desktop/tests/prepare-windows-ci.spec.ts @@ -1,56 +1,22 @@ -import { parseEnv } from 'node:util' import { describe, expect, it } from 'vitest' -import { windowsCiSettings } from '../scripts/prepare-windows-ci.mjs' -import { validateDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs' +import { windowsCiVersion } from '../scripts/prepare-windows-ci.mjs' -const inputs = { - PACKAGE_BUILD_VERSION: 'auto', - PACKAGE_DEPLOYMENT: 'test', - PACKAGE_POLICY_ORIGIN: 'https://policy.example.com', - PACKAGE_LOGIN_ORIGINS: 'https://login.example.com, https://sso.example.com', - GITHUB_RUN_NUMBER: '42', - GITHUB_RUN_ATTEMPT: '2', -} -const productVersion = '0.2.1-alpha.1' -const now = new Date('2026-10-08T23:59:59Z') +const inputs = { PACKAGE_BUILD_VERSION: 'auto', GITHUB_RUN_NUMBER: '42', GITHUB_RUN_ATTEMPT: '2' } +const now = new Date('2026-10-09T01:02:03Z') -describe('manual Windows package inputs', () => { - it('numbers fresh runners and reruns without storage credentials', () => { - const result = windowsCiSettings(inputs, productVersion, now) - expect(result.version).toBe('0.2.1-alpha.1.20261008.42.2') - const settings = parseEnv(result.settings) - expect(() => { validateDesktopPackageEnvironment(settings, { platform: 'win32', arch: 'x64' }, { unsigned: true }) }).not.toThrow() - expect(Object.keys(settings).sort()).toEqual([ - 'DSH_DESKTOP_APP_ID', 'DSH_DESKTOP_AUTO_UPDATE_ENV', - 'DSH_DESKTOP_MANDATORY_UPDATE_TEST_ORIGIN', 'DSH_DESKTOP_MANDATORY_UPDATE_CONFIG', - ].sort()) +describe('manual Windows CI version', () => { + it('uses the selected product prefix and UTC run identity', () => { + expect(windowsCiVersion(inputs, '0.2.1-alpha.1', now)).toBe('0.2.1-alpha.1.20261009.42.2') + expect(windowsCiVersion(inputs, '0.2.1', now)).toBe('0.2.1-test.20261009.42.2') }) - - it('accepts an explicit version without a GitHub run identity', () => { - const result = windowsCiSettings({ ...inputs, PACKAGE_BUILD_VERSION: '0.2.1-alpha.1.20261008.7', - GITHUB_RUN_NUMBER: undefined, GITHUB_RUN_ATTEMPT: undefined }, productVersion, now) - expect(result.version).toBe('0.2.1-alpha.1.20261008.7') + it.each(['0.2.1-alpha.1', '0.2.1-alpha.1.20261009.7'])('accepts explicit version %s without run identity', (version) => { + expect(windowsCiVersion({ PACKAGE_BUILD_VERSION: version }, '0.2.1-alpha.1', now)).toBe(version) }) - - it('uses the stable product test prefix and anonymous production policy', () => { - const result = windowsCiSettings({ ...inputs, PACKAGE_DEPLOYMENT: 'production', PACKAGE_LOGIN_ORIGINS: '' }, '0.2.1', now) - expect(result.version).toBe('0.2.1-test.20261008.42.2') - expect(() => { validateDesktopPackageEnvironment(parseEnv(result.settings), { platform: 'win32', arch: 'x64' }, { unsigned: true }) }).not.toThrow() + it.each(['', 'bad', '0.3.0'])('reports checkout-specific guidance for %s', (version) => { + expect(() => windowsCiVersion({ PACKAGE_BUILD_VERSION: version }, '0.2.1-alpha.1', now)) + .toThrow(/auto, 0\.2\.1-alpha\.1, or e\.g\. 0\.2\.1-alpha\.1\.20261009\.1/u) }) - - it.each([ - { PACKAGE_BUILD_VERSION: '' }, - { PACKAGE_BUILD_VERSION: '0.3.0' }, - { PACKAGE_DEPLOYMENT: 'staging' }, - { PACKAGE_POLICY_ORIGIN: '' }, - { PACKAGE_POLICY_ORIGIN: 'http://policy.example.com' }, - { PACKAGE_POLICY_ORIGIN: 'https://policy.example.com/path' }, - { PACKAGE_LOGIN_ORIGINS: '' }, - { PACKAGE_LOGIN_ORIGINS: 'https://user:password@login.example.com' }, - { PACKAGE_DEPLOYMENT: 'production' }, - { GITHUB_RUN_NUMBER: '0' }, - { GITHUB_RUN_ATTEMPT: '1\nINJECTED=value' }, - ])('rejects invalid manual settings %j', (override) => { - expect(() => windowsCiSettings({ ...inputs, ...override }, productVersion, now)).toThrow() + it.each([{ GITHUB_RUN_NUMBER: '0' }, { GITHUB_RUN_ATTEMPT: '1\nINJECTED=value' }])('rejects invalid run identity %j', (override) => { + expect(() => windowsCiVersion({ ...inputs, ...override }, '0.2.1', now)).toThrow(/positive integer/u) }) }) diff --git a/apps/desktop/tests/ptc-runtime.spec.ts b/apps/desktop/tests/ptc-runtime.spec.ts index e2f8fca009..0766da0e67 100644 --- a/apps/desktop/tests/ptc-runtime.spec.ts +++ b/apps/desktop/tests/ptc-runtime.spec.ts @@ -30,7 +30,7 @@ it.skipIf(process.platform !== 'darwin' || !electronInstalled).each(['workspace- await mkdir(cwd) vi.stubEnv('ELECTRON_RUN_AS_NODE', '1') vi.stubEnv('DSH_TEST_RUNTIME_SECRET', 'must-not-inherit') - const runtime = await mountRuntime(ctx, { launch: { kind: 'node-script', executable: electron } }, { mode, workspaceRoot: cwd }) + const { runtime } = await mountRuntime(ctx, { launch: { kind: 'node-script', executable: electron } }, { mode, workspaceRoot: cwd }) const result = await runtime.run(runtime.resolve({ // Bound startup failure before the outer test deadline, leaving time for managed cleanup. timeoutMs: 30_000, diff --git a/apps/desktop/tests/runtime-file-policy.spec.ts b/apps/desktop/tests/runtime-file-policy.spec.ts index a0b392f41e..ed478b42f6 100644 --- a/apps/desktop/tests/runtime-file-policy.spec.ts +++ b/apps/desktop/tests/runtime-file-policy.spec.ts @@ -27,6 +27,8 @@ it('omits development artifacts while preserving executable modules, assets and 'node-pty/prebuilds/win32-x64/conpty.pdb', '@koromix/koffi-win32-x64/win32_x64/koffi.lib', '@mixmark-io/domino/test/entities.html', + '@mixmark-io/domino/.yarn/plugins/@yarnpkg/plugin-version.cjs', + '@mixmark-io/domino/.yarn/versions/release.yml', '@deepseek-ai/libreoffice-kit-wasm/assets/soffice.data', '@deepseek-ai/libreoffice-kit-darwin-arm64/bin/libreoffice-kit', '.modules.yaml', '.pnpm-workspace-state-v1.json', '.bin/tool', '.pnpm/cache', @@ -45,6 +47,8 @@ it('omits development artifacts while preserving executable modules, assets and 'node-pty/third_party/conpty/win10-x64/OpenConsole.exe', '@koromix/koffi-win32-x64/win32_x64/koffi.node', '@mixmark-io/domino/lib/HTMLParser.js', '@mixmark-io/domino/lib/EntityParser.js', + '@mixmark-io/domino/LICENSE', '@mixmark-io/domino/package.json', + 'example/.yarn/runtime.cjs', '@mixmark-io/domino/.yarn-data.json', '@img/sharp-win32-x64/lib/libvips-42.dll', '@deepseek-ai/libreoffice-kit-win32-x64/bin/libreoffice-kit.exe', '@deepseek-ai/libreoffice-kit-win32-x64/sources/core-source.json', @@ -73,6 +77,8 @@ it('omits development artifacts while preserving executable modules, assets and it('applies package-specific rules inside scoped and nested dependency containers', () => { expect(desktopRuntimeFileExclusion('outer/node_modules/@mixmark-io/domino/test/data.html', windows, 'win32-x64')).toBeDefined() + expect(desktopRuntimeFileExclusion('outer/node_modules/@mixmark-io/domino/.yarn/plugin.cjs', windows, 'win32-x64')).toBeDefined() + expect(desktopRuntimeFileExclusion('@mixmark-io/domino/.yarn', windows, 'win32-x64')).toBeDefined() expect(desktopRuntimeFileExclusion('outer\\node_modules\\node-pty\\prebuilds\\win32-arm64\\conpty.node', windows, 'win32-x64')).toBeDefined() expect(desktopRuntimeFileExclusion('outer/node_modules/unrelated/test/data.html', windows, 'win32-x64')).toBeUndefined() expect(desktopRuntimeFileExclusion('outer/fs-ext/build/Release/fs_ext.lib', windows, 'win32-x64')).toBeUndefined() diff --git a/apps/desktop/tests/windows-package-preset.spec.ts b/apps/desktop/tests/windows-package-preset.spec.ts new file mode 100644 index 0000000000..c64372309b --- /dev/null +++ b/apps/desktop/tests/windows-package-preset.spec.ts @@ -0,0 +1,93 @@ +import { spawnSync } from 'node:child_process' +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { loadDesktopPackageEnvironment } from '../scripts/desktop-package-environment.mjs' + +async function withPreset(run: (root: string) => Promise) { + const root = await mkdtemp(join(tmpdir(), 'dsh-windows-preset-')) + try { + await mkdir(join(root, 'presets')) + await mkdir(join(root, 'secrets')) + await writeFile(join(root, 'presets/test.env'), 'DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDSH_DESKTOP_APP_ID=com.example.desktop\n') + await run(root) + } finally { + await rm(root, { recursive: true, force: true }) + } +} + +it('loads unsigned public settings without requiring the signing secret file or personal dotenv', async () => { + await withPreset(async (root) => { + const environment = loadDesktopPackageEnvironment('win32', { + DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test', DSH_DESKTOP_WINDOWS_TOKEN_PIN: 'ambient-secret', + }, join(root, 'missing-checkout'), { unsigned: true }) + expect(environment.DSH_DESKTOP_APP_ID).toBe('com.example.desktop') + expect(environment.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined() + const prepared = loadDesktopPackageEnvironment('win32', { + DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test', + }, root, { prepareOnly: true }) + expect(prepared.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBeUndefined() + expect(prepared.DSH_PACKAGING_PRESET).toBe('test') + expect(() => loadDesktopPackageEnvironment('win32', { DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' })) + .toThrow(/cannot read/u) + }) +}) + +it('resolves signing file paths relative to the secret file and rejects public overrides there', async () => { + await withPreset(async (root) => { + const env = { DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' } + const file = join(root, 'secrets/windows-signing.env') + await writeFile(file, 'DSH_DESKTOP_WINDOWS_CER_FILE=../certificates/ev.cer\nDSH_DESKTOP_WINDOWS_TOKEN_PIN="private-value"\n') + const result = loadDesktopPackageEnvironment('win32', env) + expect(result.DSH_DESKTOP_WINDOWS_CER_FILE).toBe(join(root, 'certificates/ev.cer')) + expect(result.DSH_DESKTOP_WINDOWS_TOKEN_PIN).toBe('private-value') + await writeFile(file, 'DSH_DESKTOP_AUTO_UPDATE_ENV=production\n') + expect(() => loadDesktopPackageEnvironment('win32', env)).toThrow(/unsupported setting/u) + }) +}) + +it('preserves the selected preset when Windows environment enumeration uses lowercase keys', async () => { + await withPreset(async (root) => { + const values: NodeJS.ProcessEnv = { dsh_packaging_config_dir: root, dsh_packaging_preset: 'test' } + const environment = new Proxy(values, { + get: (target, name) => typeof name === 'string' ? target[name.toLowerCase()] : undefined, + }) + const selected = loadDesktopPackageEnvironment('win32', environment, root, { unsigned: true }) + expect(selected.DSH_PACKAGING_PRESET).toBe('test') + }) +}) + +it('rejects missing presets, traversal, deployment mismatches and secrets in public configuration', async () => { + await withPreset(async (root) => { + const env = { DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' } + const load = (override = {}) => loadDesktopPackageEnvironment('win32', { ...env, ...override }, root, { unsigned: true }) + expect(() => load({ DSH_PACKAGING_CONFIG_DIR: 'relative' })).toThrow(/absolute/u) + expect(() => load({ DSH_PACKAGING_CONFIG_DIR: undefined })).toThrow(/absolute/u) + expect(() => loadDesktopPackageEnvironment('darwin', env)).toThrow(/Windows only/u) + expect(() => load({ DSH_PACKAGING_PRESET: '../secrets' })).toThrow(/preset must/u) + expect(() => load({ DSH_PACKAGING_PRESET: 'production' })).toThrow(/cannot read/u) + await writeFile(join(root, 'presets/test.env'), 'DSH_DESKTOP_AUTO_UPDATE_ENV=production\n') + expect(() => load()).toThrow(/must match/u) + await writeFile(join(root, 'presets/test.env'), 'DSH_DESKTOP_WINDOWS_TOKEN_PIN=private-value\n') + expect(() => load()).toThrow(/unsupported setting DSH_DESKTOP_WINDOWS_TOKEN_PIN/u) + expect(() => load()).not.toThrow(/private-value/u) + }) +}) + +it('cache maintenance reaches cache path validation without a signing file', async () => { + await withPreset(async (root) => { + await writeFile(join(root, 'presets/test.env'), + 'DSH_DESKTOP_AUTO_UPDATE_ENV=test\nDSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR=relative-cache\n') + const result = spawnSync(process.execPath, + [join(import.meta.dirname, '../scripts/manage-windows-signature-cache.mjs'), '--usage'], { + env: { ...process.env, DSH_PACKAGING_CONFIG_DIR: root, DSH_PACKAGING_PRESET: 'test' }, + encoding: 'utf8', timeout: 10_000, windowsHide: true, + }) + expect(result.error).toBeUndefined() + expect(result.signal).toBeNull() + expect(result.status).toBe(1) + expect(result.stderr).toContain('absolute local') + expect(result.stderr).not.toContain('cannot read') + }) +}) diff --git a/apps/web/katex-fonts.ts b/apps/web/katex-fonts.ts new file mode 100644 index 0000000000..702437384b --- /dev/null +++ b/apps/web/katex-fonts.ts @@ -0,0 +1,33 @@ +/** WOFF2-only KaTeX font sources for the Web and Desktop browser bundle. */ + +import { transform } from 'lightningcss' +import type { Plugin } from 'vite' + +/** + * Select WOFF2 before Vite collects KaTeX font assets, preserving every face and layout rule. + * A face without WOFF2 rejects the build. Other packages' stylesheets are unchanged. + * @returns Vite stylesheet transform for the installed KaTeX distribution. + */ +export function katexWoff2Fonts(): Plugin { + return { + name: 'dsh-katex-woff2-fonts', + enforce: 'pre', + transform(code, id) { + if (!/\/node_modules\/katex\/dist\/katex(?:\.min)?\.css(?:\?|$)/u.test(id.replaceAll('\\', '/'))) return + const result = transform({ + filename: id, code: Buffer.from(code), sourceMap: true, + visitor: { Rule: { 'font-face'(rule) { + const descriptors = rule.value.properties.filter(property => property.type === 'source') + if (descriptors.length === 0) throw new Error('KaTeX font face requires a WOFF2 source') + for (const property of descriptors) { + const sources = property.value.filter(source => source.type === 'url' && source.value.format?.type === 'woff2') + if (sources.length === 0) throw new Error('KaTeX font face requires a WOFF2 source') + property.value = sources + } + return rule + } } }, + }) + return { code: result.code.toString(), map: result.map?.toString() } + }, + } +} diff --git a/apps/web/package.json b/apps/web/package.json index 0b44c5cd00..1684c9a9d8 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -49,8 +49,6 @@ "@deepseek-ai/dsh-session-projection-cache": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@types/node": "^22.20.1", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "@types/ws": "8.18.1", "@vitejs/plugin-react": "^4.7.0", "http-server": "^14.1.1", diff --git a/apps/web/tests/agent-preset-selection.e2e.ts b/apps/web/tests/agent-preset-selection.e2e.ts index 6fc12aba02..61a9a2ad34 100644 --- a/apps/web/tests/agent-preset-selection.e2e.ts +++ b/apps/web/tests/agent-preset-selection.e2e.ts @@ -455,8 +455,9 @@ it.each([false, true])('starts Creator from Plugins with Coding Tools=%s without await page.getByRole('navigation', { name: 'Global panels' }).getByRole('button', { name: 'Plugins', exact: true }).click() await page.getByRole('button', { name: 'Choose how to add a plugin', exact: true }).click() + // The Creator entry reuses the draft's blank Session and names its preset in the creation request. await Promise.all([ - page.waitForResponse('**/api/agentPresets/select'), + page.waitForResponse('**/api/session/create'), page.getByRole('menuitem', { name: /^Let the agent create a plugin/ }).click(), ]) const picker = page.getByTitle('Choose the agent preset for your new task', { exact: true }).filter({ hasText: 'Creator mode' }) @@ -469,8 +470,9 @@ it.each([false, true])('starts Creator from Plugins with Coding Tools=%s without expect(scaffold.ctx.agentPresets.composedPreset(creator.ctx)).toBe('cordis') expect(scaffold.ctx.tools.schemas(creator).map(tool => tool.name)) .toEqual(expect.arrayContaining(['cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager'])) - expect(creator.session.snapshotEvents().some(event => event.type === 'agent-preset/selected' - && event.data.agentPreset === 'cordis')).toBe(true) + // The chip may also select Creator once the list updates; the registry records the switch only once. + expect(creator.session.snapshotEvents().filter(event => event.type === 'agent-preset/selected' + && event.data.agentPreset === 'cordis')).toHaveLength(1) expect(creator.session.snapshotEvents().some(event => event.type === 'user/message' || event.type === 'turn/start')).toBe(false) expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: developerTools }) expect(scaffold.ctx.agentPresets.defaultId).toBe('standard') diff --git a/apps/web/tests/blank-preset-reuse.e2e.ts b/apps/web/tests/blank-preset-reuse.e2e.ts new file mode 100644 index 0000000000..5f9958ab5f --- /dev/null +++ b/apps/web/tests/blank-preset-reuse.e2e.ts @@ -0,0 +1,131 @@ +/** Blank Session reuse under the requested or default Agent preset through the shipped Web composition. */ + +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { newEnglishPage } from './support.ts' + +/** A preset these blank Sessions recorded that the deployment no longer declares. */ +const UNDECLARED = 'liangshen' + +describe('web e2e: blank Session reuse under the requested preset', () => { + let scaffold: WebScaffold + let browser: Browser + const tripwires: ReturnType[] = [] + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + browser = await chromium.launch() + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + /** Store a blank Session recorded under `agentPreset`, with a plan-mode switch, as the only member of a new Workspace. */ + async function storeBlank(sessionId: SessionId, folder: string, agentPreset: string): Promise { + const path = join(scaffold.workspaceCwd, folder) + await mkdir(path) + const workspace = await scaffold.ctx.workspaceRegistry.create(path) + const handle = await scaffold.ctx.agents.create({ + sessionId, + meta: { cwd: path, agentPreset }, + agentOptions: scaffold.ctx.agentDefaultModel.currentSelection(), + }) + try { + handle.agent.session.append('plan/mode', { active: true }) + await workspace.attachSession(sessionId) + } finally { + await handle.dispose() + } + } + + async function openPage(saved?: SessionId): Promise { + const page = await newEnglishPage(browser) + tripwires.push(watchConsole(page)) + if (saved !== undefined) { + await page.addInitScript((id) => { + localStorage.setItem('dsh.sessions.current', JSON.stringify({ sessionId: id })) + }, saved) + } + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.locator('[data-composer-input]').first().waitFor({ timeout: 30_000 }) + return page + } + + async function selected(page: Page): Promise { + return page.evaluate(() => { + const value = localStorage.getItem('dsh.sessions.current') + return value === null ? undefined : (JSON.parse(value) as { sessionId?: string }).sessionId + }) + } + + /** The live Agent's mounted preset, its projected preset, and its plan-mode state. */ + function liveComposition(sessionId: SessionId) { + const agent = scaffold.ctx.agents.get(sessionId) + if (agent === undefined) return undefined + return { + mounted: scaffold.ctx.agentPresets.composedPreset(agent.ctx), + projected: scaffold.ctx.sessionProjections.stateOf(agent.session, 'agentPreset'), + plan: scaffold.ctx.sessionProjections.stateOf(agent.session, 'plan'), + } + } + + async function storedSelections(sessionId: SessionId): Promise { + const handle = await scaffold.ctx.sessionPersistence.open(sessionId, 'read') + try { + const { events } = await handle.read() + return events + .filter((event: SessionEvent) => event.type === 'agent-preset/selected') + .map((event: SessionEvent) => event.data) + } finally { + await handle.close() + } + } + + it('reuses a blank recorded under an undeclared preset under the default when startup connects its Workspace', async () => { + const stale = SessionId('blank-undeclared') + await storeBlank(stale, 'undeclared', UNDECLARED) + + const page = await openPage() + await expect.poll(() => selected(page)).toBe(stale) + await expect.poll(() => liveComposition(stale)).toMatchObject({ + mounted: 'standard', projected: 'standard', plan: { active: true }, + }) + expect(await storedSelections(stale)).toEqual([{ agentPreset: 'standard' }]) + expect(scaffold.ctx.workspaceRegistry.list().find(item => item.sessionIds.includes(stale))?.sessionIds).toEqual([stale]) + expect(await page.getByRole('alert').count()).toBe(0) + }) + + it('restores a saved blank under the preset it recorded', async () => { + const picked = SessionId('blank-picked') + await storeBlank(picked, 'picked', 'minimal') + + const page = await openPage(picked) + await expect.poll(() => selected(page)).toBe(picked) + await expect.poll(() => liveComposition(picked)).toMatchObject({ mounted: 'minimal', projected: 'minimal' }) + expect(await storedSelections(picked)).toEqual([]) + }) + + it('restores a saved blank under the default once its recorded preset is undeclared', async () => { + const saved = SessionId('saved-undeclared') + await storeBlank(saved, 'saved-undeclared', UNDECLARED) + + const page = await openPage(saved) + await expect.poll(() => selected(page)).toBe(saved) + await expect.poll(() => liveComposition(saved)).toMatchObject({ + mounted: 'standard', projected: 'standard', plan: { active: true }, + }) + expect(await storedSelections(saved)).toEqual([{ agentPreset: 'standard' }]) + expect(await page.getByRole('alert').count()).toBe(0) + for (const tripwire of tripwires) { + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } + }) +}) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index 16a053b6aa..955d251ab7 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -6,15 +6,15 @@ import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page } from 'playwright' +import type { Browser, Page, Route } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import type { StreamChunk } from '@deepseek-ai/dsh-llm' -import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { ToolCallId, createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import type { AssistantStreamFrame } from '@deepseek-ai/dsh-agent' import type { ReplayEntry, ReplayOverrideDoc } from '@deepseek-ai/dsh-llm-replay' import type { SessionEvent } from '@deepseek-ai/dsh-session' -import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' +import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session' import { createChatScrollFixture, type ChatScrollFixture } from './chat-scroll-fixture.ts' import { launchWebScaffold, @@ -28,7 +28,7 @@ import { expandOwningTurnProcess, newEnglishPage, openSettings, saveFailureShot const MODE = webSnapshotMode() const HISTORY_SESSION_ID = 'chat-scroll-history-e2e' -const TOOL_SESSION_ID = 'chat-scroll-tool-e2e' +const TOOL_SESSION_ID = SessionId('chat-scroll-tool-e2e') const RESTORE_SESSION_A_ID = 'chat-scroll-restore-a-e2e' const RESTORE_SESSION_B_ID = 'chat-scroll-restore-b-e2e' const REPLAY_CONTEXT_WINDOW = 10_000_000 @@ -47,7 +47,7 @@ const TOOL_READY_FILE = '.chat-scroll-tool-ready' const TOOL_RELEASE_FILE = '.chat-scroll-tool-release' const INPUTS_SESSION_ID = 'chat-scroll-inputs-e2e' const RAIL_SESSION_ID = 'chat-scroll-rail-e2e' -const FLING_SESSION_ID = 'chat-scroll-fling-e2e' +const FLING_SESSION_ID = SessionId('chat-scroll-fling-e2e') const LIVE_FLING_PROMPT = 'CHAT_SCROLL_FLING_USER Keep streaming while I fling back through older output.' const LIVE_FLING_FIRST = 'CHAT_SCROLL_FLING_STREAM_FIRST' const LIVE_FLING_DONE = 'CHAT_SCROLL_FLING_STREAM_DONE' @@ -74,6 +74,22 @@ const INPUTS_FIXTURE = createChatScrollFixture({ title: 'CHAT_SCROLL_INPUTS non-wheel reader input session', }) +interface FoldMotionSample { + readonly t: number + readonly ordinaryGrowth: boolean + readonly top: number + readonly bodyY: number + readonly earlierY: number + readonly messageY: number | null + readonly stepY: number | null + readonly flowHeight: number + readonly height: number + readonly spacer: number + readonly folding: boolean + readonly raceApplied: boolean + readonly composerTop: number +} + interface ScrollGeometry { readonly distanceFromBottom: number readonly scrollTop: number @@ -95,6 +111,8 @@ interface ScrollWorld { interface ScrollWorldOptions { readonly failureShot: string + /** Install a controllable browser clock before boot; omitted worlds use real time. */ + readonly controlledClock?: boolean readonly paceMs?: number readonly replay?: ReplayOverrideDoc readonly seeds: readonly { fixture: ChatScrollFixture; id: string }[] @@ -190,6 +208,7 @@ async function launchScrollWorld(options: ScrollWorldOptions): Promise { events.push(event) }) scaffold.ctx.on('agent/assistant-stream', ({ frame }) => { assistantFrames.push(frame) }) page = await newEnglishPage(browser, 900) + if (options.controlledClock) await page.clock.install() const tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) @@ -525,115 +544,374 @@ describe('web e2e: long Chat scroll contract', () => { await browser?.close() }) - it.skipIf(MODE === 'record')('merges a large process fold with new-input following without returning downward', async () => { - const fixture = createChatScrollFixture({ markerPrefix: 'FOLD', title: 'CHAT_FOLD_INPUT', turns: 8 }) - const input = 'CHAT_FOLD_NEXT_INPUT' - const artifactRoot = fileURLToPath(new URL('../../../.artifacts/fold-input-e2e/', import.meta.url)) - await mkdir(artifactRoot, { recursive: true }) - const evidence = await mkdtemp(join(artifactRoot, 'run-')) - await withScrollWorld({ - failureShot: 'web-e2e-fold-input-motion', - replay: [replayEntry(textStream('CHAT_FOLD_REPLY', 'CHAT_FOLD_DONE', 2))], - seeds: [{ fixture, id: 'chat-fold-input-e2e' }], - }, async (world) => { - const { page } = world - await page.setViewportSize({ width: 1280, height: 720 }) - await page.emulateMedia({ reducedMotion: 'no-preference' }) - await openSeed(page, fixture, fixture.markers.assistant(8)) - await openSettings(page, 'en') - await page.getByRole('dialog', { name: 'Settings', exact: true }) - .getByText('When to Collapse Work Details', { exact: true }).locator('../..') - .getByRole('button', { name: 'On completion', exact: true }).click() - await page.getByRole('menuitem', { name: 'On next message', exact: true }).click() - await page.keyboard.press('Escape') - for (const index of [1, 2]) { - const row = page.locator(`[data-chat-call-id="chat-scroll-008-${index}"] [data-sample="bash"]`) - await row.click() - await expect.poll(() => row.getAttribute('aria-expanded')).toBe('true') + for (const scenario of [ + { name: 'body-only', bodyParagraphs: 32, inputLines: 1, reduced: false }, + { name: 'visible-steps', bodyParagraphs: 2, inputLines: 1, reduced: false }, + { name: 'large-input', bodyParagraphs: 2, inputLines: 18, reduced: false }, + { name: 'reduced-motion', bodyParagraphs: 2, inputLines: 1, reduced: true }, + { name: 'cancel-all-during-fold', bodyParagraphs: 2, inputLines: 1, reduced: false }, + { name: 'content-growth-during-fold', bodyParagraphs: 32, inputLines: 1, reduced: false }, + ]) { + it.skipIf(MODE === 'record')(`uses only visible fold room in one upward movement: ${scenario.name}`, async () => { + const base = createChatScrollFixture({ markerPrefix: 'VISIBLE_FOLD', title: `CHAT_VISIBLE_FOLD_${scenario.name}`, turns: 8 }) + const parsed = parseSeedFixture(base.log) + const boundary = parsed.events.findIndex(event => event.type === 'turn/start' && event.data.turn === 8) + const drafts: (SessionEvent | { type: string; data: object; surfaceOp?: 'append' })[] = [ + ...parsed.events.slice(0, boundary), + { type: 'turn/start', data: { turn: 8 } }, + { type: 'user/message', data: createUserMessage({ + content: [{ type: 'text', text: 'VISIBLE_FOLD_EARLIER_ANCHOR' }], source: { kind: 'user' }, + }), surfaceOp: 'append' }, + ] + for (let step = 1; step <= 6; step++) { + drafts.push({ type: 'step/start', data: { turn: 8, step } }) + drafts.push({ type: 'assistant/message', surfaceOp: 'append', data: { + turn: 8, step, stream: [], message: createAssistantMessage({ + content: [ + { type: 'reasoning', text: `VISIBLE_FOLD_STEP_${step}\n\n${Array.from({ length: 18 }, (_, line) => + `Reasoning stage ${step}, paragraph ${line}: retained work details explain this intermediate decision.`).join('\n\n')}` }, + { type: 'text', text: `VISIBLE_FOLD_PROGRESS_${step}` }, + ], source: { provider: 'fixture', model: 'fixture' }, + }), + } }) + drafts.push({ type: 'step/end', data: { turn: 8, step } }) } - await wheelTranscript(page, -600) - await page.getByRole('button', { name: 'Back to bottom', exact: true }).click() - await expectBottom(page) - const beforeHeight = await page.locator('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])') - .evaluate(element => element.getBoundingClientRect().height) - const release = holdTextAfter(world, 0) - const trace = page.evaluate(marker => new Promise<{ - readonly t: number - readonly top: number - readonly messageY: number - readonly columnHeight: number - readonly spacer: number - readonly folding: boolean - }[]>((resolve) => { - const host = document.querySelector('[data-conversation-scroll]')! - const column = host.querySelector('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])')! - const samples: { t: number; top: number; messageY: number; columnHeight: number; spacer: number; folding: boolean }[] = [] - let frame = 0 - let timer = 0 - const sample = (): void => { - const message = Array.from(column.querySelectorAll('*')) - .find(element => element.children.length === 0 && element.textContent === marker) - if (message === undefined) return - samples.push({ t: performance.now(), top: host.scrollTop, messageY: message.getBoundingClientRect().top, - columnHeight: column.getBoundingClientRect().height, - spacer: Number.parseFloat(host.querySelector('[data-chat-turn-spacer]')?.style.height ?? '') || 0, - folding: column.querySelector('[data-chat-motion="collapse"]') !== null }) + const bodyMarker = 'VISIBLE_FOLD_BODY' + drafts.push({ type: 'step/start', data: { turn: 8, step: 7 } }) + drafts.push({ type: 'assistant/message', surfaceOp: 'append', data: { + turn: 8, step: 7, stream: [], message: createAssistantMessage({ + content: [{ type: 'text', text: `${bodyMarker}\n\n${Array.from({ length: scenario.bodyParagraphs }, (_, line) => + `Final answer paragraph ${line}: this content remains after the preceding work details fold.`).join('\n\n')}` }], + source: { provider: 'fixture', model: 'fixture' }, + }), + } }) + drafts.push({ type: 'step/end', data: { turn: 8, step: 7 } }, + { type: 'turn/end', data: { turn: 8, reason: { kind: 'completed' } } }) + const fixture: ChatScrollFixture = { ...base, log: [parsed.headerLine, + ...drafts.map((event, seq) => JSON.stringify({ ...event, seq, time: seq + 1 })), ''].join('\n') } + const input = Array.from({ length: scenario.inputLines }, (_, index) => `VISIBLE_FOLD_NEXT_${index}`).join('\n') + const artifactRoot = fileURLToPath(new URL('../../../.artifacts/screenshots/visible-fold/', import.meta.url)) + await mkdir(artifactRoot, { recursive: true }) + const evidence = await mkdtemp(join(artifactRoot, `${scenario.name}-`)) + const controlledClock = scenario.name === 'content-growth-during-fold' || scenario.name === 'cancel-all-during-fold' + await withScrollWorld({ + failureShot: `visible-fold-${scenario.name}`, + controlledClock, + replay: [replayEntry(textStream('VISIBLE_FOLD_REPLY', 'VISIBLE_FOLD_DONE', 2))], + seeds: [{ fixture, id: `visible-fold-${scenario.name}` }], + }, async (world) => { + const { page } = world + await page.setViewportSize({ width: 1280, height: 720 }) + await page.emulateMedia({ reducedMotion: scenario.reduced ? 'reduce' : 'no-preference' }) + await openSeed(page, fixture, bodyMarker) + await openSettings(page, 'en') + const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }) + const timing = dialog.getByText('When to Collapse Work Details', { exact: true }).locator('../..') + await timing.getByRole('button').click() + await page.getByRole('menuitem', { name: 'On next message', exact: true }).click() + const details = dialog.getByText('Work details', { exact: true }).locator('../..') + await details.getByRole('button').click() + await page.getByRole('menuitem', { name: 'Detailed', exact: true }).click() + await dialog.getByRole('button', { name: 'Close', exact: true }).click() + const thoughts = page.locator('[data-chat-turn="8"] [data-variant="think"]') + await expect.poll(() => thoughts.count()).toBe(6) + for (let index = 0; index < 6; index++) { + const button = thoughts.nth(index).getByRole('button').first() + if (await button.getAttribute('aria-expanded') !== 'true') await button.click() } - const tick = (): void => { - timer = window.setTimeout(() => { sample(); frame = requestAnimationFrame(tick) }, 0) - } - host.addEventListener('dsh-test-fold-stop', () => { - cancelAnimationFrame(frame) - window.clearTimeout(timer) - sample() - host.removeAttribute('data-fold-probe-ready') - resolve(samples) - }, { once: true }) - host.setAttribute('data-fold-probe-ready', '') - frame = requestAnimationFrame(tick) - }), input) - await page.locator('[data-fold-probe-ready]').waitFor() - let settled: ReturnType | undefined - try { - await page.locator('[data-composer-input][contenteditable="true"]').last().fill(input) - await page.getByRole('button', { name: 'Send message', exact: true }).click() - settled = world.scaffold.whenTurnSettled(30_000) - await page.getByText(input, { exact: true }).waitFor() - await expect.poll(() => page.locator('[data-chat-motion="collapse"]').count()).toBe(0) + await wheelTranscript(page, -600) + await page.getByRole('button', { name: 'Back to bottom', exact: true }).click() await expectBottom(page) await nextPaint(page) - } finally { - await page.locator('[data-conversation-scroll]').evaluate(host => host.dispatchEvent(new Event('dsh-test-fold-stop'))) - release() - await settled - } - const samples = await trace - expect(samples.length).toBeGreaterThan(4) - const first = samples[0]! - let minimum = first.messageY - let reversal = 0 - let maximumScroll = first.top - let viewportBacktrack = 0 - for (const sample of samples) { - minimum = Math.min(minimum, sample.messageY) - if (first.messageY - minimum > 4) reversal = Math.max(reversal, sample.messageY - minimum) - maximumScroll = Math.max(maximumScroll, sample.top) - viewportBacktrack = Math.max(viewportBacktrack, maximumScroll - sample.top) - } - const last = samples.at(-1)! - const afterHeight = last.columnHeight - await writeFile(join(evidence, 'motion.json'), JSON.stringify({ beforeHeight, afterHeight, reversal, viewportBacktrack, samples }, null, 2)) - await page.screenshot({ path: join(evidence, 'settled.png') }) - console.log(`fold-input e2e: message reversal=${reversal}px, viewport backtrack=${viewportBacktrack}px, spacer=${last.spacer}px, evidence=${evidence}`) - expect(beforeHeight - afterHeight).toBeGreaterThan(250) - expect(first.messageY - minimum).toBeGreaterThan(40) - expect(reversal).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) - expect(viewportBacktrack).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) - expect(Math.abs(last.spacer - (beforeHeight - afterHeight))).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) - await expectBottom(page) - assertClean(world) - }) - }, 180_000) + await page.locator('[data-composer-input][contenteditable="true"]').last().fill(input) + await nextPaint(page) + if (scenario.name === 'visible-steps') { + const offset = 20 + await thoughts.last().getByRole('button').first().evaluate((button, offset) => { + const host = button.closest('[data-conversation-scroll]')! + const group = button.closest('[data-chat-group-key]')! + host.scrollTop += group.getBoundingClientRect().top - host.getBoundingClientRect().top - offset + host.dispatchEvent(new Event('scroll')) + }, offset) + await nextPaint(page) + } + const before = await page.locator('[data-conversation-scroll]').evaluate((host) => { + const viewport = host.getBoundingClientRect() + const composer = host.querySelector('[data-composer-seat]')! + const body = [...host.querySelectorAll('[data-chat-turn="8"][data-chat-group-part="response"]')].at(-1)! + const groups = [...host.querySelectorAll('[data-chat-turn="8"][data-chat-group-key]')] + const candidates = [...host.querySelectorAll('[data-chat-turn="8"][data-chat-group-key], [data-chat-turn="8"][data-turn-process-member="true"]')] + .filter(element => !element.parentElement?.closest('[data-chat-turn="8"][data-chat-group-key], [data-chat-turn="8"][data-turn-process-member="true"]')) + return { top: host.scrollTop, height: host.scrollHeight, viewportTop: viewport.top, + removed: candidates.map((element) => { + const rect = element.getBoundingClientRect() + const margin = Number.parseFloat(getComputedStyle(element).marginTop) || 0 + return { top: rect.top - viewport.top - margin, height: rect.height + margin } + }), + floor: Math.max(0, host.scrollHeight - host.clientHeight), + viewport: host.clientHeight, visibleHeight: composer.getBoundingClientRect().top - viewport.top, + bodyTop: body.getBoundingClientRect().top, bodyHeight: body.getBoundingClientRect().height, + flowHeight: host.querySelector('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])')!.getBoundingClientRect().height, + groupHeight: groups.reduce((sum, group) => sum + group.getBoundingClientRect().height, 0), + visibleSteps: groups.reduce((sum, group) => { + const rect = group.getBoundingClientRect() + return sum + Math.max(0, Math.min(rect.bottom, composer.getBoundingClientRect().top) - Math.max(rect.top, viewport.top)) + }, 0) } + }) + expect(before.groupHeight).toBeGreaterThan(before.visibleHeight * 3) + if (scenario.bodyParagraphs === 32) expect(before.visibleSteps).toBe(0) + else expect(before.visibleSteps).toBeGreaterThan(0) + if (scenario.name === 'cancel-all-during-fold') { + await openSettings(page, 'en') + const settings = page.getByRole('dialog', { name: 'Settings', exact: true }) + await settings.getByText('Work details', { exact: true }).locator('../..').getByRole('button').click() + await page.getByRole('menuitem', { name: 'Verbose', exact: true }).waitFor() + } + const release = holdTextAfter(world, 0) + const finishGate = Promise.withResolvers() + const finishBlocked = Promise.withResolvers() + const holdFinish = world.scaffold.ctx.on('llm/stream', async function* (_options, next) { + for await (const chunk of next()) { + if (chunk.type === 'finish') { + finishBlocked.resolve(undefined) + await finishGate.promise + } + yield chunk + } + }) + const promptGate = Promise.withResolvers() + const promptBlocked = Promise.withResolvers() + const holdPrompt = async (route: Route): Promise => { + promptBlocked.resolve(undefined) + await promptGate.promise + await route.continue() + } + await page.route('**/api/session/prompt', holdPrompt) + const trace = page.evaluate(({ marker, race }) => new Promise((resolveTrace) => { + const host = document.querySelector('[data-conversation-scroll]')! + const column = host.querySelector('[data-chat-flow]:has(> [data-slot="conversation.chat.flow"])')! + const body = [...column.querySelectorAll('[data-chat-turn="8"][data-chat-group-part="response"]')].at(-1)! + const earlier = [...column.querySelectorAll('*')].find(element => + element.children.length === 0 && element.textContent === 'VISIBLE_FOLD_EARLIER_ANCHOR')! + const samples: FoldMotionSample[] = [] + const visibleStep = [...column.querySelectorAll('[data-chat-turn="8"] [data-variant="think"] [role="button"]')].at(-1) + let frame = 0 + let ordinaryGrowth = false + let raceApplied = false + let closingHeight: number | undefined + const markGrowth = (): void => { ordinaryGrowth = true } + host.addEventListener('dsh-test-fold-growth', markGrowth) + const stepPosition = (): number | null => { + if (visibleStep === undefined || !visibleStep.isConnected || visibleStep.closest('[hidden]') !== null) return null + const rect = visibleStep.getBoundingClientRect() + if (rect.height === 0 || rect.width === 0) return null + const walker = document.createTreeWalker(visibleStep, NodeFilter.SHOW_TEXT) + let textNode = walker.nextNode() + while (textNode !== null && !(textNode.textContent ?? '').trim()) textNode = walker.nextNode() + if (textNode === null) return null + const range = document.createRange() + range.selectNodeContents(textNode) + const glyph = range.getBoundingClientRect() + return glyph.height === 0 ? null : glyph.top + } + const sample = (): void => { + const closing = [...column.querySelectorAll('[data-chat-motion="collapse"]')] + .filter(element => element.parentElement?.closest('[data-chat-motion="collapse"]') === null) + const height = closing.reduce((sum, element) => sum + element.getBoundingClientRect().height, 0) + if (closing.length > 0) closingHeight ??= height + if (!raceApplied && closingHeight !== undefined && height > 0 && height < closingHeight - 1) { + if (race === 'cancel-all-during-fold') { + const verbose = [...document.querySelectorAll('[role="menuitem"]')] + .find(element => element.textContent?.trim() === 'Verbose') + if (verbose !== undefined) { + raceApplied = true + verbose.click() + } + } else if (race === 'content-growth-during-fold') { + // Controlled layout growth exercises ResizeObserver overlap, not Session-event delivery. + raceApplied = true + column.style.paddingBottom = '320px' + } + if (raceApplied) host.setAttribute('data-fold-race-applied', '') + } + const message = [...column.querySelectorAll('[data-submission-echo], [data-chat-flow-kind="user"]')] + .find(element => element.textContent?.includes(marker)) + const step = stepPosition() + samples.push({ t: performance.now(), ordinaryGrowth, top: host.scrollTop, bodyY: body.getBoundingClientRect().top, + earlierY: earlier.getBoundingClientRect().top, messageY: message?.getBoundingClientRect().top ?? null, + stepY: step, + flowHeight: column.getBoundingClientRect().height, height: host.scrollHeight, + spacer: host.querySelector('[data-chat-turn-spacer]')!.getBoundingClientRect().height, + folding: column.querySelector('[data-chat-motion="collapse"]') !== null, raceApplied, + composerTop: host.querySelector('[data-composer-seat]')!.getBoundingClientRect().top }) + } + const tick = (): void => { sample(); frame = requestAnimationFrame(tick) } + host.addEventListener('dsh-test-fold-stop', () => { + cancelAnimationFrame(frame); sample() + host.removeEventListener('dsh-test-fold-growth', markGrowth) + host.removeAttribute('data-fold-race-applied') + host.removeAttribute('data-fold-probe-ready'); resolveTrace(samples) + }, { once: true }) + sample(); host.setAttribute('data-fold-probe-ready', ''); frame = requestAnimationFrame(tick) + }), { marker: 'VISIBLE_FOLD_NEXT_0', race: scenario.name }) + await page.locator('[data-fold-probe-ready]').waitFor() + let settled: ReturnType | undefined + let samples: Awaited = [] + try { + settled = world.scaffold.whenTurnSettled(30_000) + if (controlledClock) { + // Advance every animation frame so the race cannot miss the intermediate fold height. + await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000)) + try { + await page.getByRole('button', { name: 'Send message', exact: true }).evaluate((button) => { + if (!(button instanceof HTMLButtonElement)) throw new Error('Send control is not a button') + button.click() + }) + await expect.poll(async () => { + await page.clock.runFor(16) + return page.locator('[data-fold-race-applied]').count() + }, { timeout: 10_000 }).toBe(1) + await expect.poll(async () => { + await page.clock.runFor(16) + return page.locator('[data-chat-motion="collapse"]').count() + }, { timeout: 10_000 }).toBe(0) + } finally { + await page.clock.resume() + } + } else await page.getByRole('button', { name: 'Send message', exact: true }).click() + await promptBlocked.promise + await page.getByText(input, { exact: true }).waitFor() + await expect.poll(() => page.locator('[data-chat-motion="collapse"]').count()).toBe(0) + if (scenario.name !== 'cancel-all-during-fold') await expectBottom(page) + await page.locator('[data-conversation-scroll]').evaluate(async (host) => { + let previous = host.scrollTop + let stableSince = performance.now() + await new Promise((resolveStable) => { + const check = (): void => { + const now = performance.now() + if (Math.abs(host.scrollTop - previous) > 0.25) stableSince = now + previous = host.scrollTop + if (now - stableSince >= 240) resolveStable() + else requestAnimationFrame(check) + } + requestAnimationFrame(check) + }) + }) + await page.locator('[data-conversation-scroll]').evaluate(host => host.dispatchEvent(new Event('dsh-test-fold-growth'))) + promptGate.resolve(undefined) + release() + await finishBlocked.promise + await page.getByText('VISIBLE_FOLD_DONE', { exact: false }).waitFor() + await expectBottom(page) + await nextPaint(page) + } finally { + promptGate.resolve(undefined) + release() + await page.unroute('**/api/session/prompt', holdPrompt) + await page.locator('[data-conversation-scroll]').evaluate(host => host.dispatchEvent(new Event('dsh-test-fold-stop'))) + samples = await trace + finishGate.resolve(undefined) + holdFinish() + await settled + } + const allSamples = samples + const ordinarySamples = samples.filter(sample => sample.ordinaryGrowth) + samples = samples.filter(sample => !sample.ordinaryGrowth) + const first = samples[0]! + const last = samples.at(-1)! + const closedBoxesHeight = before.removed.reduce((sum, box) => sum + box.height, 0) + const removedHeight = first.bodyY + first.top - last.bodyY - last.top + const boundaryGrowth = closedBoxesHeight - removedHeight + const aboveRemoved = Math.min(removedHeight, + before.removed.reduce((sum, box) => sum + Math.min(box.height, Math.max(0, -box.top)), 0)) + const remainingHeight = last.height - last.spacer + const newHeight = remainingHeight - before.height + removedHeight + const baseTop = Math.max(0, before.top - aboveRemoved) + const expectedTop = Math.max(baseTop, remainingHeight - before.viewport, 0) + const expectedSpacer = expectedTop === 0 ? 0 : Math.max(0, expectedTop + before.viewport - remainingHeight) + const ordinaryFollow = expectedTop - baseTop + const expectedBodyShift = removedHeight - aboveRemoved + ordinaryFollow + const bodyShift = first.bodyY - last.bodyY + const reversalOf = (values: readonly number[]): number => { + let lowest = values[0] ?? 0 + let reversal = 0 + for (const value of values) { + lowest = Math.min(lowest, value) + reversal = Math.max(reversal, value - lowest) + } + return reversal + } + const reversal = reversalOf(samples.map(sample => sample.bodyY)) + const inputReversal = reversalOf(samples.flatMap(sample => sample.messageY === null ? [] : [sample.messageY])) + const ordinaryBodyReversal = reversalOf([samples.at(-1)!.bodyY, ...ordinarySamples.map(sample => sample.bodyY)]) + const ordinaryInputReversal = reversalOf(ordinarySamples.flatMap(sample => sample.messageY === null ? [] : [sample.messageY])) + const stepReversal = reversalOf(samples.flatMap(sample => sample.stepY === null ? [] : [sample.stepY])) + const firstFoldIdle = samples.findIndex((sample, index) => index > 0 && !sample.folding && samples[index - 1]!.folding) + const afterFold = firstFoldIdle < 0 ? [] : samples.slice(firstFoldIdle) + const range = (values: number[]): number => values.length === 0 ? 0 : Math.max(...values) - Math.min(...values) + const foldBoundaryMovement = firstFoldIdle > 0 + ? Math.abs(samples[firstFoldIdle]!.bodyY - samples[firstFoldIdle - 1]!.bodyY) : 0 + const priorFrameMovements = samples.slice(1, Math.max(1, firstFoldIdle - 1)) + .map((sample, index) => Math.abs(sample.bodyY - samples[index]!.bodyY)) + const secondMovement = range(afterFold.map(sample => sample.bodyY)) + const secondInputMovement = range(afterFold.flatMap(sample => sample.messageY === null ? [] : [sample.messageY])) + const earlierShift = first.earlierY - last.earlierY + await writeFile(join(evidence, 'motion.json'), JSON.stringify({ scenario, before, closedBoxesHeight, removedHeight, boundaryGrowth, aboveRemoved, + remainingHeight, newHeight, expectedTop, expectedSpacer, expectedBodyShift, bodyShift, ordinaryFollow, + earlierShift, reversal, inputReversal, stepReversal, secondMovement, secondInputMovement, + ordinaryBodyReversal, ordinaryInputReversal, samples: allSamples }, null, 2)) + console.log(`visible-fold ${scenario.name}: spacer=${last.spacer}/${expectedSpacer}, top=${last.top}/${expectedTop}, reversal=${reversal}, secondMovement=${secondMovement}, evidence=${evidence}`) + if (scenario.name === 'cancel-all-during-fold') { + expect(samples.some(sample => sample.raceApplied)).toBe(true) + expect(last.folding).toBe(false) + expect(last.spacer).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect(await page.getByRole('dialog', { name: 'Settings', exact: true }) + .getByText('Work details', { exact: true }).locator('../..') + .getByRole('button', { name: 'Verbose', exact: true }).count()).toBe(1) + expect(await page.locator('[data-input-fold]').count()).toBe(0) + assertClean(world) + return + } + if (scenario.name === 'content-growth-during-fold') { + expect(samples.some(sample => sample.raceApplied && sample.folding)).toBe(true) + expect.soft(foldBoundaryMovement).toBeLessThanOrEqual(Math.max(...priorFrameMovements) + GEOMETRY_TOLERANCE) + } + expect.soft(removedHeight).toBeGreaterThan(before.visibleHeight * 3) + if (!scenario.reduced) { + expect.soft(samples.some(sample => sample.folding)).toBe(true) + const movingSamples = samples.filter((sample, index) => index > 0 + && Math.abs(sample.bodyY - samples[index - 1]!.bodyY) > 0.25) + expect.soft(movingSamples.length).toBeGreaterThan(1) + expect.soft(firstFoldIdle).toBeGreaterThan(0) + } + if (scenario.name === 'visible-steps') { + expect.soft(first.stepY).not.toBeNull() + expect.soft(first.stepY!).toBeGreaterThanOrEqual(before.viewportTop) + expect.soft(first.stepY!).toBeLessThan(first.composerTop) + const initial = samples.filter(sample => sample.stepY !== null && sample.t <= samples[firstFoldIdle - 1]!.t) + expect.soft(Math.max(...initial.map(sample => sample.stepY!)) - first.stepY!).toBeLessThanOrEqual(0.5) + } + expect.soft(Math.abs(last.top - expectedTop)).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(Math.abs(last.spacer - expectedSpacer)).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(Math.abs(bodyShift - expectedBodyShift)).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(reversal).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(inputReversal).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(stepReversal).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(ordinarySamples.length).toBeGreaterThan(0) + expect.soft(ordinaryBodyReversal).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(ordinaryInputReversal).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(secondMovement).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(secondInputMovement).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + if (first.earlierY >= before.viewportTop) { + expect.soft(Math.abs(earlierShift - ordinaryFollow)).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + } + if (scenario.name === 'body-only' || scenario.name === 'large-input') expect.soft(last.spacer).toBeLessThanOrEqual(GEOMETRY_TOLERANCE) + expect.soft(last.messageY).not.toBeNull() + expect.soft(last.messageY!).toBeLessThan(last.composerTop) + assertClean(world) + }) + }, 180_000) + } it.skipIf(MODE === 'record')('resets transcript height when switching from Verbose back to Standard during a reply', async () => { const fixture = createChatScrollFixture({ markerPrefix: 'MODE', title: 'CHAT_MODE_HEIGHT', turns: 8 }) @@ -1317,6 +1595,9 @@ describe('web e2e: long Chat scroll contract', () => { const readyPath = join(world.scaffold.workspaceCwd, TOOL_READY_FILE) const releasePath = join(world.scaffold.workspaceCwd, TOOL_RELEASE_FILE) await openSeed(world.page, TOOL_FIXTURE, TOOL_FIXTURE.markers.assistant(TOOL_FIXTURE.turns)) + const resolved = await world.scaffold.ctx.sessionController.resolveAgent(TOOL_SESSION_ID) + if ('error' in resolved) throw resolved.error + world.scaffold.ctx.permissionPresets.set(resolved.agent.session, 'danger-full-access') const settled = world.scaffold.whenTurnSettled(60_000) let released = false try { @@ -1549,6 +1830,9 @@ describe('web e2e: long Chat scroll contract', () => { const readyPath = join(world.scaffold.workspaceCwd, TOOL_READY_FILE) const releasePath = join(world.scaffold.workspaceCwd, TOOL_RELEASE_FILE) await openSeed(world.page, INPUTS_FIXTURE, INPUTS_FIXTURE.markers.assistant(INPUTS_FIXTURE.turns)) + const resolved = await world.scaffold.ctx.sessionController.resolveAgent(FLING_SESSION_ID) + if ('error' in resolved) throw resolved.error + world.scaffold.ctx.permissionPresets.set(resolved.agent.session, 'danger-full-access') const backToBottom = world.page.getByRole('button', { name: 'Back to bottom', exact: true }) const settled = world.scaffold.whenTurnSettled(60_000) const releaseText = holdTextAfter(world, 16) diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index 21c131a764..db35e15a1f 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -30,7 +30,7 @@ it('places dynamic Session menu rows by order among the shipped ones and removes const scaffold = await launchWebScaffold({ extraInstallAnchors: [join(FIXTURE, 'package.json')] }) onTestFinished(() => scaffold.close()) const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd) - const sessionId = await seedSession(scaffold, await readFile(SESSION_SEED, 'utf8'), 'session-menu-actions-web-e2e') + const sessionId = await seedSession(scaffold, await readFile(SESSION_SEED, 'utf8'), 'session-c4421b66-252e-44c0-80ed-6e320abeba25') await workspace.attachSession(sessionId) await scaffold.ctx.sessionController.rename({ sessionId, title: SESSION_TITLE }) const entryId = await scaffold.ctx.loader.create({ name: '@fixture/live-client' }) @@ -71,13 +71,18 @@ it('places dynamic Session menu rows by order among the shipped ones and removes await row.hover() await trigger.click() await menu.waitFor() - const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Archive session'] + const remainingNames = ['Pin session', 'Rename', 'Fork session', 'Archive session', 'Copy Session ID'] const remainingItems = menu.getByRole('menuitem') expect(await remainingItems.count()).toBe(remainingNames.length) for (const [index, name] of remainingNames.entries()) { expect(await remainingItems.nth(index).and(menu.getByRole('menuitem', { name, exact: true })).count()).toBe(1) } expect(await menu.getByRole('separator').count()).toBe(0) + await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) + await menu.getByRole('menuitem', { name: 'Copy Session ID', exact: true }).click() + await expect.poll(() => menu.count()).toBe(0) + await page.getByRole('alert').filter({ hasText: 'Session ID copied' }).waitFor() + expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(sessionId) expect(console.pageErrors).toEqual([]) await assertFixtureInventory(EXPECTED, [ 'bootstrap-rebuild.expected.md', 'enabled.expected.md', 'recovered.expected.md', diff --git a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md index f3c45cace9..51df861f77 100644 --- a/apps/web/tests/expected/client-plugin-live/session-actions.expected.md +++ b/apps/web/tests/expected/client-plugin-live/session-actions.expected.md @@ -3,6 +3,7 @@ - menuitem "Rename" - menuitem "Fork session" - menuitem "Archive session" + - menuitem "Copy Session ID" - separator - menuitem "Export session" - menuitem "Copy session ID" diff --git a/apps/web/tests/expected/menu-material/session-menu.expected.md b/apps/web/tests/expected/menu-material/session-menu.expected.md index 88405f3950..ebb1786386 100644 --- a/apps/web/tests/expected/menu-material/session-menu.expected.md +++ b/apps/web/tests/expected/menu-material/session-menu.expected.md @@ -3,3 +3,4 @@ - menuitem "Rename" - menuitem "Fork session" - menuitem "Archive session" + - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/navigation-panes/command-wrap.expected.md b/apps/web/tests/expected/navigation-panes/command-wrap.expected.md new file mode 100644 index 0000000000..cafac4c6df --- /dev/null +++ b/apps/web/tests/expected/navigation-panes/command-wrap.expected.md @@ -0,0 +1,14 @@ +[ + { + "colorScheme": "light", + "wrapped": true, + "text": "echo NAVIGATION_OK", + "copiedText": "echo NAVIGATION_OK" + }, + { + "colorScheme": "dark", + "wrapped": true, + "text": "echo NAVIGATION_OK", + "copiedText": "echo NAVIGATION_OK" + } +] diff --git a/apps/web/tests/expected/seeded-history/blank-reasoning.expected.md b/apps/web/tests/expected/seeded-history/blank-reasoning.expected.md new file mode 100644 index 0000000000..ab493a1aff --- /dev/null +++ b/apps/web/tests/expected/seeded-history/blank-reasoning.expected.md @@ -0,0 +1,4 @@ +- button "Think" [expanded] +- paragraph: The user wants me to read a.txt and b.txt, then reply with "DONE". Let me do both reads in parallel. + +- Reasoning rows: 1 diff --git a/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md b/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md index b4584b0486..239b4855e7 100644 --- a/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md +++ b/apps/web/tests/expected/settings-chrome/plugin-instances.expected.md @@ -1,18 +1,20 @@ - list: - listitem: - - button "tool-subagent-control, 已启用": - - strong: tool-subagent-control - - text: Globally named send_message, interrupt_agent, and list_agents tools over ctx.subagents continuations + - button "子智能体控制工具, tool-subagent-control, 已启用": + - strong: 子智能体控制工具 + - text: 让 AI 向子智能体发送消息或中断其运行。 + - code: tool-subagent-control - listitem: - - button "tool-subagent-control/list-agents, tool-subagent-list-agents, 已启用": - - strong: tool-subagent-control/list-agents + - button "子智能体列表工具, tool-subagent-list-agents, 已启用": + - strong: 子智能体列表工具 - code: tool-subagent-list-agents - listitem: - - button "tool-subagent, 已启用": - - strong: tool-subagent - - text: Model-facing subagent delegation tool over the ctx.subagents seam + - button "子智能体委派工具, tool-subagent, 已启用": + - strong: 子智能体委派工具 + - text: 让 AI 将任务交给子智能体,并获取运行结果。 + - code: tool-subagent - listitem: - - button "tool-subagent, tool-subagent-fork, 已启用": - - strong: tool-subagent - - text: Model-facing subagent delegation tool over the ctx.subagents seam + - button "子智能体委派工具, tool-subagent-fork, 已启用": + - strong: 子智能体委派工具 + - text: 让 AI 将任务交给子智能体,并获取运行结果。 - code: tool-subagent-fork diff --git a/apps/web/tests/expected/settings-chrome/plugins.expected.md b/apps/web/tests/expected/settings-chrome/plugins.expected.md index 20e096a308..22b5bc2c80 100644 --- a/apps/web/tests/expected/settings-chrome/plugins.expected.md +++ b/apps/web/tests/expected/settings-chrome/plugins.expected.md @@ -1,4 +1,5 @@ - listitem: - - button "tool-subagent, 已启用": - - strong: tool-subagent - - text: Model-facing subagent delegation tool over the ctx.subagents seam + - button "子智能体委派工具, tool-subagent, 已启用": + - strong: 子智能体委派工具 + - text: 让 AI 将任务交给子智能体,并获取运行结果。 + - code: tool-subagent diff --git a/apps/web/tests/expected/shell-command-details/background-long-token.expected.md b/apps/web/tests/expected/shell-command-details/background-long-token.expected.md new file mode 100644 index 0000000000..c9e1765740 --- /dev/null +++ b/apps/web/tests/expected/shell-command-details/background-long-token.expected.md @@ -0,0 +1,3 @@ +- button "Bash Start the diagnostic worker" [expanded] +- text: {{workspace}} node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log --token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +- button "Inspect" diff --git a/apps/web/tests/expected/shell-command-details/background.expected.md b/apps/web/tests/expected/shell-command-details/background.expected.md index ffc21b3098..1b579bfa11 100644 --- a/apps/web/tests/expected/shell-command-details/background.expected.md +++ b/apps/web/tests/expected/shell-command-details/background.expected.md @@ -1,5 +1,3 @@ - button "Bash Start the diagnostic worker" [expanded] -- text: IN -- group "Command arguments": "{ \"command\": \"node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log\", \"description\": \"Start the diagnostic worker\", \"run_in_background\": true }" -- text: OUT started background job bash-1 +- text: {{workspace}} node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log - button "Inspect" diff --git a/apps/web/tests/expected/shell-command-details/foreground-multiline.expected.md b/apps/web/tests/expected/shell-command-details/foreground-multiline.expected.md new file mode 100644 index 0000000000..05fadfea88 --- /dev/null +++ b/apps/web/tests/expected/shell-command-details/foreground-multiline.expected.md @@ -0,0 +1,5 @@ +- button "Bash Start the diagnostic worker" [expanded] +- text: Done {{workspace}} node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log --token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx $ echo done +- button "Copy" +- text: done +- button "Inspect" diff --git a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md index 88405f3950..ebb1786386 100644 --- a/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md +++ b/apps/web/tests/expected/shortcuts-workspace/session-menu.expected.md @@ -3,3 +3,4 @@ - menuitem "Rename" - menuitem "Fork session" - menuitem "Archive session" + - menuitem "Copy Session ID" diff --git a/apps/web/tests/expected/web-runtime-context/web-surface-prompt.expected.md b/apps/web/tests/expected/web-runtime-context/web-surface-prompt.expected.md index bb37e36cfb..cc84fced0a 100644 --- a/apps/web/tests/expected/web-runtime-context/web-surface-prompt.expected.md +++ b/apps/web/tests/expected/web-runtime-context/web-surface-prompt.expected.md @@ -1 +1 @@ -You are interacting with the user through the DeepSeek Harness Web GUI at {{webUrl}}. When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. The browser provides no implicit DOM, route, or screenshot context. The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. Starting another server does not update this GUI. The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL. +You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. The browser provides no implicit DOM, route, or screenshot context. The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. Starting another server does not update this GUI. The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL. diff --git a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js index 6a6f8b9777..7736cb2949 100644 --- a/apps/web/tests/fixtures/plugins/fixture-live-client/client.js +++ b/apps/web/tests/fixtures/plugins/fixture-live-client/client.js @@ -89,7 +89,7 @@ window.__ModuleLoader__.load({ ) }) ctx.slots.inject('sidebar.workspaces.session.menu.item', function* () { - // The shipped rows end at archive (400); these follow as one group, + // The shipped rows end at Session ID (450); these follow as one group, // opened by the export row's hairline. yield registerSessionAction('fixture.export-session', 500, 'exportSession', true) yield registerSessionAction('fixture.copy-session-id', 600, 'copySessionId', false) diff --git a/apps/web/tests/katex-fonts.spec.ts b/apps/web/tests/katex-fonts.spec.ts new file mode 100644 index 0000000000..1e7d2f47c5 --- /dev/null +++ b/apps/web/tests/katex-fonts.spec.ts @@ -0,0 +1,75 @@ +import { readFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { transform } from 'lightningcss' +import { build, loadConfigFromFile } from 'vite' +import { expect, it, onTestFinished } from 'vitest' + +const require = createRequire(new URL('../../../packages/client/ui-primitives/package.json', import.meta.url)) +const stylesheet = require.resolve('katex/dist/katex.min.css') + +/** Build a stylesheet with the application's asset plugins without writing artifacts. */ +async function bundleStyle(source: { path: string } | { package: string; css: string }) { + const root = await mkdtemp(join(tmpdir(), 'katex-fonts-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + let input: string + if ('path' in source) input = source.path + else { + input = join(root, 'node_modules', source.package, 'dist', 'katex.min.css') + await mkdir(dirname(input), { recursive: true }) + await writeFile(input, source.css) + await writeFile(join(dirname(input), 'font.woff'), 'fixture font') + } + const loaded = await loadConfigFromFile({ command: 'build', mode: 'production' }, fileURLToPath(new URL('../vite.config.ts', import.meta.url))) + if (!loaded) throw new Error('Expected the Web build configuration') + // The product isolation check requires the full application's HTML entry. + const plugins = (loaded.config.plugins ?? []).flat().filter(plugin => !(plugin && typeof plugin === 'object' + && 'name' in plugin && plugin.name === 'dsh-product-web-bundle-isolation')) + const result = await build({ + ...loaded.config, configFile: false, plugins, + root, logLevel: 'silent', + build: { write: false, cssMinify: false, assetsInlineLimit: 0, rollupOptions: { input } }, + }) + if ('on' in result) throw new Error('Expected a completed build') + return (Array.isArray(result) ? result : [result]).flatMap(bundle => bundle.output) +} + +/** Normalize layout CSS independently of emitted font URLs and format fallbacks. */ +function layoutCss(css: string): string { + return transform({ + filename: 'layout.css', code: Buffer.from(css), minify: true, + visitor: { Rule: { 'font-face'(rule) { + rule.value.properties = rule.value.properties.filter(property => property.type !== 'source') + return rule + } } }, + }).code.toString() +} + +it('ships all KaTeX WOFF2 faces with identical font bytes and layout styles', async () => { + const output = await bundleStyle({ path: stylesheet }) + const fonts = output.filter(asset => asset.type === 'asset' && /\.(?:woff2?|ttf)$/u.test(asset.fileName)) + expect(fonts).toHaveLength(20) + for (const font of fonts) { + expect(font.fileName).toMatch(/\.woff2$/u) + if (font.type !== 'asset') throw new Error('Expected a font asset') + const name = font.names[0]! + expect(Buffer.from(font.source)).toEqual(await readFile(join(dirname(stylesheet), 'fonts', name))) + } + const css = output.find(asset => asset.type === 'asset' && asset.fileName.endsWith('.css')) + if (css?.type !== 'asset') throw new Error('Expected a stylesheet asset') + const text = Buffer.from(css.source).toString() + expect(text).not.toMatch(/\.(?:woff|ttf)["')]/u) + expect(layoutCss(text)).toBe(layoutCss(await readFile(stylesheet, 'utf8'))) +}) + +it.each(['src: url(font.woff) format("woff");', ''])('rejects a KaTeX face without WOFF2 (src=%s)', async (source) => { + await expect(bundleStyle({ package: 'katex', css: `@font-face { font-family: KaTeX_Main; ${source} }` })) + .rejects.toThrow('KaTeX font face requires a WOFF2 source') +}) + +it('preserves older font formats in unrelated stylesheets', async () => { + const output = await bundleStyle({ package: 'other', css: '@font-face { font-family: Other; src: url(font.woff) format("woff"); }' }) + expect(output.some(asset => asset.type === 'asset' && asset.fileName.endsWith('.woff'))).toBe(true) +}) diff --git a/apps/web/tests/markdown-file-links.e2e.ts b/apps/web/tests/markdown-file-links.e2e.ts index e7acd74152..3b9cb9879b 100644 --- a/apps/web/tests/markdown-file-links.e2e.ts +++ b/apps/web/tests/markdown-file-links.e2e.ts @@ -1,18 +1,66 @@ /** Cold-replayed Markdown references open Session files through the shipped Web composition. */ import { mkdir, readFile, writeFile } from 'node:fs/promises' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium, type Browser, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import { SESSION_FORMAT_VERSION, Session, SessionId } from '@deepseek-ai/dsh-session' +import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' +import type {} from '@deepseek-ai/dsh-session-title' import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { newEnglishPage, saveFailureShot } from './support.ts' +import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links', import.meta.url)) const MODE = webSnapshotMode() +/** Build live test input with a parent-path link and a read result naming the same Host file. */ +function parentPathFixture(path: string): string { + const session = Session.create(SessionId('parent-file-links-source')) + session.append('turn/start', { turn: 1 }) + const user = session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Read the parent-path file and link lines 24 and 30.' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('session/title', { title: 'Parent file links', messageSeqs: [user.seq], source: { kind: 'fallback' } }) + session.append('step/start', { turn: 1, step: 1 }) + const callId = ToolCallId('parent-file-read') + const args = JSON.stringify({ file_path: path, offset: 24, limit: 7 }) + session.append('assistant/message', { + turn: 1, step: 1, stream: [], + message: createAssistantMessage({ + content: [{ type: 'tool-call', id: callId, name: 'read', arguments: args }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) + const call = session.append('tool/call', { turn: 1, step: 1, callId, name: 'read', arguments: args }) + session.append('tool/result', { + turn: 1, step: 1, meta: { path: '{{cwd}}/parent.txt' }, + message: createToolResultMessage({ callId, content: [{ type: 'text', text: 'parent line 24\n' }], isError: false }), + }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + session.append('step/end', { turn: 1, step: 1 }) + session.append('step/start', { turn: 1, step: 2 }) + session.append('assistant/message', { + turn: 1, step: 2, stream: [], + message: createAssistantMessage({ + content: [{ type: 'text', text: `[Parent file:24–30](<${path}#L24-L30>) · [Parent file:30](<${path}#L30>)` }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn: 1, step: 2 }) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + return [ + JSON.stringify({ + type: 'session', version: SESSION_FORMAT_VERSION, id: '{{sessionId}}', createdAt: 0, + cwd: '{{cwd}}', isSeeded: false, delegationDepth: 0, + }), + ...session.snapshotEvents().map(event => JSON.stringify(event)), + '', + ].join('\n') +} + describe('web e2e: Markdown file links', () => { let scaffold: WebScaffold let browser: Browser @@ -78,4 +126,55 @@ describe('web e2e: Markdown file links', () => { expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, ['session.v3.jsonl', 'links.expected.md', 'preview.expected.md']) }) + + it('opens parent-path prose and read-card links while retaining each address across reload', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-parent-file-links')) + // Return through the parent into this owned temp root; no shared parent file is created. + const path = `../${basename(scaffold.workspaceCwd)}/parent.txt` + await writeFile(join(scaffold.workspaceCwd, 'parent.txt'), + Array.from({ length: 60 }, (_, i) => `parent line ${i + 1}\n`).join('')) + const id = await seedSession(scaffold, parentPathFixture(path), 'parent-file-links') + await page.reload({ waitUntil: 'load' }) + const workspace = page.getByRole('treeitem').first() + await workspace.waitFor() + if (await workspace.getAttribute('aria-expanded') !== 'true') await workspace.click() + await page.locator(`[data-row-key="session:${id}"]`).click() + + const source = page.getByRole('button', { name: 'Parent file:24–30', exact: true }) + await source.click() + const column = page.locator('[data-rightbar-col]') + const stored = () => page.evaluate(key => localStorage.getItem(key), `dsh.sidebar-right.v1.${id}`) + const address = sessionFileAddress(id, path) + await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('parent line 24\n') + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()).toBe(join(scaffold.workspaceCwd, 'parent.txt')) + await expect.poll(stored).toContain(address) + const tabs = column.locator('[data-dockkit-tab-title]') + expect(await tabs.allTextContents()).toEqual(['parent.txt']) + + const later = page.getByRole('button', { name: 'Parent file:30', exact: true }) + await later.focus() + await later.press('Enter') + await expect.poll(() => column.locator('[data-textpreview-target="30"]').textContent()).toBe('parent line 30\n') + expect(await tabs.allTextContents()).toEqual(['parent.txt']) + + await page.reload({ waitUntil: 'load' }) + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()).toBe(join(scaffold.workspaceCwd, 'parent.txt')) + await expect.poll(stored).toContain(address) + await source.click() + await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('parent line 24\n') + expect(await tabs.allTextContents()).toEqual(['parent.txt']) + + const readCardLink = page.locator('[data-tool="read"] button').filter({ hasText: 'parent.txt' }) + await expandOwningTurnProcess(page, readCardLink) + await readCardLink.click() + await expect.poll(() => column.locator('[data-textpreview-path]').textContent()).toBe(join(scaffold.workspaceCwd, 'parent.txt')) + await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('parent line 24\n') + // The Host-reported path and the unresolved prose path are distinct resource identities. + expect(await tabs.allTextContents()).toEqual(['parent.txt', 'parent.txt']) + await expect.poll(stored).toContain(sessionFileAddress(id, 'parent.txt')) + await source.click() + expect(await tabs.allTextContents()).toEqual(['parent.txt', 'parent.txt']) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) }) diff --git a/apps/web/tests/math-rendering.e2e.ts b/apps/web/tests/math-rendering.e2e.ts index 5e7d11d7fd..d7fa2b8873 100644 --- a/apps/web/tests/math-rendering.e2e.ts +++ b/apps/web/tests/math-rendering.e2e.ts @@ -122,6 +122,13 @@ describe('web e2e: settled Markdown math rendering', () => { await expect.poll(() => page.locator('.katex').count(), { timeout: 10_000 }).toBe(6) await expect.poll(() => page.locator('.katex-display').count(), { timeout: 10_000 }).toBe(2) expect(await page.locator('.katex-error').count()).toBe(0) + const fonts = await page.evaluate(async () => { + const faces = [...document.fonts].filter(face => face.family.includes('KaTeX_')) + await Promise.all(faces.map(face => face.load())) + return faces.map(face => face.status) + }) + expect(fonts).toHaveLength(20) + expect(fonts.every(status => status === 'loaded')).toBe(true) await expect.poll( () => page.getByText('1 turns 1 steps', { exact: false }).count(), { timeout: 10_000 }, diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index d121cbf579..75202aea47 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -20,7 +20,7 @@ import { launchWebScaffold, recordFixture, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts' -import { expectSelectableTerminalCommand } from './terminal-command-browser.ts' +import { expectWrappedTerminalCommand } from './terminal-command-browser.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/navigation-panes', import.meta.url)) const SEED = join(SNAPSHOT_DIR, 'session.v3.jsonl') @@ -29,6 +29,7 @@ const TIMING_EXPECTED = join(SNAPSHOT_DIR, 'timing.expected.md') const SEARCH_EXPECTED = join(SNAPSHOT_DIR, 'search-results.expected.md') const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal-card.expected.md') const CODE_CARD_DIR = fileURLToPath(new URL('./expected/navigation-panes', import.meta.url)) +const COMMAND_WRAP_EXPECTED = join(CODE_CARD_DIR, 'command-wrap.expected.md') const CODE_CARD_EXPECTED = join(CODE_CARD_DIR, 'code-card.expected.md') const MODE = webSnapshotMode() const SEED_ID = 'navigation-panes-web-e2e' @@ -472,7 +473,8 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { if (await bashRow.getAttribute('aria-expanded') !== 'true') await bashRow.click() const card = page.locator('[data-sample="bash"] ~ div [data-terminal]').first() await card.waitFor({ timeout: 15_000 }) - await expectSelectableTerminalCommand(page, card, 'echo NAVIGATION_OK', 300) + const commandWrap = await expectWrappedTerminalCommand(page, card, 'echo NAVIGATION_OK', 300) + await compareOrRefreshGolden(COMMAND_WRAP_EXPECTED, JSON.stringify(commandWrap, null, 2), MODE) // Real layout, not jsdom's stub (which computes no geometry at all): // squeeze the output pane below its content width and the line must keep // its single row and overflow sideways instead of folding. Soft-wrapping @@ -547,7 +549,7 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { }, 60_000) it.skipIf(MODE === 'record')('keeps the recorded fixture inventory exact', async () => { - await assertFixtureInventory(CODE_CARD_DIR, ['code-card.expected.md']) + await assertFixtureInventory(CODE_CARD_DIR, ['code-card.expected.md', 'command-wrap.expected.md']) await assertFixtureInventory(SNAPSHOT_DIR, [ 'session.v3.jsonl', 'search-results.expected.md', 'trajectory.expected.md', 'terminal-card.expected.md', 'timing.expected.md', diff --git a/apps/web/tests/notice-wake-tail.e2e.ts b/apps/web/tests/notice-wake-tail.e2e.ts new file mode 100644 index 0000000000..884adcb9d3 --- /dev/null +++ b/apps/web/tests/notice-wake-tail.e2e.ts @@ -0,0 +1,218 @@ +/** + * A Turn this Client did not submit (a subagent-settled notice) wakes while the + * reader follows the tail of a long Turn under "On next message" folding. The + * notice Turn belongs to the long Turn's exchange, so the long Turn stays + * expanded through the host's pre-Step gap and after the notice arrives, and a + * reader who was following sees the notice and its reply at the tail. + */ +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { ToolCallId, createAssistantMessage, createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { SubagentSettledMessageSource } from '@deepseek-ai/dsh-subagent' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { connectFreshWorkspace, newEnglishPage } from './support.ts' + +/** Settled Turns before the long one, so every work-details mode overflows the viewport. */ +const HISTORY_TURNS = 3 +const LONG_TURN = HISTORY_TURNS + 1 +const NOTICE_TURN = HISTORY_TURNS + 2 +/** Tool Steps in the finished Turn; their folded height must exceed the notice Turn's height. */ +const TOOL_STEPS = 12 +const OUTPUT_LINES = 40 +/** The recorded host gap between the waking claim and Step 1, spent assembling the system prompt. */ +const PRE_STEP_GAP_MS = 187 +const REPLY = 'NOTICE_WAKE_REPLY' + +interface Tail { + /** Height of the room reserved below the flow. */ + readonly spacer: number + readonly noticeVisible: boolean + readonly replyVisible: boolean + /** Whether the long Turn's process disclosure reports itself expanded. */ + readonly longTurnOpen: boolean +} + +function readTail(page: Page): Promise { + return page.evaluate(([reply, longTurn]) => { + const host = document.querySelector('[data-conversation-scroll]') + if (host === null) throw new Error('conversation scrollport is absent') + const viewTop = host.getBoundingClientRect().top + const viewBottom = host.querySelector('[data-composer-seat]')?.getBoundingClientRect().top + ?? host.getBoundingClientRect().bottom + const inView = (element: Element): boolean => { + const rect = element.getBoundingClientRect() + return rect.height > 0.5 && rect.bottom > viewTop && rect.top < viewBottom + } + const spacer = host.querySelector('[data-chat-turn-spacer]') + return { + spacer: spacer === null ? 0 : Number.parseFloat(spacer.style.height) || 0, + noticeVisible: [...host.querySelectorAll('[data-turn-trigger]')].some(inView), + replyVisible: [...host.querySelectorAll('[data-chat-flow-kind="assistant-step"]')] + .some(row => (row.textContent ?? '').includes(reply) && inView(row)), + longTurnOpen: host.querySelector(`[data-turn-process="${longTurn}"]`)?.getAttribute('aria-expanded') === 'true', + } + }, [REPLY, String(LONG_TURN)] as const) +} + +describe('web e2e: notice Turn after a long Detailed Turn', () => { + let browser: Browser + + beforeAll(async () => { + browser = await chromium.launch({ headless: true }) + }, 60_000) + + afterAll(async () => { + await browser?.close() + }) + + it.each(['detailed', 'standard'] as const)('keeps the new tail visible in %s work details', async (view) => { + const scaffold: WebScaffold = await launchWebScaffold({}) + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + try { + await page.setViewportSize({ width: 1280, height: 800 }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + await connectFreshWorkspace(page, scaffold.workspaceCwd) + await scaffold.ctx.settings.update('ui-chat', { transcriptView: view, collapseTiming: 'next-input' }) + const agent = scaffold.ctx.agents.list().at(-1) + if (agent === undefined) throw new Error('connected workspace created no Agent') + const session = agent.session + const setRunning = (running: boolean): void => { scaffold.ctx.emit('api-session/status', agent.id, running) } + + for (let turn = 1; turn <= HISTORY_TURNS; turn += 1) { + session.append('turn/start', { turn }) + session.append('step/start', { turn, step: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: `Earlier question ${String(turn)}.` }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('assistant/message', { + stream: [], + turn, + step: 1, + message: createAssistantMessage({ + content: [{ type: 'text', text: `Earlier answer ${String(turn)}. ${'This settled reply wraps across several lines of prose. '.repeat(24)}` }], + source: { provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + } + + // A long running Turn streams Step by Step while the reader follows the tail. + setRunning(true) + session.append('turn/start', { turn: LONG_TURN }) + session.append('step/start', { turn: LONG_TURN, step: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Run the long diagnostic.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + for (let step = 1; step <= TOOL_STEPS; step += 1) { + const callId = ToolCallId(`notice-wake-${String(step)}`) + const args = JSON.stringify({ command: `diagnose ${String(step)}`, description: `Diagnostic ${String(step)}` }) + session.append('assistant/message', { + stream: [], + turn: LONG_TURN, + step, + message: createAssistantMessage({ + content: [ + { type: 'reasoning', text: `Checking diagnostic ${String(step)}.` }, + { type: 'tool-call', id: callId, name: 'bash', arguments: args }, + ], + source: { provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + const call = session.append('tool/call', { turn: LONG_TURN, step, callId, name: 'bash', arguments: args }) + session.append('tool/result', { + turn: LONG_TURN, + step, + message: createToolResultMessage({ + callId, + content: [{ + type: 'text', + text: Array.from({ length: OUTPUT_LINES }, (_, line) => `diagnostic ${String(step)} line ${String(line + 1)}`).join('\n'), + }], + isError: false, + }), + }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + session.append('step/end', { turn: LONG_TURN, step }) + session.append('step/start', { turn: LONG_TURN, step: step + 1 }) + await scaffold.ctx.sessions.flush(session) + await page.locator(`[data-chat-node-key$="${callId}"]`).waitFor({ state: 'attached', timeout: 15_000 }) + } + session.append('assistant/message', { + stream: [], + turn: LONG_TURN, + step: TOOL_STEPS + 1, + message: createAssistantMessage({ + content: [{ type: 'text', text: 'All diagnostics finished.' }], + source: { provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn: LONG_TURN, step: TOOL_STEPS + 1 }) + await scaffold.ctx.sessions.flush(session) + await page.getByText('All diagnostics finished.').waitFor({ timeout: 30_000 }) + await page.evaluate(() => { + const host = document.querySelector('[data-conversation-scroll]') + if (host !== null) host.scrollTop = host.scrollHeight + }) + await page.locator('[data-chat-following-tail]').waitFor({ timeout: 10_000 }) + + // The Turn ends; 15 ms later (the recorded production gap) a settled subagent wakes the next Turn. + session.append('turn/end', { turn: LONG_TURN, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(session) + setRunning(false) + await page.waitForTimeout(15) + const source: SubagentSettledMessageSource = { + kind: 'subagent-settled', + form: 'notice', + summary: 'Background subagent finished.', + senderSessionId: SessionId('notice-wake-child'), + } + const notice = createUserMessage({ + content: [{ type: 'text', text: 'Background subagent notice-wake-child finished.' }], + source, + }) + session.append('agent/inbox/spliced', { target: 'next-turn', start: 0, inserted: [notice] }) + session.append('turn/start', { turn: NOTICE_TURN }) + session.append('agent/inbox/spliced', { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }) + setRunning(true) + await scaffold.ctx.sessions.flush(session) + // The browser has applied the notice Turn's start before the gap is held and sampled. + await page.locator(`[data-chat-turn="${String(NOTICE_TURN)}"]`).first().waitFor({ state: 'attached', timeout: 15_000 }) + await page.waitForTimeout(PRE_STEP_GAP_MS) + const gap = await readTail(page) + session.append('step/start', { turn: NOTICE_TURN, step: 1 }) + session.append('user/message', notice, { surfaceOp: 'append' }) + await scaffold.ctx.sessions.flush(session) + await page.locator('[data-turn-trigger]').first().waitFor({ state: 'attached', timeout: 15_000 }) + session.append('assistant/message', { + stream: [], + turn: NOTICE_TURN, + step: 1, + message: createAssistantMessage({ + content: [{ type: 'text', text: `${REPLY} the subagent result is acknowledged.` }], + source: { provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + await scaffold.ctx.sessions.flush(session) + + expect(gap).toMatchObject({ longTurnOpen: true, spacer: 0 }) + const settled = { noticeVisible: true, replyVisible: true, longTurnOpen: true, spacer: 0 } + await expect.poll(() => readTail(page), { timeout: 15_000 }).toMatchObject(settled) + // The settled tail survives later frames instead of passing through on the way to a fold. + await page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) }) + })) + expect(await readTail(page)).toMatchObject(settled) + expect(tripwire.warnings).toEqual([]) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await page.context().close() + await scaffold.close() + } + }, 180_000) +}) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index ac2f8c72f7..2b1fa6df62 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -37,6 +37,8 @@ import { } from '@deepseek-ai/dsh-experimental-webworker-runtime' import { VFS_EXAMPLE_SESSION_IDS, + VFS_EXAMPLE_REASONING, + VFS_EXAMPLE_WRAPPED_COMMAND, buildVfsExampleFiles, } from '../../../packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts' import { captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './scaffold.ts' @@ -455,6 +457,57 @@ async function bootPreview(origin: string, browser: Browser): Promise { await page.getByText('Update to-do list', { exact: true }).waitFor() await page.getByText('Error: ENOENT: no such file, open missing.txt', { exact: true }).waitFor() + const reasoning = page.locator('[data-variant="think"]') + await expect.poll(() => reasoning.count()).toBe(VFS_EXAMPLE_REASONING.length) + for (const [index, text] of VFS_EXAMPLE_REASONING.entries()) { + const row = reasoning.nth(index) + await row.getByRole('button').click() + await row.getByText(text.split('\n\n').at(-1)!, { exact: true }).waitFor({ state: 'visible' }) + } + + const wrappedCall = page.locator('[data-chat-call-id="preview-wrapped-bash"]') + await wrappedCall.locator('[data-sample="bash"]').click() + const terminal = wrappedCall.locator('[data-terminal]') + const originalWidth = await terminal.evaluate(element => element.style.width) + try { + await terminal.evaluate((element) => { element.style.width = '380px' }) + const commands = terminal.locator('[data-command-text]') + expect(await commands.allTextContents()).toEqual(VFS_EXAMPLE_WRAPPED_COMMAND.slice(0, -1).split('\n')) + await commands.first().scrollIntoViewIfNeeded() + const geometry = await commands.first().evaluate((element) => { + const prompt = element.parentElement! + const header = element.closest('[class*="_header_"]')! + header.scrollTop = 0 + const dot = prompt.querySelector('[data-state="done"]') + if (dot === null) throw new Error('wrapped preview command has no successful status dot') + const range = document.createRange() + range.selectNodeContents(element) + const lines = [...range.getClientRects()].filter(rect => rect.width > 0 && rect.height > 0) + const marker = dot.getBoundingClientRect() + const viewport = header.getBoundingClientRect() + return { + wrapped: new Set(lines.map(rect => Math.round(rect.top))).size > 1, + whitespace: getComputedStyle(element).whiteSpace, + alignmentError: Math.abs(marker.top + marker.height / 2 + - (prompt.getBoundingClientRect().top + Number.parseFloat(getComputedStyle(prompt).lineHeight) / 2)), + visible: marker.top >= viewport.top && marker.bottom <= viewport.bottom, + } + }) + expect(geometry.wrapped).toBe(true) + expect(geometry.whitespace).toBe('pre-wrap') + expect(geometry.alignmentError).toBeLessThanOrEqual(1) + expect(geometry.visible).toBe(true) + expect(await terminal.locator('[data-state="done"]').count()).toBe(1) + } finally { + await terminal.evaluate((element, width) => { element.style.width = width }, originalWidth) + } + + await page.getByRole('button', { name: 'Parent workspace guide:1–8', exact: true }).click() + const preview = page.locator('[data-rightbar-col]') + await expect.poll(() => preview.locator('[data-textpreview-path]').textContent()).toBe('/dsh/workspace/PREVIEW.md') + await preview.getByRole('heading', { name: 'Preview Workspace', exact: true }).waitFor({ state: 'visible' }) + expect(await preview.locator('[data-dockkit-tab-title]').allTextContents()).toEqual(['PREVIEW.md']) + const subagents = page.getByRole('button', { name: '2 subagents', exact: true }) await subagents.waitFor({ timeout: 15_000 }) await subagents.hover() diff --git a/apps/web/tests/replay-round-trip.e2e.ts b/apps/web/tests/replay-round-trip.e2e.ts index 77d9c9c54d..2b3124ad3f 100644 --- a/apps/web/tests/replay-round-trip.e2e.ts +++ b/apps/web/tests/replay-round-trip.e2e.ts @@ -213,7 +213,7 @@ describe('web e2e: fresh round trip through the real assembly', () => { } }, 200_000) - it('keeps source checkout and Web context in the system prompt and cwd in user context', async () => { + it('keeps value-free Web guidance in the system prompt and process values in runtime context', async () => { if (settledSessionId === undefined) throw new Error('the drive turn did not publish a session id') const agent = scaffold.ctx.agents.get(settledSessionId) if (agent === undefined) throw new Error(`the settled Web agent ${settledSessionId} is no longer live`) @@ -230,6 +230,8 @@ describe('web e2e: fresh round trip through the real assembly', () => { const userText = agent.session.deriveMessages().filter(message => message.role === 'user') .flatMap(message => message.content.flatMap(block => block.type === 'text' ? [block.text] : [])) expect(userText.some(text => text.includes(`Current working directory: ${JSON.stringify(cwd)}.`))).toBe(true) + expect(system).not.toContain(scaffold.baseUrl) + expect(userText.some(text => text.includes(`Current DeepSeek Harness Web GUI URL: ${JSON.stringify(scaffold.baseUrl)}.`))).toBe(true) const suffix = paragraphs.slice(-2).join('\n\n') .split(REPO_ROOT).join('{{sourceRoot}}') .split(join(scaffold.workspaceCwd, 'workspace')).join('{{cwd}}') diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index f1524ed0a5..9d8d41ccf0 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -1126,6 +1126,9 @@ export function normalizeWebSessionVolatiles(log: string, workspaceCwd?: string) let record = normalizeClientTimeZones(mapJsonStringValues(JSON.parse(line), (value) => { let normalized = value .replace(/Anonymous user: [0-9a-f-]{36}(?=\.$)/gi, 'Anonymous user: {{anonymousUserId}}') + // The checkout path and listener port differ per machine and run. + .replace(/Current DeepSeek Harness implementation checkout: "(?:[^"\\]|\\.)*"\./g, 'Current DeepSeek Harness implementation checkout: "{{sourceRoot}}".') + .replace(/Current DeepSeek Harness Web GUI URL: "(?:[^"\\]|\\.)*"\./g, 'Current DeepSeek Harness Web GUI URL: "{{webUrl}}".') for (const cwd of cwdSpellings) normalized = replaceWebCwd(normalized, cwd) return normalized })) as { type?: unknown; data?: { endpoint?: unknown } } diff --git a/apps/web/tests/seeded-history.e2e.ts b/apps/web/tests/seeded-history.e2e.ts index 085f358b85..4c6fff7f18 100644 --- a/apps/web/tests/seeded-history.e2e.ts +++ b/apps/web/tests/seeded-history.e2e.ts @@ -16,7 +16,7 @@ import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' -import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContentBlock, ContextFormed, Message, MessageSource } from '@deepseek-ai/dsh-llm' import { deriveEventMessage, SessionId } from '@deepseek-ai/dsh-session' import type { SessionEvent } from '@deepseek-ai/dsh-session' @@ -41,6 +41,7 @@ type CheckpointSource = Extract const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/seeded-history', import.meta.url)) +const REASONING_EXPECTED_DIR = fileURLToPath(new URL('./expected/seeded-history', import.meta.url)) const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) const UI_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/ui.expected.md', import.meta.url)) const UI_EXPANDED_EXPECTED = fileURLToPath( @@ -856,11 +857,68 @@ describe('web e2e: seeded history renders through cold resume', () => { await terminal.getByRole('textbox', { name: 'Terminal', exact: true }).waitFor() }) + it.skipIf(MODE === 'record')('omits blank reasoning rows around recorded text in an appended fixture turn', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-seeded-blank-reasoning')) + const session = scaffold.ctx.sessions.get(SessionId(SEED_ID)) + if (session === undefined) throw new Error('seeded session is unavailable') + const events = session.snapshotEvents() + const recorded = events.flatMap(event => event.type === 'assistant/message' ? event.data.message.content : []) + .find(block => block.type === 'reasoning' && block.text.trim() !== '') + if (recorded?.type !== 'reasoning') throw new Error('seeded history requires recorded reasoning text') + const previousEnd = events.findLast(event => event.type === 'turn/end') + if (previousEnd?.type !== 'turn/end') throw new Error('seeded history requires a closed turn') + const turn = previousEnd.data.turn + 1 + const answer = 'BLANK_REASONING_FIXTURE_DONE' + // The blank blocks are a test condition around authentic recorded text, not model output. + session.append('turn/start', { turn }) + session.append('step/start', { turn, step: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Show recorded reasoning surrounded by blank blocks.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + const message = session.append('assistant/message', { + turn, step: 1, stream: [], + message: createMessage({ + role: 'assistant', + source: { kind: 'model', provider: 'fixture', model: 'fixture' }, + content: [ + { type: 'reasoning', text: '' }, + { type: 'reasoning', text: recorded.text }, + { type: 'reasoning', text: ' \t\r\n' }, + { type: 'reasoning', text: '' }, + { type: 'text', text: answer }, + ], + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(session) + await page.getByText(answer, { exact: true }).waitFor({ timeout: 10_000 }) + const selector = `[data-chat-turn="${turn}"][data-chat-group-part="reasoning"]` + const rows = page.locator(selector).locator('[data-variant="think"]') + await expect.poll(() => rows.count(), { timeout: 10_000 }).toBe(1) + await expandOwningTurnProcess(page, rows.first()) + const toggle = rows.getByRole('button').first() + expect(await toggle.getAttribute('aria-expanded')).toBe('false') + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('true') + const body = rows.locator('[data-markdown-variant="compact"]') + await body.waitFor({ state: 'visible' }) + expect(await body.innerText()).not.toBe('') + expect(message.data.message.content[1]).toEqual({ type: 'reasoning', text: recorded.text }) + await compareOrRefreshGolden(join(REASONING_EXPECTED_DIR, 'blank-reasoning.expected.md'), [ + await captureStableAria(page, selector, scaffold.workspaceCwd), + '', + `- Reasoning rows: ${await rows.count()}`, + ].join('\n'), 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([]) + await assertFixtureInventory(REASONING_EXPECTED_DIR, ['blank-reasoning.expected.md']) await assertFixtureInventory(SNAPSHOT_DIR, [ 'command-row.expected.md', 'feedback-row.expected.md', 'file-preview.expected.md', 'session.v3.jsonl', 'sticky-geometry.expected.md', 'thinking-expanded.expected.md', diff --git a/apps/web/tests/settings-chrome.e2e.ts b/apps/web/tests/settings-chrome.e2e.ts index 2b64c107fc..6d6fd3e808 100644 --- a/apps/web/tests/settings-chrome.e2e.ts +++ b/apps/web/tests/settings-chrome.e2e.ts @@ -163,8 +163,8 @@ describe('web e2e: settings modal and General preferences', () => { expect(await enabledRows.count()).toBeGreaterThan(0) expect(await enabledRows.getByText('已启用', { exact: true }).count()).toBe(0) expect(await dialog.locator('[data-plugin-scope="global"] [role="img"][aria-label="运行中"]').count()).toBe(0) - expect(await dialog.locator('[data-plugin-count]').getAttribute('data-plugin-count')) - .toBe(String(expectedPluginCount)) + expect(await dialog.getByText('由 Agent 预设按会话组成', { exact: true }).count()).toBe(1) + expect(await dialog.getByText('系统与所有会话共用', { exact: true }).count()).toBe(1) expect(await dialog.getByRole('button', { name: '内置插件', exact: true }).getAttribute('aria-current')).toBe('true') // One contribution shows as the page itself, without a tab row. expect(await dialog.getByRole('tab').count()).toBe(0) @@ -182,17 +182,11 @@ describe('web e2e: settings modal and General preferences', () => { ] as const for (const [entryId, status] of instanceRows) { const row = dialog.locator(`[data-plugin-scope="preset"] [data-plugin-entry="${entryId}"]`) - // An id that repeats the title adds nothing, so its card shows no chip and its name omits it. - const repeatsTitle = entryId === 'tool-subagent' - const name = repeatsTitle ? `tool-subagent, ${status}` : `tool-subagent, ${entryId}, ${status}` + const name = `子智能体委派工具, ${entryId}, ${status}` const trigger = row.getByRole('button', { name, exact: true }) await trigger.waitFor({ timeout: 10_000 }) expect(await trigger.getAttribute('aria-expanded')).toBe('false') const identity = row.locator('code') - if (repeatsTitle) { - expect(await identity.count()).toBe(0) - continue - } expect(await identity.textContent()).toBe(entryId) expect(await identity.getAttribute('title')).toBe(entryId) } @@ -204,7 +198,7 @@ describe('web e2e: settings modal and General preferences', () => { ) await compareOrRefreshGolden(PLUGIN_INSTANCES_EXPECTED, instancesSnapshot, MODE) await dialog.getByRole('button', { - name: 'tool-subagent, tool-subagent-fork, 已启用', + name: '子智能体委派工具, tool-subagent-fork, 已启用', exact: true, }).click() expect(await dialog.locator('[data-plugin-entry="tool-subagent-fork"] button') @@ -943,7 +937,7 @@ describe('web e2e: settings modal and General preferences', () => { }) }) -describe('web e2e: browser-local collapse timing preference', () => { +describe('web e2e: Host-backed collapse timing preference', () => { let scaffold: WebScaffold let browser: Browser const uiWait = { timeout: 10_000 } @@ -974,11 +968,12 @@ describe('web e2e: browser-local collapse timing preference', () => { title: 'When to Collapse Work Details', completion: 'On completion', nextInput: 'On next message', description: 'Choose when to automatically collapse work details', }, - ] as const)('keeps $locale collapse timing on $theme only for the current Client', async (copy) => { + ] as const)('persists $locale collapse timing on $theme across Clients', async (copy) => { const contextOptions = { viewport: { width: 1680, height: 1000 }, locale: copy.browserLocale, colorScheme: copy.theme, timezoneId: 'Asia/Shanghai', } + await scaffold.ctx.settings.update('ui-chat', { collapseTiming: 'completion' }) const context = await browser.newContext(contextOptions) onTestFinished(() => context.close()) const page = await context.newPage() @@ -1076,19 +1071,23 @@ describe('web e2e: browser-local collapse timing preference', () => { await menu.waitFor({ state: 'hidden' }) await page.setViewportSize({ width: 1680, height: 1000 }) await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() - expect(await readPersistence()).toEqual(before) + await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait) + .toMatchObject({ transcriptView: 'detailed', collapseTiming: 'next-input' }) + const saved = await readPersistence() + expect(saved.host).not.toBe(before.host) + expect(saved.storage).toEqual(before.storage) await dialog.getByRole('button', { name: copy.close, exact: true }).click() await openSettings(page, copy.locale) await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() - expect(await readPersistence()).toEqual(before) + expect(await readPersistence()).toEqual(saved) await dialog.getByRole('button', { name: copy.close, exact: true }).click() const warningStart = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) await openSettings(page, copy.locale) - await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await timing.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() acknowledgeReloadConnectionLoss(tripwire, warningStart) - expect(await readPersistence()).toEqual(before) + expect(await readPersistence()).toEqual(saved) if (screenshotDir !== undefined) { await page.screenshot({ path: join(screenshotDir, 'reloaded.png'), fullPage: true }) } @@ -1100,10 +1099,10 @@ describe('web e2e: browser-local collapse timing preference', () => { await openSettings(sharedPage, copy.locale) const sharedTiming = sharedPage.getByRole('dialog', { name: copy.settings, exact: true }) .getByText(copy.title, { exact: true }).locator('../..') - await sharedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await sharedTiming.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() const sharedPersistence = await readPersistence(sharedPage) - expect(sharedPersistence.host).toBe(before.host) - expect(sharedPersistence.settings).toEqual(before.settings) + expect(sharedPersistence.host).toBe(saved.host) + expect(sharedPersistence.settings).toEqual(saved.settings) expect(sharedPersistence.storage.local).toEqual(before.storage.local) if (screenshotDir !== undefined) { await sharedPage.screenshot({ path: join(screenshotDir, 'shared-tab.png'), fullPage: true }) @@ -1119,22 +1118,24 @@ describe('web e2e: browser-local collapse timing preference', () => { await openSettings(isolatedPage, copy.locale) const isolatedTiming = isolatedPage.getByRole('dialog', { name: copy.settings, exact: true }) .getByText(copy.title, { exact: true }).locator('../..') - await isolatedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await isolatedTiming.getByRole('button', { name: copy.nextInput, exact: true }).waitFor() const isolatedPersistence = await readPersistence(isolatedPage) - expect(isolatedPersistence.host).toBe(before.host) - expect(isolatedPersistence.settings).toEqual(before.settings) + expect(isolatedPersistence.host).toBe(saved.host) + expect(isolatedPersistence.settings).toEqual(saved.settings) if (screenshotDir !== undefined) { await isolatedPage.screenshot({ path: join(screenshotDir, 'isolated-context.png'), fullPage: true }) } - expect(await readPersistence()).toEqual(before) - await timing.getByRole('button', { name: copy.completion, exact: true }).click() - await page.getByRole('menuitem', { name: copy.nextInput, exact: true }).click() + expect(await readPersistence()).toEqual(saved) await timing.getByRole('button', { name: copy.nextInput, exact: true }).click() await page.getByRole('menuitem', { name: copy.completion, exact: true }).click() await timing.getByRole('button', { name: copy.completion, exact: true }).waitFor() - expect(await readPersistence()).toEqual(before) - expect(settingsWrites).toEqual([]) + await expect.poll(() => scaffold.ctx.settings.describe().find(row => row.ns === 'ui-chat')?.value, uiWait) + .toMatchObject({ transcriptView: 'detailed', collapseTiming: 'completion' }) + expect((await readPersistence()).storage).toEqual(before.storage) + await sharedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + await isolatedTiming.getByRole('button', { name: copy.completion, exact: true }).waitFor() + expect(settingsWrites.length).toBeGreaterThan(0) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) expect(sharedTripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/shell-command-details.e2e.ts b/apps/web/tests/shell-command-details.e2e.ts index a219fb6941..f9c50ad056 100644 --- a/apps/web/tests/shell-command-details.e2e.ts +++ b/apps/web/tests/shell-command-details.e2e.ts @@ -8,21 +8,22 @@ import { seedSession, watchConsole, webSnapshotMode, } from './scaffold.ts' import { expandOwningTurnProcess, newEnglishPage } from './support.ts' -import { expectCommandFocusAfterResize, expectSelectableCommandText } from './terminal-command-browser.ts' +import { expectFirstLineTerminalState, expectWrappedCommandText } from './terminal-command-browser.ts' const COMMAND = 'node ./scripts/start-worker.mjs --workspace=/tmp/diagnostics/long-workspace-name-for-background-command-details --log-level=debug --trace-tag=background-shell-full-command-selection --include=worker,lifecycle,transport,subscriptions --output=/tmp/diagnostics/background-worker.log' const ARGS = { command: COMMAND, description: 'Start the diagnostic worker', run_in_background: true } const OUTPUT = 'started background job bash-1' -const EXPECTED = fileURLToPath(new URL('./expected/shell-command-details/background.expected.md', import.meta.url)) +const LONG_ARGS = { ...ARGS, command: `${COMMAND} --token=${'x'.repeat(1024)}` } -/** A settled background launch acknowledgement rendered from durable call arguments. */ -function backgroundFixture(): string { +/** A settled shell call rendered from durable arguments and its original result. */ +function shellFixture(arguments_: typeof ARGS, output: string): string { const session = Session.create(SessionId('shell-command-details-source')) const callId = ToolCallId('shell-command-details-background') - const args = JSON.stringify(ARGS) + const args = JSON.stringify(arguments_) session.append('turn/start', { turn: 1 }) session.append('user/message', createUserMessage({ - content: [{ type: 'text', text: 'Start the diagnostic worker in the background.' }], + content: [{ type: 'text', text: arguments_.run_in_background + ? 'Start the diagnostic worker in the background.' : 'Run the diagnostic worker.' }], source: { kind: 'user' }, }), { surfaceOp: 'append' }) session.append('step/start', { turn: 1, step: 1 }) @@ -36,7 +37,7 @@ function backgroundFixture(): string { const call = session.append('tool/call', { turn: 1, step: 1, callId, name: 'bash', arguments: args }) session.append('tool/result', { turn: 1, step: 1, - message: createToolResultMessage({ callId, content: [{ type: 'text', text: OUTPUT }], isError: false }), + message: createToolResultMessage({ callId, content: [{ type: 'text', text: output }], isError: false }), }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) session.append('step/end', { turn: 1, step: 1 }) session.append('step/start', { turn: 1, step: 2 }) @@ -56,10 +57,18 @@ function backgroundFixture(): string { ].join('\n') } -it('expands a background Bash launch to selectable arguments and its original acknowledgement', async () => { +it.each([ + { name: 'background', args: ARGS, output: OUTPUT }, + { name: 'background-long-token', args: LONG_ARGS, output: OUTPUT }, + { + name: 'foreground-multiline', + args: { ...LONG_ARGS, command: `${LONG_ARGS.command}\necho done\n`, run_in_background: false }, + output: 'done\n[exit code: 0]', + }, +])('expands $name to wrapped commands with only foreground output', async ({ name, args, output }) => { const scaffold = await launchWebScaffold({}) try { - await seedSession(scaffold, backgroundFixture(), 'shell-command-details-browser') + await seedSession(scaffold, shellFixture(args, output), 'shell-command-details-browser') const browser = await chromium.launch() try { const page = await newEnglishPage(browser) @@ -76,25 +85,52 @@ it('expands a background Bash launch to selectable arguments and its original ac expect(await row.getAttribute('aria-expanded')).toBe('false') await row.click() const card = row.locator('..') - const input = card.locator('[data-command-text]') + const commands = card.locator('[data-command-text]') + const input = commands.first() await input.waitFor() - expect(await input.textContent()).toBe(JSON.stringify(ARGS, null, 2)) - expect(await card.getByText(OUTPUT, { exact: true }).count()).toBe(1) - expect(await card.locator('[data-terminal]').count()).toBe(0) + const background = args.run_in_background + const selectableText = args.command.split('\n')[0]! + const inputSection = card.locator('[data-terminal] [class*="_header_"]') + expect(await input.textContent()).toBe(selectableText) + if (background) { + expect(await commands.allTextContents()).toEqual([args.command]) + expect(await card.locator('[data-terminal]').count()).toBe(1) + expect(await card.getByText(OUTPUT, { exact: true }).count()).toBe(0) + expect(await card.locator('[data-terminal][data-body], [data-terminal][data-running], [data-terminal] [data-state]').count()).toBe(0) + expect(await card.getByRole('button', { name: 'Copy', exact: true }).count()).toBe(0) + } else { + expect(await commands.allTextContents()).toEqual([selectableText, 'echo done']) + expect(await card.locator('[data-terminal]').count()).toBe(1) + expect(await card.getByText('done', { exact: true }).count()).toBe(1) + } expect(await card.getByRole('button', { name: 'Inspect', exact: true }).count()).toBe(1) for (const colorScheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme }) await expect.poll(() => page.locator('body').evaluate(element => element.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark') - for (const width of ['', '380px']) { + for (const width of ['', '380px', '']) { await card.evaluate((element, value) => { element.style.width = value }, width) - await input.scrollIntoViewIfNeeded() - await expectSelectableCommandText(page, input, COMMAND, 'Command arguments') - await expectCommandFocusAfterResize(card, input) + if (!background && width === '380px') await expectFirstLineTerminalState(card.locator('[data-terminal]'), 'done') + await expectWrappedCommandText(page, input, selectableText, inputSection) + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + if (name !== 'background') { + expect(await inputSection.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true) + await inputSection.evaluate((element) => { element.scrollTop = 0 }) + await row.focus() + await page.keyboard.press('Tab') + const focusTarget = background ? inputSection : card.getByRole('button', { name: 'Copy', exact: true }) + expect(await focusTarget.evaluate(element => document.activeElement === element)).toBe(true) + await page.keyboard.press('End') + await expect.poll(() => inputSection.evaluate(element => + element.scrollTop + element.clientHeight >= element.scrollHeight - 1)).toBe(true) + await page.keyboard.press('Home') + await expect.poll(() => inputSection.evaluate(element => element.scrollTop)).toBe(0) + } } await card.evaluate((element) => { element.style.width = '' }) } await page.emulateMedia({ colorScheme: null }) - await compareOrRefreshGolden(EXPECTED, + const expected = fileURLToPath(new URL(`./expected/shell-command-details/${name}.expected.md`, import.meta.url)) + await compareOrRefreshGolden(expected, await captureStableAria(page, '[data-chat-call-id="shell-command-details-background"]', scaffold.workspaceCwd), webSnapshotMode()) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) @@ -105,3 +141,94 @@ it('expands a background Bash launch to selectable arguments and its original ac await scaffold.close() } }) + +it.each([ + { name: 'bash', background: false }, + { name: 'pwsh', background: false }, + { name: 'bash', background: true }, + { name: 'pwsh', background: true }, +] as const)('keeps the $name command mounted through settlement (background=$background)', async ({ name, background }) => { + const scaffold = await launchWebScaffold({}) + try { + const id = await seedSession(scaffold, shellFixture(ARGS, OUTPUT), 'shell-status-dot-browser') + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl) + await page.getByRole('treeitem').first().click() + await page.getByRole('treeitem').nth(1).click() + await page.locator('[data-sample="bash"]').waitFor({ state: 'attached' }) + const resolved = await scaffold.ctx.sessionController.resolveAgent(id) + if ('error' in resolved) throw resolved.error + const session = resolved.agent.session + const callId = ToolCallId(`status-dot-${name}-${background ? 'background' : 'foreground'}`) + const args = JSON.stringify({ command: LONG_ARGS.command, description: `Long ${name} command`, run_in_background: background }) + session.append('turn/start', { turn: 2 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Show a long running command.' }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + session.append('step/start', { turn: 2, step: 1 }) + session.append('assistant/message', { + turn: 2, step: 1, stream: [], + message: createAssistantMessage({ + content: [{ type: 'tool-call', id: callId, name, arguments: args }], + source: { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, + }), + }, { surfaceOp: 'append' }) + const call = session.append('tool/call', { turn: 2, step: 1, callId, name, arguments: args }) + await scaffold.ctx.sessions.flush(session) + const callRow = page.locator(`[data-chat-call-id="${callId}"]`) + const toggle = callRow.locator('[data-expandable]').first() + await toggle.waitFor({ state: 'attached' }) + await expandOwningTurnProcess(page, toggle) + await toggle.click() + const card = callRow.locator('[data-terminal]') + await card.waitFor() + await card.evaluate((element) => { element.style.width = '380px' }) + await card.scrollIntoViewIfNeeded() + const header = card.locator('[class*="_header_"]') + const mountedCard = await card.elementHandle() + if (mountedCard === null) throw new Error('Running command card is not mounted') + expect(await header.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true) + expect(await card.getByRole('button', { name: 'Copy', exact: true }).count()).toBe(0) + for (const state of ['ongoing', 'done'] as const) { + if (state === 'done') { + session.append('tool/result', { + turn: 2, step: 1, + message: createToolResultMessage({ + callId, content: [{ type: 'text', text: background ? OUTPUT : 'status dot output\n[exit code: 0]' }], isError: false, + }), + }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + session.append('step/end', { turn: 2, step: 1 }) + session.append('turn/end', { turn: 2, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(session) + } + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await expect.poll(() => page.locator('body').evaluate(element => + element.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark') + if (background && state === 'done') { + await expect.poll(() => card.getAttribute('data-running')).toBeNull() + expect(await card.evaluate((element, previous) => element === previous, mountedCard)).toBe(true) + expect(await toggle.getAttribute('aria-expanded')).toBe('true') + expect(await card.getAttribute('data-body')).toBeNull() + expect(await card.getAttribute('data-running')).toBeNull() + expect(await card.locator('[data-state]').count()).toBe(0) + } else await expectFirstLineTerminalState(card, state) + expect(await card.locator('[data-command-text]').textContent()).toBe(LONG_ARGS.command) + } + } + expect(await card.getByText('status dot output', { exact: true }).count()).toBe(background ? 0 : 1) + expect(await card.getByText(OUTPUT, { exact: true }).count()).toBe(0) + expect(await card.getByRole('button', { name: 'Copy', exact: true }).count()).toBe(background ? 0 : 1) + expect(await callRow.getByRole('button', { name: 'Inspect', exact: true }).count()).toBe(1) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tests/smoke-real.e2e.ts b/apps/web/tests/smoke-real.e2e.ts index 31f102bff7..cf1546ccf2 100644 --- a/apps/web/tests/smoke-real.e2e.ts +++ b/apps/web/tests/smoke-real.e2e.ts @@ -476,8 +476,13 @@ describe('dsh web keyless CLI smoke', () => { .flatMap(message => message.content ?? []) .find(block => block.type === 'text' && block.text?.includes('web-workspace-context-probe')) const expectedWebSection = readFileSync(WEB_SURFACE_PROMPT, 'utf8').trimEnd() - .replace('{{webUrl}}', new URL(baseUrl).origin) expect(captured.system).toContain(expectedWebSection) + expect(captured.system).not.toContain(new URL(baseUrl).origin) + expect(captured.messages?.filter(message => message.role === 'user') + .flatMap(message => message.content ?? []) + .some(block => block.type === 'text' + && block.text?.includes(`Current DeepSeek Harness Web GUI URL: ${JSON.stringify(new URL(baseUrl).origin)}.`))) + .toBe(true) expect(workspaceMessage).toMatchInlineSnapshot(` { "text": " diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 49fe63b3d0..2324f0ae2b 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -567,7 +567,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = Math.round(clickAreaBox!.x - menuBox!.x), Math.round(menuBox!.x + menuBox!.width - clickAreaBox!.x - clickAreaBox!.width), // The outer menu padding insets the scrollable tree rows. - ]).toEqual([3, 3]) + ]).toEqual([4, 4]) await compareOrRefreshGolden( BRANCHLESS_EXPECTED, await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), diff --git a/apps/web/tests/terminal-command-browser.ts b/apps/web/tests/terminal-command-browser.ts index a1ebb77850..fb715cecea 100644 --- a/apps/web/tests/terminal-command-browser.ts +++ b/apps/web/tests/terminal-command-browser.ts @@ -64,6 +64,138 @@ export async function expectSelectableTerminalCommand(page: Page, card: Locator, } } +/** + * Select and copy text that wraps through the consumer's own stylesheet. + * @param page - Browser page that owns the text. + * @param command - One authored command line or the complete formatted arguments. + * @param expected - Exact selectable text, including authored whitespace. + * @param scrollport - Existing vertical scroll container around the text. + * @returns Observed wrapping and native clipboard text for a semantic snapshot. + */ +export async function expectWrappedCommandText( + page: Page, command: Locator, expected: string, scrollport: Locator, +): Promise<{ wrapped: boolean; text: string | null; copiedText: string }> { + expect(await command.textContent()).toBe(expected) + expect(await command.evaluate(element => getComputedStyle(element).whiteSpace)).toBe('pre-wrap') + await expectNoCommandTabStop(command) + const wrapped = await command.evaluate((element, value) => { + const text = element.firstChild + if (!(text instanceof Text)) throw new Error('Command has no text node') + const longest = value.split('\n').reduce((a, b) => a.length >= b.length ? a : b) + const offset = value.indexOf(longest) + const range = document.createRange() + range.setStart(text, offset) + range.setEnd(text, offset + longest.length) + const rows = [...range.getClientRects()].filter(rect => rect.width > 0 && rect.height > 0) + .map(rect => Math.round(rect.top)) + return new Set(rows).size > 1 + }, expected) + expect(wrapped).toBe(true) + expect(await scrollport.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + const originalScrollTop = await scrollport.evaluate(element => element.scrollTop) + const geometry = () => command.evaluate((element) => { + const text = element.firstChild + if (!(text instanceof Text) || text.length === 0) throw new Error('Command has no text node') + const first = document.createRange() + first.setStart(text, 0) + first.setEnd(text, 1) + const last = document.createRange() + last.setStart(text, text.length - 1) + last.setEnd(text, text.length) + const head = first.getBoundingClientRect() + const tail = last.getBoundingClientRect() + return { head: { x: head.left, y: head.top + head.height / 2 }, tail: { x: tail.right, y: tail.top + tail.height / 2 } } + }) + try { + await scrollport.scrollIntoViewIfNeeded() + await scrollport.evaluate((element) => { element.scrollTop = 0 }) + const start = await geometry() + const viewport = await scrollport.boundingBox() + if (viewport === null) throw new Error('Command scrollport is not visible') + await page.mouse.move(start.head.x + 0.1, start.head.y) + await page.mouse.down() + try { + if (start.tail.y > viewport.y + viewport.height) { + await page.mouse.move(start.head.x + 0.1, viewport.y + viewport.height - 2) + await page.mouse.wheel(0, await scrollport.evaluate(element => element.scrollHeight)) + await expect.poll(async () => (await geometry()).tail.y < viewport.y + viewport.height).toBe(true) + } + const end = await geometry() + await page.mouse.move(end.tail.x - 0.1, end.tail.y, { steps: 5 }) + } finally { + await page.mouse.up() + } + await expect.poll(() => page.evaluate(() => document.getSelection()?.toString())).toBe(expected) + await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(page.url()).origin }) + const sentinel = `${expected}\nclipboard-before-copy` + await page.evaluate(value => navigator.clipboard.writeText(value), sentinel) + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(sentinel) + await page.keyboard.press('ControlOrMeta+C') + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe(expected) + return { wrapped, text: await command.textContent(), copiedText: await page.evaluate(() => navigator.clipboard.readText()) } + } finally { + await scrollport.evaluate((element, top) => { element.scrollTop = top }, originalScrollTop) + await command.evaluate(() => { document.getSelection()?.removeAllRanges() }) + } +} + +/** + * Verify a chat terminal wraps at a narrow width without changing its text. + * @param page - Browser page that owns the card. + * @param card - Chat terminal card with consumer-owned wrapping styles. + * @param expected - Complete single authored command line. + * @param width - Narrow card width that forces soft wrapping. + * @returns Observed command wrapping and copied text in both themes. + */ +export async function expectWrappedTerminalCommand(page: Page, card: Locator, expected: string, width: number) { + const originalWidth = await card.evaluate(element => element.style.width) + const command = card.locator('[data-command-text]').first() + const header = card.locator('[class*="_header_"]').first() + const observations: ({ colorScheme: 'light' | 'dark' } & Awaited>)[] = [] + try { + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }) + await expect.poll(() => page.locator('body').evaluate(element => element.hasAttribute('data-ds-dark-theme'))).toBe(colorScheme === 'dark') + await card.evaluate((element, value) => { element.style.width = `${value}px` }, width) + observations.push({ colorScheme, ...await expectWrappedCommandText(page, command, expected, header) }) + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await card.evaluate((element, value) => { element.style.width = value }, originalWidth) + await expectNoCommandTabStop(command) + expect(await command.textContent()).toBe(expected) + } + return observations + } finally { + await card.evaluate((element, value) => { element.style.width = value }, originalWidth) + await page.emulateMedia({ colorScheme: null }) + } +} + +/** + * Verify a terminal's status dot remains visible beside the first visual command line. + * @param card - Terminal card with its command banner scrolled to the start. + * @param state - Expected running or settled state. + * @returns Resolves after the dot fits inside the banner and aligns with the first line. + */ +export async function expectFirstLineTerminalState(card: Locator, state: 'ongoing' | 'done'): Promise { + const dot = card.locator('[class*="_runState_"][data-state]') + await expect.poll(() => dot.getAttribute('data-state')).toBe(state) + const geometry = await dot.evaluate((element) => { + const prompt = element.closest('[class*="_promptLine_"]') + const header = element.closest('[class*="_header_"]') + if (prompt === null || header === null) throw new Error('Terminal status has no prompt banner') + const bounds = element.getBoundingClientRect() + const viewport = header.getBoundingClientRect() + return { + visible: bounds.top >= viewport.top && bounds.bottom <= viewport.bottom + && bounds.left >= viewport.left && bounds.right <= viewport.right, + center: bounds.top + bounds.height / 2, + firstLineCenter: prompt.getBoundingClientRect().top + Number.parseFloat(getComputedStyle(prompt).lineHeight) / 2, + } + }) + expect(geometry.visible).toBe(true) + expect(geometry.center).toBeCloseTo(geometry.firstLineCenter, 1) +} + /** * Verify a resized command drops its explicit keyboard stop when all text fits. * @param container - Width owner of the command. diff --git a/apps/web/tests/user-text-secret-mask.e2e.ts b/apps/web/tests/user-text-secret-mask.e2e.ts new file mode 100644 index 0000000000..b45755e04f --- /dev/null +++ b/apps/web/tests/user-text-secret-mask.e2e.ts @@ -0,0 +1,74 @@ +/** A cold-seeded user message that carries a credential draws it masked behind its reveal control. */ +import { readFile } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser, type Page } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { + assertFixtureInventory, compareOrRefreshGolden, fixtureUserPrompts, + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { newEnglishPage, saveFailureShot } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/user-text-secret-mask', import.meta.url)) +// Borrowed read-only: this scenario needs any settled user message, not a new recording. +const SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url)) +const MODE = webSnapshotMode() +const RECORDED_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.' +// Assembled at run time so the repository holds no literal in a credential format. +const KEY = ['sk', '-', '0123456789abcdef0123456789abcdef'].join('') +const PROMPT = `${KEY} is the key for this task.` + +describe('web e2e: credential mask in user text', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + scaffold = await launchWebScaffold({}) + const raw = (await readFile(SEED, 'utf8')).replace(RECORDED_PROMPT, PROMPT) + expect(fixtureUserPrompts(raw), 'adapted seed must carry the credential prompt').toContain(PROMPT) + await seedSession(scaffold, raw, 'user-text-secret-mask') + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.locator('[role="treeitem"]').first().click() + await page.locator('[role="treeitem"]').nth(1).click() + await page.getByRole('button', { name: 'Show secret', exact: true }).waitFor() + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('masks the credential in the bubble and reveals it from its own control', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-user-text-secret-mask')) + const text = page.locator('[class*="bubble"]', { has: page.locator('[data-secret]') }) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'bubble.expected.md'), await text.ariaSnapshot(), MODE) + expect(await text.textContent()).not.toContain(KEY) + const run = page.locator('[data-secret]') + // The mask marks and the control share one vertical center. + const centers = await run.evaluate((box) => { + const middle = (element: Element): number => { + const rect = element.getBoundingClientRect() + return rect.top + rect.height / 2 + } + const [value, control] = [...box.children] + return { mask: middle(value!.lastElementChild!), control: middle(control!) } + }) + expect(Math.abs(centers.control - centers.mask)).toBeLessThanOrEqual(1) + const masked = { run: await run.boundingBox(), bubble: await text.boundingBox() } + await page.getByRole('button', { name: 'Show secret', exact: true }).click() + await expect.poll(() => text.textContent()).toBe(PROMPT) + // The monospace run keeps one mask character per original character, so revealing does not move the line. + expect({ run: await run.boundingBox(), bubble: await text.boundingBox() }).toEqual(masked) + await page.getByRole('button', { name: 'Hide secret', exact: true }).click() + await expect.poll(() => text.textContent()).not.toContain(KEY) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + await assertFixtureInventory(SNAPSHOT_DIR, ['bubble.expected.md']) + }) +}) diff --git a/apps/web/tests/workspace-management.e2e.ts b/apps/web/tests/workspace-management.e2e.ts index d97a0bd6b9..2b11bfe72c 100644 --- a/apps/web/tests/workspace-management.e2e.ts +++ b/apps/web/tests/workspace-management.e2e.ts @@ -17,7 +17,7 @@ import { join, sep } from 'node:path' import type { Browser, Locator, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' -import { SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session' +import { SessionId } from '@deepseek-ai/dsh-session' import { logPath } from '../../../packages/session/session-persistence-jsonl/src/format.ts' import { acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, @@ -779,11 +779,10 @@ describe('web e2e: New Session after an outdated blank cache', () => { undefined, { createdAt: now - 60_000 }) const stored = await scaffold.ctx.sessionPersistence.stat(id) if (stored === undefined) throw new Error('seeded Session is missing') - // A durable log may advance after its last blank projection checkpoint. - // An unregistered Session writes only the checkpoint, leaving the persisted log intact. - const blank = scaffold.ctx.sessions.prepare(id, { - eventState: 'detached', seed: [], meta: stored.header, inheritedEventCount: SessionLogOffset(0), - }) + // A durable log may advance after its last blank projection checkpoint, + // which then records the cut before the first turn. An unregistered + // Session writes only the checkpoint, leaving the persisted log intact. + const blank = scaffold.ctx.sessions.prepare(id, { meta: stored.header }) await scaffold.ctx.sessionProjectionCache.write(blank) const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd, 'New session regression') await workspace.attachSession(id) @@ -794,8 +793,14 @@ describe('web e2e: New Session after an outdated blank cache', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-new-session-stale-blank')) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor() const selected = page.locator('[role="treeitem"][aria-selected="true"]') + // Startup asks for a new conversation with the stale blank as its reuse + // candidate; the Host declines the started Session and creates a blank one. + await expect.poll(() => selected.innerText()).toBe('New Session') + await expect.poll(() => workspace.sessionIds.length).toBe(2) + // The declined Session's projections are reloaded, so its stale blank row reappears. + await page.getByRole('treeitem', { name: /^Use the read tool twice/ }).click() + await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor() await expect.poll(() => selected.innerText()).not.toBe('New Session') const previous = (await selected.innerText()).split('\n')[0]! const before = await captureStableAria(page, '[role="tree"]', scaffold.workspaceCwd) @@ -803,7 +808,8 @@ describe('web e2e: New Session after an outdated blank cache', () => { await page.getByRole('button', { name: 'New session', exact: true }).last().click() await expect.poll(() => selected.innerText()).toBe('New Session') await page.getByRole('tab', { name: 'Chat', exact: true }).waitFor({ state: 'hidden' }) - await expect.poll(() => workspace.sessionIds.length).toBe(2) + // New Session creates a fresh Session; the blank startup created stays a member. + await expect.poll(() => workspace.sessionIds.length).toBe(3) expect(workspace.sessionIds).toContain(id) await page.getByRole('treeitem').filter({ hasText: previous }).waitFor() const after = await captureStableAria(page, '[role="tree"]', scaffold.workspaceCwd) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index f9269cd333..04f42721a5 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -23,6 +23,7 @@ // cannot see both sides of the cordis Context merges). "exclude": [ "tests/collapse-timing.e2e.ts", + "tests/notice-wake-tail.e2e.ts", "tests/chat-flow-layout.e2e.ts", "tests/layout-bottom.e2e.ts", "tests/shortcuts-desktop.e2e.ts", @@ -147,6 +148,7 @@ "tests/message-feedback.e2e.ts", "tests/markdown-images.e2e.ts", "tests/markdown-file-links.e2e.ts", + "tests/user-text-secret-mask.e2e.ts", "tests/reference-composer.e2e.ts", "tests/markdown-wide-table.e2e.ts", "tests/thinking-markdown.e2e.ts", @@ -158,6 +160,7 @@ "tests/idle-submission-handoff.e2e.ts", "tests/cold-blank-session.e2e.ts", "tests/blank-writer-reuse.e2e.ts", + "tests/blank-preset-reuse.e2e.ts", "tests/queue-image.e2e.ts", "tests/skill-invocation-policy.e2e.ts", "tests/skill-user-invoke.e2e.ts", diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 010e4307f7..d0463af079 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -6,6 +6,7 @@ import type { Plugin } from 'vite' import react from '@vitejs/plugin-react' import { clientBuildEnvironmentDefines } from '../../scripts/client-build-environment.ts' import { productWebBundleIsolation } from './product-isolation.ts' +import { katexWoff2Fonts } from './katex-fonts.ts' const src = (rel: string): string => fileURLToPath(new URL(rel, import.meta.url)) const STANDALONE_ERROR = 'apps/web is not a standalone application: bare Vite cannot inject window.__DSH_BOOT__. ' @@ -149,7 +150,7 @@ const BOOT_GRAMMAR_FILES: readonly string[] = [ 'dist/json.mjs', ] -/** Font asset extensions routed to assets/fonts/ (KaTeX's woff2/woff/ttf faces). */ +/** Font asset extensions routed to assets/fonts/. */ const FONT_EXTENSIONS: readonly string[] = ['.woff2', '.woff', '.ttf'] /** @@ -170,7 +171,7 @@ export default defineConfig({ // directory, and the served index resolves identically from the site root. base: './', plugins: [ - rejectStandaloneServe(), clientDocumentTitle(), brandFontLicense(), react(), emitPreviewPage(), + rejectStandaloneServe(), clientDocumentTitle(), brandFontLicense(), katexWoff2Fonts(), react(), emitPreviewPage(), productWebBundleIsolation(src('../..'), src('.')), ], build: { diff --git a/benchmarks/package.json b/benchmarks/package.json index 68ce69fa23..4a2be7ed1d 100644 --- a/benchmarks/package.json +++ b/benchmarks/package.json @@ -19,6 +19,7 @@ "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-deque": "workspace:*", "@deepseek-ai/dsh-lazy-require": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", diff --git a/benchmarks/support/built-worker.ts b/benchmarks/support/built-worker.ts index 6e91fde0df..8167cc9a4f 100644 --- a/benchmarks/support/built-worker.ts +++ b/benchmarks/support/built-worker.ts @@ -18,6 +18,8 @@ export interface BuiltBenchmarkWorkerOptions { readonly timeoutMs: number readonly exposeGc?: boolean readonly heapLimitMb?: number + /** Fixed semi-space size, so an allocation interval smaller than it runs without a scavenge. */ + readonly semiSpaceMb?: number } /** @@ -40,6 +42,9 @@ export function runBuiltBenchmarkWorker( ...options.heapLimitMb === undefined ? [] : [`--max-old-space-size=${String(options.heapLimitMb)}`], + ...options.semiSpaceMb === undefined + ? [] + : [`--min-semi-space-size=${String(options.semiSpaceMb)}`, `--max-semi-space-size=${String(options.semiSpaceMb)}`], options.worker, ...options.args ?? [], ], { diff --git a/benchmarks/tsdown.config.ts b/benchmarks/tsdown.config.ts index 36c4386865..cb91a1a830 100644 --- a/benchmarks/tsdown.config.ts +++ b/benchmarks/tsdown.config.ts @@ -66,4 +66,11 @@ export default defineConfig([ clean: true, tsconfig: 'tsconfig.client.json', }, + { + ...shared, + entry: { 'user-text.worker': 'user-text/user-text.worker.client.ts' }, + outDir: '.dsh-build/user-text', + clean: true, + tsconfig: 'tsconfig.client.json', + }, ]) diff --git a/benchmarks/user-text/user-text.bench.client.ts b/benchmarks/user-text/user-text.bench.client.ts new file mode 100644 index 0000000000..9377281819 --- /dev/null +++ b/benchmarks/user-text/user-text.bench.client.ts @@ -0,0 +1,161 @@ +/** Required time and allocation budgets for sent-user-text evaluation with the credential matcher. */ + +import { join } from 'node:path' +import { beforeAll, describe, expect, it } from 'vitest' +import { runBuiltBenchmarkWorker } from '../support/built-worker.ts' +import { ciTimeBudget, PERFORMANCE_BUDGET_HEADROOM } from '../support/calibration.ts' +import { recordTimings, type BenchmarkCase } from '../support/scaling-report.ts' +import type { + UserTextAllocationReport, UserTextTimeReport, UserTextWorkloadAllocation, UserTextWorkloadTiming, +} from './user-text.worker.client.ts' + +/** Fresh registries and documents per sample in one compiled worker; the fastest sample removes scheduler delay. */ +const ATTEMPTS = 5 +/** A stuck worker is reaped before the outer benchmark deadline. */ +const WORKER_TIMEOUT_MS = 180_000 +/** Larger than every workload's allocation, so the allocation interval runs without a scavenge. */ +const ALLOCATION_SEMI_SPACE_MB = 256 +const WORKER = join(import.meta.dirname, '..', '.dsh-build', 'user-text', 'user-text.worker.js') + +/** + * Documents without credentials: reference-machine milliseconds with the matcher, and the + * ratio to the shipped rules without it. Ratios do not depend on machine speed. The matcher + * adds one native literal scan, about 2 ns per character, plus format checks where a literal + * occurs (`://`, `sk-` in identifiers); 5,000 messages also pay the scheduler's cost for one + * more matcher. Running sixteen format patterns from every query offset measures 1.6–4.9×. + */ +const UNMATCHED_EXPECTED = { + 'typical-messages': { ms: 28, ratio: 1.25 }, + 'prose-256k': { ms: 1.25, ratio: 1.8 }, + 'code-256k': { ms: 1.7, ratio: 2.3 }, + 'base64-256k': { ms: 1.4, ratio: 2.05 }, + 'markdown-256k': { ms: 1.6, ratio: 2.15 }, + 'log-256k': { ms: 1.75, ratio: 2.05 }, + 'json-256k': { ms: 2.05, ratio: 2.75 }, + 'shell-256k': { ms: 3.8, ratio: 1.3 }, +} as const +/** Reference-machine milliseconds with the matcher for documents whose credentials it masks. */ +const MATCHED_EXPECTED_MS = { + 'messages-with-model-key': 28, + 'messages-with-github-token': 28, + 'messages-with-cloud-key-id': 28, + 'messages-with-json-web-token': 29, + 'messages-with-address-password': 31, + 'messages-with-private-key-block': 45, + 'env-keys-2000': 2.1, +} as const +/** + * 128 KiB shaped against one format's prefix, length, or separator rules. Format patterns + * that backtrack, or a per-query memo whose digit search reaches the end of the text from + * every query, measure 60–720 ms and up to 4× per doubling. + */ +const ADVERSARIAL_EXPECTED_MS = 3.25 +/** Doubling the input doubles a linear scan. */ +const MAX_DOUBLING_SCALING = 2 * PERFORMANCE_BUDGET_HEADROOM + +/** Measurement floor: heap statistics objects created while reading the young generation. */ +const ALLOCATION_FLOOR_BYTES = 16 * 1024 +/** + * One credential node: the node and data objects, the visible-prefix slice, and the + * concatenation with a slice of a shared mark string; measured at about 180 bytes. + */ +const ALLOCATION_PER_CREDENTIAL_BYTES = 256 +/** A multi-line mask adds one slice of a shared mark string and one concatenation per line; measured at about 60 bytes. */ +const ALLOCATION_PER_MASKED_LINE_BREAK_BYTES = 64 +/** A slice shorter than a sliced string copies its characters: at most two bytes per masked character. */ +const ALLOCATION_PER_MASKED_CHARACTER_BYTES = 2 + +const ADVERSARIAL = [ + 'digitless-sk', 'jwt-header-runs', 'jwt-two-segments', 'unterminated-key-blocks', 'address-without-at', + 'colon-run', 'long-scheme-user', 'short-token-runs', 'tokens-between-digitless-keys', 'closed-one-line-key-blocks', +] as const + +function benchmarkCase(id: string, measures: string): BenchmarkCase { + return { id: `user-text/${id}`, measures, affects: 'Rendering sent user messages, queued messages, and goal input in the Web GUI.' } +} + +async function worker(args: readonly string[], semiSpaceMb?: number): Promise { + const run = await runBuiltBenchmarkWorker({ + worker: WORKER, args, timeoutMs: WORKER_TIMEOUT_MS, exposeGc: true, ...semiSpaceMb === undefined ? {} : { semiSpaceMb }, + }) + if (run.report === undefined) { + throw new Error(`user-text worker failed: exit=${String(run.exitCode)}, signal=${String(run.signal)}, ` + + `timedOut=${String(run.timedOut)}\n${run.stderr.trim().split('\n').slice(-10).join('\n')}`) + } + return run.report +} + +describe('sent user text with the credential matcher', () => { + let timings: ReadonlyMap + let allocations: ReadonlyMap + + beforeAll(async () => { + const time = await worker(['time', String(ATTEMPTS)]) + const allocation = await worker(['allocation'], ALLOCATION_SEMI_SPACE_MB) + console.log(JSON.stringify({ benchmark: 'user-text', ...time, allocation: allocation.workloads })) + timings = new Map(time.workloads.map(workload => [workload.id, workload])) + allocations = new Map(allocation.workloads.map(workload => [workload.id, workload])) + }, 2 * WORKER_TIMEOUT_MS) + + const timing = (id: string): UserTextWorkloadTiming => { + const found = timings.get(id) + if (found === undefined) throw new Error(`user-text worker reported no ${id} workload`) + return found + } + const record = (benchmark: BenchmarkCase, measured: UserTextWorkloadTiming, budgetMs: number): void => { + recordTimings(benchmark, { withSecretMs: { ms: measured.withSecretMs, cpuMs: measured.withSecretCpuMs } }, { withSecretMs: budgetMs }) + } + + it.each(Object.entries(UNMATCHED_EXPECTED))('evaluates %s without credentials within its budget and ratio', (id, expected) => { + const measured = timing(id) + const budgetMs = ciTimeBudget(expected.ms) + record(benchmarkCase(id, `Fresh ${id} documents without credentials through every shipped matcher.`), measured, budgetMs) + expect(measured.group).toBe('unmatched') + expect(measured.secrets).toBe(0) + expect(measured.withSecretMs).toBeLessThanOrEqual(budgetMs) + expect(measured.ratio).toBeLessThanOrEqual(expected.ratio * PERFORMANCE_BUDGET_HEADROOM) + }) + + it.each(Object.entries(MATCHED_EXPECTED_MS))('masks every credential of %s within its budget', (id, expectedMs) => { + const measured = timing(id) + const budgetMs = ciTimeBudget(expectedMs) + record(benchmarkCase(id, `Fresh ${id} documents, each credential masked, through every shipped matcher.`), measured, budgetMs) + expect(measured.group).toBe('matched') + expect(measured.secrets).toBe(id === 'env-keys-2000' ? 2_000 : 5_000) + expect(measured.withSecretMs).toBeLessThanOrEqual(budgetMs) + }) + + it('masks 2,000 pasted keys in time linear in their number', () => { + const half = timing('env-keys-1000') + const full = timing('env-keys-2000') + expect([half.secrets, full.secrets]).toEqual([1_000, 2_000]) + expect(full.withSecretMs / half.withSecretMs).toBeLessThanOrEqual(MAX_DOUBLING_SCALING) + }) + + it.each(ADVERSARIAL)('scans adversarial %s input linearly without backtracking', (name) => { + const half = timing(`adversarial-${name}-64k`) + const full = timing(`adversarial-${name}-128k`) + const budgetMs = ciTimeBudget(ADVERSARIAL_EXPECTED_MS) + record(benchmarkCase(`adversarial-${name}`, `One 128 KiB document repeating a ${name} unit.`), full, budgetMs) + expect(full.withSecretMs).toBeLessThanOrEqual(budgetMs) + expect(full.withSecretMs / half.withSecretMs).toBeLessThanOrEqual(MAX_DOUBLING_SCALING) + }) + + it.each(workloadIds())('allocates only result nodes and masks for %s', (id) => { + const allocation = allocations.get(id) + if (allocation === undefined) throw new Error(`user-text worker reported no ${id} allocation`) + expect(allocation.secrets).toBe(timing(id).secrets) + const budgetBytes = ALLOCATION_FLOOR_BYTES + ALLOCATION_PER_CREDENTIAL_BYTES * allocation.secrets + + ALLOCATION_PER_MASKED_LINE_BREAK_BYTES * allocation.maskedLineBreaks + + ALLOCATION_PER_MASKED_CHARACTER_BYTES * allocation.maskedCharacters + expect(allocation.ruleAllocatedBytes).toBeLessThanOrEqual(budgetBytes) + }) +}) + +/** Every workload id, in the worker's order, so each has an allocation case. */ +function workloadIds(): readonly string[] { + return [ + ...Object.keys(UNMATCHED_EXPECTED), ...Object.keys(MATCHED_EXPECTED_MS), 'env-keys-1000', + ...ADVERSARIAL.flatMap(name => [`adversarial-${name}-64k`, `adversarial-${name}-128k`]), + ] +} diff --git a/benchmarks/user-text/user-text.worker.client.ts b/benchmarks/user-text/user-text.worker.client.ts new file mode 100644 index 0000000000..ca7ab3c099 --- /dev/null +++ b/benchmarks/user-text/user-text.worker.client.ts @@ -0,0 +1,338 @@ +/** Compiled worker for sent-user-text evaluation cost and allocation with and without the credential matcher. */ + +import { PerformanceObserver, performance } from 'node:perf_hooks' +import { getHeapSpaceStatistics } from 'node:v8' +import { Context } from '@deepseek-ai/cordis' +import type { UserTextFacts, UserTextRule, UserTextTransformContext } from '@deepseek-ai/dsh-client-ui-conversation/client' +// These Client-only UserText modules have no plain-Node package export and are compiled into this worker. +import { UserTextRegistry } from '../../packages/client/ui-conversation/src/client/conversation/user-text-registry.ts' +import { sessionReferenceRule } from '../../packages/client/ui-conversation/src/client/user-text/session-reference-rule.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from '../../packages/client/ui-conversation/src/client/user-text/whitespace-rules.ts' +import { fileReferenceRule, folderReferenceRule } from '../../packages/client/ui-reference/src/client/user-text-rules.ts' +import { skillReferenceRule } from '../../packages/client/ui-skill/src/client/user-text-rules.ts' +import { goalCommandReferenceRule } from '../../packages/client/ui-goal/src/client/user-text-rules.ts' +import { createSecretRule } from '../../packages/client/ui-secret-mask/src/client/secret-rule.ts' +import { assertBuiltBenchmarkRuntime } from '../support/built-worker.ts' + +/** What a workload contains: no credential, real credentials, or input shaped against one format. */ +export type UserTextWorkloadGroup = 'unmatched' | 'matched' | 'adversarial' + +/** Timing of one workload evaluated by the shipped rule set with and without the credential matcher. */ +export interface UserTextWorkloadTiming { + readonly id: string + readonly group: UserTextWorkloadGroup + readonly documents: number + readonly characters: number + readonly secrets: number + /** Characters inside credential ranges, whose masks the matcher builds. */ + readonly maskedCharacters: number + readonly baseMs: number + readonly withSecretMs: number + /** Process CPU time over the fastest with-credential sample. */ + readonly withSecretCpuMs: number + readonly ratio: number +} + +/** Heap allocation of the credential matcher over one workload, with the size of what it returns. */ +export interface UserTextWorkloadAllocation { + readonly id: string + /** Young-generation bytes the matcher allocates answering every query of every document, nodes included; no GC ran meanwhile. */ + readonly ruleAllocatedBytes: number + readonly secrets: number + /** Characters inside credential ranges. */ + readonly maskedCharacters: number + /** Line breaks inside credential ranges, each of which ends one piece of a multi-line mask. */ + readonly maskedLineBreaks: number +} + +/** Result of `time `: the fastest of `attempts` fresh samples per workload. */ +export interface UserTextTimeReport { + readonly attempts: number + readonly workloads: readonly UserTextWorkloadTiming[] +} + +/** Result of `allocation`, which needs `--expose-gc` and a young generation larger than one evaluation. */ +export interface UserTextAllocationReport { + readonly workloads: readonly UserTextWorkloadAllocation[] +} + +/** Matchers the Web composition registers besides the credential matcher. */ +const BASE_RULES: readonly UserTextRule[] = [ + sessionReferenceRule, fileReferenceRule, folderReferenceRule, skillReferenceRule, + goalCommandReferenceRule, collapseWhitespaceRule, trimWhitespaceRule, +] +/** Facts a sent message bubble supplies. */ +const FACTS: Readonly> = { sessionLabels: ['会话一'], skillNames: ['plan', 'review'] } + +const KIB = 1024 +const PROSE = '帮我看看这个函数为什么慢,顺便把 README 也更新一下。The quick brown fox jumps over the lazy dog, 1234 times. ' +const CODE = 'const value = await fetch(`https://api.example.com/v1/items?id=${id}`); if (!value.ok) throw new Error("bad: " + value.status);\n' +const BASE64 = 'QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLw' +const MARKDOWN = [ + '## 安装与配置', '', '- 运行 `pnpm install`,然后执行 `pnpm run build`。', + '- 详见 [文档](https://example.com/docs/setup?ref=readme#install)。', '', + '| 选项 | 默认值 | 说明 |', '|---|---|---|', '| `timeout` | 30s | 请求超时 |', '| `retries` | 3 | 失败重试次数 |', '', + '```ts', "const client = createClient({ baseUrl: 'https://api.example.com/v1', timeout: 30_000 })", '```', '', '', +].join('\n') +const LOG = '2026-10-11T12:00:00.123Z INFO [worker-3] GET https://api.example.com/v1/items?id=1234&page=2 200 12ms ' + + 'trace=4bf92f3577b34da6a3ce929d0e0e4736 user=alice@example.com\n' +const JSON_LINES = '{"id":"123e4567-e89b-12d3-a456-426614174000","url":"https://cdn.example.com/assets/img_0001.png",' + + '"name":"task-runner","tags":["sk-button","api_key_name"],"created_at":"2026-10-11T12:00:00Z","size":10240},\n' +const SHELL = 'pnpm --filter @deepseek-ai/dsh-client-ui-secret-mask run test -- --coverage --reporter=verbose' + + ' && git push origin feat/user-text-secret-mask\n' +/** Ordinary message fragments: prose, references, a slash skill, a URL without credentials, and code. */ +const MESSAGE_PARTS = [ + PROSE, '参照 @src/app/main.ts 修复一下', ' /plan 先列计划', ' 见 https://example.com/docs/a?b=c#d ', + '`const total = items.reduce((a, b) => a + b, 0)`', ' 然后跑 pnpm run test -- --watch=false。', +] as const + +const fill = (unit: string, characters: number): string => unit.repeat(Math.ceil(characters / unit.length)).slice(0, characters) +const MIXED = 'a1B2c3D4e5F6g7H8i9J0' +// Samples are assembled at run time so the repository holds no literal in a credential format. +const key = (index: number): string => ['sk', '-', `${index.toString(16).padStart(8, '0')}0123456789abcdef01234567`].join('') +const CREDENTIALS = { + 'model-key': key(7), + 'github-token': ['gh', 'p_', fill(MIXED, 36)].join(''), + 'cloud-key-id': ['AK', 'IA', 'ABCDEFGHIJ234567'].join(''), + 'json-web-token': ['ey', 'J', fill(MIXED, 17), '.', 'ey', 'J', fill(MIXED, 30), '.', fill(MIXED, 43)].join(''), + 'address-password': ['postgres://admin:', 'p4ss-W0rd', '@db.internal:5432/app'].join(''), + 'private-key-block': [ + ['-----BEGIN', ' RSA PRIVATE KEY-----'].join(''), ...Array.from({ length: 10 }, () => fill(BASE64, 64)), + ['-----END', ' RSA PRIVATE KEY-----'].join(''), + ].join('\n'), +} as const + +function messages(count: number): string[] { + return Array.from({ length: count }, (_, index) => { + const parts = Array.from({ length: 4 }, (_unused, part) => MESSAGE_PARTS[(index + part * 2) % MESSAGE_PARTS.length]!) + return `${String(index)} ${parts.join('')}`.slice(0, 200) + }) +} + +/** Ordinary 200-character messages, each carrying one credential whole. */ +function credentialMessages(count: number, credential: string): string[] { + return Array.from({ length: count }, (_, index) => { + const head = `${String(index)} 帮我看看这个配置能不能用:` + const tail = `,${MESSAGE_PARTS[index % MESSAGE_PARTS.length]!}${PROSE}` + return head + credential + tail.slice(0, Math.max(0, 200 - head.length - credential.length)) + }) +} + +const envFile = (count: number): string => + Array.from({ length: count }, (_, index) => `SERVICE_${String(index)}_API_KEY=${key(index)}`).join('\n') + +/** Inputs shaped against each credential format's prefix, length, and separator rules. */ +const ADVERSARIAL_UNITS = { + 'digitless-sk': 'sk-', + 'jwt-header-runs': 'eyJabcdefgh-', + 'jwt-two-segments': 'eyJabcdefgh.eyJabcdefgh-', + 'unterminated-key-blocks': ['-----BEGIN', ' RSA PRIVATE KEY-----\nabc\n'].join(''), + 'address-without-at': 'a://u:', + 'colon-run': ':', + 'long-scheme-user': `abcdefghijklmnop://${'u'.repeat(250)}:`, + 'short-token-runs': `ghp_${fill('a1B2c3', 35)} `, + // Closed one-line blocks, each its own credential: mask searches confined to each block keep them linear. + 'closed-one-line-key-blocks': ['-----BEGIN', ' PRIVATE KEY-----abcd', '-----END', ' PRIVATE KEY----- '].join(''), + // Each query starts after an accepted digit-free token and meets a digit-free `sk-` whose digit search reaches the end. + 'tokens-between-digitless-keys': ['-', 'sk', '-', 'gh', 'p_', fill('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 36)].join(''), +} as const + +interface Workload { + readonly id: string + readonly group: UserTextWorkloadGroup + readonly texts: readonly string[] +} + +/** Named fixed workloads; adversarial inputs appear at two sizes so their scaling is observable. */ +function workloads(): readonly Workload[] { + return [ + { id: 'typical-messages', group: 'unmatched', texts: messages(5_000) }, + ...Object.entries({ prose: PROSE, code: CODE, base64: BASE64, markdown: MARKDOWN, log: LOG, json: JSON_LINES, shell: SHELL }) + .map(([name, unit]): Workload => ({ id: `${name}-256k`, group: 'unmatched', texts: [fill(unit, 256 * KIB)] })), + ...Object.entries(CREDENTIALS).map(([name, credential]): Workload => ({ + id: `messages-with-${name}`, group: 'matched', texts: credentialMessages(5_000, credential), + })), + { id: 'env-keys-1000', group: 'matched', texts: [envFile(1_000)] }, + { id: 'env-keys-2000', group: 'matched', texts: [envFile(2_000)] }, + ...Object.entries(ADVERSARIAL_UNITS).flatMap(([name, unit]): Workload[] => [ + { id: `adversarial-${name}-64k`, group: 'adversarial', texts: [fill(unit, 64 * KIB)] }, + { id: `adversarial-${name}-128k`, group: 'adversarial', texts: [fill(unit, 128 * KIB)] }, + ]), + ] +} + +interface Sample { + readonly ms: number + readonly cpuMs: number + readonly secrets: number + readonly maskedCharacters: number +} + +/** Rules for one sample; a fresh credential matcher per sample carries no state from an earlier sample. */ +type RuleSet = () => readonly UserTextRule[] +const withoutSecret: RuleSet = () => BASE_RULES +const withSecret: RuleSet = () => [...BASE_RULES, createSecretRule()] + +function registryWith(rules: RuleSet): { readonly registry: UserTextRegistry; readonly scope: Context } { + const scope = new Context() + const registry = new UserTextRegistry(scope) + for (const rule of rules()) registry.register(rule) + return { registry, scope } +} + +/** + * Evaluate every text once as a fresh document, as a newly rendered message does. + * @returns elapsed and CPU milliseconds, credential nodes produced, and their characters. + */ +function evaluateAll(rules: RuleSet, texts: readonly string[]): Sample { + const { registry, scope } = registryWith(rules) + let secrets = 0 + let maskedCharacters = 0 + const cpuStart = process.cpuUsage() + const start = performance.now() + for (const text of texts) { + for (const node of registry.createEvaluator()({ text, facts: FACTS })) { + if (node.id !== 'secret') continue + secrets++ + maskedCharacters += node.end - node.start + } + } + const ms = performance.now() - start + const cpu = process.cpuUsage(cpuStart) + void scope.fiber.dispose() + return { ms, cpuMs: (cpu.user + cpu.system) / 1_000, secrets, maskedCharacters } +} + +function fastest(rules: RuleSet, texts: readonly string[], attempts: number): Sample { + let best = evaluateAll(rules, texts) + for (let attempt = 1; attempt < attempts; attempt++) { + const sample = evaluateAll(rules, texts) + if (sample.ms < best.ms) best = sample + } + return best +} + +declare const gc: (() => void) | undefined + +/** + * Young-generation bytes in use. Code and feedback that compilation allocates during a + * measurement live in other spaces, so they do not count as allocation by the evaluation. + */ +function youngBytes(): number { + let total = 0 + for (const space of getHeapSpaceStatistics()) { + if (space.space_name === 'new_space' || space.space_name === 'new_large_object_space') total += space.space_used_size + } + return total +} + +/** The credential matcher reads no Facts. */ +const NO_FACTS: UserTextTransformContext = { read: () => undefined } + +/** + * Query the credential matcher over every document as the scheduler does when no other + * matcher produces a node; an index loop, so the loop itself allocates nothing. + */ +function queryAll(rule: UserTextRule, texts: readonly string[]): void { + for (let index = 0; index < texts.length; index++) { + const text = texts[index]! + for (let from = 0; ;) { + const node = rule.match(text, from, NO_FACTS) + if (node === undefined) break + from = node.end + } + } +} + +/** Credential nodes the matcher returns over every document, counted outside any measured interval. */ +function returned(texts: readonly string[]): Omit { + const rule = createSecretRule() + let secrets = 0 + let maskedCharacters = 0 + let maskedLineBreaks = 0 + for (const text of texts) { + for (let node = rule.match(text, 0, NO_FACTS); node !== undefined; node = rule.match(text, node.end, NO_FACTS)) { + secrets++ + maskedCharacters += node.end - node.start + for (let index = node.start; index < node.end; index++) { + const code = text.charCodeAt(index) + if (code === 10 || code === 13) maskedLineBreaks++ + } + } + } + return { secrets, maskedCharacters, maskedLineBreaks } +} + +/** + * Bytes one warmed pass of every query allocates, measured across an interval without GC. + * @returns young-generation growth over the interval. + */ +async function allocatedBytes(texts: readonly string[], collect: () => void): Promise { + const collections: number[] = [] + const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) collections.push(entry.startTime) }) + observer.observe({ entryTypes: ['gc'] }) + try { + const rule = createSecretRule() + for (let warm = 0; warm < 10; warm++) queryAll(rule, texts) + collect() + collect() + const start = performance.now() + const used = youngBytes() + queryAll(rule, texts) + const grown = youngBytes() - used + const end = performance.now() + // GC entries arrive on a later turn. + await new Promise(resolve => { setTimeout(resolve, 20) }) + const inside = collections.filter(time => time >= start && time <= end).length + if (inside > 0) throw new Error(`${String(inside)} garbage collections ran inside the allocation interval; enlarge the young generation`) + return grown + } finally { + observer.disconnect() + } +} + +function positiveInteger(value: string | undefined, name: string): number { + const parsed = Number(value) + if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`${name} must be a positive integer`) + return parsed +} + +async function allocations(): Promise { + if (gc === undefined) throw new Error('user-text allocation mode needs --expose-gc') + const collect = gc + const results: UserTextWorkloadAllocation[] = [] + for (const { id, texts } of workloads()) { + results.push({ id, ruleAllocatedBytes: await allocatedBytes(texts, collect), ...returned(texts) }) + } + return { workloads: results } +} + +function timings(attempts: number): UserTextTimeReport { + return { + attempts, + workloads: workloads().map(({ id, group, texts }) => { + const base = fastest(withoutSecret, texts, attempts) + const secret = fastest(withSecret, texts, attempts) + return { + id, + group, + documents: texts.length, + characters: texts.reduce((sum, text) => sum + text.length, 0), + secrets: secret.secrets, + maskedCharacters: secret.maskedCharacters, + baseMs: base.ms, + withSecretMs: secret.ms, + withSecretCpuMs: secret.cpuMs, + ratio: secret.ms / base.ms, + } + }), + } +} + +assertBuiltBenchmarkRuntime(import.meta.url, { + '@deepseek-ai/cordis': import.meta.resolve('@deepseek-ai/cordis'), + '@deepseek-ai/dsh-client-store': import.meta.resolve('@deepseek-ai/dsh-client-store'), +}) +const [mode, count] = process.argv.slice(2) +if (mode !== 'time' && mode !== 'allocation') throw new Error('usage: user-text.worker.js time | allocation') +console.log(JSON.stringify(mode === 'time' ? timings(positiveInteger(count, 'attempts')) : await allocations())) diff --git a/docs/api-gateway.i18n.yaml b/docs/api-gateway.i18n.yaml index d85a74ff21..3f9e8b79ab 100644 --- a/docs/api-gateway.i18n.yaml +++ b/docs/api-gateway.i18n.yaml @@ -12,8 +12,8 @@ en: e29f1d7026291075 zh: 15e361e797d44fce /api-gateway/strict-generation-pipeline: - en: cb8da81a92acfa52 - zh: be5f3c268f8571df + en: 9c4a98eb0539ec7f + zh: ad2a145abd805fdd /api-gateway/runtime-invocation: en: 2a2fed340aaa926c zh: 46bb1f500c870a76 @@ -21,8 +21,8 @@ en: 9570ffe7a348e5ac zh: 2b70b61b1ff1fbb0 /api-gateway/development-mode: - en: ba090d76471dd663 - zh: edf362f71b73eaf0 + en: 23ae422bd65300da + zh: 67dd9c02f4ffec53 /api-gateway/boundaries: en: e6befc5f8c90f97b zh: 4ace4a493fd2b41f diff --git a/docs/api-gateway.md b/docs/api-gateway.md index 0fb3edcb79..0a891cd244 100644 --- a/docs/api-gateway.md +++ b/docs/api-gateway.md @@ -96,7 +96,7 @@ The API Gateway package owns the Host dispatcher and Client Remote endpoint as p ## Strict generation pipeline -The root build runs `build:lib:host`, `build:lib:client`, and `build:web` in order. The Host lib phase first runs `tsc -b tsconfig.host.json`, then `tsdown --env.DSH_BUILD_FACE host`; the normal Host Project Reference graph compiles the Typert generator, which runs during this tsdown pass with the Host aggregate as its only `ts.Program` seed. The Client lib phase then runs `tsc -b tsconfig.client.json` and `tsdown --env.DSH_BUILD_FACE client`, consuming the newly generated Remote Client declarations and runtime contributions without starting Typert again. +The root build compiles and bundles the Host face, then the Client face, then builds the Web shell ([step order](development.md#typescript-project-layout)). The Host phase first compiles the Host package references, then runs `tsdown --env.DSH_BUILD_FACE host`; the normal Host Project Reference graph compiles the Typert generator, which runs during this tsdown pass with the Host aggregate as its only `ts.Program` seed. The Client phase then compiles the Client package references and runs `tsdown --env.DSH_BUILD_FACE client`, consuming the newly generated Remote Client declarations and runtime contributions without starting Typert again. Both tsdown passes match `vendor/*`, `packages/*/*`, and `apps/cli`, the Host pass also `apps/desktop-host` ([build order](development.md#typescript-project-layout)), and both bundle only JavaScript emitted to `lib/types` by the corresponding tsc phase. The root config does not scan Client artifacts, classify package names, or pass a maintained filter to tsdown; package-local configs return entries for the current phase based on `DSH_BUILD_FACE`. An ordinary Client plugin produces both its Node loader entry and browser bundle during the Client phase. @@ -154,7 +154,7 @@ Changing only a Remote method's implementation body without changing its contrac pnpm run build:lib ``` -The running Client watcher consumes these generated files when it rebundles. If `pnpm run build:lib:host` has already refreshed the Host contract, `pnpm run build:lib:client` can complete the Client side; a clean worktree cannot skip the Host phase. Recompiling only the frontend source cannot infer new types from Host decorators. `pnpm run typecheck` runs the Host lib phase before Client tsc, and CI and release builds use the same order. +The running Client watcher consumes these generated files when it rebundles. If `pnpm run build:lib:host` has already refreshed the Host contract, `pnpm run build:lib:client` can complete the Client side; a clean worktree cannot skip the Host phase. Recompiling only the frontend source cannot infer new types from Host decorators. `pnpm run typecheck` generates the Host contract with the bundle-free Typert pass before Client tsc, and the CI build lanes and release builds generate it in the Host bundle phase before Client tsc. ## Boundaries diff --git a/docs/api-gateway.zh.md b/docs/api-gateway.zh.md index 81b504685e..4cc33ee24b 100644 --- a/docs/api-gateway.zh.md +++ b/docs/api-gateway.zh.md @@ -98,7 +98,7 @@ API Gateway 包同时拥有 Host dispatcher 与 Client Remote endpoint 两个对 ## 严格生成流水线 -根构建依次执行 `build:lib:host`、`build:lib:client` 与 `build:web`。Host lib 阶段先运行 `tsc -b tsconfig.host.json`,再运行 `tsdown --env.DSH_BUILD_FACE host`;Typert generator 由正常 Host Project Reference 图编译,并在这次 tsdown 中以 Host aggregate 为唯一 `ts.Program` 种子运行。Client lib 阶段随后运行 `tsc -b tsconfig.client.json` 与 `tsdown --env.DSH_BUILD_FACE client`,使用刚生成的 Remote Client 声明和运行时贡献,但不再次启动 Typert。 +根构建依次编译并打包 Host face、Client face,再构建 Web 壳层([步骤顺序](development.zh.md#typescript-project-layout))。Host 阶段先编译 Host 包 reference,再运行 `tsdown --env.DSH_BUILD_FACE host`;Typert generator 由正常 Host Project Reference 图编译,并在这次 tsdown 中以 Host aggregate 为唯一 `ts.Program` 种子运行。Client 阶段随后编译 Client 包 reference 并运行 `tsdown --env.DSH_BUILD_FACE client`,使用刚生成的 Remote Client 声明和运行时贡献,但不再次启动 Typert。 两次 tsdown 都匹配 `vendor/*`、`packages/*/*` 与 `apps/cli`,Host 阶段另外匹配 `apps/desktop-host`([构建顺序](development.zh.md#typescript-project-layout)),且都只打包 `lib/types` 中由对应 tsc 阶段发射的 JavaScript。根配置不扫描 Client 产物、不按包名分类,也不向 tsdown 传维护式 filter;各包的本地配置根据 `DSH_BUILD_FACE` 返回当前阶段的入口。普通 Client 插件在 Client 阶段一起生成 Node loader 入口与 browser bundle。 @@ -156,7 +156,7 @@ pnpm run dev:web pnpm run build:lib ``` -运行中的 Client watcher 会在重新打包时消费这些生成文件。若已单独运行 `pnpm run build:lib:host` 刷新 Host 约定,也可再运行 `pnpm run build:lib:client` 完成 Client 侧;干净工作树不能跳过 Host 阶段。仅重新编译前端源码不能从 Host decorator 推导新类型。`pnpm run typecheck` 会执行 Host lib 阶段后再运行 Client tsc,CI 与发布构建也使用同一顺序。 +运行中的 Client watcher 会在重新打包时消费这些生成文件。若已单独运行 `pnpm run build:lib:host` 刷新 Host 约定,也可再运行 `pnpm run build:lib:client` 完成 Client 侧;干净工作树不能跳过 Host 阶段。仅重新编译前端源码不能从 Host decorator 推导新类型。`pnpm run typecheck` 先以不打包的 Typert 生成刷新 Host 约定,再运行 Client tsc;CI 的构建 lane 与发布构建则在 Client tsc 之前的 Host bundle 阶段生成它。 diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 182bb9349e..ba4bb17387 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 912784044de3337d - zh: 6a03f65751cda74a + en: 2e9d4cb22f8f2a6b + zh: 81f523914e8531f7 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 7619be90f4..95ab26504b 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -272,6 +272,9 @@ flowchart LR svc_webServer["ctx.webServer
HTTP route registration"] pkg_client_modules["client-modules"] pkg_client_hmr["client-hmr"] + pkg_web_app["web-app"] + svc_webApp["ctx.webApp
Served Web GUI"] + pkg_harness_dev_context["harness-dev-context"] svc_clientModules["ctx.clientModules
Client plugin graph host"] pkg_workflow["workflow"] svc_workflowEngine["ctx.workflowEngine
Workflow script engine"] @@ -428,6 +431,7 @@ flowchart LR pkg_user_approval --> svc_approval pkg_user_questions --> svc_userQuestions pkg_web --> svc_web + pkg_web_app --> svc_webApp pkg_web_fetch_http --> svc_web pkg_web_search_deepseek --> svc_web pkg_web_search_exa --> svc_web @@ -572,6 +576,7 @@ flowchart LR svc_typert --> pkg_typert_loader svc_userQuestions --> pkg_tool_ask_user svc_web --> pkg_tool_web + svc_webApp --> pkg_harness_dev_context svc_webServer --> pkg_client_connection svc_webServer --> pkg_client_hmr svc_webServer --> pkg_client_modules @@ -682,6 +687,7 @@ flowchart LR | `ctx.spillStore` | `seam` | [`spill`](../packages/spill/spill) | [`spill-local`](../packages/spill/spill-local) | [`spill-policy`](../packages/spill/spill-policy) | - | The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill. | | `ctx.directoryPicker` | `seam` | [`host-directory-picker`](../packages/host/directory-picker) | [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | [`api-workspace-controller`](../packages/api/workspace-controller) | - | Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; dual-face backends fill ui-workspace directory-flow slots from their browser halves (no wire advertisement). | | `ctx.webServer` | `core` | [`host-webserver`](../packages/host/webserver) | - | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`client-hmr`](../packages/client/hmr) | - | Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes. | +| `ctx.webApp` | `core` | [`web-app`](../packages/bundle/web-app) | - | [`harness-dev-context`](../packages/context/harness-dev-context) | - | The web-runtime row advertises one URL for its Web GUI: the configured publicUrl, otherwise the listener origin; DSH_WEB_URL, the startup URL, and harness-dev-context read the same value. | | `ctx.clientModules` | `core` | [`client-modules`](../packages/client/modules) | - | [`client-hmr`](../packages/client/hmr) | - | Composes the __DSH_BOOT__ entry graph from an incremental dsh.client scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers. | | `ctx.workflowEngine` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-ptc`](../packages/workflow/workflow-ptc) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/experimental/tool-ralph) | - | One engine per context, as in bash, with no named-provider registry; the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. | | `ctx.webhookRuntime` | `core` | [`webhook`](../packages/experimental/webhook) | - | [`webhook-github`](../packages/experimental/webhook-github) | - | Provider adapters dispatch authenticated deliveries; trusted plugins register independent process-local rules, and the runtime turns non-null results into ordinary Workspace-backed Sessions without delivery or completion state. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index b02ec2e41c..ee3ec60466 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -274,6 +274,9 @@ flowchart LR svc_webServer["ctx.webServer
HTTP route registration"] pkg_client_modules["client-modules"] pkg_client_hmr["client-hmr"] + pkg_web_app["web-app"] + svc_webApp["ctx.webApp
Served Web GUI"] + pkg_harness_dev_context["harness-dev-context"] svc_clientModules["ctx.clientModules
Client plugin graph host"] pkg_workflow["workflow"] svc_workflowEngine["ctx.workflowEngine
Workflow script engine"] @@ -430,6 +433,7 @@ flowchart LR pkg_user_approval --> svc_approval pkg_user_questions --> svc_userQuestions pkg_web --> svc_web + pkg_web_app --> svc_webApp pkg_web_fetch_http --> svc_web pkg_web_search_deepseek --> svc_web pkg_web_search_exa --> svc_web @@ -574,6 +578,7 @@ flowchart LR svc_typert --> pkg_typert_loader svc_userQuestions --> pkg_tool_ask_user svc_web --> pkg_tool_web + svc_webApp --> pkg_harness_dev_context svc_webServer --> pkg_client_connection svc_webServer --> pkg_client_hmr svc_webServer --> pkg_client_modules @@ -684,6 +689,7 @@ flowchart LR | `ctx.spillStore` | `seam` | [`spill`](../packages/spill/spill) | [`spill-local`](../packages/spill/spill-local) | [`spill-policy`](../packages/spill/spill-policy) | - | 后端保存过大的工具文本,并返回面向模型的定位信息和取回提示;spill-policy 是 tools/post-execute 消费方,负责决定何时 spill。 | | `ctx.directoryPicker` | `seam` | [`host-directory-picker`](../packages/host/directory-picker) | [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | [`api-workspace-controller`](../packages/api/workspace-controller) | - | 带判别标记的交互能力:原生后端在 Host 显示设备上打开一个操作系统选择器,浏览后端为应用内浏览器提供列表与创建原语;双端后端通过其浏览器侧填充 ui-workspace 目录流程的 slot(不通过协议发布)。 | | `ctx.webServer` | `core` | [`host-webserver`](../packages/host/webserver) | - | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`client-hmr`](../packages/client/hmr) | - | 普通的 node:http 载体:具名路由注册表、索引转换 tap,以及静态 dist 回退;Web 传输插件注册自己的路由。 | +| `ctx.webApp` | `core` | [`web-app`](../packages/bundle/web-app) | - | [`harness-dev-context`](../packages/context/harness-dev-context) | - | web-runtime 行为其 Web GUI 公告一个 URL:配置了 publicUrl 时用它,否则用监听器 origin;DSH_WEB_URL、启动 URL 与 harness-dev-context 读取同一个值。 | | `ctx.clientModules` | `core` | [`client-modules`](../packages/client/modules) | - | [`client-hmr`](../packages/client/hmr) | - | 通过增量 `dsh.client` 扫描组合 __DSH_BOOT__ 入口图,提供插件组合包,并通知重建/图变更订阅方。 | | `ctx.workflowEngine` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-ptc`](../packages/workflow/workflow-ptc) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/experimental/tool-ralph) | - | 每个上下文使用一个引擎,与 bash 相同,且没有具名提供方注册表;通用工作流与固定 Ralph 消费方启动运行,其中的 agent() 调用通过 ctx.subagents 扇出。 | | `ctx.webhookRuntime` | `core` | [`webhook`](../packages/experimental/webhook) | - | [`webhook-github`](../packages/experimental/webhook-github) | - | 提供方适配器分派已认证交付;可信插件注册独立的进程本地规则,runtime 把非 null 结果转换为普通的 Workspace-backed Session,不保留交付或完成状态。 | diff --git a/docs/cli-help.md b/docs/cli-help.md index 9796709587..c14b06ac73 100644 --- a/docs/cli-help.md +++ b/docs/cli-help.md @@ -180,7 +180,7 @@ Options: --port listen port; pass 0 to let the OS pick a free one --public-url advertise this HTTP(S) root in the printed, - opened, web-surface, and DSH_WEB_URL forms; + opened, runtime-context, and DSH_WEB_URL forms; grants no trust --trusted-host extra authority the /api browser-trust fence accepts (host or host:port; repeatable) diff --git a/docs/cli-help.zh.md b/docs/cli-help.zh.md index 54b10f9d16..f646eac073 100644 --- a/docs/cli-help.zh.md +++ b/docs/cli-help.zh.md @@ -182,7 +182,7 @@ Options: --port listen port; pass 0 to let the OS pick a free one --public-url advertise this HTTP(S) root in the printed, - opened, web-surface, and DSH_WEB_URL forms; + opened, runtime-context, and DSH_WEB_URL forms; grants no trust --trusted-host extra authority the /api browser-trust fence accepts (host or host:port; repeatable) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 0e22cad9db..77cb0819ed 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1315,7 +1315,7 @@ export interface Config { directory?: string /** Prefix for automatically generated branch and checkout names. */ namePrefix?: string - /** Git 2.45 or newer executable name or absolute execution-world path. */ + /** Executable name or absolute execution-world path of a Git release that honors `GIT_NO_LAZY_FETCH`. */ gitCommand?: string /** Node executable used for sandboxed directory allocation. */ nodeCommand?: string @@ -2441,13 +2441,15 @@ export interface Config { ## `@deepseek-ai/dsh-ptc-runtime-node` - `inject`: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` -- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/index.ts:27`](../packages/ptc-runtime/ptc-runtime-node/src/index.ts) +- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:7`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts) ```ts config-catalog /** Deployment-varying runtime bounds and launch choices. */ export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig + /** per-call starts fresh processes; persistent-in-memory retains a REPL per owner under the same file policy. */ + executionMode?: 'per-call' | 'persistent-in-memory' /** Default elapsed deadline, including nested tool and approval waits. */ timeoutMs?: number /** Maximum numeric elapsed budget accepted by resolve. */ @@ -3475,7 +3477,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:254`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:257`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -4264,7 +4266,7 @@ export interface WebRuntimeConfig { ## `@deepseek-ai/dsh-web-app` - `inject`: `webServer` -- `source`: [`packages/bundle/web-app/src/index.ts:43`](../packages/bundle/web-app/src/index.ts) +- `source`: [`packages/bundle/web-app/src/index.ts:55`](../packages/bundle/web-app/src/index.ts) ```ts config-catalog /** Plugin config: composed deployment settings plus per-invocation command-line values. */ @@ -4274,16 +4276,14 @@ export interface Config { /** Print the URL line on activation; a non-interactive layer can turn it off. */ printUrl: boolean /** - * Register the model-visible surface context (the `app:web-surface` prompt - * section and the `DSH_WEB_URL` bash variable). A one-shot non-interactive - * layer can turn it off when its user is not in the GUI, so the - * orientation text would be false. + * Register the `DSH_WEB_URL` bash variable naming this GUI. A one-shot + * non-interactive layer can turn it off when its user is not in the GUI. */ surfaceContext: boolean /** * Canonical HTTP(S) root to advertise in the printed and opened URL, - * `DSH_WEB_URL`, and the web-surface orientation, e.g. - * `https://app.example/ui/`, normalized to end in `/`. Configures no routing + * `DSH_WEB_URL`, and `webApp.getAdvertisedUrl()`, which supplies the Web GUI + * URL in agent runtime context, e.g. `https://app.example/ui/`, normalized to end in `/`. Configures no routing * or authentication; see [public deployments](../README.md#public-deployments). * Absent or YAML `null` advertises the bind-address URL. */ @@ -4530,6 +4530,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-ui-reference` | — | [`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts) | | `@deepseek-ai/dsh-client-ui-renderer` | — | [`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts) | | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/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-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | @@ -4572,6 +4573,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-fs-observation-policy` | — | [`packages/fs/fs-observation-policy/src/index.ts`](../packages/fs/fs-observation-policy/src/index.ts) | | `@deepseek-ai/dsh-fs-ssh` | `ssh` · `sandboxPolicy` | [`packages/ssh/fs-ssh/src/index.ts`](../packages/ssh/fs-ssh/src/index.ts) | | `@deepseek-ai/dsh-goal-round-driver` | `agents` · `goals` · `sessions` | [`packages/goal/goal-round-driver/src/index.ts`](../packages/goal/goal-round-driver/src/index.ts) | +| `@deepseek-ai/dsh-harness-dev-context` | `systemPrompt` · `sessionProjections` · `webApp` | [`packages/context/harness-dev-context/src/index.ts`](../packages/context/harness-dev-context/src/index.ts) | | `@deepseek-ai/dsh-host-directory-picker-auto` | `webServer` · `connection` · `loader` | [`packages/host/directory-picker-auto/src/index.ts`](../packages/host/directory-picker-auto/src/index.ts) | | `@deepseek-ai/dsh-host-directory-picker-native` | — | [`packages/host/directory-picker-native/src/index.ts`](../packages/host/directory-picker-native/src/index.ts) | | `@deepseek-ai/dsh-host-plugin-inventory` | `loader` | [`packages/host/plugin-inventory/src/index.ts`](../packages/host/plugin-inventory/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 1ee1b383ed..2e84ccb01f 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1317,7 +1317,7 @@ export interface Config { directory?: string /** Prefix for automatically generated branch and checkout names. */ namePrefix?: string - /** Git 2.45 or newer executable name or absolute execution-world path. */ + /** Executable name or absolute execution-world path of a Git release that honors `GIT_NO_LAZY_FETCH`. */ gitCommand?: string /** Node executable used for sandboxed directory allocation. */ nodeCommand?: string @@ -2443,13 +2443,15 @@ export interface Config { ## `@deepseek-ai/dsh-ptc-runtime-node` - `inject`: `fs` · `subprocess` · `sandbox` · `sandboxPolicy` -- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/index.ts:27`](../packages/ptc-runtime/ptc-runtime-node/src/index.ts) +- `source`: [`packages/ptc-runtime/ptc-runtime-node/src/config.ts:7`](../packages/ptc-runtime/ptc-runtime-node/src/config.ts) ```ts config-catalog /** Deployment-varying runtime bounds and launch choices. */ export interface Config { /** Worker invocation in the subprocess world; omitted selects the local carrier. */ launch?: LaunchConfig + /** per-call starts fresh processes; persistent-in-memory retains a REPL per owner under the same file policy. */ + executionMode?: 'per-call' | 'persistent-in-memory' /** Default elapsed deadline, including nested tool and approval waits. */ timeoutMs?: number /** Maximum numeric elapsed budget accepted by resolve. */ @@ -3477,7 +3479,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:254`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:257`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -4266,7 +4268,7 @@ export interface WebRuntimeConfig { ## `@deepseek-ai/dsh-web-app` - `inject`: `webServer` -- `source`: [`packages/bundle/web-app/src/index.ts:43`](../packages/bundle/web-app/src/index.ts) +- `source`: [`packages/bundle/web-app/src/index.ts:55`](../packages/bundle/web-app/src/index.ts) ```ts config-catalog /** Plugin config: composed deployment settings plus per-invocation command-line values. */ @@ -4276,16 +4278,14 @@ export interface Config { /** Print the URL line on activation; a non-interactive layer can turn it off. */ printUrl: boolean /** - * Register the model-visible surface context (the `app:web-surface` prompt - * section and the `DSH_WEB_URL` bash variable). A one-shot non-interactive - * layer can turn it off when its user is not in the GUI, so the - * orientation text would be false. + * Register the `DSH_WEB_URL` bash variable naming this GUI. A one-shot + * non-interactive layer can turn it off when its user is not in the GUI. */ surfaceContext: boolean /** * Canonical HTTP(S) root to advertise in the printed and opened URL, - * `DSH_WEB_URL`, and the web-surface orientation, e.g. - * `https://app.example/ui/`, normalized to end in `/`. Configures no routing + * `DSH_WEB_URL`, and `webApp.getAdvertisedUrl()`, which supplies the Web GUI + * URL in agent runtime context, e.g. `https://app.example/ui/`, normalized to end in `/`. Configures no routing * or authentication; see [public deployments](../README.md#public-deployments). * Absent or YAML `null` advertises the bind-address URL. */ @@ -4532,6 +4532,7 @@ export interface Config { | `@deepseek-ai/dsh-client-ui-reference` | — | [`packages/client/ui-reference/src/index.ts`](../packages/client/ui-reference/src/index.ts) | | `@deepseek-ai/dsh-client-ui-renderer` | — | [`packages/client/ui-renderer/src/index.ts`](../packages/client/ui-renderer/src/index.ts) | | `@deepseek-ai/dsh-client-ui-schedule` | — | [`packages/client/ui-schedule/src/index.ts`](../packages/client/ui-schedule/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-secret-mask` | — | [`packages/client/ui-secret-mask/src/index.ts`](../packages/client/ui-secret-mask/src/index.ts) | | `@deepseek-ai/dsh-client-ui-session` | — | [`packages/client/ui-session/src/index.ts`](../packages/client/ui-session/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-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) | @@ -4574,6 +4575,7 @@ export interface Config { | `@deepseek-ai/dsh-fs-observation-policy` | — | [`packages/fs/fs-observation-policy/src/index.ts`](../packages/fs/fs-observation-policy/src/index.ts) | | `@deepseek-ai/dsh-fs-ssh` | `ssh` · `sandboxPolicy` | [`packages/ssh/fs-ssh/src/index.ts`](../packages/ssh/fs-ssh/src/index.ts) | | `@deepseek-ai/dsh-goal-round-driver` | `agents` · `goals` · `sessions` | [`packages/goal/goal-round-driver/src/index.ts`](../packages/goal/goal-round-driver/src/index.ts) | +| `@deepseek-ai/dsh-harness-dev-context` | `systemPrompt` · `sessionProjections` · `webApp` | [`packages/context/harness-dev-context/src/index.ts`](../packages/context/harness-dev-context/src/index.ts) | | `@deepseek-ai/dsh-host-directory-picker-auto` | `webServer` · `connection` · `loader` | [`packages/host/directory-picker-auto/src/index.ts`](../packages/host/directory-picker-auto/src/index.ts) | | `@deepseek-ai/dsh-host-directory-picker-native` | — | [`packages/host/directory-picker-native/src/index.ts`](../packages/host/directory-picker-native/src/index.ts) | | `@deepseek-ai/dsh-host-plugin-inventory` | `loader` | [`packages/host/plugin-inventory/src/index.ts`](../packages/host/plugin-inventory/src/index.ts) | diff --git a/docs/development.i18n.yaml b/docs/development.i18n.yaml index 2a08605a85..297872610b 100644 --- a/docs/development.i18n.yaml +++ b/docs/development.i18n.yaml @@ -21,14 +21,14 @@ en: 3221d1076554001f zh: 29f166be6a5c04d9 /development-guide/contributor-reference/typescript-project-layout: - en: e3327c5492a593cb - zh: d43a5edcb11523ae + en: f0582a3a145a4d93 + zh: 9cab4abec6935b3c /development-guide/contributor-reference/environment-variables: en: dba2c72ee6ffa930 zh: b65c27fbb9129ec8 /development-guide/contributor-reference/git-integrations: - en: dc98eda4f4021feb - zh: b08766708803cf10 + en: 4e782ec2ca27dd1f + zh: 7a60e8c0d60de3c8 /development-guide/contributor-reference/ci-gates: en: b64a914e41b1d285 zh: 6c031b507c3c0e84 @@ -39,8 +39,8 @@ en: 7ce6264a6a06dc4a zh: e12b684f2bef942b /development-guide/contributor-reference/application-commands: - en: 28a029c8768f0880 - zh: 67c17256e046624e + en: 98828fc2b972bf39 + zh: 1dc889a3d766bf35 /development-guide/contributor-reference/todo-markers: en: 85b38f78d87fc88f zh: 00d5eb625e7dfb61 diff --git a/docs/development.md b/docs/development.md index 668beec326..39e05c25ef 100644 --- a/docs/development.md +++ b/docs/development.md @@ -74,24 +74,38 @@ Host and Client stay two aggregate programs because both sides declaration-merge Six packages split Host and Client tsconfigs: `api/remotes`, `api/gateway`, `api/session-controller`, `api/workspace-controller`, `client/connection`, and `session-query/session-log-export`. `api/remotes`' Host entry participates in the Host Typert graph while its Client entry imports generated `/remote` declarations; `session-log-export` keeps Node archive production out of its browser controller. Each split package-root `tsconfig.json` is therefore only a solution, and the two aggregates and direct consumers reference `tsconfig.host.json` or `tsconfig.client.json` respectively. The workspace `constraints` gate walks the reachable Project Reference graph and checks each referencing project's own compiler face: a single-config target remains valid from either face, while a split target must name the matching leaf rather than its solution root or opposite leaf; it discovers split packages from the presence of both leaf configs, so a new split joins the gate automatically. The [`api-remotes` README](../packages/api/remotes/README.md) and [`session-log-export` README](../packages/session-query/session-log-export/README.md) explain their splits. -The root build follows the generated dependency order: +`pnpm run build:artifacts` emits every artifact in the generated dependency order, checking and compiling only the package references of each compiler face: ```sh -tsc -b tsconfig.host.json +pnpm run build:native-system +tsc -b tsdown --env.DSH_BUILD_FACE host pnpm --filter @deepseek-ai/dsh-desktop run bundle -tsc -b tsconfig.client.json +tsc -b tsdown --env.DSH_BUILD_FACE client pnpm run build:web ``` -`pnpm run build --artifacts-only` emits the same project and application artifacts while checking and compiling only the existing package references of each compiler face. Required Linux and Windows normal builds and public `typecheck` also check the repository-wide test and script programs. CI benchmark preparation additionally uses `--noCheck` for its disposable library outputs, relying on those required builds for diagnostics; other artifact builders keep package checking ([rationale](../.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md)). +`pnpm run build:check` runs only `tsc -p tsconfig.host.json` and `tsc -p tsconfig.client.json` concurrently. Project mode checks each aggregate's repository-wide test and script program against the package declarations already on disk and never compiles a reference, so `build:check` neither detects nor rebuilds missing or stale `build:artifacts` output; missing output surfaces as compiler errors. `pnpm run build` runs both step sets as one [scheduled](../scripts/run-gates.ts) dependency graph: each aggregate check starts once its own face's package compilation finishes and overlaps the remaining artifact steps. In all three commands `DSH_GATE_CONCURRENCY` bounds concurrent steps (`1` runs them in dependency order) and `DSH_GATE_FAIL_FAST=1` stops the remaining steps at the first failure; otherwise a failure skips only its dependents, so independent errors are all reported. A failed step prints its own output, and any failure exits non-zero without writing the client build record. + +Choose the command by what the change needs: + +| Situation | Command | +|---|---| +| Iterating on package sources and needing runnable artifacts | `pnpm run build:artifacts`; `dev:web` and `dev:desktop` run it before launching | +| Type-checking tests, scripts, benchmarks, or website code | `pnpm run build:check` after the latest `build:artifacts`; rerun `build:artifacts` first when package sources changed | +| Before declaring TypeScript work complete | `pnpm run build:check` after the latest `build:artifacts`, or `pnpm run build` | +| Complete verification, as the required CI build lanes run it | `pnpm run build` | +| Type checks without the Web and Desktop artifacts | `pnpm run typecheck` | +| Lint or documentation code-block checks | `pnpm run lint` or `pnpm run doc-typecheck`; each prepares `host-contracts` itself | + +PR artifact builders run `build:artifacts`; required Linux and Windows normal builds and public `typecheck` also check the repository-wide test and script programs. CI benchmark preparation additionally uses `--noCheck` for its disposable library outputs, relying on those required builds for diagnostics; other artifact builders keep package checking ([rationale](../.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.md)). Both tsdown passes match `vendor/*`, `packages/*/*`, and `apps/cli`; the Host pass also matches `apps/desktop-host`. They neither scan build artifacts to discover Client packages nor maintain a Host/Client package filter list. Package-local tsdown configs select entries for the current phase through `DSH_BUILD_FACE`: an ordinary Client plugin produces both its Node loader and browser bundle during the Client phase; `api-remotes` uses `hostPhase: true` to produce its Host entry early and only its browser bundle during the Client phase. Tsdown consumes only the JavaScript emitted to `lib/types` by the preceding tsc phase. Tsdown builds the matched workspace members concurrently, so `apps/desktop`, whose main bundle inlines workspace devDependencies from their `lib/` output, bundles in its own step after the Host pass ([Desktop README](../apps/desktop/README.md#bundled-workspace-dependencies)). -Typert runs only during Host tsdown, seeded by `tsconfig.host.json`. It analyzes Host types and generates both Host reflection artifacts and the Host-for-Client Remote projection; Client tsdown does not start Typert. Consequently, `pnpm run typecheck` runs the complete Host lib phase before Client tsc, while `pnpm run build` continues through Client tsdown and the Web build. +Typert analyzes Host types, seeded by `tsconfig.host.json`, and generates both Host reflection artifacts and the Host-for-Client Remote projection; Client tsdown does not start Typert. Host tsdown runs it as a plugin, and [`generate-typert.ts`](../scripts/generate-typert.ts) runs the same generation without bundling and writes byte-identical files. The bundle-free pass reads workspace packages only from source and fails when the Host program would load a package's `lib/` output, naming the import and the `paths` alias to add, so it can run beside Host package compilation. Client package compilation always follows one of the two passes because Client sources import the generated Remote declarations. `pnpm run typecheck` runs the `build.ts --scope typecheck` graph: Host package compilation beside the bundle-free Typert pass, then Client package compilation, with each aggregate checked in build mode (`tsc -b`) once its own face's packages compile; it skips the native addon, every bundle, Web, and the client build record. `lint`, `lint:fix`, and `doc-typecheck` read the generated declarations but not the Host aggregate check, so they prepare only Host package compilation and the bundle-free Typert pass (`compile-referenced-projects.ts host-contracts`). None of these commands writes bundles: the runnable `lib/` output stays as the last `build:artifacts` left it, so run `build:artifacts` before launching or testing built output. -`pnpm run build` embeds the root package version, the seven-character source commit, and a dirty marker when Git reports local changes; it also inherits other caller-supplied `DSH_CLIENT_*` values. `pnpm run build:official` is the cross-platform local equivalent of the CI and release artifact build and omits the local dirty marker. Each successful complete build writes a gitignored record that binds the exact public values to the Vite output and dynamic client bundles; release packing and built Web tests reject a missing record or artifacts changed by a later partial build. `pnpm run dev:web` runs that complete build first (`--skip-build` reuses an existing artifact tree instead), then samples the current version and Git state once and shares that environment across every watcher stage for the session; it does not validate the complete-build record because the watcher stages rewrite its recorded artifacts. +`pnpm run build` and `build:artifacts` embed the root package version, the seven-character source commit, and a dirty marker when Git reports local changes; they also inherit other caller-supplied `DSH_CLIENT_*` values. `pnpm run build:official` is the cross-platform local equivalent of the CI and release artifact build and omits the local dirty marker. Each successful `build` or `build:artifacts` writes a gitignored record that binds the exact public values to the Vite output and dynamic client bundles; release packing and built Web tests reject a missing record or artifacts changed by a later partial build. `pnpm run dev:web` runs `build:artifacts` first (`--skip-build` reuses an existing artifact tree instead), then samples the current version and Git state once and shares that environment across every watcher stage for the session; it does not validate the complete-build record because the watcher stages rewrite its recorded artifacts. Static 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. Generated Host-for-Client Remote declarations are the deliberate exception: the public `typecheck`, `lint`, and `doc-typecheck` commands generate them first, while internal `*:contracts-ready` scripts assume that an invoking public command or scheduler gate already depends on the Typert contract-generation pass or the complete build. See the [Typert Remote note](../.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.md) for the gate-preparation contract. @@ -122,9 +136,9 @@ DEEPSEEK_BASE_URL=https://... # optional lefthook is configured in `lefthook.yml` as a fast local checkpoint: -- `pre-commit` verifies staged pairing records against the staged owner blobs, validates staged files with the project-free `.oxlintrc.staged.json` profile and applies Oxlint fixes with one bounded retry, regenerates `THIRD_PARTY_NOTICES.md` when a staged file is one of its inputs, checks the staged diff for whitespace errors, and runs the vendor manifest guard. +- `pre-commit` verifies staged pairing records against the staged owner blobs, validates staged files with the project-free `.oxlintrc.staged.json` profile and applies Oxlint fixes with one bounded retry, checks the staged diff for whitespace errors, and runs the vendor manifest guard. - `pre-merge-commit` performs the same index-backed pairing check before Git creates an automatic merge commit. -- `pre-push` runs `pnpm run typecheck`, which completes the Host lib phase, including generated Typert contracts, before the Client TypeScript check. +- `pre-push` runs `pnpm run typecheck`, which generates Typert contracts without bundling before the Client TypeScript check and checks both aggregates. The 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. @@ -132,6 +146,8 @@ Apart from the scoped staged-record verification, the hooks intentionally do not Contributors can opt into the comprehensive local gate set with `pnpm run check:all`. The command is independent of the Git hooks and is not an agent instruction. +Outside CI (`CI` other than `true`), default worker counts follow the [local worker budget](../scripts/parallelism.ts): 12 for gate schedulers, `build`, `typecheck`, Oxlint, and publint, and 48 for Vitest forks and local coverage. `doc-sync`, `test:docs`, `hygiene`, and `check:all` run at most 8 gates at once, in CI as well. `os.availableParallelism()` reports host CPUs rather than a container's CPU quota, so uncapped defaults oversubscribe shared hosts. CI keeps the runner's CPU count. `DSH_GATE_CONCURRENCY`, `DSH_OXLINT_THREADS`, `DSH_COVERAGE_MAX_WORKERS`, and Vitest `--maxWorkers` override the defaults. + ### CI gates The 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. Coverage partitions reuse file timings scoped to their platform and runner pool to balance work within the configured worker limit. Required benchmarks run separately on standard GitHub-hosted Linux; the [benchmark runner reference](../benchmarks/AGENTS.md) owns routing and the job timeout. 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. @@ -164,7 +180,7 @@ pnpm run demo:ptc -- "summarize this workspace" ### Application commands -Web and Desktop share one command pair. `start:*` launches the artifacts of a prior `pnpm run build`; `dev:*` runs that build first and then launches. Web additionally keeps client bundles rebuilt on source edits, because its Host runs from source while the browser loads built bundles: +Web and Desktop share one command pair. `start:*` launches the artifacts of a prior `pnpm run build` or `build:artifacts`; `dev:*` runs `build:artifacts` first and then launches. Web additionally keeps client bundles rebuilt on source edits, because its Host runs from source while the browser loads built bundles: ```sh pnpm run start:web # serve built Web artifacts through the source launcher (the same launch as pnpm dsh web) diff --git a/docs/development.zh.md b/docs/development.zh.md index 5446ee3a89..c8b50343fd 100644 --- a/docs/development.zh.md +++ b/docs/development.zh.md @@ -78,24 +78,38 @@ Host 与 Client 保持两个 aggregate program,是因为两侧在相同键下 拆分 Host/Client tsconfig 的包有六个:`api/remotes`、`api/gateway`、`api/session-controller`、`api/workspace-controller`、`client/connection` 与 `session-query/session-log-export`。`api/remotes` 的 Host 入口进入 Host Typert 图,而 Client 入口导入生成的 `/remote` 声明;`session-log-export` 则让 Node archive 生产代码不进入浏览器 controller。每个拆分包根 `tsconfig.json` 因此只作为 solution,两个 aggregate 和直接消费方分别引用 `tsconfig.host.json` 或 `tsconfig.client.json`。workspace `constraints` 门禁遍历可达的 Project Reference 图,并按各引用 project 自身的 compiler face 检查:只有单一配置的目标可由任一 face 引用,拆分配置的目标则必须引用匹配的 leaf,不得引用 solution 根或另一侧 leaf;该门禁按「两个 leaf 配置同时存在」自动发现拆分包,所以新拆分的包会自动纳入管辖。[`api-remotes` README](../packages/api/remotes/README.zh.md) 与 [`session-log-export` README](../packages/session-query/session-log-export/README.zh.md)分别说明其拆分。 -根构建按生成依赖排序: +`pnpm run build:artifacts` 按生成依赖顺序产出全部产物,只检查并编译各 compiler face 的包 reference: ```sh -tsc -b tsconfig.host.json +pnpm run build:native-system +tsc -b tsdown --env.DSH_BUILD_FACE host pnpm --filter @deepseek-ai/dsh-desktop run bundle -tsc -b tsconfig.client.json +tsc -b tsdown --env.DSH_BUILD_FACE client pnpm run build:web ``` -`pnpm run build --artifacts-only` 产出相同的 project 和应用产物,但只检查并编译各 compiler face 的现有包 reference。必需的 Linux 与 Windows 普通构建以及公开 `typecheck` 还检查仓库级测试和脚本 program。CI benchmark 准备阶段还对其临时 library 输出使用 `--noCheck`,由这些必需构建负责诊断;其他产物 builder 保留包检查([理由](../.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md))。 +`pnpm run build:check` 只并发运行 `tsc -p tsconfig.host.json` 与 `tsc -p tsconfig.client.json`。project mode 依据磁盘上已有的包声明检查各 aggregate 的仓库级测试和脚本 program,从不编译 reference,因此 `build:check` 既不检测也不重建缺失或过期的 `build:artifacts` 产物;产物缺失时表现为编译器错误。`pnpm run build` 把两组步骤作为一张[调度](../scripts/run-gates.ts)依赖图运行:每个 aggregate 检查在本 face 的包编译完成后立即开始,与其余产物步骤重叠执行。三个命令中,`DSH_GATE_CONCURRENCY` 限制并发步骤数(`1` 按依赖顺序执行),`DSH_GATE_FAIL_FAST=1` 在第一个失败时停止其余步骤;否则失败只跳过其依赖方,因此会报告所有相互独立的错误。失败步骤打印自身输出,任一失败都以非零状态退出且不写 client build record。 + +按改动需要选择命令: + +| 场景 | 命令 | +|---|---| +| 迭代包源码并需要可运行的产物 | `pnpm run build:artifacts`;`dev:web` 与 `dev:desktop` 启动前会先执行它 | +| 检查测试、脚本、benchmarks 或 website 代码的类型 | 在最近一次 `build:artifacts` 之后运行 `pnpm run build:check`;包源码有改动时先重新运行 `build:artifacts` | +| 声明 TypeScript 工作完成之前 | 在最近一次 `build:artifacts` 之后运行 `pnpm run build:check`,或运行 `pnpm run build` | +| 完整验证(与 CI 必需的构建 lane 相同) | `pnpm run build` | +| 只做类型检查、不需要 Web 与 Desktop 产物 | `pnpm run typecheck` | +| lint 或文档代码块检查 | `pnpm run lint` 或 `pnpm run doc-typecheck`;它们各自先准备 `host-contracts` | + +PR 产物 builder 运行 `build:artifacts`;必需的 Linux 与 Windows 普通构建以及公开 `typecheck` 还检查仓库级测试和脚本 program。CI benchmark 准备阶段还对其临时 library 输出使用 `--noCheck`,由这些必需构建负责诊断;其他产物 builder 保留包检查([理由](../.agents/notes/implemented/process/2026-10-05-pr-artifact-typechecks.zh.md))。 两次 tsdown 都匹配 `vendor/*`、`packages/*/*` 与 `apps/cli`,Host 阶段另外匹配 `apps/desktop-host`;两者都不扫描构建产物来发现 Client 包,也不维护 Host/Client 包过滤表。包内 tsdown 配置根据 `DSH_BUILD_FACE` 决定当前阶段的入口:普通 Client 插件在 Client 阶段同时生成 Node loader 与 browser bundle;`api-remotes` 通过 `hostPhase: true` 提前生成 Host 入口,再在 Client 阶段只生成 browser bundle。tsdown 只消费 `lib/types` 中由前置 tsc 发射的 JavaScript。tsdown 并发构建匹配到的 workspace 成员;`apps/desktop` 的主进程 bundle 需要从工作区 devDependencies 的 `lib/` 产物内联这些包,因此在 Host 阶段之后单独一步打 bundle([Desktop README](../apps/desktop/README.zh.md#bundled-workspace-dependencies))。 -Typert 只在 Host tsdown 中以 `tsconfig.host.json` 为种子运行。它分析 Host 类型并生成 Host 反射产物及 Host-for-Client Remote 投影;Client tsdown 不启动 Typert。`pnpm run typecheck` 因此先执行完整 Host lib 阶段,再运行 Client tsc;`pnpm run build` 继续执行 Client tsdown 和 Web 构建。 +Typert 以 `tsconfig.host.json` 为种子分析 Host 类型,生成 Host 反射产物及 Host-for-Client Remote 投影;Client tsdown 不启动 Typert。Host tsdown 以插件形式运行它,[`generate-typert.ts`](../scripts/generate-typert.ts) 则不打包地执行同一生成,写出逐字节相同的文件。不打包的这一轮只从源码读取工作区包;若 Host program 会载入某个包的 `lib/` 产物,它就失败并指出该 import 及应补的 `paths` 别名,因此可以与 Host 包编译并行。Client 源码 import 生成的 Remote 声明,所以 Client 包编译总在这两种生成之一之后。`pnpm run typecheck` 运行 `build.ts --scope typecheck` 图:Host 包编译与不打包的 Typert 生成并行,之后是 Client 包编译,每个 aggregate 在本 face 的包编译完成后以 build mode(`tsc -b`)检查;它跳过 native addon、所有 bundle、Web 以及 client build record。`lint`、`lint:fix` 与 `doc-typecheck` 读取生成的声明但不依赖 Host aggregate 检查,因此只准备 Host 包编译与不打包的 Typert 生成(`compile-referenced-projects.ts host-contracts`)。这些命令都不写 bundle:可运行的 `lib/` 产物保持上一次 `build:artifacts` 的状态,因此启动或测试构建产物之前先运行 `build:artifacts`。 -`pnpm run build` 会内联根包版本、七位源码 commit,并在 Git 报告本地变化时内联 dirty 标记;调用方提供的其他 `DSH_CLIENT_*` 值也会被继承。`pnpm run build:official` 是与 CI 和 release 产物构建等价的跨平台本地命令,并省略本地 dirty 标记。每次完整构建成功后都会写入一份被 gitignore 的记录,把精确公开值与 Vite 输出及动态 client bundle 绑定;release 打包和 built Web 测试会拒绝缺少记录或被后续局部构建改动的产物。`pnpm run dev:web` 会先执行这次完整构建(`--skip-build` 则复用现有产物树),再读取一次当前版本和 Git 状态,并在本次会话的所有 watcher stage 之间共享该环境;它不会校验完整构建记录,因为 watcher stage 会重写记录覆盖的产物。 +`pnpm run build` 与 `build:artifacts` 会内联根包版本、七位源码 commit,并在 Git 报告本地变化时内联 dirty 标记;调用方提供的其他 `DSH_CLIENT_*` 值也会被继承。`pnpm run build:official` 是与 CI 和 release 产物构建等价的跨平台本地命令,并省略本地 dirty 标记。每次 `build` 或 `build:artifacts` 成功后都会写入一份被 gitignore 的记录,把精确公开值与 Vite 输出及动态 client bundle 绑定;release 打包和 built Web 测试会拒绝缺少记录或被后续局部构建改动的产物。`pnpm run dev:web` 会先执行 `build:artifacts`(`--skip-build` 则复用现有产物树),再读取一次当前版本和 Git 状态,并在本次会话的所有 watcher stage 之间共享该环境;它不会校验完整构建记录,因为 watcher stage 会重写记录覆盖的产物。 静态分析和测试通过 base 的 `paths` 映射把工作区 import 解析到 `src`,且必须在干净树上通过;消费构建产物 `lib/` 的门禁显式声明该依赖。生成的 Host-for-Client Remote 声明是有意设置的例外:公共 `typecheck`、`lint` 和 `doc-typecheck` 命令会先生成这些声明,而内部 `*:contracts-ready` 脚本假定调用它的公共命令或调度器门禁已经依赖 Typert 约定生成阶段或完整构建。门禁准备约定见 [Typert Remote Agent Note](../.agents/notes/implemented/architecture/2026-08-02-typert-remote-method-calls.zh.md)。 @@ -127,9 +141,9 @@ DEEPSEEK_BASE_URL=https://... # optional lefthook 在 `lefthook.yml` 中配置,作为快速的本地检查点: -- `pre-commit` 对照暂存的配对文档 blob 校验暂存的配对记录,使用不加载项目的 `.oxlintrc.staged.json` 配置验证暂存文件,并通过一次有界重试应用 Oxlint 修复,在暂存文件属于 `THIRD_PARTY_NOTICES.md` 的输入时重新生成该文件,然后检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫; +- `pre-commit` 对照暂存的配对文档 blob 校验暂存的配对记录,使用不加载项目的 `.oxlintrc.staged.json` 配置验证暂存文件,并通过一次有界重试应用 Oxlint 修复,然后检查暂存 diff 中的空白错误,并运行 vendor manifest(元数据清单)守卫; - `pre-merge-commit` 在 Git 创建自动合并提交前执行同样以索引为准的配对检查; -- `pre-push` 运行 `pnpm run typecheck`;该命令会先完成包含 Typert 约定生成的完整 Host lib 阶段,再运行 Client TypeScript 检查。 +- `pre-push` 运行 `pnpm run typecheck`;该命令先不打包地生成 Typert 约定,再运行 Client TypeScript 检查,并检查两个 aggregate。 vendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `vendor/README.md` manifest 更新一起暂存。请在编辑 vendor 代码前先阅读 `vendor/README.md`。 @@ -137,6 +151,8 @@ vendor manifest 守卫检查 `vendor/*/src` 下的改动是否连同对应的 `v 贡献者可以选择运行 `pnpm run check:all`,执行全面的本地门禁集。该命令独立于 Git 钩子,也不是对 agent 的指令。 +在 CI 之外(`CI` 不为 `true`),默认 worker 数遵循[本地 worker 预算](../scripts/parallelism.ts):门禁调度器、`build`、`typecheck`、Oxlint 与 publint 为 12,Vitest fork 与本地覆盖率为 48。`doc-sync`、`test:docs`、`hygiene` 与 `check:all` 最多同时运行 8 个门禁,CI 中同样如此。`os.availableParallelism()` 报告的是宿主 CPU 数而不是容器的 CPU 配额,因此不设上限的默认值会在共享主机上超额订阅。CI 仍使用 runner 的 CPU 数。`DSH_GATE_CONCURRENCY`、`DSH_OXLINT_THREADS`、`DSH_COVERAGE_MAX_WORKERS` 与 Vitest 的 `--maxWorkers` 可覆盖这些默认值。 + ### CI 门禁 keyless [CI 工作流](../.github/workflows/ci.yml) 将独立门禁分组到若干宽粒度 lane,并在受支持的 Node 版本上运行一组较小的兼容性检查。产物消费方在各自 lane 内等待一次 build。覆盖率分区复用按平台和运行器池隔离的文件耗时,在配置的 worker 上限内均衡工作量。必需 benchmark 在标准 GitHub 托管 Linux 上独立运行;[benchmark 运行器说明](../benchmarks/AGENTS.md)拥有路由及 job 超时。单独的真实 API 工作流按其配置的 worker 上限运行 `pnpm run test:e2e`。当前门禁和 job 清单以 [scripts/run-gates.ts](../scripts/run-gates.ts) 和工作流文件为准。 @@ -169,7 +185,7 @@ pnpm run demo:ptc -- "summarize this workspace" ### 应用命令 -Web 与 Desktop 共用同一对命令。`start:*` 启动上一次 `pnpm run build` 的产物;`dev:*` 先执行该构建再启动。Web 还会在源码修改时持续重建 client bundle,因为它的 Host 从源码运行,而浏览器加载的是构建产物: +Web 与 Desktop 共用同一对命令。`start:*` 启动上一次 `pnpm run build` 或 `build:artifacts` 的产物;`dev:*` 先执行 `build:artifacts` 再启动。Web 还会在源码修改时持续重建 client bundle,因为它的 Host 从源码运行,而浏览器加载的是构建产物: ```sh pnpm run start:web # serve built Web artifacts through the source launcher (the same launch as pnpm dsh web) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 9691933dda..4017a84fa3 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -22,12 +22,12 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:605`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:612`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:53`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:610`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:617`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:52`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | @@ -63,7 +63,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:54`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:63`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `agent-team`, `file-upload`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:74`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:74`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:82`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index cb8ea84aac..3d621ea377 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -24,12 +24,12 @@ | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:353`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | | `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:280`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:381`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:619`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:599`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:626`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:605`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:612`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:53`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:624`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:604`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:631`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:610`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:617`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:52`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | | `commands/change` | `emit` | [`packages/interaction/commands/src/types.ts:89`](../packages/interaction/commands/src/types.ts) | [`commands`](../packages/interaction/commands) (`events.dispatch`) | `remotes` | @@ -65,7 +65,7 @@ | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | | `session/created` | `emit` | [`packages/core/session/src/index.ts:54`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`permission-presets`](../packages/interaction/permission-presets), [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:63`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `agent-team`, `file-upload`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:74`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:74`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:82`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | diff --git a/docs/glossary.i18n.yaml b/docs/glossary.i18n.yaml index e2e49e31f5..532c84896c 100644 --- a/docs/glossary.i18n.yaml +++ b/docs/glossary.i18n.yaml @@ -18,8 +18,8 @@ en: 38a55fc61b359ace zh: 567cae201b3a1bdf /glossary/loop-hierarchy: - en: 343a7cb31b8191c2 - zh: 6831415a7fe1726a + en: 6bf1ad7dd53f79cc + zh: 6231e68c769fdefa /glossary/ralph: en: 5059f8a377980b9d zh: 39bf11c10e5c0a84 diff --git a/docs/glossary.md b/docs/glossary.md index 1a9ac39a73..e30e4e2122 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -37,6 +37,7 @@ Domain vocabulary for DeepSeek Harness uses one canonical term per concept. Term - **turn** — one drain of admitted input in a session, ending after the model and its tools stop or a terminal policy intervenes. - **step** — one model request plus the tool executions caused by its response; a turn contains zero or more steps. - **round** — an outer policy iteration containing a turn, such as a [goal round](#goal-round) or one fresh-agent Ralph attempt. Round counters belong to that policy and do not count every turn in a session. +- **exchange** — consecutive [turns](#turn) from a turn whose first [step](#step) admits human input until the next such turn; turns woken by notices, such as settled subagents, goal rounds, or schedules, stay in the preceding exchange. Chat's next-message folding keeps the latest exchange expanded. ## Ralph diff --git a/docs/glossary.zh.md b/docs/glossary.zh.md index cd41876d41..68f5e4bf8c 100644 --- a/docs/glossary.zh.md +++ b/docs/glossary.zh.md @@ -37,6 +37,7 @@ DeepSeek Harness 的领域词汇为每个概念规定一个规范术语。各术 - **轮次**:会话中一次对已接纳输入的排空过程,在模型及其工具停止工作或终止策略介入后结束。 - **步骤**:一次模型请求,以及由模型响应引发的工具执行;一个轮次包含零个或多个步骤。 - **Round**:承载一个轮次的外层策略迭代,例如一个 [Goal Round](#goal-round) 或一次使用全新 agent 的 Ralph 尝试。Round 计数器归该策略所有,并不统计会话中的每个轮次。 +- **交互段**:连续的[轮次](#turn),从首个[步骤](#step)接纳真人输入的轮次起,到下一个这样的轮次为止;由通知(子 agent 完成、Goal Round、定时任务等)唤醒的轮次归入前面的交互段。Chat 的「下次发送时收起」保持最新交互段展开。 ## Ralph diff --git a/docs/i18n/terminology.md b/docs/i18n/terminology.md index cf7009ff7f..5971f88600 100644 --- a/docs/i18n/terminology.md +++ b/docs/i18n/terminology.md @@ -127,6 +127,7 @@ | event log | 事件日志 | | | | | event stream | 事件流 | | | | | event-sourced | 事件溯源 | | | 沿用 DDD 社区通行译法 | +| exchange | 交互段 | | 回合、交换 | Chat 中从真人输入开启的轮次起、到下一个这样的轮次为止的连续轮次;见术语表 | | Executive summary | 摘要 | | | 事故复盘标题用语 | | executor | 执行器 | | | | | expected output | 预期输出 | | 金标 | 指 snapshot 比较产物;翻译语料的人工校准样例不在此列 | diff --git a/docs/module-graph.md b/docs/module-graph.md index 12a6608993..fe417d9b07 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -175,6 +175,7 @@ flowchart TD pkg_client_ui_reference["client-ui-reference"] pkg_client_ui_renderer["client-ui-renderer"] pkg_client_ui_schedule["client-ui-schedule"] + pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] @@ -219,6 +220,7 @@ flowchart TD pkg_agent_instructions["agent-instructions"] pkg_file_reference["file-reference"] pkg_file_reference_local["file-reference-local"] + pkg_harness_dev_context["harness-dev-context"] pkg_session_reference["session-reference"] pkg_time_context["time-context"] pkg_tmux_context["tmux-context"] @@ -450,6 +452,8 @@ flowchart TD pkg_web --> pkg_llm pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand + pkg_app_boot --> pkg_home_paths + pkg_app_boot --> pkg_launch_environment pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand @@ -484,9 +488,8 @@ flowchart TD pkg_api_terminal_controller --> pkg_subprocess pkg_attachment_local --> pkg_attachment pkg_attachment_local --> pkg_home_paths - pkg_app_boot --> pkg_home_paths - pkg_app_boot --> pkg_launch_environment - pkg_app_boot --> pkg_system_prompt + pkg_hmr --> pkg_app_boot + pkg_hmr --> pkg_cmdline pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_inspector --> pkg_client_connection pkg_experimental_inspector --> pkg_client_modules @@ -528,8 +531,8 @@ flowchart TD pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence - pkg_hmr --> pkg_app_boot - pkg_hmr --> pkg_cmdline + pkg_config_editor --> pkg_app_boot + pkg_config_editor --> pkg_hmr pkg_experimental_speech_to_text --> pkg_settings pkg_experimental_translator --> pkg_credentials pkg_experimental_translator --> pkg_launch_environment @@ -597,8 +600,6 @@ flowchart TD pkg_api_workspace_controller --> pkg_storage_domain pkg_api_workspace_controller --> pkg_typert_protocol pkg_api_workspace_controller --> pkg_workspace - pkg_config_editor --> pkg_app_boot - pkg_config_editor --> pkg_hmr pkg_experimental_api_speech_to_text --> pkg_experimental_speech_to_text pkg_experimental_api_speech_to_text --> pkg_typert_protocol pkg_experimental_speech_to_text_sensevoice --> pkg_experimental_speech_to_text @@ -637,6 +638,10 @@ flowchart TD pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol pkg_file_reference --> pkg_agent + pkg_harness_dev_context --> pkg_agent + pkg_harness_dev_context --> pkg_session + pkg_harness_dev_context --> pkg_session_projection + pkg_harness_dev_context --> pkg_system_prompt pkg_time_context --> pkg_agent pkg_time_context --> pkg_llm pkg_time_context --> pkg_session @@ -1045,7 +1050,6 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env - pkg_web_app --> pkg_system_prompt pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions pkg_experimental_auto_review --> pkg_llm @@ -1494,6 +1498,7 @@ flowchart TD | [`client-ui-reference`](../packages/client/ui-reference) | `client` | — | | [`client-ui-renderer`](../packages/client/ui-renderer) | `client` | — | | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | +| [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | @@ -1561,6 +1566,7 @@ flowchart TD | [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand) | +| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | @@ -1582,7 +1588,7 @@ flowchart TD | [`api-gateway`](../packages/api/gateway) | `api` | [`client-connection`](../packages/client/connection) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | -| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`system-prompt`](../packages/core/system-prompt) | +| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1603,7 +1609,7 @@ flowchart TD | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | -| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | +| [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | | [`experimental-translator`](../packages/experimental/translator) | `experimental` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) | @@ -1622,7 +1628,6 @@ flowchart TD | [`fs-observation-policy`](../packages/fs/fs-observation-policy) | `fs` | [`fs`](../packages/fs/fs) | | [`skill-filesystem`](../packages/skill/skill-filesystem) | `skill` | [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`skill`](../packages/skill/skill) | | [`api-workspace-controller`](../packages/api/workspace-controller) | `api` | [`api-gateway`](../packages/api/gateway), [`client-connection`](../packages/client/connection), [`host-directory-picker`](../packages/host/directory-picker), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol), [`workspace`](../packages/workspace/workspace) | -| [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`typert-protocol`](../packages/typert/protocol) | | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`subprocess`](../packages/subprocess/subprocess) | | [`hook-protocol`](../packages/experimental/hook-protocol) | `experimental` | [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | @@ -1634,6 +1639,7 @@ flowchart TD | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | +| [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | | [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | @@ -1714,7 +1720,7 @@ flowchart TD | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compaction`](../packages/compaction/compaction), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | -| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt) | +| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index b9a744b112..792f2730d1 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -177,6 +177,7 @@ flowchart TD pkg_client_ui_reference["client-ui-reference"] pkg_client_ui_renderer["client-ui-renderer"] pkg_client_ui_schedule["client-ui-schedule"] + pkg_client_ui_secret_mask["client-ui-secret-mask"] pkg_client_ui_session["client-ui-session"] pkg_client_ui_settings["client-ui-settings"] pkg_client_ui_settings_account["client-ui-settings-account"] @@ -221,6 +222,7 @@ flowchart TD pkg_agent_instructions["agent-instructions"] pkg_file_reference["file-reference"] pkg_file_reference_local["file-reference-local"] + pkg_harness_dev_context["harness-dev-context"] pkg_session_reference["session-reference"] pkg_time_context["time-context"] pkg_tmux_context["tmux-context"] @@ -452,6 +454,8 @@ flowchart TD pkg_web --> pkg_llm pkg_api_remotes --> pkg_scope pkg_attachment --> pkg_brand + pkg_app_boot --> pkg_home_paths + pkg_app_boot --> pkg_launch_environment pkg_browser_use --> pkg_brand pkg_client_connection --> pkg_scope pkg_computer_use --> pkg_brand @@ -486,9 +490,8 @@ flowchart TD pkg_api_terminal_controller --> pkg_subprocess pkg_attachment_local --> pkg_attachment pkg_attachment_local --> pkg_home_paths - pkg_app_boot --> pkg_home_paths - pkg_app_boot --> pkg_launch_environment - pkg_app_boot --> pkg_system_prompt + pkg_hmr --> pkg_app_boot + pkg_hmr --> pkg_cmdline pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_inspector --> pkg_client_connection pkg_experimental_inspector --> pkg_client_modules @@ -530,8 +533,8 @@ flowchart TD pkg_spill_local --> pkg_spill pkg_session_log_export --> pkg_session pkg_session_log_export --> pkg_session_persistence - pkg_hmr --> pkg_app_boot - pkg_hmr --> pkg_cmdline + pkg_config_editor --> pkg_app_boot + pkg_config_editor --> pkg_hmr pkg_experimental_speech_to_text --> pkg_settings pkg_experimental_translator --> pkg_credentials pkg_experimental_translator --> pkg_launch_environment @@ -599,8 +602,6 @@ flowchart TD pkg_api_workspace_controller --> pkg_storage_domain pkg_api_workspace_controller --> pkg_typert_protocol pkg_api_workspace_controller --> pkg_workspace - pkg_config_editor --> pkg_app_boot - pkg_config_editor --> pkg_hmr pkg_experimental_api_speech_to_text --> pkg_experimental_speech_to_text pkg_experimental_api_speech_to_text --> pkg_typert_protocol pkg_experimental_speech_to_text_sensevoice --> pkg_experimental_speech_to_text @@ -639,6 +640,10 @@ flowchart TD pkg_goal --> pkg_session_projection pkg_goal --> pkg_typert_protocol pkg_file_reference --> pkg_agent + pkg_harness_dev_context --> pkg_agent + pkg_harness_dev_context --> pkg_session + pkg_harness_dev_context --> pkg_session_projection + pkg_harness_dev_context --> pkg_system_prompt pkg_time_context --> pkg_agent pkg_time_context --> pkg_llm pkg_time_context --> pkg_session @@ -1047,7 +1052,6 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env - pkg_web_app --> pkg_system_prompt pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions pkg_experimental_auto_review --> pkg_llm @@ -1496,6 +1500,7 @@ flowchart TD | [`client-ui-reference`](../packages/client/ui-reference) | `client` | — | | [`client-ui-renderer`](../packages/client/ui-renderer) | `client` | — | | [`client-ui-schedule`](../packages/client/ui-schedule) | `client` | — | +| [`client-ui-secret-mask`](../packages/client/ui-secret-mask) | `client` | — | | [`client-ui-session`](../packages/client/ui-session) | `client` | — | | [`client-ui-settings`](../packages/client/ui-settings) | `client` | — | | [`client-ui-settings-account`](../packages/client/ui-settings-account) | `client` | — | @@ -1563,6 +1568,7 @@ flowchart TD | [`web`](../packages/web/web) | `web` | [`llm`](../packages/llm/llm) | | [`api-remotes`](../packages/api/remotes) | `api` | [`scope`](../packages/core/scope) | | [`attachment`](../packages/attachment/attachment) | `attachment` | [`brand`](../packages/util/brand) | +| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) | | [`browser-use`](../packages/browser-use/browser-use) | `browser-use` | [`brand`](../packages/util/brand) | | [`client-connection`](../packages/client/connection) | `client` | [`scope`](../packages/core/scope) | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | [`brand`](../packages/util/brand) | @@ -1584,7 +1590,7 @@ flowchart TD | [`api-gateway`](../packages/api/gateway) | `api` | [`client-connection`](../packages/client/connection) | | [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) | | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | -| [`app-boot`](../packages/boot/app-boot) | `boot` | [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`system-prompt`](../packages/core/system-prompt) | +| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-inspector`](../packages/experimental/inspector) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1605,7 +1611,7 @@ flowchart TD | [`fs`](../packages/fs/fs) | `fs` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`spill-local`](../packages/spill/spill-local) | `spill` | [`spill`](../packages/spill/spill) | | [`session-log-export`](../packages/session-query/session-log-export) | `session-query` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) | -| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | +| [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | `experimental` | [`settings`](../packages/settings/settings) | | [`experimental-translator`](../packages/experimental/translator) | `experimental` | [`credentials`](../packages/credentials/credentials), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`timeout`](../packages/util/timeout), [`util-values`](../packages/util/values) | | [`host-product-telemetry-otel`](../packages/host/product-telemetry-otel) | `host` | [`otel`](../packages/telemetry/otel) | @@ -1624,7 +1630,6 @@ flowchart TD | [`fs-observation-policy`](../packages/fs/fs-observation-policy) | `fs` | [`fs`](../packages/fs/fs) | | [`skill-filesystem`](../packages/skill/skill-filesystem) | `skill` | [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`skill`](../packages/skill/skill) | | [`api-workspace-controller`](../packages/api/workspace-controller) | `api` | [`api-gateway`](../packages/api/gateway), [`client-connection`](../packages/client/connection), [`host-directory-picker`](../packages/host/directory-picker), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol), [`workspace`](../packages/workspace/workspace) | -| [`config-editor`](../packages/boot/config-editor) | `boot` | [`app-boot`](../packages/boot/app-boot), [`hmr`](../packages/boot/hmr) | | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`typert-protocol`](../packages/typert/protocol) | | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`subprocess`](../packages/subprocess/subprocess) | | [`hook-protocol`](../packages/experimental/hook-protocol) | `experimental` | [`session`](../packages/core/session), [`shell`](../packages/shell/shell) | @@ -1636,6 +1641,7 @@ flowchart TD | [`agent-default-model`](../packages/core/agent-default-model) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm) | | [`goal`](../packages/goal/goal) | `goal` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`typert-protocol`](../packages/typert/protocol) | | [`file-reference`](../packages/context/file-reference) | `context` | [`agent`](../packages/core/agent) | +| [`harness-dev-context`](../packages/context/harness-dev-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`system-prompt`](../packages/core/system-prompt) | | [`time-context`](../packages/context/time-context) | `context` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`tmux-context`](../packages/context/tmux-context) | `context` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell) | | [`deepseek-account`](../packages/credentials/deepseek-account) | `credentials` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm) | @@ -1716,7 +1722,7 @@ flowchart TD | [`token-meter`](../packages/llm/token-meter) | `llm` | [`compaction`](../packages/compaction/compaction), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm`](../packages/llm/llm), [`llm-retry`](../packages/llm/llm-retry), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) | | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | -| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env), [`system-prompt`](../packages/core/system-prompt) | +| [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | | [`tool-cordis`](../packages/extensions/tool-cordis) | `extensions` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`cordis-host-runner`](../packages/extensions/cordis-host-runner), [`tools`](../packages/core/tools) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index dab112d89b..897241e388 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -1299,8 +1299,8 @@ en: 386989934d1bb62e zh: 69b8bc182a5acbd3 /session-persistence-event-catalog/resolved-persistence-types/string: - en: 90d3fd7202322ca4 - zh: 88cce532aed9f6d4 + en: 52f664fd6203444e + zh: dbebfaccbc666386 /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1623,8 +1623,8 @@ en: c53129cf7214286c zh: 8c5183b6dabbf714 /session-persistence-event-catalog/resolved-persistence-types/kind-ptc-mode: - en: 26b3b9239392dcc9 - zh: f4c6c0195c9119fc + en: 8de77980e11a0562 + zh: 6de199e70a666a71 /session-persistence-event-catalog/resolved-persistence-types/kind-repeat-tool-reminder: en: e3a0ef98a197374e zh: 95e9363529a62cc3 @@ -1782,8 +1782,8 @@ en: 79db83dd2c430faf zh: 173f568241f5ce86 /session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: cb5d3fbab4debac6 - zh: 72add55254356149 + en: d23abbfb20eb4fc0 + zh: 65207e79db74e2fe /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 6d4c694309..84af055163 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -5382,7 +5382,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:403`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -6747,7 +6747,7 @@ Sources: [`packages/session/session-title/src/types.ts:30`](../packages/session/ SHA-256: `dba54c09c6e7aafc9acbed7792ecc920d99f92d0784aeeed10af55f7fe0bc8cd` -Sources: [`packages/core/tools/src/ptc.ts:14`](../packages/core/tools/src/ptc.ts) +Sources: [`packages/core/tools/src/ptc.ts:15`](../packages/core/tools/src/ptc.ts) | Property | Presence | Type | |---|---|---| @@ -7341,7 +7341,7 @@ Sources: [`packages/core/tools/src/index.ts:35`](../packages/core/tools/src/inde SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7` -Sources: [`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:413`](../packages/api/session-controller/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index 92024676bd..5da8c3966f 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -5384,7 +5384,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:403`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:20`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -6749,7 +6749,7 @@ SHA-256: `b81e9de81a481b24e1e1f9adf038bfc59e57b4f35ce62f8f1e45284186f4f812` SHA-256: `dba54c09c6e7aafc9acbed7792ecc920d99f92d0784aeeed10af55f7fe0bc8cd` -来源:[`packages/core/tools/src/ptc.ts:14`](../packages/core/tools/src/ptc.ts) +来源:[`packages/core/tools/src/ptc.ts:15`](../packages/core/tools/src/ptc.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7343,7 +7343,7 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` SHA-256: `6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7` -来源:[`packages/api/session-controller/src/types.ts:408`](../packages/api/session-controller/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:413`](../packages/api/session-controller/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index e9046242ff..23d8e571e4 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -23137,7 +23137,7 @@ "packages/workflow/workflow/src/types.ts#WorkflowRunId" ], "sources": [ - "packages/api/session-controller/src/types.ts:403", + "packages/api/session-controller/src/types.ts:408", "packages/attachment/attachment/src/brand.ts:6", "packages/compaction/compaction/src/brand.ts:4", "packages/core/session/src/types.ts:20", @@ -23582,7 +23582,7 @@ "digest": "6a4f72e2e179e17b922f2a9392c0e1c8f8c707f32494372454850a3eb184a6e7", "names": [], "sources": [ - "packages/api/session-controller/src/types.ts:408" + "packages/api/session-controller/src/types.ts:413" ] }, { @@ -25173,7 +25173,7 @@ "digest": "dba54c09c6e7aafc9acbed7792ecc920d99f92d0784aeeed10af55f7fe0bc8cd", "names": [], "sources": [ - "packages/core/tools/src/ptc.ts:14" + "packages/core/tools/src/ptc.ts:15" ] }, { diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index c6c02c6c42..42f6d2e24a 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -557,7 +557,9 @@ serviceFor(agent: { ctx: Context }, name: K): */ async recompose(ctx: Context, id: string): Promise -/** Select a preset before a session starts its first turn. +/** Select a preset before a session starts its first turn. A Session whose + * log records the preset and whose Agent runs its current revision keeps its + * composition; nothing is logged or announced. * @param agent Target Agent. * @param agentPreset Requested identity. * @returns Committed preset identity. diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index beb65f2c60..9714c7c62f 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -569,7 +569,9 @@ serviceFor(agent: { ctx: Context }, name: K): */ async recompose(ctx: Context, id: string): Promise -/** Select a preset before a session starts its first turn. +/** Select a preset before a session starts its first turn. A Session whose + * log records the preset and whose Agent runs its current revision keeps its + * composition; nothing is logged or announced. * @param agent Target Agent. * @param agentPreset Requested identity. * @returns Committed preset identity. diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index e4031e772d..7c6f634157 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -6,8 +6,8 @@ en: 337a6580d7571274 zh: f4ae98899120d122 /ptc-runtime/the-run-request-in-result-out: - en: b11e176bee0ca6bd - zh: 843d5d70c58dec42 + en: 0305ed1d4f8bc618 + zh: fcfeb156574b5779 /ptc-runtime/bindings-host-functions-as-program-globals: en: 182147ddf388c600 zh: c0a7d77602c78bcd diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index c0bf80b405..d9ad8138a0 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -18,11 +18,18 @@ Source: [`packages/ptc-runtime/ptc-runtime/src/types.ts`](../../packages/ptc-run interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It - * runs as the body of an async function: top-level `await` and `return` - * are available, and the completion value becomes + * follows the provider's programFormat: an async function body supports + * top-level `await` and `return`; a REPL supports top-level declarations, + * `await`, and a final expression. The completion value becomes * {@link PtcRunResult.value}. */ program: string + /** + * Object-identity owner for optional in-memory state. Omission requests a fresh + * environment. Consumers must await runtime.release(owner) when the owner ends. + * Stateless providers ignore this field; retained state is never durable. + */ + stateOwner?: object /** Host functions exposed to the program, one global object per namespace. */ bindings: PtcBindingNamespace[] /** Working directory in the mounted filesystem and subprocess execution world. */ @@ -77,7 +84,7 @@ interface PtcRunResult { /** Applied file policy and observed denial, when the provider enforces file policy. */ sandbox?: PtcRunSandbox /** - * The program's completion value (its top-level `return`), when it ran to + * The program's completion value (a return or final REPL expression), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. * Invalid or over-limit completions fail the run instead of substituting a * rendered string; a failed or value-less run leaves this absent. @@ -94,6 +101,8 @@ interface PtcRunResult { } ``` +`programFormat` distinguishes async function bodies from REPL statements. `stateOwner` is an in-process object identity for optional retained memory; distinct objects remain isolated. Consumers await `release(owner)` when that owner ends; cleanup failures reject that call. Omitted owners are one-shot, and stateless providers ignore ownership. The [persistent Node provider](../../packages/ptc-runtime/ptc-runtime-node/README.md#persistent-repl) defines reset and recovery behavior; no retained object enters the durable Session format. + ## Bindings: host functions as program globals Each `PtcBindingNamespace` becomes a global object of async callables; PTC passes `tools`. Arguments and resolutions must be lossless JSON. Providers enforce their own transport caps; the seam sets no uniform binding-byte limit. An optional error-class descriptor creates program-visible typed rejections without naming a consumer inside the runtime. Binding names are own properties, so `__proto__` cannot traverse a prototype: @@ -209,9 +218,18 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam) -Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal. +Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal. ```ts cordis-catalog +/** + * Release an owner's retained environment and await its execution resources. + * Stateless providers have no retained resources to release. + * @param owner - The exact object supplied as the request's state owner. + * @returns Completion after all owned execution resources have been released. + * @throws When managed resource cleanup fails. + */ +release(owner: object): Promise + /** * Resolve supported options and provider defaults before execution. * @param request - Program, bindings, cancellation and optional execution choices. diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index 3896ffc61d..ba747b5369 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -18,11 +18,18 @@ PTC 执行[能力 seam](../../.agents/notes/implemented/architecture/2026-06-13- interface PtcRunRequest { /** * The program source, in the runtime's {@link ../index.ts | language}. It - * runs as the body of an async function: top-level `await` and `return` - * are available, and the completion value becomes + * follows the provider's programFormat: an async function body supports + * top-level `await` and `return`; a REPL supports top-level declarations, + * `await`, and a final expression. The completion value becomes * {@link PtcRunResult.value}. */ program: string + /** + * Object-identity owner for optional in-memory state. Omission requests a fresh + * environment. Consumers must await runtime.release(owner) when the owner ends. + * Stateless providers ignore this field; retained state is never durable. + */ + stateOwner?: object /** Host functions exposed to the program, one global object per namespace. */ bindings: PtcBindingNamespace[] /** Working directory in the mounted filesystem and subprocess execution world. */ @@ -77,7 +84,7 @@ interface PtcRunResult { /** Applied file policy and observed denial, when the provider enforces file policy. */ sandbox?: PtcRunSandbox /** - * The program's completion value (its top-level `return`), when it ran to + * The program's completion value (a return or final REPL expression), when it ran to * completion and the value crossed the runtime's lossless-JSON boundary. * Invalid or over-limit completions fail the run instead of substituting a * rendered string; a failed or value-less run leaves this absent. @@ -94,6 +101,8 @@ interface PtcRunResult { } ``` +`programFormat` 区分异步函数体与 REPL 语句。`stateOwner` 是标识可选保留内存的进程内对象身份;不同对象相互隔离。消费者在所有者结束时等待 `release(owner)`;清理失败时该调用拒绝。省略所有者时仅执行一次,无状态提供方忽略所有权。[持久 Node 提供方](../../packages/ptc-runtime/ptc-runtime-node/README.zh.md#persistent-repl)定义重置和恢复行为;保留对象不会进入持久 Session 格式。 + ## 绑定:宿主函数作为程序全局变量 每个 `PtcBindingNamespace` 成为一个异步可调用函数的全局对象;PTC 传入 `tools`。参数与返回值必须是无损 JSON。提供方强制各自的传输上限;seam 不设统一的绑定字节上限。可选错误类描述符创建程序可见的类型化拒绝,无需在运行时内点名消费方。绑定名是自有属性,因此 `__proto__` 不能遍历原型: @@ -209,9 +218,18 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.ptcRuntime` — `PtcRuntime` (abstract seam) -Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate runs from one another, and terminate and await in-flight runs during disposal. +Registers one `ctx.ptcRuntime` implementation. Program, budget, abort, and substrate failures resolve in PtcRunResult; only Service Definition contract misuse rejects. Implementations bridge structured-cloneable bindings, materialize each declared namespace rejection class, treat programs as hostile peers, isolate distinct state owners, and terminate and await in-flight runs during disposal. ```ts cordis-catalog +/** + * Release an owner's retained environment and await its execution resources. + * Stateless providers have no retained resources to release. + * @param owner - The exact object supplied as the request's state owner. + * @returns Completion after all owned execution resources have been released. + * @throws When managed resource cleanup fails. + */ +release(owner: object): Promise + /** * Resolve supported options and provider defaults before execution. * @param request - Program, bindings, cancellation and optional execution choices. diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md index 24d4833a81..bb40e7f93f 100644 --- a/docs/subsystems/session.md +++ b/docs/subsystems/session.md @@ -856,9 +856,9 @@ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise /** - * Create or idempotently adopt one ordinary Session. - * @param request - requested identity, location, and Agent preset. - * @returns the Session identity and resolved preset when configured. + * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable. + * @param request - optional blank Session to reuse, location, and Agent preset. + * @returns the created or reused Session identity and its preset when configured. */ @Remote('create') create(request: SessionCreateRequest): Promise diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index d214c4b471..298b704bde 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -860,9 +860,9 @@ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise /** - * Create or idempotently adopt one ordinary Session. - * @param request - requested identity, location, and Agent preset. - * @returns the Session identity and resolved preset when configured. + * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable. + * @param request - optional blank Session to reuse, location, and Agent preset. + * @returns the created or reused Session identity and its preset when configured. */ @Remote('create') create(request: SessionCreateRequest): Promise diff --git a/docs/subsystems/sidebar-right.i18n.yaml b/docs/subsystems/sidebar-right.i18n.yaml index 385b99e972..83cd761e68 100644 --- a/docs/subsystems/sidebar-right.i18n.yaml +++ b/docs/subsystems/sidebar-right.i18n.yaml @@ -12,8 +12,8 @@ en: 465f0c330fc1054b zh: bd0b68a05790fff8 /right-sidebar/tab-type-registration: - en: 1e01c817c5879c40 - zh: a79abd92ee4c8f85 + en: b7b8a7b411aee94d + zh: 7298c20000945d97 /right-sidebar/navigation-ctx-sidebarright: en: 0f80b5364cbad804 zh: db81652a5374fad1 diff --git a/docs/subsystems/sidebar-right.md b/docs/subsystems/sidebar-right.md index 6315827c27..1342a7f938 100644 --- a/docs/subsystems/sidebar-right.md +++ b/docs/subsystems/sidebar-right.md @@ -46,6 +46,8 @@ Tab identity is the pair `(kind, address)`: the registry's claim uses the addres | `keepMounted` | Optional lazy retention of visited bodies across hiding, Session switches and docking; the owning View holds the Session reference. | | `guide` | Optional entry boxes for the guide page: `{ order, title(), description?(), icon? }`. Picking a box opens the contributing type as a page; omit to stay off the page. | +Whole-address patterns match the raw address: picomatch globstar (`**`) excludes standalone `.` and `..` segments even with `dot: true`, which includes dotfiles but does not change that exclusion. Resource-specific code parses addresses; the Host enforces file-read permissions. + Routing is a ranked claim. `candidates(address)` ranks the types whose patterns match and whose `canOpen` does not veto: by band, then by the length of the longest matched pattern, then by registration order. `claim(address, kind?)` picks the first candidate, or the named `kind` outright — its globs are skipped, its `canOpen` still applies — and returns `{ kind, contentId: address, title }`. An address no type claims throws: it is a wiring mistake, not a user error. One `kind` may carry one `builtin` and one `extension` registration at the same time. The extension is the one in force for claims, `get(kind)`, `openTab(kind)`, and the guide page, and the seat finds a tab's body and title under the definition in force's `id`, so no slot priority is involved; when the extension unregisters, the builtin resumes. Every other collision on a kind, and every duplicate `id`, throws. diff --git a/docs/subsystems/sidebar-right.zh.md b/docs/subsystems/sidebar-right.zh.md index 1df6007e12..e7df97d11c 100644 --- a/docs/subsystems/sidebar-right.zh.md +++ b/docs/subsystems/sidebar-right.zh.md @@ -46,6 +46,8 @@ tab 身份是 `(kind, address)` 二元组:注册表的认领把地址原文用 | `keepMounted` | 可选的懒保活:已访问正文跨隐藏、Session 切换与停靠切换保留,由所属 View 持有 Session reference。 | | `guide` | 可选的引导页入口框:`{ order, title(), description?(), icon? }`。点一框即把贡献它的类型作为页面打开;省略即不上引导页。 | +完整地址模式匹配地址原文:picomatch 的 globstar(`**`)即使启用 `dot: true` 也排除独立的 `.` 和 `..` 段;该选项允许匹配 dotfile,不改变点段排除规则。地址由资源业务代码解析,文件读取仍受 Host 文件系统权限限制。 + 路由是一次排序认领。`candidates(address)` 对模式命中且未被 `canOpen` 否决的类型排序:先按档,再按最长命中模式的长度,最后按注册顺序。`claim(address, kind?)` 取第一个候选,或直接用点名的 `kind`——跳过它的 glob,但 `canOpen` 仍生效——返回 `{ kind, contentId: address, title }`。没有任何类型认领的地址会抛错:这是接线错误,不是用户错误。 同一个 `kind` 可同时携带一个 `builtin` 与一个 `extension` 注册。extension 在认领、`get(kind)`、`openTab(kind)` 与引导页上生效,席位按生效定义的 `id` 找 tab 的正文与标题,不涉及任何 slot 优先级;extension 注销后 builtin 恢复。kind 上的其它任何撞名以及任何重复的 `id` 都抛错。 diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index 9aa254ff44..1dd04a5ab9 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -18,11 +18,11 @@ en: 2fcfc55fbac80f72 zh: ea3016f394c56b07 /web-client-slots/developer-provided-injection: - en: 4fb5222bb2b064e7 - zh: b961f792052b4ce5 -/web-client-slots/current-hierarchy: - en: 8a4cc4b8608ce0f6 - zh: 7dcc51b213782a40 + en: 3481dfa6cd3097da + zh: acbd6f06a7da1752 +/web-client-slots/conversation-hierarchy: + en: e1d572c42e91d663 + zh: 5a649dea2682be7f /web-client-slots/extension-rules: en: b2cce357141883ee zh: 278080a5fb941189 diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index c0fa352a4f..30f8acedb4 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -108,92 +108,84 @@ The owner of a slot may put an `inject` face in the child declaration when every Use owner props for values already known at one render occurrence, registration `inject` for one entry's callbacks and private observables, slot-level `inject` for a capability controlled by the slot owner, and a declared store for mutable view state shared across entries or preserved across remounts. React nodes compose through child slots, not through injected values. -## Current hierarchy + -The hierarchy below is the shipped declaration tree. A child exists only while the named parent entry is mounted; optional feature entries can therefore make a subtree appear or disappear as one lifecycle unit. +## Conversation hierarchy + +The following Conversation paths distinguish declaration owners from reusable Factory roots; unrelated shell positions are omitted. An entry owns its declared children, while a Factory owns its child declarations for the lifetime of its registered definition. Bracketed names identify the default React components; a plain React descendant can render its owner's Slot. Factory calls are references to independent reusable definitions, not new Slot declarations. ```text -root -├─ sidebar -│ ├─ sidebar.brand.mark -│ ├─ sidebar.brand.name -│ ├─ sidebar.panellist -│ ├─ sidebar.footer.action -│ ├─ sidebar.workspaces -│ │ ├─ sidebar.workspaces.directoryFlow -│ │ ├─ sidebar.workspaces.session.menu.item -│ │ └─ sidebar.workspaces.session.row.action -│ └─ sidebar.settings -│ ├─ settings.trigger -│ ├─ settings.header -│ ├─ settings.action -│ ├─ settings.close -│ ├─ settings.onboarding -│ └─ settings.section -│ ├─ settings.general.item -│ ├─ settings.models.provider-card -│ ├─ settings.models.footer -│ └─ settings.plugins.tab -├─ main -│ ├─ plugins.add.actions -│ ├─ plugins.item -│ ├─ plugins.bundle.config -│ ├─ plugins.row.config -│ ├─ plugins.detail.actions -│ ├─ plugins.detail.badge -│ ├─ plugins.detail.section -│ └─ main.conversation -│ ├─ conversation.session -│ │ └─ conversation.view -│ │ ├─ conversation.chat.flow -│ │ │ ├─ conversation.chat.node -│ │ │ │ ├─ conversation.chat.assistant-actions -│ │ │ │ ├─ conversation.chat.reasoning.body -│ │ │ │ ├─ conversation.chat.commandview -│ │ │ │ ├─ conversation.chat.turnTail -│ │ │ │ └─ tool.call.toolview -│ │ │ │ ├─ tool.call.images -│ │ │ │ └─ tool.view.cordis -│ │ │ └─ conversation.message.images -│ │ └─ conversation.trajectory.images -│ ├─ conversation.header -│ │ ├─ conversation.header.leading -│ │ └─ conversation.session.header -│ │ ├─ conversation.session.header.lineage -│ │ ├─ conversation.session.header.actions -│ │ ├─ conversation.session.header.utilities -│ │ └─ conversation.session.header.corner -│ ├─ conversation.composer -│ │ ├─ conversation.approval.detail -│ │ └─ conversation.plan-review.actions -│ ├─ conversation.composer.bar -│ │ ├─ conversation.input.attachments -│ │ ├─ conversation.input.permission -│ │ ├─ conversation.input.plan -│ │ └─ conversation.input.model -│ ├─ conversation.input.overlay -│ ├─ conversation.input.dock -│ ├─ conversation.composer.dock -│ ├─ conversation.input.left -│ ├─ conversation.input.right -│ ├─ conversation.hero.brand.mark -│ ├─ conversation.hero.workspace -│ │ └─ conversation.hero.workspace.directoryFlow -│ └─ conversation.hero.agentPreset -├─ rightbar -│ └─ rightbar.session -│ ├─ sidebar.right.pane.tab -│ │ ├─ sidebar.right.tab.guide -│ │ └─ sidebar.right.tab.guide.entry -│ ├─ sidebar.right.pane.tab.title -│ └─ sidebar.right.tab.menu.item -├─ shell.bottom -├─ shell.leading -└─ shell.overlay - └─ shell.quota-notice +root [AppFrame] +└─ main[key=conversation] [ConversationPanel] + └─ main.conversation [ConversationRoot / ConversationMainPanel] + ├─ conversation.header [ConversationHeader] + │ ├─ conversation.header.leading + │ └─ conversation.session.header [ConversationSessionHeader] + │ ├─ conversation.session.header.lineage + │ ├─ conversation.session.header.actions + │ ├─ conversation.session.header.utilities + │ └─ conversation.session.header.corner + └─ calls Factory: conversation.content + +Factory: conversation.content [ConversationContent] +├─ conversation.session [ConversationSession / DefaultConversationViews] +│ └─ conversation.view +│ ├─ id=chat [ChatView] +│ │ └─ conversation.chat.flow [ChatFlow] +│ │ └─ conversation.chat.node [ChatNodeSeat dispatch] +│ │ ├─ key=user,steering [UserMessageNodeView] +│ │ │ └─ calls Factory: conversation.chat.user.content +│ │ ├─ key=assistant-step [AssistantNodeView / AssistantMarkdown] +│ │ │ ├─ conversation.chat.message.images [MessageImages] +│ │ │ └─ conversation.chat.reasoning.body [DefaultReasoningBody] +│ │ │ └─ calls Factory: conversation.chat.reasoning.content +│ │ ├─ key=tool-call [ToolCallTree] +│ │ │ └─ tool.call.toolview +│ │ │ └─ key=read_image [ReadImageRow / ToolRow] +│ │ │ └─ tool.call.images [MessageImages] +│ │ ├─ key=command-input [GoalCommandInputView] +│ │ │ └─ calls Factory: conversation.user.text +│ │ ├─ key=command [CommandNodeView] +│ │ │ └─ conversation.chat.commandview +│ │ └─ key=turn-tail [TurnTailNodeView] +│ │ ├─ conversation.chat.turnTail +│ │ └─ conversation.chat.assistant-actions +│ └─ id=trajectory [TrajectoryView / TrajectoryTable] +│ └─ conversation.trajectory.images [MessageImages] +├─ conversation.composer +│ ├─ conversation.approval.detail +│ └─ conversation.plan-review.actions +├─ conversation.composer.bar [InputBar] +│ ├─ conversation.input.attachments +│ ├─ conversation.input.permission +│ ├─ conversation.input.plan +│ ├─ conversation.input.model +│ ├─ conversation.input.overlay +│ ├─ conversation.composer.dock +│ ├─ conversation.input.left +│ └─ conversation.input.right +├─ conversation.input.dock +│ └─ id=queue [QueueDock] +│ └─ calls Factory: conversation.user.text +├─ conversation.hero.brand.mark +├─ conversation.hero.workspace +│ └─ conversation.hero.workspace.directoryFlow +└─ conversation.hero.agentPreset + +Factory: conversation.chat.user.content [UserContent] +├─ conversation.chat.user.images [MessageImages] +└─ calls Factory: conversation.user.text + +Factory: conversation.user.text [UserText] +└─ conversation.user.text.node [keyed, inline] + +Factory: conversation.images.content [MessageImagesContent / ImageGallery] +Factory: conversation.chat.reasoning.content [ReasoningContent / MarkdownText] ``` -The generated Client inspect catalog is the exhaustive contract for each key: cardinality, scope, owner props, standard props, current occupants, declaration owner, and replacement risk. A running dynamic package can query the live tree and an exact key with `cordis_inspect what:"client"`; the source catalog is generated from `SlotMap` declarations and `slots.register()` call sites by `pnpm run gen-client-catalog`. +All four image Slots default to `MessageImages`, which calls `conversation.images.content` with the caller's image references and authorized loader. User and output image replacements are independent. The `conversation.user.text` Factory is shared by user content, Queue, and Goal; its `inline: true` keyed Slot renders span anchors and inline error placeholders rather than block wrappers. + +The generated [Client inspect catalog](../../packages/extensions/cordis-client-runner/src/client/slot-catalog.ts) covers all shell branches and is the exhaustive contract for each key: cardinality, scope, owner props, standard props, current occupants, declaration owner, and replacement risk. A running dynamic package can query the live tree and an exact key with `cordis_inspect what:"client"`; the source catalog is generated from `SlotMap` declarations and `slots.register()` call sites by `pnpm run gen-client-catalog`. ## Extension rules diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index d51825c579..a660f720e4 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -110,92 +110,84 @@ Renderer 还会根据声明的 store 创建 `useStore`,并根据声明的 loca 一次渲染时 owner 已知的值走 owner props;单个 entry 的 callback 与私有 observable 走注册项 `inject`;由 slot owner 控制、所有 occupant 共享的能力走 slot 级 `inject`;需要跨 entry 共享或跨重新挂载保留的可变视图状态走声明的 store。React node 通过 child slot 组合,不通过注入值传递。 -## 当前层级 + -下图是当前发布组合的声明树。只有具名 parent entry 已挂载时,其 child 才存在;因此可选功能 entry 可以作为一个生命周期单元让整棵子树出现或消失。 +## Conversation 层级 + +下面的 Conversation 路径区分声明所有者与可复用 Factory 根,省略无关的外壳位置。条目拥有其声明的子 Slot;Factory 在其定义注册期间拥有子 Slot 声明。方括号标出默认 React 组件,普通 React 后代组件可以渲染其所有者的 Slot。Factory 调用指向独立的可复用定义,不是新的 Slot 声明。 ```text -root -├─ sidebar -│ ├─ sidebar.brand.mark -│ ├─ sidebar.brand.name -│ ├─ sidebar.panellist -│ ├─ sidebar.footer.action -│ ├─ sidebar.workspaces -│ │ ├─ sidebar.workspaces.directoryFlow -│ │ ├─ sidebar.workspaces.session.menu.item -│ │ └─ sidebar.workspaces.session.row.action -│ └─ sidebar.settings -│ ├─ settings.trigger -│ ├─ settings.header -│ ├─ settings.action -│ ├─ settings.close -│ ├─ settings.onboarding -│ └─ settings.section -│ ├─ settings.general.item -│ ├─ settings.models.provider-card -│ ├─ settings.models.footer -│ └─ settings.plugins.tab -├─ main -│ ├─ plugins.add.actions -│ ├─ plugins.item -│ ├─ plugins.bundle.config -│ ├─ plugins.row.config -│ ├─ plugins.detail.actions -│ ├─ plugins.detail.badge -│ ├─ plugins.detail.section -│ └─ main.conversation -│ ├─ conversation.session -│ │ └─ conversation.view -│ │ ├─ conversation.chat.flow -│ │ │ ├─ conversation.chat.node -│ │ │ │ ├─ conversation.chat.assistant-actions -│ │ │ │ ├─ conversation.chat.reasoning.body -│ │ │ │ ├─ conversation.chat.commandview -│ │ │ │ ├─ conversation.chat.turnTail -│ │ │ │ └─ tool.call.toolview -│ │ │ │ ├─ tool.call.images -│ │ │ │ └─ tool.view.cordis -│ │ │ └─ conversation.message.images -│ │ └─ conversation.trajectory.images -│ ├─ conversation.header -│ │ ├─ conversation.header.leading -│ │ └─ conversation.session.header -│ │ ├─ conversation.session.header.lineage -│ │ ├─ conversation.session.header.actions -│ │ ├─ conversation.session.header.utilities -│ │ └─ conversation.session.header.corner -│ ├─ conversation.composer -│ │ ├─ conversation.approval.detail -│ │ └─ conversation.plan-review.actions -│ ├─ conversation.composer.bar -│ │ ├─ conversation.input.attachments -│ │ ├─ conversation.input.permission -│ │ ├─ conversation.input.plan -│ │ └─ conversation.input.model -│ ├─ conversation.input.overlay -│ ├─ conversation.input.dock -│ ├─ conversation.composer.dock -│ ├─ conversation.input.left -│ ├─ conversation.input.right -│ ├─ conversation.hero.brand.mark -│ ├─ conversation.hero.workspace -│ │ └─ conversation.hero.workspace.directoryFlow -│ └─ conversation.hero.agentPreset -├─ rightbar -│ └─ rightbar.session -│ ├─ sidebar.right.pane.tab -│ │ ├─ sidebar.right.tab.guide -│ │ └─ sidebar.right.tab.guide.entry -│ ├─ sidebar.right.pane.tab.title -│ └─ sidebar.right.tab.menu.item -├─ shell.bottom -├─ shell.leading -└─ shell.overlay - └─ shell.quota-notice +root [AppFrame] +└─ main[key=conversation] [ConversationPanel] + └─ main.conversation [ConversationRoot / ConversationMainPanel] + ├─ conversation.header [ConversationHeader] + │ ├─ conversation.header.leading + │ └─ conversation.session.header [ConversationSessionHeader] + │ ├─ conversation.session.header.lineage + │ ├─ conversation.session.header.actions + │ ├─ conversation.session.header.utilities + │ └─ conversation.session.header.corner + └─ calls Factory: conversation.content + +Factory: conversation.content [ConversationContent] +├─ conversation.session [ConversationSession / DefaultConversationViews] +│ └─ conversation.view +│ ├─ id=chat [ChatView] +│ │ └─ conversation.chat.flow [ChatFlow] +│ │ └─ conversation.chat.node [ChatNodeSeat dispatch] +│ │ ├─ key=user,steering [UserMessageNodeView] +│ │ │ └─ calls Factory: conversation.chat.user.content +│ │ ├─ key=assistant-step [AssistantNodeView / AssistantMarkdown] +│ │ │ ├─ conversation.chat.message.images [MessageImages] +│ │ │ └─ conversation.chat.reasoning.body [DefaultReasoningBody] +│ │ │ └─ calls Factory: conversation.chat.reasoning.content +│ │ ├─ key=tool-call [ToolCallTree] +│ │ │ └─ tool.call.toolview +│ │ │ └─ key=read_image [ReadImageRow / ToolRow] +│ │ │ └─ tool.call.images [MessageImages] +│ │ ├─ key=command-input [GoalCommandInputView] +│ │ │ └─ calls Factory: conversation.user.text +│ │ ├─ key=command [CommandNodeView] +│ │ │ └─ conversation.chat.commandview +│ │ └─ key=turn-tail [TurnTailNodeView] +│ │ ├─ conversation.chat.turnTail +│ │ └─ conversation.chat.assistant-actions +│ └─ id=trajectory [TrajectoryView / TrajectoryTable] +│ └─ conversation.trajectory.images [MessageImages] +├─ conversation.composer +│ ├─ conversation.approval.detail +│ └─ conversation.plan-review.actions +├─ conversation.composer.bar [InputBar] +│ ├─ conversation.input.attachments +│ ├─ conversation.input.permission +│ ├─ conversation.input.plan +│ ├─ conversation.input.model +│ ├─ conversation.input.overlay +│ ├─ conversation.composer.dock +│ ├─ conversation.input.left +│ └─ conversation.input.right +├─ conversation.input.dock +│ └─ id=queue [QueueDock] +│ └─ calls Factory: conversation.user.text +├─ conversation.hero.brand.mark +├─ conversation.hero.workspace +│ └─ conversation.hero.workspace.directoryFlow +└─ conversation.hero.agentPreset + +Factory: conversation.chat.user.content [UserContent] +├─ conversation.chat.user.images [MessageImages] +└─ calls Factory: conversation.user.text + +Factory: conversation.user.text [UserText] +└─ conversation.user.text.node [keyed, inline] + +Factory: conversation.images.content [MessageImagesContent / ImageGallery] +Factory: conversation.chat.reasoning.content [ReasoningContent / MarkdownText] ``` -生成的 Client inspect catalog 是每个 key 的完整参考,包含 cardinality、scope、owner props、标准 props、当前 occupant、声明 owner 与替换风险。运行中的动态包可以用 `cordis_inspect what:"client"` 查询实时树与某个精确 key;源码 catalog 由 `pnpm run gen-client-catalog` 根据 `SlotMap` 声明和 `slots.register()` 调用点生成。 +四个图片 Slot 默认均填入 `MessageImages`,由它携带调用者的图片引用和授权 loader 调用 `conversation.images.content`。用户与输出图片的替换互不影响。`conversation.user.text` Factory 由用户内容、Queue 和 Goal 共用;其 `inline: true` keyed Slot 使用 span 锚点及行内错误占位,而不是块级包装。 + +生成的 [Client inspect catalog](../../packages/extensions/cordis-client-runner/src/client/slot-catalog.ts) 是包含所有外壳分支及每个 key 的完整参考,包含 cardinality、scope、owner props、标准 props、当前 occupant、声明 owner 与替换风险。运行中的动态包可以用 `cordis_inspect what:"client"` 查询实时树与某个精确 key;源码 catalog 由 `pnpm run gen-client-catalog` 根据 `SlotMap` 声明和 `slots.register()` 调用点生成。 diff --git a/docs/subsystems/web-server.md b/docs/subsystems/web-server.md index 5150ddd01f..4fcb42f3cc 100644 --- a/docs/subsystems/web-server.md +++ b/docs/subsystems/web-server.md @@ -143,6 +143,22 @@ authenticatedUrl(baseUrl: string): string Source: [`packages/client/connection/src/rpc.ts`](../../packages/client/connection/src/rpc.ts) + + +### `ctx.webApp` — `WebApp` + +The Web GUI this process serves, provided by the `web-runtime` row. + +```ts cordis-catalog +/** + * The URL this GUI advertises, also used for `DSH_WEB_URL` and the startup URL line. + * @returns the configured `publicUrl`, otherwise the listener origin. + */ +getAdvertisedUrl(): string +``` + +Source: [`packages/bundle/web-app/src/index.ts`](../../packages/bundle/web-app/src/index.ts) + ### `ctx.webServer` — `WebServer` @@ -150,6 +166,14 @@ Source: [`packages/client/connection/src/rpc.ts`](../../packages/client/connecti The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and the fallback handler answers anything not yet claimed during startup with 404 until its owner registers. ```ts cordis-catalog +/** + * The root URL local clients use to reach the bound listener: the protocol, + * the {@link bindUrlHost} form of the bind address, and the listening port. + * @returns the origin, for example `http://127.0.0.1:3080`. + * @throws before `listen` binds a port, or when the bind address has no URL form. + */ +getOrigin(): string + /** * Register a named route. Duplicate (kind, path) throws — route patterns are * a composition-level contract, so a collision is a misconfiguration. diff --git a/docs/subsystems/web-server.zh.md b/docs/subsystems/web-server.zh.md index f91bfdcdbd..67d67b15de 100644 --- a/docs/subsystems/web-server.zh.md +++ b/docs/subsystems/web-server.zh.md @@ -143,6 +143,22 @@ authenticatedUrl(baseUrl: string): string Source: [`packages/client/connection/src/rpc.ts`](../../packages/client/connection/src/rpc.ts) + + +### `ctx.webApp` — `WebApp` + +The Web GUI this process serves, provided by the `web-runtime` row. + +```ts cordis-catalog +/** + * The URL this GUI advertises, also used for `DSH_WEB_URL` and the startup URL line. + * @returns the configured `publicUrl`, otherwise the listener origin. + */ +getAdvertisedUrl(): string +``` + +Source: [`packages/bundle/web-app/src/index.ts`](../../packages/bundle/web-app/src/index.ts) + ### `ctx.webServer` — `WebServer` @@ -150,6 +166,14 @@ Source: [`packages/client/connection/src/rpc.ts`](../../packages/client/connecti The browser HTTP carrier service. Activation loads any configured TLS material, then listens immediately; a material or listen failure rejects initialization, and the boot process reports the failed fiber. Route registration order does not affect requests because configured named routes must be distinct, and the fallback handler answers anything not yet claimed during startup with 404 until its owner registers. ```ts cordis-catalog +/** + * The root URL local clients use to reach the bound listener: the protocol, + * the {@link bindUrlHost} form of the bind address, and the listening port. + * @returns the origin, for example `http://127.0.0.1:3080`. + * @throws before `listen` binds a port, or when the bind address has no URL form. + */ +getOrigin(): string + /** * Register a named route. Duplicate (kind, path) throws — route patterns are * a composition-level contract, so a collision is a misconfiguration. diff --git a/docs/subsystems/workspace.i18n.yaml b/docs/subsystems/workspace.i18n.yaml index 7701312154..bf01196282 100644 --- a/docs/subsystems/workspace.i18n.yaml +++ b/docs/subsystems/workspace.i18n.yaml @@ -9,8 +9,8 @@ en: d61a7e78bbc1fb56 zh: 8397869f70cd5b28 /workspaces/the-workspace-entity: - en: 697698bc46adc477 - zh: 73d073933ed68c53 + en: ce5b65fb4d0b0c7b + zh: aa332a17810d583a /workspaces/the-registry-ctx-workspaceregistry: en: 73b54ccf836b7f46 zh: 7ee93ba8bb0a616a diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index e501d7b7bb..8e69b7c597 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -25,9 +25,10 @@ Consumers see only the `Workspace` interface; the implementation stays package-p ```ts type-equiv /** * One workspace: a stable id over an existing directory, a display title, and - * 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. + * an ordered candidate account of sessions. Membership validates header cwd + * against the workspace path, but preserves an existing account when its + * fully qualified cwd is missing. Consumers only see this interface; the + * implementation stays private. */ interface Workspace { /** Stable record id (generated uuid). */ @@ -54,8 +55,11 @@ interface Workspace { * 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. + * and canonical cwd mismatches are never returned. A fully qualified cwd + * whose realpath or directory stat fails with ENOENT preserves an existing + * candidate, including a dangling symlink; other filesystem failures do not. + * A subsequent mutation prunes filtered candidates, not missing-directory + * candidates. This does not admit new sessions or recreate directories. */ readonly sessionIds: readonly SessionId[] @@ -113,7 +117,7 @@ interface Workspace { } ``` -Ownership truth is the record's ordered `sessionIds`, never derived from session cwd — but membership requires both: an id on the account and a header whose canonical cwd equals the workspace path, so one session structurally belongs to at most one workspace. Failed writes reject (`insertSessionBefore` account errors as `WorkspaceMoveInvalidError`, storage failures as plain errors); every accepted mutation stamps `updatedAt` and durably prunes candidates that no longer pass the membership check. +Ownership truth is the record's ordered `sessionIds`, never derived from session cwd. Membership validates the recorded header cwd against the workspace path; an existing candidate remains owned when its fully qualified cwd fails resolution or directory stat with `ENOENT`. This preserves missing-directory and dangling-symlink accounts without admitting new sessions. Failed writes reject (`insertSessionBefore` account errors as `WorkspaceMoveInvalidError`, storage failures as plain errors); every accepted mutation stamps `updatedAt` and durably prunes candidates that no longer pass the membership check. ## The registry: `ctx.workspaceRegistry` diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index 868712b4c9..4c15fc2ffd 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -25,9 +25,10 @@ type WorkspaceId = Branded<'WorkspaceId'> ```ts type-equiv /** * One workspace: a stable id over an existing directory, a display title, and - * 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. + * an ordered candidate account of sessions. Membership validates header cwd + * against the workspace path, but preserves an existing account when its + * fully qualified cwd is missing. Consumers only see this interface; the + * implementation stays private. */ interface Workspace { /** Stable record id (generated uuid). */ @@ -54,8 +55,11 @@ interface Workspace { * 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. + * and canonical cwd mismatches are never returned. A fully qualified cwd + * whose realpath or directory stat fails with ENOENT preserves an existing + * candidate, including a dangling symlink; other filesystem failures do not. + * A subsequent mutation prunes filtered candidates, not missing-directory + * candidates. This does not admit new sessions or recreate directories. */ readonly sessionIds: readonly SessionId[] @@ -113,7 +117,7 @@ interface Workspace { } ``` -所有权的真源是记录中有序的 `sessionIds`,绝不从会话 cwd 派生——但成员资格要求两者同时成立:账本上有其 id,且 header 的规范 cwd 等于工作区路径,因此一个会话在结构上至多属于一个工作区。失败的写入会拒绝(`insertSessionBefore` 的账本错误以 `WorkspaceMoveInvalidError` 拒绝,存储失败以普通错误拒绝);每次被接受的变更都盖上 `updatedAt` 时间戳,并持久修剪不再通过成员资格检查的候选项。 +所有权的真源是记录中有序的 `sessionIds`,绝不从会话 cwd 派生。成员资格将记录的 header cwd 与工作区路径校验;已有候选的完全限定 cwd 在路径解析或目录 stat 时返回 `ENOENT`,仍保留其归属。这会保留目录缺失或符号链接失效时的记账关系,但不会接纳新会话。失败的写入会拒绝(`insertSessionBefore` 的账本错误以 `WorkspaceMoveInvalidError` 拒绝,存储失败以普通错误拒绝);每次被接受的变更都盖上 `updatedAt` 时间戳,并持久修剪不再通过成员资格检查的候选项。 ## 注册表:`ctx.workspaceRegistry` diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index 2ab2f56624..639b01a6e4 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -60,8 +60,8 @@ en: 76fbbf0fe38aef10 zh: 76fbbf0fe38aef10 /tool-schema-catalog/deepseek-ai-dsh-tools/run-code: - en: 2cfa8042a920b191 - zh: bbd0aae394fb3806 + en: d03bca78d96757a7 + zh: 0e7cd389c38e2d9f /tool-schema-catalog/deepseek-ai-dsh-plan-mode: en: b500b530845e26a9 zh: b500b530845e26a9 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index 8aa9fb0096..0d415975c6 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -525,7 +525,7 @@ ask_user_question keeps the original blocking behavior by default; set `mode: ti ### `run_code` -Execute a TypeScript program against the available tools. Takes two required arguments: `description`, a short summary of what the program does, and `code`, the BODY of an async function (erasable syntax only; top-level `await` and `return` work). Call tools as `await tools.name(args)` per the declarations in the system prompt. Only what you print or return is program output — curate it. Image-bearing subtool results are attached after the run. +Execute a TypeScript program against the available tools. Takes two required arguments: `description`, a short summary of what the program does, and `code`, the program to execute. Call tools as `await tools.name(args)` per the declarations in the system prompt. Curate the program output. Image-bearing subtool results are attached after the run. ```json { @@ -537,7 +537,7 @@ Execute a TypeScript program against the available tools. Takes two required arg }, "code": { "type": "string", - "description": "The program: the body of an async TypeScript function." + "description": "The TypeScript program to execute, following this tool's execution instructions." }, "timeoutMs": { "type": "number", diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index b505568dde..1622182f0f 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -529,7 +529,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 ### `run_code` -针对可用工具执行 TypeScript 程序。接受两个必填参数:`description`,简要说明该程序做什么;以及 `code`,即异步函数的**函数体**(仅使用可擦除语法;支持顶层 `await` 和 `return`)。请根据系统提示词中的声明,以 `await tools.name(args)` 形式调用工具。只有打印或返回的内容属于程序输出,请谨慎筛选。含图片的子工具结果会在运行结束后附加。 +针对可用工具执行 TypeScript 程序。接受两个必填参数:`description`,简要说明该程序做什么;以及 `code`,要执行的程序。请根据系统提示词中的声明,以 `await tools.name(args)` 形式调用工具。请筛选程序输出。含图片的子工具结果会在运行结束后附加。 ```json { @@ -541,7 +541,7 @@ ask_user_question 默认保持原有阻塞行为;设置 `mode: timed` 后才 }, "code": { "type": "string", - "description": "The program: the body of an async TypeScript function." + "description": "The TypeScript program to execute, following this tool's execution instructions." }, "timeoutMs": { "type": "number", diff --git a/docs/ui-radius.i18n.yaml b/docs/ui-radius.i18n.yaml index a5015aa946..0c8d58fcd9 100644 --- a/docs/ui-radius.i18n.yaml +++ b/docs/ui-radius.i18n.yaml @@ -15,14 +15,14 @@ en: cd8120cba5566e19 zh: 65359436088c8bc5 /dsh-unified-corner-radius-standard/select-the-radius: - en: 06ddd6bf9ef1e48c - zh: 4c42d0c9266a00e8 + en: e736416ec85d6e16 + zh: 0edf60fccc867295 /dsh-unified-corner-radius-standard/reuse-tokens-and-preserve-deliberate-shapes: en: fb6d50f3139ad186 zh: 668cb0c02bd22167 /dsh-unified-corner-radius-standard/nested-geometry-and-hover: - en: 3920921700d8ad1c - zh: fc99da8a5e905a27 + en: 7fe4eb7707e6a9f3 + zh: be7530a05c205e27 /dsh-unified-corner-radius-standard/settings-card-materials: en: 85e7e63183df06d1 zh: 1da2b44083d7ebe2 diff --git a/docs/ui-radius.md b/docs/ui-radius.md index d6d28568ca..303e7c9382 100644 --- a/docs/ui-radius.md +++ b/docs/ui-radius.md @@ -38,9 +38,9 @@ H means designed outer height in CSS pixels, including borders. R means CSS `bor Prefer an existing shared size variant when a proposed control falls between these bands. A taller card remains a card: do not promote it to R28 merely because it exceeds a button's height. A multiline cell intentionally designed for multiple lines uses R16; an ordinary button whose label wraps retains its button variant. -Concrete defaults: `Button` uses H28/R8 for `sm` and H36/R12 for `md`, including outline variants. Standard H32 inputs and H36 selectors use R12. The Workspace files and New terminal guide entries both use R20, including title-only and described variants. Reserve R28 for their enclosing panel or dialog, not those entries. +Concrete defaults: `Button` uses H28/R8 for `sm` and H36/R12 for `md`, including outline variants. Standard H32 inputs and H36 selectors use R12. The Workspace files and New terminal guide entries both use R20, including title-only and described variants. Reserve R28 for their enclosing panel or dialog, not those entries. Composer statistics and the context-occupancy trigger use compact-control R8 with the theme curve, including hover, expanded, and focus states. -Code blocks, diffs, and file previews share R16: changed-file entry cards, delivered-file cards, generic file attachment cards, and hover preview panels. The 40px file-icon tiles inside changed-file and delivery cards use R10 on all four corners as a component-specific exception. Their hover fills keep the same contour. +Code blocks, diffs, and preview cards share R16: changed-file entry cards, delivered-file cards, submitted-plan cards, created-task cards, generic file attachment cards before and after sending, and hover preview panels. The 40px icon tiles inside changed-file, delivery, submitted-plan, and created-task cards use R10 on all four corners as a component-specific exception and share the same neutral tile fill and border in both themes. Their hover fills keep the same contour. ## Reuse tokens and preserve deliberate shapes @@ -64,11 +64,13 @@ Distinguish these three arrangements before changing a child radius: | Arrangement | Rule | Example | |---|---|---| -| Concentric inset | Inner R = max(0, outer R − inset); use the same curve | Outer R16, inset 4, inner R12 | +| Circular concentric inset | Inner R = max(0, outer R − inset); both arcs share a center and use `round` | Outer R16, inset 4, inner R12 | | Fill flush against an enclosing edge | The enclosure owns the visible corner; clip the fill or inherit the matching corner | A split-button card with two independent hover regions | | Separate card or form group inside another surface | Choose the child's semantic tier; do not subtract all parent padding mechanically | R16 editor within an R20 settings card | -Standard menus use outer R16, 4px padding, and R12 items. Compact menus use outer R12, 4px padding, and R8 items. Shared `SegmentedControl` uses outer R12, 4px inset, and R8 segments/indicator; `SegmentedTabs` uses outer R16, 4px inset, and R12 segments/indicator. Keep indicator offsets, width calculations, submenu alignment, and pointer bridges consistent when changing padding. +Standard menus use outer R16, 4px padding, and R12 items, including command selection, task menus, and the exposed highlights in subagent and background-job menus. Tree disclosure gutters retain their indentation; controls inside a filled job row keep their own compact geometry. Compact menus use outer R12, 4px padding, and R8 items. Shared `SegmentedControl` uses outer R12, 4px inset, and R8 segments/indicator; `SegmentedTabs` uses outer R16, 4px inset, and R12 segments/indicator. Keep indicator offsets, width calculations, submenu alignment, and pointer bridges consistent when changing padding. + +The radius subtraction is also the nominal sizing rule for nested superellipses. Equal exponents do not make them exact offset curves, so their diagonal gap may differ from the side inset. Keep the shared superellipse menu and segmented-control treatments; use circular arcs when strict equal radial spacing is required. A single clickable surface paints hover on itself. A flush pseudo-element or overlay uses the same radius and curve as the visible enclosure. Avoid a separately rounded fill that leaves a crescent between the background and the border. diff --git a/docs/ui-radius.zh.md b/docs/ui-radius.zh.md index 657684ebc7..80edb753c6 100644 --- a/docs/ui-radius.zh.md +++ b/docs/ui-radius.zh.md @@ -38,9 +38,9 @@ H 表示以 CSS 像素计、包含边框的设计外部高度。R 表示浏览 拟定控件尺寸落在档位之间时,优先复用已有的公共尺寸变体。高卡片仍是卡片,不因高度超过按钮就升到 R28。专门设计为多行的 cell 使用 R16;普通按钮的文字发生换行时,仍保留其按钮变体。 -具体默认值:`Button` 的 `sm` 使用 H28/R8,`md` 使用 H36/R12,包含描边变体。标准 H32 输入框和 H36 选择器使用 R12。“工作区文件”和“新建终端”引导入口统一使用 R20,包含仅标题与带描述的变体。R28 留给包围它们的面板或对话框,不用于这些入口。 +具体默认值:`Button` 的 `sm` 使用 H28/R8,`md` 使用 H36/R12,包含描边变体。标准 H32 输入框和 H36 选择器使用 R12。“工作区文件”和“新建终端”引导入口统一使用 R20,包含仅标题与带描述的变体。R28 留给包围它们的面板或对话框,不用于这些入口。输入框统计控件与上下文占用率入口使用紧凑控件的 R8 和主题曲线,包含 hover、展开与焦点状态。 -代码块、diff 与文件预览共用 R16:包括改动文件入口卡片、交付文件卡片、通用附件文件卡片和悬停预览浮层。改动文件与交付文件卡片内部的 40px 文件图标底框作为组件特例,四角统一使用 R10。各自的 hover 保持同一轮廓。 +代码块、diff 与预览卡片共用 R16:包括改动文件入口卡片、交付文件卡片、已提交计划卡片、已创建任务卡片、发送前后的通用附件文件卡片和悬停预览浮层。改动文件、交付文件、已提交计划与已创建任务卡片内部的 40px 图标底框作为组件特例,四角统一使用 R10,并在明暗两种主题下分别共用相同的中性底色与边框。各自的 hover 保持同一轮廓。 ## 复用 token,保留有意设计的形状 @@ -64,11 +64,13 @@ H 表示以 CSS 像素计、包含边框的设计外部高度。R 表示浏览 | 关系 | 规则 | 示例 | |---|---|---| -| 同心内缩 | 内层 R = max(0, 外层 R − 内缩距离);使用相同曲线 | 外层 R16,内缩 4,内层 R12 | +| 圆弧同心内缩 | 内层 R = max(0, 外层 R − 内缩距离);两段圆弧同心且使用 `round` | 外层 R16,内缩 4,内层 R12 | | 底色紧贴容器边缘 | 由外框决定可见圆角;裁切底色或继承相应圆角 | 两个独立 hover 区域组成的分体按钮卡片 | | 容器内独立的卡片或表单组 | 按子元素用途选择档位;不机械减去全部父级内边距 | R20 设置卡片内的 R16 编辑器 | -标准菜单使用外层 R16、4px 内边距、R12 菜单项。紧凑菜单使用外层 R12、4px 内边距、R8 菜单项。公共 `SegmentedControl` 使用外层 R12、4px 内缩、R8 分段和指示器;`SegmentedTabs` 使用外层 R16、4px 内缩、R12 分段和指示器。修改内边距时,同步保持指示器偏移、宽度计算、子菜单对齐与指针桥接区域一致。 +标准菜单使用外层 R16、4px 内边距、R12 菜单项,包含命令选择、任务菜单,以及子会话和后台任务菜单的外露高亮区域。树形展开操作保留缩进;带底色任务行内的控件保留各自的紧凑几何。紧凑菜单使用外层 R12、4px 内边距、R8 菜单项。公共 `SegmentedControl` 使用外层 R12、4px 内缩、R8 分段和指示器;`SegmentedTabs` 使用外层 R16、4px 内缩、R12 分段和指示器。修改内边距时,同步保持指示器偏移、宽度计算、子菜单对齐与指针桥接区域一致。 + +半径相减也用于嵌套超级椭圆的名义尺寸关系。相同指数不意味着两条曲线严格等距,因此对角线间隙可能不同于侧边内缩。菜单与分段控件保留公共的超级椭圆样式;要求径向严格等距时使用圆弧。 单个可点击表面在自身绘制 hover。贴边的伪元素或覆盖层使用与可见外框相同的圆角和曲线。避免单独给底色设置圆角,导致背景与边框之间出现月牙状空隙。 diff --git a/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.i18n.yaml b/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.i18n.yaml new file mode 100644 index 0000000000..5fae57fcd3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.md +/: + en: a4f973e3aed3cbb1 + zh: e33e5eb33838f82e +/custom-python-runtime-aliases-must-target-a-sibling-interpreter: + en: c38fad48cd870c4c + zh: 49fff1636ca8c8fd +/custom-python-runtime-aliases-must-target-a-sibling-interpreter/change: + en: 55f21ac0b9190e37 + zh: 2d1c7aaa89ddfe19 +/custom-python-runtime-aliases-must-target-a-sibling-interpreter/migration: + en: 2839866a08be236d + zh: 11a01d35a7f396ce diff --git a/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.md b/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.md new file mode 100644 index 0000000000..1a3545ee9b --- /dev/null +++ b/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Custom primary-runtime payloads require relocatable Python interpreter aliases." +--- + +# Custom Python runtime aliases must target a sibling interpreter + +English | [中文](guide.zh.md) + +## Change + +On macOS and Linux, `DSH_PRIMARY_RUNTIME` previously accepted interpreter links that resolved outside their payload or through other links. Payload validation now requires each linked `dependencies/python/bin/python` or `python3` to point directly to the regular sibling interpreter named for `runtime.json`'s Python major and minor version, such as `python3.12`. Regular command files remain supported, including those distributed in Python wheels. Windows is unchanged. + +## Migration + +1. For a custom payload, keep the versioned interpreter in `dependencies/python/bin/` and make `python` and `python3` relative links to its filename. The [runtime preparation instructions](../../../../packages/skill/tool-workspace-dependencies/README.md) list the required target and output arguments. +2. Preserve relative links when copying prepared resources. With Node `fs.cp`, use `verbatimSymlinks: true`; wheel builders must materialize the command files because pip does not restore links. The native build smoke requires the prepared resource tree to retain both aliases. +3. Confirm that `readlink` reports only the sibling filename for both aliases, then move the payload away from its build directory, point `DSH_PRIMARY_RUNTIME` at its new directory, and verify that `load_workspace_dependencies` and the returned Python command succeed. diff --git a/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.zh.md b/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.zh.md new file mode 100644 index 0000000000..e623f41857 --- /dev/null +++ b/docs/upgrade-guide/v0.2.0-rc.2/primary-runtime-python-aliases/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "自定义 primary-runtime payload 的 Python 解释器别名必须支持目录迁移。" +--- + +# 自定义 Python 运行时别名必须指向同目录解释器 + +[English](guide.md) | 中文 + +## 变更 + +在 macOS 和 Linux 上,`DSH_PRIMARY_RUNTIME` 之前接受指向 payload 外部或经过其他链接的解释器链接。现在,payload 校验要求 `dependencies/python/bin/python` 或 `python3` 的链接直接指向同目录的普通解释器文件,文件名由 `runtime.json` 中 Python 的主版本号和次版本号决定,例如 `python3.12`。普通命令文件仍受支持,包括 Python wheel 中分发的文件。Windows 不变。 + +## 迁移 + +1. 对于自定义 payload,将版本化解释器保留在 `dependencies/python/bin/` 中,并让 `python` 和 `python3` 以该文件名为目标建立相对链接。[运行时准备说明](../../../../packages/skill/tool-workspace-dependencies/README.zh.md)列出了必需的目标与输出参数。 +2. 复制准备好的资源时保留相对链接。使用 Node `fs.cp` 时设置 `verbatimSymlinks: true`;wheel 构建器必须将命令展开为普通文件,因为 pip 不会还原链接。本机构建冒烟检查要求准备好的资源目录保留两个别名。 +3. 确认 `readlink` 对两个别名都只返回同目录解释器的文件名,再将 payload 移离构建目录,将 `DSH_PRIMARY_RUNTIME` 指向新目录,验证 `load_workspace_dependencies` 和返回的 Python 命令均可成功执行。 diff --git a/docs/user/guide/public-deployments.i18n.yaml b/docs/user/guide/public-deployments.i18n.yaml index cba21115ff..757429dcc0 100644 --- a/docs/user/guide/public-deployments.i18n.yaml +++ b/docs/user/guide/public-deployments.i18n.yaml @@ -6,8 +6,8 @@ en: 867565aa675f3fb3 zh: c60606b5e5bdb778 /publish-the-web-ui-behind-a-reverse-proxy/what-public-url-advertises: - en: 576292b93ccf299a - zh: ded5adc55396869c + en: 924b28b211478f01 + zh: b098d5a53a29c883 /publish-the-web-ui-behind-a-reverse-proxy/what-the-proxy-must-do: en: 2f93051763125365 zh: 1dd699cb84ecf034 diff --git a/docs/user/guide/public-deployments.md b/docs/user/guide/public-deployments.md index b6b4efc0ca..70e107fe6d 100644 --- a/docs/user/guide/public-deployments.md +++ b/docs/user/guide/public-deployments.md @@ -10,7 +10,7 @@ dsh --profile web --public-url https://app.example/ui/ --trusted-host app.exampl ## What `--public-url` advertises -`--public-url` accepts an `http://` or `https://` root with an optional mount prefix and normalizes it to end in `/`. It supplies the printed and opened startup URL, `DSH_WEB_URL`, and the web-surface orientation. The webserver keeps serving origin-root routes and never learns the mount. The `publicUrl` config field publishes the same advertisement. +`--public-url` accepts an `http://` or `https://` root with an optional mount prefix and normalizes it to end in `/`. It supplies the printed and opened startup URL, `DSH_WEB_URL`, and the Web GUI URL in the agent's runtime context. The webserver keeps serving origin-root routes and never learns the mount. The `publicUrl` config field publishes the same advertisement. ## What the proxy must do diff --git a/docs/user/guide/public-deployments.zh.md b/docs/user/guide/public-deployments.zh.md index 2cb0e8fd4a..93572f0db1 100644 --- a/docs/user/guide/public-deployments.zh.md +++ b/docs/user/guide/public-deployments.zh.md @@ -10,7 +10,7 @@ dsh --profile web --public-url https://app.example/ui/ --trusted-host app.exampl ## `--public-url` 公告什么 -`--public-url` 接受可带挂载前缀的 `http://` 或 `https://` 根,并把它归一化为以 `/` 结尾。它提供打印与打开的启动 URL、`DSH_WEB_URL` 与 web 表层定位。webserver 继续提供 origin-root 路由,且从不了解挂载。`publicUrl` 配置字段发布同样的公告。 +`--public-url` 接受可带挂载前缀的 `http://` 或 `https://` 根,并把它归一化为以 `/` 结尾。它提供打印与打开的启动 URL、`DSH_WEB_URL`,以及 agent 运行时上下文中的 Web GUI URL。webserver 继续提供 origin-root 路由,且从不了解挂载。`publicUrl` 配置字段发布同样的公告。 ## 代理必须做什么 diff --git a/lefthook.yml b/lefthook.yml index 1d5c8898c6..75c03f9a26 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -21,16 +21,6 @@ pre-commit: run: node_modules/.bin/tsx scripts/run-oxlint.ts --config .oxlintrc.staged.json --fix --no-error-on-unmatched-pattern {staged_files} stage_fixed: true - # Regenerate rather than reject: a dependency edit that forgot the notices - # would otherwise fail the test lane long after the commit. The glob matches - # every input the generator reads, including the generator itself and the - # build-time pin source. Deleting a manifest cannot trigger this job — - # lefthook only inspects files present on disk — so that one case still - # falls through to the freshness assertion in the test lane. - - name: third-party notices (staged) - glob: '{package.json,*/package.json,*/*/package.json,*/*/*/package.json,*/*/*/*/package.json,pnpm-workspace.yaml,*/*/pnpm-workspace.yaml,pnpm-lock.yaml,vendor/README.md,python/*/pyproject.toml,scripts/primary-runtime/lock.json,scripts/gen-third-party-notices.ts,scripts/browser-bundled-externals.ts,scripts/build-exe-for-python-sdk.ts,tsconfig.base*.json,packages/*/*/src/**/*,packages/*/*/tsdown.config.ts,packages/client/tsdown.client.ts,apps/*/src/**/*,apps/*/vite.config.ts}' - run: node_modules/.bin/tsx scripts/gen-third-party-notices.ts && git add THIRD_PARTY_NOTICES.md - - name: whitespace (staged) run: git diff --cached --check diff --git a/package.json b/package.json index 2d76805736..3b9e5f2b36 100644 --- a/package.json +++ b/package.json @@ -19,6 +19,8 @@ "scripts": { "prepare:primary-runtime": "tsx scripts/primary-runtime/prepare.ts", "build": "tsx scripts/build.ts", + "build:artifacts": "tsx scripts/build.ts --scope artifacts", + "build:check": "tsx scripts/build.ts --scope check", "build:bench": "npm run build:native-system && npm run build:lib && tsdown --config-loader native --config benchmarks/tsdown.config.ts", "build:official": "tsx scripts/build.ts --profile official", "build:lib": "pnpm run build:lib:host && pnpm run build:lib:client", @@ -48,11 +50,11 @@ "upload:latest:win:x64": "pnpm --filter @deepseek-ai/dsh-desktop run upload:latest:win:x64", "clean": "tsx scripts/clean.ts", "change-scope": "tsx scripts/change-scope.ts", - "typecheck": "npm run build:lib:host && npm run typecheck:contracts-ready", + "typecheck": "tsx scripts/build.ts --scope typecheck", "typecheck:contracts-ready": "tsc -b tsconfig.client.json", - "lint": "npm run build:lib:host && npm run lint:contracts-ready", + "lint": "tsx scripts/compile-referenced-projects.ts host-contracts && npm run lint:contracts-ready", "lint:contracts-ready": "tsx scripts/run-oxlint.ts .", - "lint:fix": "npm run build:lib:host && npm run lint:fix:contracts-ready", + "lint:fix": "tsx scripts/compile-referenced-projects.ts host-contracts && npm run lint:fix:contracts-ready", "lint:fix:contracts-ready": "tsx scripts/run-oxlint.ts --config .oxlintrc.staged.json packages/typert/generator/tests/fixtures/type-model --fix && tsx scripts/run-oxlint.ts . --fix", "duplication": "jscpd --config .jscpd.json packages scripts", "test": "pnpm run build:native-system && vitest run", @@ -99,7 +101,7 @@ "check:ci:windows-observational-ready": "tsx scripts/run-gates.ts ci-windows-observational-ready", "check:node-compat": "tsx scripts/run-gates.ts node-compat", "publint": "tsx scripts/publint-all.ts", - "doc-typecheck": "npm run build:lib:host && npm run doc-typecheck:contracts-ready", + "doc-typecheck": "tsx scripts/compile-referenced-projects.ts host-contracts && npm run doc-typecheck:contracts-ready", "doc-typecheck:contracts-ready": "tsx scripts/doc-typecheck.ts", "verify-md-wrap": "tsx scripts/verify-md-wrap.ts", "verify-md-links": "tsx scripts/verify-md-links.ts", @@ -240,6 +242,8 @@ "@types/mdast": "^4.0.4", "@types/papaparse": "^5.5.2", "@types/node": "^22.20.1", + "@types/react": "~18.3.1", + "@types/react-dom": "~18.3.0", "@types/semver": "^7.8.0", "@types/spdx-expression-parse": "^4.0.0", "@vitest/coverage-v8": "^4.1.11", diff --git a/packages/api/account-controller/locale/en.json b/packages/api/account-controller/locale/en.json new file mode 100644 index 0000000000..4c7e6dd036 --- /dev/null +++ b/packages/api/account-controller/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-account-controller" + } +} diff --git a/packages/api/account-controller/locale/zh.json b/packages/api/account-controller/locale/zh.json new file mode 100644 index 0000000000..f404257eaa --- /dev/null +++ b/packages/api/account-controller/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "账号操作接口", + "description": "向已认证的客户端提供账号操作能力。" + } +} diff --git a/packages/api/account-controller/package.json b/packages/api/account-controller/package.json index 21e34502d8..fd3a002a5d 100644 --- a/packages/api/account-controller/package.json +++ b/packages/api/account-controller/package.json @@ -31,9 +31,11 @@ "./remote": { "types": "./lib/typert.remote-client.d.ts", "default": "./lib/typert.remote-client.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", diff --git a/packages/api/gateway/README.i18n.yaml b/packages/api/gateway/README.i18n.yaml index e8cf3b7f4b..5be8cde9cc 100644 --- a/packages/api/gateway/README.i18n.yaml +++ b/packages/api/gateway/README.i18n.yaml @@ -15,8 +15,8 @@ en: d9859219cdb0f367 zh: 2a3cfa8cb786e327 /deepseek-ai-dsh-api-gateway/host-service-typertgatewayservice-ctx-key-typertgateway: - en: 5179435c09004549 - zh: c904462396531947 + en: 2aabd26516a45771 + zh: 5907f472a4d536df /deepseek-ai-dsh-api-gateway/client-service-clientremote-ctx-key-remote: en: c106f0ca3e547f84 zh: 833e30d7151c41c7 @@ -27,8 +27,8 @@ en: af5abeee32f2d93b zh: b320bb727a223a13 /deepseek-ai-dsh-api-gateway/known-limitations-and-deferred-work: - en: 3ade2903f40a0a98 - zh: 9af1d557fefdbd89 + en: 5af0d863582fbc4f + zh: d87e4b97b579c456 /deepseek-ai-dsh-api-gateway/known-limitations-and-deferred-work/dev-note: en: 10727471030aee01 zh: e6bee82abd12127d diff --git a/packages/api/gateway/README.md b/packages/api/gateway/README.md index 41cfc3a324..c2d896972e 100644 --- a/packages/api/gateway/README.md +++ b/packages/api/gateway/README.md @@ -32,7 +32,7 @@ The Host entry registers a trusted-host interceptor on Connection's shared `/api A cancellation-aware Remote method declares `signal: AbortSignal` as its final Host parameter. The signal is descriptor metadata rather than a wire argument: Connection supplies it to the Gateway, and the Gateway injects it after decoded business parameters. SRC recognizes the reserved final name, while strict generation additionally requires the global `AbortSignal` type. -A stream Remote uses `@Remote({ mode: 'stream' })` and returns an `Iterable` or `AsyncIterable`. `ctx.typertGateway.stream()` applies the same endpoint, argument, lookup, and cancellation checks as unary invocation, then returns a cancellation-aware iterable over the business items. The Client opens the Gateway-owned `/api/remote.mux` WebSocket when its plugin activates and keeps it connected while idle. Connection owns the retry schedule; before each retry it asks the mux to cancel any candidate or active socket and make exactly one fresh physical attempt. The Host sends Ping control frames at the configured `websocketHeartbeatIntervalMs` interval (two seconds by default), and the browser answers Pong at the WebSocket protocol layer, so idle network intermediaries see traffic without any Remote stream frame. A socket that has not answered the previous Ping is terminated at the next interval. Independently cancellable logical streams share that socket; an in-process Connection carrier provides equivalent streams directly without opening it. +A stream Remote uses `@Remote({ mode: 'stream' })` and returns an `Iterable` or `AsyncIterable`. `ctx.typertGateway.stream()` applies the same endpoint, argument, lookup, and cancellation checks as unary invocation, then returns a cancellation-aware iterable over the business items. The Client opens the Gateway-owned `/api/remote.mux` WebSocket when its plugin activates and keeps it connected while idle. Connection owns the retry schedule; before each retry it asks the mux to cancel any candidate or active socket and make exactly one fresh physical attempt. The Host sends Ping control frames at the configured `websocketHeartbeatIntervalMs` interval (two seconds by default), and the browser answers Pong at the WebSocket protocol layer, so idle network intermediaries see traffic without any Remote stream frame. A Pong, any received frame, or a downlink write that waited in the full local send buffer and then completed counts as peer activity; a socket with no activity across two Ping intervals is terminated, so a congested link that delays the Pong behind data stays connected. Independently cancellable logical streams share that socket; an in-process Connection carrier provides equivalent streams directly without opening it. When the launcher supplies `ctx.appReady`, Gateway registers the WebSocket upgrade route only after successful application startup. Earlier connection attempts remain carrier failures handled by Connection's retry policy, so a restarting Host cannot accept streams while its controllers are still initializing. Unloading cancels a pending readiness subscription and closes any registered carrier. Embedded Hosts without `appReady` register immediately and own their startup ordering; in-process invocation is unchanged. @@ -86,7 +86,8 @@ No direct effect; invoked business Services own any model-visible result. - `$stream()` supervises carrier replacement but does not infer replay semantics; each domain owns its resume cursor or replacement-baseline validation and normal-end classification. Connection generations reopen the internal `$events` stream; one-way notifications are not replayed, while pending scoped waterfalls retain their event id across replay. - Lookup resolvers are configured per key; an individual Remote parameter or endpoint cannot currently select a live-only policy under the same `agent`/`session` key. - Forwarded events reach `$on` without business-payload projection or redaction. Ordinary notifications are not replayed after reconnect; Agent-scoped waterfalls project only the top-level Agent identity needed to select the Client Context and carry their own pending lifetime. -- `websocketHeartbeatIntervalMs` is both the Ping cadence and the Pong deadline. The Host terminates a peer that does not answer before the next interval, so a deployment whose event loop or network can stall longer than this interval must raise it. +- `websocketHeartbeatIntervalMs` is both the Ping cadence and the activity deadline. The Host terminates a peer that shows no activity for two intervals, so a deployment whose event loop or network can stall longer than this interval must raise it. +- A completed queued write shows that the TCP peer acknowledged data. Behind a buffering reverse proxy that peer is the proxy, so a vanished Client during sustained downlink is detected only after the proxy stops accepting data. - Uplinks have no flow control beyond the bounded Host inbox: a Client that sends faster than the method reads, or that sends to a method never taking its uplink, fails its stream with `gateway/uplink-overflow`, and no uplink item is replayed across carrier generations; a domain that must resume an uplink carries its own acknowledgement cursor in the reopened request. diff --git a/packages/api/gateway/README.zh.md b/packages/api/gateway/README.zh.md index c73b0f45b6..d92ae276f6 100644 --- a/packages/api/gateway/README.zh.md +++ b/packages/api/gateway/README.zh.md @@ -32,7 +32,7 @@ Connection 可用时,Host 入口会在 Connection 共享的 `/api` FetchHandle 支持取消的 Remote 方法会把 `signal: AbortSignal` 声明为最后一个 Host 参数。signal 是 descriptor 元数据,而不是 wire 参数:Connection 将它提供给 Gateway,Gateway 则在已解码的业务参数之后注入它。SRC 识别这个保留的末位参数名,严格生成还要求它具有全局 `AbortSignal` 类型。 -流式 Remote 使用 `@Remote({ mode: 'stream' })` 并返回 `Iterable` 或 `AsyncIterable`。`ctx.typertGateway.stream()` 执行与一元调用相同的 endpoint、参数、lookup 和取消校验,再返回可取消的业务项 iterable。Client 插件激活时打开 Gateway 自有的 `/api/remote.mux` WebSocket,并让它在空闲时保持连接。Connection 拥有重试调度;每次 retry 前,它要求 mux 取消候选或活动 socket,并且只做一次全新的物理连接尝试。Host 按配置的 `websocketHeartbeatIntervalMs` 间隔(默认 2 秒)发送 Ping 控制帧,浏览器在 WebSocket 协议层自动回复 Pong,使空闲网络中间层持续看到流量,而不新增 Remote 流帧。若 socket 尚未回复上一次 Ping,Host 会在下一间隔终止它。可独立取消的逻辑流共享这条连接;进程内 Connection 载体直接提供等价的流,不打开该 WebSocket。 +流式 Remote 使用 `@Remote({ mode: 'stream' })` 并返回 `Iterable` 或 `AsyncIterable`。`ctx.typertGateway.stream()` 执行与一元调用相同的 endpoint、参数、lookup 和取消校验,再返回可取消的业务项 iterable。Client 插件激活时打开 Gateway 自有的 `/api/remote.mux` WebSocket,并让它在空闲时保持连接。Connection 拥有重试调度;每次 retry 前,它要求 mux 取消候选或活动 socket,并且只做一次全新的物理连接尝试。Host 按配置的 `websocketHeartbeatIntervalMs` 间隔(默认 2 秒)发送 Ping 控制帧,浏览器在 WebSocket 协议层自动回复 Pong,使空闲网络中间层持续看到流量,而不新增 Remote 流帧。Pong、收到的任意帧,或曾在已满的本机发送缓冲区中等待后完成的下行写入,都视为对端活动;连续两个 Ping 间隔没有活动的 socket 会被终止,因此 Pong 被数据阻塞在拥塞链路上时连接仍会保持。可独立取消的逻辑流共享这条连接;进程内 Connection 载体直接提供等价的流,不打开该 WebSocket。 启动器提供 `ctx.appReady` 时,Gateway 仅在应用成功启动后注册 WebSocket 升级路由。此前的连接尝试仍属于载体故障,由 Connection 的重试策略处理,因此重启中的 Host 不会在控制器仍在初始化时接受流。卸载会取消尚未触发的就绪订阅,并关闭已注册的载体。不提供 `appReady` 的嵌入式 Host 会立即注册,并自行负责启动顺序;进程内调用不变。 @@ -86,7 +86,8 @@ Client waterfall 的 Context 解析保持同步。解析器可以返回借用的 - `$stream()` 监督载体替换,但不推断回放语义;各领域自行拥有恢复 cursor 或替换 baseline 的校验,以及正常结束的分类。Connection generation 会重开内部 `$events` 流;单向通知不会重放,仍处于 pending 的 scoped waterfall 则沿用同一个 event id 重放。 - lookup 解析器按 key 配置;当前无法让单个 Remote 参数或 endpoint 在同一 `agent`/`session` key 下选择 live-only 策略。 - 被转发的事件到达 `$on` 时不做业务载荷投影或脱敏。普通通知在重连后不重放;Agent-scoped waterfall 只投影选择 Client Context 所需的顶层 Agent 身份,并自行携带 pending 生命周期。 -- `websocketHeartbeatIntervalMs` 同时是 Ping 周期和 Pong 截止时间。对端未在下一周期前回复时,Host 会终止连接;如果部署的事件循环或网络可能停顿超过该间隔,必须调大此配置。 +- `websocketHeartbeatIntervalMs` 同时是 Ping 周期和活动截止时间。对端连续两个周期没有活动时,Host 会终止连接;如果部署的事件循环或网络可能停顿超过该间隔,必须调大此配置。 +- 排队写入完成只说明 TCP 对端确认了数据。经过带缓冲的反向代理时,该对端是代理,因此持续下行期间 Client 消失,要等代理不再接收数据后才会被检测到。 - 上行除了有界的 Host inbox 之外没有流控:Client 发送快于方法读取,或发给从未取用 uplink 的方法时,其流以 `gateway/uplink-overflow` 失败;上行项不会跨载体代际重放,需要恢复上行的领域在重开的请求里自带确认游标。 diff --git a/packages/api/gateway/locale/en.json b/packages/api/gateway/locale/en.json new file mode 100644 index 0000000000..3aaa997318 --- /dev/null +++ b/packages/api/gateway/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-gateway" + } +} diff --git a/packages/api/gateway/locale/zh.json b/packages/api/gateway/locale/zh.json new file mode 100644 index 0000000000..616ee05866 --- /dev/null +++ b/packages/api/gateway/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "远程调用网关", + "description": "接收客户端的接口调用,并分发给对应的服务。" + } +} diff --git a/packages/api/gateway/package.json b/packages/api/gateway/package.json index d6fe3d21a2..d4469cf8cd 100644 --- a/packages/api/gateway/package.json +++ b/packages/api/gateway/package.json @@ -31,7 +31,8 @@ "./stream-protocol": { "types": "./lib/types/stream-protocol.d.ts", "default": "./lib/types/stream-protocol.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -48,6 +49,7 @@ "watch": "tsdown --watch" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/gateway/src/stream-server.ts b/packages/api/gateway/src/stream-server.ts index 9454f03f2d..34074722da 100644 --- a/packages/api/gateway/src/stream-server.ts +++ b/packages/api/gateway/src/stream-server.ts @@ -72,12 +72,12 @@ export class RemoteStreamMuxServer { this.server.handleUpgrade(req, socket, head, (websocket) => { const release = bindPeer(websocket, peer) if (release === undefined) return - this.missedHeartbeats.set(websocket, 0) - websocket.on('pong', () => { this.missedHeartbeats.set(websocket, 0) }) + const alive = (): void => { this.missedHeartbeats.set(websocket, 0) } + alive() this.startHeartbeat() const bound: BoundStreamOpener = (endpoint, payload, uplink, control) => this.open(endpoint, payload, uplink, peer, control) - const connection = new RemoteStreamMuxConnection(websocket, bound, this.failure, this.streamInboxBytes) + const connection = new RemoteStreamMuxConnection(websocket, bound, this.failure, this.streamInboxBytes, alive) const done = connection.run() this.connections.add(done) void done.then(() => { @@ -141,13 +141,23 @@ class RemoteStreamMuxConnection { private readonly open: BoundStreamOpener, private readonly failure: RemoteStreamFailureMapper, private readonly streamInboxBytes: number, + private readonly alive: () => void, ) {} + /** + * Serve frames until the socket closes. A Pong, any received frame, and a + * downlink write that waited in the local send buffer and then completed + * count as peer activity, so a congested link that delays the Pong behind + * data keeps its socket. A write that completes at once proves nothing + * about the peer and does not count. + */ async run(): Promise { const closed = new Promise((resolve) => { this.socket.once('close', resolve) this.socket.once('error', () => { this.socket.terminate() }) + this.socket.on('pong', this.alive) this.socket.on('message', (data, isBinary) => { + this.alive() if (isBinary) { this.socket.close(1003, 'text messages required') return @@ -283,10 +293,18 @@ class RemoteStreamMuxConnection { reject(new Error('api gateway: Remote stream socket is closed')) return } + let queued = false this.socket.send(text, (error) => { - if (error) reject(error) - else resolve() + if (error) { + reject(error) + return + } + if (queued) this.alive() + resolve() }) + // Read after send(): bytes still buffered mean the local send buffer was + // full, so their completion requires the peer to acknowledge data. + queued = this.socket.bufferedAmount > 0 })) this.writes = delivery.catch(() => undefined) return delivery diff --git a/packages/api/gateway/tests/stream-server.host.spec.ts b/packages/api/gateway/tests/stream-server.host.spec.ts index 469aa25b0c..965cbb7989 100644 --- a/packages/api/gateway/tests/stream-server.host.spec.ts +++ b/packages/api/gateway/tests/stream-server.host.spec.ts @@ -67,6 +67,54 @@ describe('Remote stream mux server carrier lifecycle', () => { await closed }) + it('counts inbound frames as liveness while Pong is delayed', async () => { + const entry = await startMux(async (_endpoint, _payload, _uplink, _peer, control) => waitForAbort(control.signal), 20) + const client = await connect(entry.url, false) + const terminated = vi.spyOn(acceptedSocket(entry.mux), 'terminate') + const traffic = setInterval(() => { client.send(JSON.stringify({ type: 'cancel', streamId: 'absent' })) }, 5) + try { + await pings(client, 4) + expect(terminated).not.toHaveBeenCalled() + } finally { + clearInterval(traffic) + } + await vi.waitFor(() => { expect(terminated).toHaveBeenCalledOnce() }) + }) + + it('counts a downlink write that waited in the send buffer as liveness', async () => { + const stop = Promise.withResolvers() + const entry = await startMux(async () => steadyItems(stop.promise), 20) + const client = await connect(entry.url, false) + const serverSocket = acceptedSocket(entry.mux) + const terminated = vi.spyOn(serverSocket, 'terminate') + Object.defineProperty(serverSocket, 'bufferedAmount', { configurable: true, value: 1 }) + client.send(openFrame('congested')) + try { + await pings(client, 4) + expect(terminated).not.toHaveBeenCalled() + } finally { + stop.resolve(undefined) + Reflect.deleteProperty(serverSocket, 'bufferedAmount') + } + await vi.waitFor(() => { expect(terminated).toHaveBeenCalledOnce() }) + }) + + it('does not count a downlink write that completed at once as liveness', async () => { + const stop = Promise.withResolvers() + const entry = await startMux(async () => steadyItems(stop.promise), 20) + const client = await connect(entry.url, false) + const terminated = vi.spyOn(acceptedSocket(entry.mux), 'terminate') + const items = vi.fn() + client.on('message', items) + client.send(openFrame('flowing')) + try { + await vi.waitFor(() => { expect(terminated).toHaveBeenCalledOnce() }) + expect(items).toHaveBeenCalled() + } finally { + stop.resolve(undefined) + } + }) + it('keeps the socket when a delayed Pong arrives before the final check', async () => { const entry = await startMux(async (_endpoint, _payload, _uplink, _peer, control) => waitForAbort(control.signal), 20) const client = await connect(entry.url, false) @@ -585,6 +633,19 @@ async function *echoUplink(uplink: AsyncIterable): AsyncIterable): AsyncIterable { + const stopped = stop.then(() => true) + while (!await Promise.race([stopped, new Promise((resolve) => { setTimeout(() => { resolve(false) }, 5) })])) { + yield 'item' + } +} + +/** Resolve after the client has received `count` Ping frames. */ +async function pings(client: WebSocket, count: number): Promise { + for (let received = 0; received < count; received++) await once(client, 'ping') +} + async function *waitForAbort(signal: AbortSignal): AsyncIterable { await new Promise((resolve) => { if (signal.aborted) resolve() diff --git a/packages/api/gateway/tsdown.config.ts b/packages/api/gateway/tsdown.config.ts index 2f199f0d1f..71d5bd77f8 100644 --- a/packages/api/gateway/tsdown.config.ts +++ b/packages/api/gateway/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../../client/tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-api-gateway', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/api/job-controller/locale/en.json b/packages/api/job-controller/locale/en.json new file mode 100644 index 0000000000..87cdb55a70 --- /dev/null +++ b/packages/api/job-controller/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-job-controller" + } +} diff --git a/packages/api/job-controller/locale/zh.json b/packages/api/job-controller/locale/zh.json new file mode 100644 index 0000000000..1d7b6c6e65 --- /dev/null +++ b/packages/api/job-controller/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "后台任务观察接口", + "description": "向客户端持续提供后台任务的状态和输出。" + } +} diff --git a/packages/api/job-controller/package.json b/packages/api/job-controller/package.json index 233b307dbd..a82912d8bf 100644 --- a/packages/api/job-controller/package.json +++ b/packages/api/job-controller/package.json @@ -35,7 +35,8 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -54,6 +55,7 @@ "watch": "tsdown --watch" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/job-controller/tsdown.config.ts b/packages/api/job-controller/tsdown.config.ts index 0391bc61bf..0e42a1163e 100644 --- a/packages/api/job-controller/tsdown.config.ts +++ b/packages/api/job-controller/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../../client/tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-api-job-controller', + import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }, ) diff --git a/packages/api/remotes/locale/en.json b/packages/api/remotes/locale/en.json new file mode 100644 index 0000000000..cc9009975d --- /dev/null +++ b/packages/api/remotes/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-remotes" + } +} diff --git a/packages/api/remotes/locale/zh.json b/packages/api/remotes/locale/zh.json new file mode 100644 index 0000000000..222afebaf9 --- /dev/null +++ b/packages/api/remotes/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "客户端 API 汇总", + "description": "汇总应用向客户端开放的服务端能力。" + } +} diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index ccf1611794..1ac78ce12f 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -27,7 +27,8 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -44,6 +45,7 @@ }, "license": "MIT", "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/remotes/tsdown.config.ts b/packages/api/remotes/tsdown.config.ts index 29349148d6..0e42a1163e 100644 --- a/packages/api/remotes/tsdown.config.ts +++ b/packages/api/remotes/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../../client/tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-api-remotes', + import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }, ) diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 94dd4e518f..3d1a5b274d 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: d26a58a8f2406cd5 - zh: 82135eceb9adb628 + en: d8c0e2b2e45fa75d + zh: 025b50be4204580c /session-controller/client-references: en: 41bdda1ac32df558 zh: aa5d0e325924066b diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index ca922877f8..ed01827a70 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -39,7 +39,7 @@ Host list generation yields between complete rows only when its configured work Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank. -Explicit-id `session.create` adopts a live Session or resumes a persisted Session while retaining its writer lock. Writer contention returns `session/writer-held`; callers may try another blank without suppressing unrelated failures. `session.list` includes persisted blanks using cached metadata, without opening cold log bodies. +`session.create` returns a Session for a new conversation, and its response names the Session actually used. A named `sessionId` is reused while it is blank (no turn has started), belongs to the requested directory, is an unarchived member of the requested Workspace, and is not written by another owner; a live Session is reused in place, and a persisted one is resumed while retaining its writer lock. The reused Session runs the requested `agentPreset`, or the configured default when the request names none: its recorded preset is not resolved, and a change is logged as `agent-preset/selected` before the Agent is published. A named Session that has started, fails the Workspace placement, or is written by another owner stays unchanged, and a new Session is created instead. A `sessionId` with no stored Session becomes the new Session's identity. A named Session in another directory fails with `session/conflict`, and one owned by subagent routing with `session/agent-busy`; both checks precede preset resolution. Creations naming one identity run in arrival order, including their preset resolution, and each response reports the preset its own request left the Session running. `session.list` includes persisted blanks using cached metadata, without opening cold log bodies. Client list refreshes retain unchanged row objects and reuse the items array when order and values match. Each row's `retainedBy` contains positive local reference-source counts; Host metadata refreshes cannot overwrite them. Cache membership checks use a per-refresh ID set, so reconciliation grows linearly with the current list and retained cache sizes. Host summary updates replace running and Agent availability; local create/fork responses only fill missing metadata on existing rows. Removed ordinary Sessions retain projection stores only when their catalogs contain children. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 585c4e0363..cc5a4ce4b2 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -39,7 +39,7 @@ Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件 Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。 -显式 ID 的 `session.create` 会收养活动 Session,或恢复持久化 Session 并持续持有其写锁。写锁争用返回 `session/writer-held`;调用方可以尝试其他空白会话,同时保留其他失败。`session.list` 根据缓存元数据列出持久化空白会话,不打开冷日志正文。 +`session.create` 返回一个用于新对话的 Session,响应指明实际使用的 Session。请求指明的 `sessionId` 在满足以下条件时被复用:仍为空白(尚未开始任何轮次)、属于请求的目录、是请求的工作区中未归档的成员,且未被其他写者占用;活动 Session 原地复用,持久化 Session 被恢复并持续持有其写锁。被复用的 Session 运行请求的 `agentPreset`,请求未指明时运行配置的默认 preset:不解析它记录的 preset,变更在 Agent 发布前记录为 `agent-preset/selected`。指明的 Session 若已开始、不满足工作区归属,或被其他写者占用,则保持不变,改为新建 Session。没有对应已存储 Session 的 `sessionId` 成为新 Session 的标识。指明其他目录中的 Session 返回 `session/conflict`,指明由 subagent 路由拥有的 Session 返回 `session/agent-busy`;这两项检查先于 preset 解析。指明同一标识的创建请求按到达顺序执行,preset 解析也包含在内,每个响应报告其自身请求完成时该 Session 运行的 preset。`session.list` 根据缓存元数据列出持久化空白会话,不打开冷日志正文。 Client 列表刷新保留未变化的行对象,并在顺序和值均相同时复用条目数组。每行的 `retainedBy` 包含正数的本地引用来源计数,Host 元数据刷新不能覆盖它们。缓存成员检查使用每次刷新构建的 ID 集合,因此对账成本随当前列表和保留缓存的规模线性增长。 Host 摘要更新会替换运行状态与 Agent 可用性;本地 create/fork 响应只补充已有行缺失的元数据。普通 Session 被移除后,仅在目录仍有子项时保留其投影 store。 diff --git a/packages/api/session-controller/locale/en.json b/packages/api/session-controller/locale/en.json new file mode 100644 index 0000000000..3be8df2f2f --- /dev/null +++ b/packages/api/session-controller/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-session-controller" + } +} diff --git a/packages/api/session-controller/locale/zh.json b/packages/api/session-controller/locale/zh.json new file mode 100644 index 0000000000..48389bed43 --- /dev/null +++ b/packages/api/session-controller/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话控制接口", + "description": "向客户端提供会话读取、运行控制和状态更新能力。" + } +} diff --git a/packages/api/session-controller/package.json b/packages/api/session-controller/package.json index f8948c3aa1..436b151bbb 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -39,7 +39,8 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -58,6 +59,7 @@ "watch": "tsdown --watch" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts index 3f0fa77944..aaacc886e7 100644 --- a/packages/api/session-controller/src/agent.ts +++ b/packages/api/session-controller/src/agent.ts @@ -1,5 +1,6 @@ /** Agent activation, composition, and model-selection policy owned by API Session. */ +import { randomUUID } from 'node:crypto' import { mkdir } from 'node:fs/promises' import type { Context } from '@deepseek-ai/cordis' import { installModelSelection } from '@deepseek-ai/dsh-agent' @@ -8,11 +9,12 @@ import type { } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-agent-default-model' import type {} from '@deepseek-ai/dsh-agent-preset-registry' +import { brandString } from '@deepseek-ai/dsh-brand' import { ReasoningEffortId } from '@deepseek-ai/dsh-llm' import type { Session, SessionId } from '@deepseek-ai/dsh-session' import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence' import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query' -import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' import type {} from '@deepseek-ai/dsh-typert-registry' import type { ModelSelection } from './types.ts' @@ -42,21 +44,49 @@ export class ApiSessionCwdConflict extends Error { } } -/** Explicit-id creation attempted to adopt a Session under another preset. */ +/** Reuse of a Session named an Agent preset while the deployment composes no preset roster. */ export class ApiSessionPresetConflict extends Error { constructor( readonly sessionId: SessionId, readonly requestedPreset: string, - readonly existingPreset: string | undefined, ) { - super( - existingPreset === undefined - ? `session "${sessionId}" records no agent preset and cannot be adopted under "${requestedPreset}"` - : `session "${sessionId}" runs agent preset "${existingPreset}", not "${requestedPreset}"`, - ) + super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`) } } +/** A blank Session chosen for reuse started a turn before this Host acquired its writer. */ +class ApiSessionStartedSinceObserved extends Error {} + +/** Placement and Agent preset for one Session created for a new conversation. */ +export interface ApiSessionCreateRequest { + /** Blank Session to reuse, or the identity of a new Session when none is stored under it. */ + readonly sessionId?: SessionId + /** Directory the Session owns. */ + readonly cwd: string + /** Preset the Session runs; the configured default when omitted. */ + readonly agentPreset?: string + /** + * Placement rule the caller owns, such as Workspace membership and archive state. + * @param sessionId - existing Session named by the request. + * @returns whether that Session may be reused. + */ + readonly reusable: (sessionId: SessionId) => boolean +} + +/** The Session one creation request created or reused. */ +export interface ApiSessionCreated { + /** Live Agent of the Session. */ + readonly agent: Agent + /** Preset the Session ran when the request finished, before a later request for the same identity; absent without a roster. */ + readonly agentPreset: string | undefined +} + +/** Resolved preset and pre-publication Agent setup for one create or resume. */ +interface ApiSessionComposition { + readonly agentPreset?: string + readonly setup: AgentSetup +} + /** Failures produced while resolving one ordinary Session identity to its live Agent. */ export type ApiSessionAgentError = RemoteError<'session/not-found' | 'session/agent-busy' | 'session/writer-held' | 'gateway/internal'> @@ -139,7 +169,7 @@ export async function inspectApiSession( /** Owns every operation that may create, resume, or configure a Web Agent. */ export class ApiSessionAgentController { private readonly resumes = new Map>() - private readonly creations = new Map>() + private readonly claims = new Map>() private readonly selections = new WeakMap() private readonly imageAdmissionChains = new WeakMap>() @@ -229,50 +259,26 @@ export class ApiSessionAgentController { } /** - * Resolve one requested identity, creating or resuming it once. - * @param sessionId - requested Session identity. - * @param cwd - directory the Session must own. - * @param checkPersistedIdentity - whether to inspect a cold identity before creation. - * @param presetId - optional Agent preset the Session must own. - * @returns the matching live ordinary Agent. + * Create a Session for a new conversation, reusing the named blank Session + * while it is still reusable. A reused Session runs the requested preset, or + * the configured default when the request names none; the preset it recorded + * is not resolved, and a change is logged as `agent-preset/selected` before + * the Agent is published. A named Session that has started a turn, fails the + * caller's placement rule, or is written by another owner stays unchanged, + * and a new Session is created instead. Requests naming one identity run in + * arrival order, including their preset resolution, and check the named + * Session's directory and ownership before resolving the preset. + * @param request - optional Session to reuse, directory, preset, and placement rule. + * @returns the reused or created Session and the preset it ran when this request finished. + * @throws ApiSessionCwdConflict when the named Session belongs to another directory. + * @throws ApiSessionSubagentOwnership when subagent routing owns the named Session. + * @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset. + * @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session. */ - async ensureSession( - sessionId: SessionId, - cwd: string, - checkPersistedIdentity: boolean, - presetId?: string, - ): Promise { - let creation = this.creations.get(sessionId) - if (creation === undefined) { - creation = this.createOrAdopt(sessionId, cwd, checkPersistedIdentity, presetId) - .catch((error: unknown) => { - const live = this.ctx.agents.get(sessionId) - if (live !== undefined) { - if (hasApiSessionSubagentOwner(this.ctx, live.session, live)) { - throw new ApiSessionSubagentOwnership(sessionId) - } - return live - } - const attached = this.ctx.sessions.get(sessionId) - if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, undefined)) { - throw new ApiSessionSubagentOwnership(sessionId) - } - throw error - }) - .finally(() => { this.creations.delete(sessionId) }) - this.creations.set(sessionId, creation) - } - const agent = await creation - if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) { - throw new ApiSessionSubagentOwnership(sessionId) - } - if (presetId !== undefined) { - this.assertPresetUnchanged(sessionId, presetId, this.presetForSession(agent.session)) - } - if (agent.session.header.cwd !== cwd) { - throw new ApiSessionCwdConflict(sessionId, cwd, agent.session.header.cwd) - } - return agent + async createSession(request: ApiSessionCreateRequest): Promise { + const named = request.sessionId + if (named === undefined) return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset))) + return this.inOrder(named, async () => this.created(await this.claim(named, request))) } /** @@ -378,10 +384,7 @@ export class ApiSessionAgentController { * @param presetId - requested preset or the configured default when omitted. * @returns the resolved preset identity and Agent setup callback. */ - async composeAgent(presetId: string | undefined): Promise<{ - readonly agentPreset?: string - readonly setup: AgentSetup - }> { + async composeAgent(presetId: string | undefined): Promise { const presets = this.ctx.get('agentPresets') if (presets === undefined) { return { setup: (_agentCtx, agent) => { this.installSelection(agent) } } @@ -441,48 +444,128 @@ export class ApiSessionAgentController { })).agent } - private async createOrAdopt( - sessionId: SessionId, - cwd: string, - checkPersistedIdentity: boolean, - presetId: string | undefined, - ): Promise { + private async inOrder(sessionId: SessionId, operation: () => Promise): Promise { + const result = (this.claims.get(sessionId) ?? Promise.resolve()).then(operation) + const settled = result.then(() => undefined, () => undefined) + this.claims.set(sessionId, settled) + try { + return await result + } finally { + if (this.claims.get(sessionId) === settled) this.claims.delete(sessionId) + } + } + + /** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */ + private async claim(sessionId: SessionId, request: ApiSessionCreateRequest): Promise { const attached = this.ctx.sessions.get(sessionId) const live = this.ctx.agents.get(sessionId) if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, live)) { throw new ApiSessionSubagentOwnership(sessionId) } - if (live !== undefined) return live - - if (checkPersistedIdentity) { - try { - using observation = await this.ctx.sessionQuery.observeSession(sessionId) - if (hasApiSessionSubagentOwner(this.ctx, { header: observation.header }, undefined)) { - throw new ApiSessionSubagentOwnership(sessionId) - } - if (observation.header.cwd !== cwd) { - throw new ApiSessionCwdConflict(sessionId, cwd, observation.header.cwd) - } - const storedPreset = this.presetForObservation(observation) - this.assertPresetUnchanged(sessionId, presetId, storedPreset) - const composition = await this.composeAgent(storedPreset) - return (await this.ctx.agents.resume({ - resumeSessionId: sessionId, - agentOptions: this.agentOptions(), - setup: composition.setup, - })).agent - } catch (error: unknown) { - if (!(error instanceof SessionQueryError) - || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND') throw error + if (live !== undefined) { + if (live.session.header.cwd !== request.cwd) { + throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd) } + const composition = await this.composeAgent(request.agentPreset) + return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition) } + let observation: SessionObservation + try { + observation = await this.ctx.sessionQuery.observeSession(sessionId) + } catch (error: unknown) { + if (!(error instanceof SessionQueryError) || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND') throw error + return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset)) + } + let reusable: boolean + { + using observed = observation + if (hasApiSessionSubagentOwner(this.ctx, { header: observed.header }, undefined)) { + throw new ApiSessionSubagentOwnership(sessionId) + } + if (observed.header.cwd !== request.cwd) { + throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd) + } + reusable = request.reusable(sessionId) && !observed.events.some(event => event.type === 'turn/start') + } + const composition = await this.composeAgent(request.agentPreset) + if (!reusable) return this.createMinted(request.cwd, composition) + this.assertPresetApplicable(sessionId, request.agentPreset) + try { + return (await this.ctx.agents.resume({ + resumeSessionId: sessionId, + agentOptions: this.agentOptions(), + setup: this.reuseSetup(composition), + })).agent + } catch (error: unknown) { + if (error instanceof ApiSessionStartedSinceObserved) return this.createMinted(request.cwd, composition) + if (!(error instanceof Error) || error.name !== 'SessionAlreadyOwnedError') throw error + // Another resume in this process may hold the writer for the Agent it published. + return this.ctx.agents.get(sessionId) === undefined + ? this.createMinted(request.cwd, composition) + : this.claim(sessionId, request) + } + } + /** @returns the live blank Session under the requested preset, or undefined when it cannot be reused. */ + private async reuseLive( + live: Agent, + request: ApiSessionCreateRequest, + composition: ApiSessionComposition, + ): Promise { + if (!request.reusable(live.id) || !this.isBlank(live.session)) return undefined + this.assertPresetApplicable(live.id, request.agentPreset) + const current = this.presetForSession(live.session) + const presets = this.ctx.get('agentPresets') + const target = composition.agentPreset + if (presets === undefined || target === undefined || target === current) return live + try { + await presets.select(live, target) + } catch (error: unknown) { + if (remoteErrorOf(error)?.code !== 'agent-preset/locked') throw error + return undefined + } + return live + } + + /** Setup that re-checks blankness under the acquired writer, then records a preset change before publication. */ + private reuseSetup(composition: ApiSessionComposition): AgentSetup { + return async (agentCtx, agent) => { + if (!this.isBlank(agent.session)) throw new ApiSessionStartedSinceObserved() + const commit = await composition.setup(agentCtx, agent) + const target = composition.agentPreset + if (target !== undefined && this.presetForSession(agent.session) !== target) { + agent.session.append('agent-preset/selected', { agentPreset: target }) + } + return commit + } + } + + /** Whether no turn has started, by the predicate the preset registry's `select` enforces. */ + private isBlank(session: Session): boolean { + const boundary = this.ctx.sessionProjections.stateOf(session, 'turnBoundary') + return boundary === undefined || (boundary.openTurnStartSeq === null && boundary.lastTurn === 0) + } + + /** Without a roster, reuse cannot apply a named preset. */ + private assertPresetApplicable(sessionId: SessionId, requested: string | undefined): void { + if (requested === undefined || this.ctx.get('agentPresets') !== undefined) return + throw new ApiSessionPresetConflict(sessionId, requested) + } + + private created(agent: Agent): ApiSessionCreated { + return { agent, agentPreset: this.presetForSession(agent.session) } + } + + private createMinted(cwd: string, composition: ApiSessionComposition): Promise { + return this.createAgent(brandString(`session-${randomUUID()}`), cwd, composition) + } + + private async createAgent(sessionId: SessionId, cwd: string, composition: ApiSessionComposition): Promise { try { await mkdir(cwd, { recursive: true }) } catch (error: unknown) { throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error }) } - const composition = await this.composeAgent(presetId) return (await this.ctx.agents.create({ sessionId, agentOptions: this.agentOptions(), @@ -514,15 +597,6 @@ export class ApiSessionAgentController { } return observation.projections.values.agentPreset ?? undefined } - - private assertPresetUnchanged( - sessionId: SessionId, - requested: string | undefined, - existing: string | undefined, - ): void { - if (requested === undefined || requested === existing) return - throw new ApiSessionPresetConflict(sessionId, requested, existing) - } } function agentModelSelection(selection: ModelSelection): AgentModelSelection { diff --git a/packages/api/session-controller/src/client/contract/sessions.ts b/packages/api/session-controller/src/client/contract/sessions.ts index 08d6ad2367..a52d2c155a 100644 --- a/packages/api/session-controller/src/client/contract/sessions.ts +++ b/packages/api/session-controller/src/client/contract/sessions.ts @@ -79,14 +79,17 @@ export interface ISessions { */ readonly searchResultLimit: number /** - * Create or adopt a Session on the Host. - * @param opts - target workspace, directory, and optional preallocated identity. - * @returns the catalogued identity; retain it before borrowing its binding. + * Create a Session for a new conversation on the Host. The Host reuses the + * named blank Session while it is reusable and otherwise creates another; the + * Session runs the named preset, or the Host default when none is named. + * @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset. + * @returns the catalogued identity the Host created or reused; retain it before borrowing its binding. */ create(opts?: { workspaceId?: WorkspaceId cwd?: string sessionId?: SessionId + agentPreset?: string }): Promise /** * Resolve an already discovered direct-parent address without opening it. diff --git a/packages/api/session-controller/src/client/sessions/manager.ts b/packages/api/session-controller/src/client/sessions/manager.ts index 9c2df4ba0e..b8bec9be8a 100644 --- a/packages/api/session-controller/src/client/sessions/manager.ts +++ b/packages/api/session-controller/src/client/sessions/manager.ts @@ -502,17 +502,21 @@ export class SessionManager { * Contract session.create; on success merge into summaries immediately (no * wait for the next refresh). A created session is blank by definition * (entity birth precedes the first message). - * @param opts - target workspace or working directory, plus an optional caller-owned id. - * @returns the create result. + * @param opts - target workspace or working directory, an optional blank Session to reuse, and an optional Agent preset. + * @returns the create result, naming the Session the Host created or reused. */ async create( opts: { workspaceId?: WorkspaceId cwd?: string sessionId?: SessionId + agentPreset?: string } = {}, ): Promise> { - const shared = opts.sessionId === undefined ? {} : { sessionId: opts.sessionId } + const shared = { + ...(opts.sessionId === undefined ? {} : { sessionId: opts.sessionId }), + ...(opts.agentPreset === undefined ? {} : { agentPreset: opts.agentPreset }), + } const payload = opts.workspaceId !== undefined ? { workspaceId: opts.workspaceId, ...shared } : { ...(opts.cwd === undefined ? {} : { cwd: opts.cwd }), ...shared } diff --git a/packages/api/session-controller/src/client/sessions/service.ts b/packages/api/session-controller/src/client/sessions/service.ts index dd86e7cac2..b992a34920 100644 --- a/packages/api/session-controller/src/client/sessions/service.ts +++ b/packages/api/session-controller/src/client/sessions/service.ts @@ -427,11 +427,16 @@ export class ClientSessions implements ISessions { /** * Create a Host Session and publish its catalog row before resolving. * Callers retain the returned identity before borrowing its binding. - * @param opts - target workspace or directory and an optional preallocated id. - * @returns the new session id. + * @param opts - target workspace or directory, an optional blank Session to reuse, and an optional Agent preset. + * @returns the created or reused session id. * @throws {SessionCreateError} with the requested id. */ - async create(opts: { workspaceId?: WorkspaceId; cwd?: string; sessionId?: SessionId } = {}): Promise { + async create(opts: { + workspaceId?: WorkspaceId + cwd?: string + sessionId?: SessionId + agentPreset?: string + } = {}): Promise { const result = await this.manager.create(opts) if (!result.ok) throw new SessionCreateError(result.error, opts.sessionId) this.projectList() diff --git a/packages/api/session-controller/src/commands.ts b/packages/api/session-controller/src/commands.ts index 7e900b92ae..5bb0a7039d 100644 --- a/packages/api/session-controller/src/commands.ts +++ b/packages/api/session-controller/src/commands.ts @@ -33,6 +33,7 @@ import { apiSessionSubagentOwnershipError, hasApiSessionSubagentOwner, inspectApiSession, + type ApiSessionCreated, } from './agent.ts' import type { SessionAttachmentRequest, @@ -98,15 +99,15 @@ export class SessionCommandController { ) {} /** - * Create or idempotently adopt one ordinary Session. - * @param request - requested identity, location, and Agent preset. - * @returns the Session identity and resolved preset when configured. + * Create one ordinary Session for a new conversation, reusing the named + * blank Session while it is an unarchived member of the requested Workspace. + * @param request - optional blank Session to reuse, location, and Agent preset. + * @returns the created or reused Session identity and its preset when configured. */ async create(request: SessionCreateRequest): Promise { if (request.workspaceId !== undefined && request.cwd !== undefined) { throw new RemoteError('gateway/bad-request', 'session.create accepts workspaceId or cwd, not both', {}) } - const sessionId = request.sessionId ?? brandString(`session-${randomUUID()}`) let workspace: Workspace | undefined if (request.workspaceId !== undefined) { workspace = this.ctx.workspaceRegistry.get(request.workspaceId) @@ -117,17 +118,19 @@ export class SessionCommandController { } } const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd - let adopted: Agent + let created: ApiSessionCreated try { - adopted = await this.agents.ensureSession( - sessionId, + created = await this.agents.createSession({ + ...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }), cwd, - request.sessionId !== undefined, - request.agentPreset, - ) + ...(request.agentPreset === undefined ? {} : { agentPreset: request.agentPreset }), + reusable: sessionId => !this.ctx.workspaceRegistry.archivedSessionIds.includes(sessionId) + && (workspace === undefined || workspace.sessionIds.includes(sessionId)), + }) } catch (error) { - this.rejectCreation(sessionId, error) + this.rejectCreation(error) } + const sessionId = created.agent.id if (workspace !== undefined) { try { await workspace.attachSession(sessionId) @@ -139,8 +142,7 @@ export class SessionCommandController { ) } } - const agentPreset = this.agents.presetForSession(adopted.session) - return { sessionId, ...(agentPreset === undefined ? {} : { agentPreset }) } + return { sessionId, ...(created.agentPreset === undefined ? {} : { agentPreset: created.agentPreset }) } } /** @@ -530,16 +532,12 @@ export class SessionCommandController { return found.agent } - private rejectCreation(sessionId: SessionId, error: unknown): never { + private rejectCreation(error: unknown): never { if (remoteErrorOf(error) !== undefined) throw error - if (error instanceof Error && error.name === 'SessionAlreadyOwnedError') { - throw new RemoteError('session/writer-held', error.message, { sessionId }) - } if (error instanceof ApiSessionPresetConflict) { throw new RemoteError('agent-preset/conflict', error.message, { sessionId: error.sessionId, requestedPreset: error.requestedPreset, - ...(error.existingPreset === undefined ? {} : { existingPreset: error.existingPreset }), }) } if (error instanceof ApiSessionCwdConflict) { @@ -552,7 +550,7 @@ export class SessionCommandController { if (error instanceof ApiSessionSubagentOwnership) { throw apiSessionSubagentOwnershipError(error.sessionId) } - throw new RemoteError('gateway/internal', `failed to create session "${sessionId}": ${String(error)}`, {}) + throw new RemoteError('gateway/internal', `failed to create session: ${String(error)}`, {}) } private async readSessionState(sessionId: SessionId): Promise { diff --git a/packages/api/session-controller/src/index.ts b/packages/api/session-controller/src/index.ts index 0ba5bf8ff0..b28be14073 100644 --- a/packages/api/session-controller/src/index.ts +++ b/packages/api/session-controller/src/index.ts @@ -273,9 +273,9 @@ export class SessionController extends TypertRemoteService { } /** - * Create or idempotently adopt one ordinary Session. - * @param request - requested identity, location, and Agent preset. - * @returns the Session identity and resolved preset when configured. + * Create one ordinary Session for a new conversation, reusing the named blank Session while it is reusable. + * @param request - optional blank Session to reuse, location, and Agent preset. + * @returns the created or reused Session identity and its preset when configured. */ @Remote('create') create(request: SessionCreateRequest): Promise { diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index 3455db1b9f..03878bfae7 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -219,7 +219,6 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'agent-preset/conflict': { readonly sessionId: SessionId readonly requestedPreset: string - readonly existingPreset?: string } 'session/attachment-invalid': { readonly reason: string } 'session/queue-item-not-found': { readonly itemId: MessageId } @@ -284,17 +283,23 @@ export interface SessionSearchValue { readonly hasMore: boolean } -/** Session creation or explicit-id adoption request. */ +/** Request for a Session for a new conversation. */ export interface SessionCreateRequest { + /** Workspace the Session joins; exclusive with `cwd`. */ readonly workspaceId?: WorkspaceId + /** Directory the Session owns when no Workspace is named. */ readonly cwd?: string + /** Blank Session to reuse while it is reusable, or the identity of a new Session when none is stored under it. */ readonly sessionId?: SessionId + /** Preset the Session runs, replacing a reused Session's recorded preset; the configured default when omitted. */ readonly agentPreset?: string } /** Session creation response value. */ export interface SessionCreateValue { + /** The created or reused Session, which may differ from the requested `sessionId`. */ readonly sessionId: SessionId + /** Preset the Session runs, when the deployment composes a preset roster. */ readonly agentPreset?: string } diff --git a/packages/api/session-controller/tests/agent.host.spec.ts b/packages/api/session-controller/tests/agent.host.spec.ts index 4756ae45b0..40dceeefb9 100644 --- a/packages/api/session-controller/tests/agent.host.spec.ts +++ b/packages/api/session-controller/tests/agent.host.spec.ts @@ -6,7 +6,7 @@ import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry' import SessionStore, { SESSION_FORMAT_VERSION, SessionLogOffset, SessionId } from '@deepseek-ai/dsh-session' -import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' +import type { SessionHeader } from '@deepseek-ai/dsh-session' import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence' import type { SessionObservation } from '@deepseek-ai/dsh-session-query' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' @@ -15,7 +15,6 @@ import { ApiSessionAgentController, ApiSessionCwdConflict, ApiSessionNotFound, - ApiSessionSubagentOwnership, inspectApiSession, } from '../src/agent.ts' import { installModelSelectionProjection } from '../src/model-selection-projection.ts' @@ -329,123 +328,8 @@ describe('ApiSession model selection', () => { }) }) -describe('ApiSession create or adoption', () => { - it('shares one in-flight creation between concurrent callers', async () => { - const { ctx, agents } = await harness() - const cwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-concurrent-')) - tempDirs.push(cwd) - const meta = header('concurrent-create', cwd) - const created = unpublishedAgent(ctx, meta) - let release!: () => void - const gate = new Promise((resolve) => { release = resolve }) - const create = vi.spyOn(ctx.agents, 'create').mockImplementation(async () => { - await gate - return { agent: created, dispose: () => Promise.resolve() } - }) - - const first = agents.ensureSession(meta.id, cwd, false) - const second = agents.ensureSession(meta.id, cwd, false) - release() - - await expect(Promise.all([first, second])).resolves.toEqual([created, created]) - expect(create).toHaveBeenCalledOnce() - }) - - it('accepts a raced ordinary creation and rejects a raced attached child', async () => { - const ordinary = await harness() - const cwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-create-')) - tempDirs.push(cwd) - const ordinaryMeta = header('create-race', cwd) - const winner = agent(ordinary.ctx, ordinaryMeta) - vi.spyOn(ordinary.ctx.agents, 'create').mockImplementation(async () => { - await ordinary.ctx.agents.register(winner) - throw new Error('raced creation') - }) - await expect(ordinary.agents.ensureSession(ordinaryMeta.id, cwd, false)) - .resolves.toBe(winner) - - const child = await harness() - const childCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-child-')) - tempDirs.push(childCwd) - const childId = SessionId('create-child-race') - vi.spyOn(child.ctx.agents, 'create').mockImplementation(async () => { - child.ctx.sessions.create(childId, { - meta: { cwd: childCwd, parentSession: SessionId('parent'), origin: 'subagent' }, - }) - throw new Error('raced child creation') - }) - await expect(child.agents.ensureSession(childId, childCwd, false)) - .rejects.toBeInstanceOf(ApiSessionSubagentOwnership) - }) - - it('validates ownership and cwd on the Agent returned by creation', async () => { - const child = await harness() - const childCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-returned-child-')) - tempDirs.push(childCwd) - const childMeta = { - ...header('returned-child', childCwd), - parentSession: SessionId('parent'), - origin: 'subagent' as const, - } - const childAgent = unpublishedAgent(child.ctx, childMeta) - vi.spyOn(child.ctx.agents, 'create').mockResolvedValue({ - agent: childAgent, - dispose: () => Promise.resolve(), - }) - await expect(child.agents.ensureSession(childMeta.id, childCwd, false)) - .rejects.toBeInstanceOf(ApiSessionSubagentOwnership) - - const wrong = await harness() - const requestedCwd = mkdtempSync(join(tmpdir(), 'dsh-session-controller-wrong-cwd-')) - tempDirs.push(requestedCwd) - const wrongAgent = unpublishedAgent(wrong.ctx, header('wrong-returned-cwd', '/other')) - vi.spyOn(wrong.ctx.agents, 'create').mockResolvedValue({ - agent: wrongAgent, - dispose: () => Promise.resolve(), - }) - await expect(wrong.agents.ensureSession(wrongAgent.id, requestedCwd, false)) - .rejects.toBeInstanceOf(ApiSessionCwdConflict) - }) - - it('resumes a matching persisted identity and preserves its selected preset', async () => { - const { ctx, agents } = await harness() - const meta = { ...header('stored'), agentPreset: 'minimal' } - const events = [{ - type: 'agent-preset/selected', - seq: 0, - time: 1, - data: { agentPreset: 'minimal' }, - }] as SessionEvent[] - providePersistence(ctx, { - list: () => Promise.resolve([meta]), - inspect: () => Promise.resolve({ meta, events }), - }) - ctx.provide('agentPresets', { - resolve: (id?: string) => Promise.resolve({ id: id ?? 'minimal' }), - mount: () => Promise.resolve(), - } as never) - const resumed = { - id: meta.id, - session: { - id: meta.id, - header: meta, - snapshotEvents: () => events, - eventAt: (seq: number) => events[seq], - seq: events.length, - }, - status: 'idle', - ctx, - } as unknown as Agent - const resume = vi.spyOn(ctx.agents, 'resume').mockResolvedValue({ - agent: resumed, - dispose: () => Promise.resolve(), - }) - - await expect(agents.ensureSession(meta.id, '/workspace', true, 'minimal')).resolves.toBe(resumed) - expect(resume).toHaveBeenCalledWith(expect.objectContaining({ resumeSessionId: meta.id })) - }) - - it('rejects an ownership race before resume and a persisted cwd conflict', async () => { +describe('ApiSession creation', () => { + it('rejects a resume that subagent routing adopts before publication', async () => { const child = await harness() const childMeta = header('resume-child-race') providePersistence(child.ctx, { @@ -464,15 +348,6 @@ describe('ApiSession create or adoption', () => { await expect(child.agents.resolveAgent(childMeta.id)).resolves.toMatchObject({ error: { code: 'session/agent-busy' }, }) - - const conflict = await harness() - const stored = header('stored-cwd-conflict', '/stored') - providePersistence(conflict.ctx, { - list: () => Promise.resolve([stored]), - inspect: () => Promise.resolve({ meta: stored, events: [] }), - }) - await expect(conflict.agents.ensureSession(stored.id, '/requested', true)) - .rejects.toBeInstanceOf(ApiSessionCwdConflict) }) it('surfaces directory creation failure', async () => { @@ -481,7 +356,7 @@ describe('ApiSession create or adoption', () => { tempDirs.push(parent) const file = join(parent, 'file') writeFileSync(file, 'not a directory') - await expect(agents.ensureSession(SessionId('mkdir-failure'), join(file, 'child'), false)) + await expect(agents.createSession({ cwd: join(file, 'child'), reusable: () => true })) .rejects.toThrow('failed to ensure project directory') }) }) diff --git a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts index 87bdc5a399..f43ce3f116 100644 --- a/packages/api/session-controller/tests/commands-create-fork.host.spec.ts +++ b/packages/api/session-controller/tests/commands-create-fork.host.spec.ts @@ -5,11 +5,14 @@ import type {} from '@deepseek-ai/dsh-agent-preset-registry' import { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import type { Workspace, WorkspaceId } from '@deepseek-ai/dsh-workspace' import { describe, expect, it, vi } from 'vitest' import { ApiSessionAgentController, ApiSessionCwdConflict, + type ApiSessionCreated, + type ApiSessionCreateRequest, } from '../src/agent.ts' import { SessionCommandController } from '../src/commands.ts' import { installSessionReadTestServices, testSessionPersistence } from './test-remote.ts' @@ -18,18 +21,31 @@ async function expectFailure(operation: Promise, code: string): Promise await expect(operation).rejects.toMatchObject({ code }) } -function controllerAgents(overrides: object = {}): ApiSessionAgentController { - return { - ensureSession: () => Promise.resolve(), - composeAgent: () => Promise.resolve({ setup: () => {} }), - presetForSession: () => undefined, - presetForObservation: () => undefined, - ...overrides, - } as unknown as ApiSessionAgentController +/** The Agent controller with a fixed Agent composition, and optionally a fixed creation outcome. */ +function controllerAgents( + ctx: Context, + fixed: { + readonly composeAgent?: ApiSessionAgentController['composeAgent'] + readonly createSession?: ApiSessionAgentController['createSession'] + } = {}, +): ApiSessionAgentController { + const agents = new ApiSessionAgentController(ctx) + vi.spyOn(agents, 'composeAgent').mockImplementation(fixed.composeAgent ?? (() => Promise.resolve({ setup: () => {} }))) + if (fixed.createSession !== undefined) vi.spyOn(agents, 'createSession').mockImplementation(fixed.createSession) + return agents +} + +/** A creation outcome that publishes `sessionId` in `cwd` as a stand-in Agent. */ +function publishedSession(ctx: Context, sessionId: SessionId) { + return (request: ApiSessionCreateRequest): Promise => { + const session = ctx.sessions.create(sessionId, { meta: { cwd: request.cwd } }) + return Promise.resolve({ agent: { id: session.id, session, status: 'idle', ctx } as Agent, agentPreset: undefined }) + } } async function baseContext(): Promise { const ctx = new Context() + await ctx.plugin(TypertRegistry) await ctx.plugin(SessionStore) await ctx.plugin(AgentRegistry) installSessionReadTestServices(ctx) @@ -41,29 +57,19 @@ async function baseContext(): Promise { } describe('Session creation failures', () => { - it('mints an identity with the default cwd when no explicit target is supplied', async () => { + it('creates in the default cwd without a named identity when no explicit target is supplied', async () => { const ctx = await baseContext() - ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never) - const ensureSession = vi.fn((sessionId: SessionId, cwd: string) => { - const session = ctx.sessions.create(sessionId, { meta: { cwd } }) - return Promise.resolve({ id: sessionId, session } as Agent) - }) - const controller = new SessionCommandController( - ctx, - controllerAgents({ ensureSession }), - '/default-workspace', - ) + ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [], archivedSessionIds: [] } as never) + const createSession = vi.fn(publishedSession(ctx, SessionId('session-minted'))) + const controller = new SessionCommandController(ctx, controllerAgents(ctx, { createSession }), '/default-workspace') const created = await controller.create({}) - expect(created.sessionId).toMatch(/^session-/) - expect(created).not.toHaveProperty('agentPreset') - expect(ensureSession).toHaveBeenCalledWith( - created.sessionId, - '/default-workspace', - false, - undefined, - ) + expect(created).toEqual({ sessionId: 'session-minted' }) + expect(createSession).toHaveBeenCalledOnce() + const request = createSession.mock.calls[0]?.[0] + expect(request?.cwd).toBe('/default-workspace') + expect(Object.keys(request ?? {}).sort()).toEqual(['cwd', 'reusable']) await ctx.fiber.dispose() }) @@ -72,7 +78,7 @@ describe('Session creation failures', () => { missing.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never) const missingController = new SessionCommandController( missing, - controllerAgents(), + controllerAgents(missing), '/default', ) await expectFailure(missingController.create({ @@ -92,7 +98,7 @@ describe('Session creation failures', () => { } as never) const failedController = new SessionCommandController( failed, - controllerAgents(), + controllerAgents(failed, { createSession: publishedSession(failed, SessionId('workspace-session')) }), '/default', ) await expectFailure(failedController.create({ @@ -119,10 +125,6 @@ describe('Session creation failures', () => { error: new ApiSessionCwdConflict(SessionId('wrong-cwd'), '/requested', '/stored'), code: 'session/conflict', }, - { - error: Object.assign(new Error('writer already held'), { name: 'SessionAlreadyOwnedError' }), - code: 'session/writer-held', - }, { error: new Error('factory unavailable'), code: 'gateway/internal', @@ -132,7 +134,7 @@ describe('Session creation failures', () => { ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [] } as never) const controller = new SessionCommandController( ctx, - controllerAgents({ ensureSession: () => Promise.reject(error) }), + controllerAgents(ctx, { createSession: () => Promise.reject(error) }), '/default', ) @@ -144,7 +146,7 @@ describe('Session creation failures', () => { it('rejects contradictory create targets', async () => { const ctx = await baseContext() - const controller = new SessionCommandController(ctx, controllerAgents(), '/default') + const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default') await expectFailure(controller.create({ workspaceId: 'workspace-1' as WorkspaceId, @@ -184,7 +186,7 @@ describe('Session fork failures', () => { const withoutPersistence = await baseContext() withoutPersistence.provide('workspaceRegistry', { list: () => [] } as never) const unavailableController = new SessionCommandController( - withoutPersistence, controllerAgents(), '/default', + withoutPersistence, controllerAgents(withoutPersistence), '/default', ) await expectFailure(unavailableController.fork({ sessionId: SessionId('missing'), @@ -197,7 +199,7 @@ describe('Session fork failures', () => { list: () => Promise.resolve([]), inspect: vi.fn(), }) as never) - const missingController = new SessionCommandController(missing, controllerAgents(), '/default') + const missingController = new SessionCommandController(missing, controllerAgents(missing), '/default') await expectFailure(missingController.fork({ sessionId: SessionId('missing'), }), 'session/not-found') @@ -208,7 +210,7 @@ describe('Session fork failures', () => { const ctx = await baseContext() ctx.provide('workspaceRegistry', { list: () => [] } as never) vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValue(new Error('storage offline')) - const controller = new SessionCommandController(ctx, controllerAgents(), '/default') + const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default') await expectFailure(controller.fork({ sessionId: SessionId('unreadable') }), 'gateway/internal') await ctx.fiber.dispose() @@ -218,7 +220,7 @@ describe('Session fork failures', () => { const ctx = await baseContext() ctx.provide('workspaceRegistry', { list: () => [] } as never) const source = ctx.sessions.create(SessionId('empty-source')) - const controller = new SessionCommandController(ctx, controllerAgents(), '/default') + const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default') await expectFailure(controller.fork({ sessionId: source.id }), 'session/fork-unavailable') await expect(controller.fork({ sessionId: source.id, atSeq: 0 })).rejects.toMatchObject({ @@ -237,7 +239,7 @@ describe('Session fork failures', () => { parentSession: SessionId('parent'), origin: 'subagent', }) - const lineageController = new SessionCommandController(lineage, controllerAgents(), '/default') + const lineageController = new SessionCommandController(lineage, controllerAgents(lineage), '/default') await expectFailure(lineageController.fork({ sessionId: child.id }), 'gateway/internal') await lineage.fiber.dispose() @@ -245,7 +247,7 @@ describe('Session fork failures', () => { creation.provide('workspaceRegistry', { list: () => [] } as never) const source = completedSession(creation, 'creation-source', '/workspace') vi.spyOn(creation.agents, 'create').mockRejectedValue(new Error('factory failed')) - const creationController = new SessionCommandController(creation, controllerAgents(), '/default') + const creationController = new SessionCommandController(creation, controllerAgents(creation), '/default') await expectFailure(creationController.fork({ sessionId: source.id }), 'gateway/internal') await creation.fiber.dispose() }) @@ -262,7 +264,7 @@ describe('Session fork failures', () => { const create = vi.spyOn(ctx.agents, 'create').mockImplementation( (options: CreateAgentOptions) => Promise.resolve(resolvedHandle(ctx, options.sessionId)), ) - const controller = new SessionCommandController(ctx, controllerAgents(), '/default') + const controller = new SessionCommandController(ctx, controllerAgents(ctx), '/default') await expectFailure(controller.fork({ sessionId: source.id }), 'session/workspace-attach-failed') const options = create.mock.calls[0]?.[0] @@ -279,7 +281,7 @@ describe('Session fork failures', () => { const create = vi.spyOn(ctx.agents, 'create').mockImplementation( (options: CreateAgentOptions) => Promise.resolve(resolvedHandle(ctx, options.sessionId)), ) - const controller = new SessionCommandController(ctx, controllerAgents({ + const controller = new SessionCommandController(ctx, controllerAgents(ctx, { composeAgent: () => Promise.resolve({ agentPreset: 'minimal', setup: () => {} }), }), '/default') diff --git a/packages/api/session-controller/tests/manager.client.spec.ts b/packages/api/session-controller/tests/manager.client.spec.ts index 2097854412..bcf4a033be 100644 --- a/packages/api/session-controller/tests/manager.client.spec.ts +++ b/packages/api/session-controller/tests/manager.client.spec.ts @@ -1194,6 +1194,17 @@ describe('remaining branches', () => { expect(await manager.create()).toMatchObject({ ok: false }) }) + it('create forwards the requested Agent preset and catalogs the identity the Host returns', async ({ mock, remote }) => { + remote.session.create.mockResolvedValue(ok({ sessionId: S2, agentPreset: 'minimal' })) + const manager = makeManager(mock, remote) + + const result = await manager.create({ workspaceId: 'w1' as never, sessionId: S1, agentPreset: 'minimal' }) + + expect(remote.session.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: 'w1', sessionId: S1, agentPreset: 'minimal' }) + expect(result).toMatchObject({ ok: true, value: { sessionId: S2 } }) + expect(manager.getListSnapshot().items.map(item => item.sessionId)).toEqual([S2]) + }) + it.for(['create', 'fork'] as const)('preserves pushed running state when a %s response arrives later', async (operation, { mock, remote }) => { const response = Promise.withResolvers>>() remote.session[operation].mockImplementation(() => response.promise) diff --git a/packages/api/session-controller/tests/session-presets.host.spec.ts b/packages/api/session-controller/tests/session-presets.host.spec.ts index 5406d235f8..0fc3132fe7 100644 --- a/packages/api/session-controller/tests/session-presets.host.spec.ts +++ b/packages/api/session-controller/tests/session-presets.host.spec.ts @@ -1,4 +1,4 @@ -/** Session creation and adoption rules for Agent preset identity. */ +/** Session creation, blank-Session reuse, and Agent preset identity through `session.create`. */ import { mkdtempSync, realpathSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -6,12 +6,14 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentFactory } from '@deepseek-ai/dsh-agent' +import { turnBoundaryProjectionDefinition } from '@deepseek-ai/dsh-agent-loop' import { agentPresetProjectionDefinition } from '@deepseek-ai/dsh-agent-preset-registry' -import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' -import type { Session } from '@deepseek-ai/dsh-session' +import SessionStore, { SESSION_FORMAT_VERSION, SessionId, SessionSeq } from '@deepseek-ai/dsh-session' +import type { Session, SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' -import { afterEach, describe, expect, it } from 'vitest' -import { createSessionTestRemote } from './test-remote.ts' +import type { WorkspaceId } from '@deepseek-ai/dsh-workspace' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createSessionTestRemote, testSessionPersistence } from './test-remote.ts' /** Booted contexts and their temp roots, torn down after each test. */ const contexts: Context[] = [] @@ -25,53 +27,137 @@ function stubAgent(session: Session): Agent { return { id: session.id, session, status: 'idle' } as unknown as Agent } -function roster(ids: readonly string[]): unknown { - const presetOf = (id: string): object => ({ - id, - trust: 'system', - }) - return { - defaultId: ids[0], - resolve: (id?: string) => { - const wanted = id ?? ids[0] ?? '' - if (!ids.includes(wanted)) { - return Promise.reject(new RemoteError( - 'agent-preset/not-found', - `agent-presets: preset "${wanted}" not found (available: ${ids.join(', ') || 'none'})`, - { agentPreset: wanted, available: ids }, - )) - } - return Promise.resolve(presetOf(wanted)) - }, - mount: (_ctx: Context, id?: string) => Promise.resolve(presetOf(id ?? ids[0] ?? '')), - } +/** A stored Session the persistence double serves until an Agent resumes it. */ +interface StoredSession { + readonly header: SessionHeader + readonly events: readonly SessionEvent[] } -async function harness(presets?: readonly string[]) { +interface HarnessOptions { + /** Declared presets; the first is the default. Omitted, no roster is composed. */ + readonly presets?: readonly string[] + /** Stored Sessions keyed by id. */ + readonly stored?: ReadonlyMap + /** Stored Sessions whose writer another owner holds. */ + readonly held?: ReadonlySet + /** Stored Sessions another resume in this process publishes while this one waits for the writer. */ + readonly publishedByOtherResume?: ReadonlySet + /** Stored Sessions whose storage fails to open for writing. */ + readonly unreadable?: ReadonlySet + /** Events a resume finds beyond the stored log, as when another Host wrote after the observation. */ + readonly writtenSinceObservation?: ReadonlyMap + /** Live Sessions whose preset switch the roster refuses as already started. */ + readonly locked?: ReadonlySet + /** Declared presets whose activation failed. */ + readonly broken?: ReadonlySet + /** Requested presets whose resolution waits for the paired promise. */ + readonly resolving?: ReadonlyMap> + /** Workspace placement served to `workspaceId` requests. */ + readonly workspace?: { readonly members: readonly SessionId[]; readonly archived: readonly SessionId[] } +} + +const WORKSPACE = 'workspace-1' as WorkspaceId + +async function harness(options: HarnessOptions = {}) { const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-'))) tempDirs.push(cwd) const ctx = new Context() contexts.push(ctx) await ctx.plugin(SessionStore) await ctx.plugin(AgentRegistry) + const presets = options.presets + const selections: { sessionId: SessionId; agentPreset: string }[] = [] + const resumed: SessionId[] = [] if (presets !== undefined) { - ctx.provide('agentPresets', roster(presets) as never) + const known = (id?: string): string => { + const wanted = id ?? presets[0] ?? '' + if (!presets.includes(wanted)) { + throw new RemoteError('agent-preset/not-found', `Unknown agent preset: ${wanted}`, { + agentPreset: wanted, available: [...presets], + }) + } + return wanted + } + const usable = (id?: string): string => { + const wanted = known(id) + if (options.broken?.has(wanted) === true) { + throw new RemoteError('agent-preset/invalid', 'activation failed', { agentPreset: wanted, reason: 'activation failed' }) + } + return wanted + } + ctx.provide('agentPresets', { + defaultId: presets[0], + resolve: (id?: string) => Promise.resolve(id === undefined ? undefined : options.resolving?.get(id)) + .then(() => ({ id: known(id) })), + mount: (_ctx: Context, id?: string) => Promise.resolve().then(() => ({ id: usable(id) })), + select: async (agent: Agent, agentPreset: string) => { + usable(agentPreset) + if (options.locked?.has(agent.id) === true) { + throw new RemoteError('agent-preset/locked', 'This session has already started', { + sessionId: agent.id, agentPreset, + }) + } + selections.push({ sessionId: agent.id, agentPreset }) + agent.session.append('agent-preset/selected', { agentPreset }) + return agentPreset + }, + } as never) } - - const factory: AgentFactory = { - async createAgent(_ownerCtx, options) { - const session = ctx.sessions.create( - options.sessionId, - options.meta === undefined ? {} : { meta: options.meta }, - ) - const agent = stubAgent(session) - ;(agent as { ctx?: Context }).ctx = ctx - await options.setup?.(ctx, agent) - const unregister = await ctx.agents.register(agent) - return { agent, dispose: async () => { await unregister() } } + const stored = options.stored ?? new Map() + ctx.provide('sessionPersistence', testSessionPersistence(ctx, { + list: () => Promise.resolve([...stored.values()].map(record => record.header)), + inspect: (id: SessionId) => { + const record = stored.get(id) + return Promise.resolve(record === undefined ? undefined : { meta: record.header, events: [...record.events] }) }, - async resume() { - throw new Error('test harness has no persisted sessions') + }) as never) + const { members, archived } = options.workspace ?? { members: [], archived: [] } + const workspace = { id: WORKSPACE, path: cwd, sessionIds: members, attachSession: () => Promise.resolve() } + ctx.provide('workspaceRegistry', { + get: (id: WorkspaceId) => id === WORKSPACE ? workspace : undefined, + list: () => [workspace], + archivedSessionIds: archived, + } as never) + + /** Run setup on the unpublished Session, then publish it and its Agent, as the Agent factory does. */ + const publish = async ( + session: Session, + setup: Parameters[1]['setup'], + ): Promise<{ agent: Agent; dispose: () => Promise }> => { + const agent = stubAgent(session) + ;(agent as { ctx?: Context }).ctx = ctx + await setup?.(ctx, agent) + ctx.effect(function* () { + yield ctx.sessions.enter(session) + ctx.sessions.announce(session) + }, 'test: published Session') + const unregister = await ctx.agents.register(agent) + return { agent, dispose: async () => { await unregister() } } + } + const factory: AgentFactory = { + async createAgent(_ownerCtx, create) { + const session = ctx.sessions.prepare(create.sessionId, create.meta === undefined ? {} : { meta: create.meta }) + return publish(session, create.setup) + }, + async resume(_ownerCtx, resume) { + const id = resume.resumeSessionId + if (options.held?.has(id) === true) { + throw Object.assign(new Error(`session "${id}" is written by another owner`), { name: 'SessionAlreadyOwnedError' }) + } + const record = stored.get(id) + if (record === undefined || options.unreadable?.has(id) === true) { + throw new Error(`test persistence cannot open Session "${id}" for writing`) + } + if (options.publishedByOtherResume?.has(id) === true) { + await publish(ctx.sessions.prepare(id, { meta: record.header, seed: [...record.events] }), undefined) + throw Object.assign(new Error(`session "${id}" is written by this process`), { name: 'SessionAlreadyOwnedError' }) + } + resumed.push(id) + const session = ctx.sessions.prepare(id, { + meta: record.header, + seed: [...record.events, ...options.writtenSinceObservation?.get(id) ?? []], + }) + return publish(session, resume.setup) }, } ctx.agents.setFactory(factory) @@ -79,13 +165,43 @@ async function harness(presets?: readonly string[]) { defaultModelSelection: () => ({ provider: 'test', model: 'test-model' }), cwd, }) + ctx.sessionProjections.register(turnBoundaryProjectionDefinition) if (presets !== undefined) ctx.sessionProjections.register(agentPresetProjectionDefinition) - return { ctx, remote } + const presetOf = (id: SessionId): string | null | undefined => { + const session = ctx.sessions.get(id) + return session === undefined ? undefined : ctx.sessionProjections.stateOf(session, 'agentPreset') + } + const selectedEvents = (id: SessionId): unknown[] => { + const session = ctx.sessions.get(id) + return session === undefined ? [] : session.snapshotEvents() + .filter(event => event.type === 'agent-preset/selected') + .map(event => event.data) + } + return { ctx, remote, cwd, selections, resumed, presetOf, selectedEvents } +} + +function storedHeader(id: SessionId, cwd: string, extra: Partial = {}): SessionHeader { + return { version: SESSION_FORMAT_VERSION, id, createdAt: 1, isSeeded: false, cwd, ...extra } +} + +function modelSelection(seq: number): SessionEvent { + return { type: 'model/selection', seq: SessionSeq(seq), time: 1, data: { provider: 'test', model: 'test-model' } } +} + +function presetSelection(seq: number, agentPreset: string): SessionEvent { + return { type: 'agent-preset/selected', seq: SessionSeq(seq), time: 1, data: { agentPreset } } +} + +function completedTurn(seq: number): SessionEvent[] { + return [ + { type: 'turn/start', seq: SessionSeq(seq), time: 1, data: { turn: 1 } }, + { type: 'turn/end', seq: SessionSeq(seq + 1), time: 2, data: { turn: 1, reason: { kind: 'completed' } } }, + ] } describe('session.create Agent preset identity', () => { it('records the requested preset on the Session header', async () => { - const { ctx, remote } = await harness(['standard', 'minimal']) + const { ctx, remote } = await harness({ presets: ['standard', 'minimal'] }) const created = await remote.create({ sessionId: SessionId('s1'), agentPreset: 'minimal' }) @@ -94,7 +210,7 @@ describe('session.create Agent preset identity', () => { }) it('records the roster default when the caller names no preset', async () => { - const { ctx, remote } = await harness(['standard', 'minimal']) + const { ctx, remote } = await harness({ presets: ['standard', 'minimal'] }) await remote.create({ sessionId: SessionId('s2') }) @@ -102,55 +218,13 @@ describe('session.create Agent preset identity', () => { }) it('rejects an unknown preset', async () => { - const { remote } = await harness(['standard']) + const { remote } = await harness({ presets: ['standard'] }) const response = await remote.create({ sessionId: SessionId('s3'), agentPreset: 'nope' }) expect(response).toMatchObject({ ok: false, error: { code: 'agent-preset/not-found' } }) }) - it('refuses to adopt a live Session under a different preset', async () => { - const { remote } = await harness(['standard', 'minimal']) - await remote.create({ sessionId: SessionId('s4'), agentPreset: 'minimal' }) - - const response = await remote.create({ sessionId: SessionId('s4'), agentPreset: 'standard' }) - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'agent-preset/conflict', - details: { - sessionId: 's4', - requestedPreset: 'standard', - existingPreset: 'minimal', - }, - }, - }) - }) - - it('adopts a live Session under the preset selected in its log', async () => { - const { ctx, remote } = await harness(['standard', 'minimal']) - await remote.create({ sessionId: SessionId('s4b'), agentPreset: 'standard' }) - ctx.sessions.get(SessionId('s4b'))?.append('agent-preset/selected', { agentPreset: 'minimal' }) - - const adopted = await remote.create({ sessionId: SessionId('s4b'), agentPreset: 'minimal' }) - const stale = await remote.create({ sessionId: SessionId('s4b'), agentPreset: 'standard' }) - - expect(adopted).toMatchObject({ ok: true, value: { agentPreset: 'minimal' } }) - expect(stale).toMatchObject({ - ok: false, - error: { details: { existingPreset: 'minimal' } }, - }) - }) - - it('adopts a live Session unchanged when the caller names no preset', async () => { - const { remote } = await harness(['standard', 'minimal']) - await remote.create({ sessionId: SessionId('s5'), agentPreset: 'minimal' }) - - await expect(remote.create({ sessionId: SessionId('s5') })) - .resolves.toMatchObject({ ok: true }) - }) - it('leaves the header preset-less when no roster is composed', async () => { const { ctx, remote } = await harness() @@ -158,6 +232,195 @@ describe('session.create Agent preset identity', () => { expect(ctx.sessions.get(SessionId('s6'))?.header.agentPreset).toBeUndefined() }) +}) + +describe('session.create reuse of a live blank Session', () => { + it('recomposes a blank Session under the default when the caller names no preset', async () => { + const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] }) + await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' }) + + const reused = await remote.create({ sessionId: SessionId('draft') }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'standard' } }) + expect(selections).toEqual([{ sessionId: 'draft', agentPreset: 'standard' }]) + expect(presetOf(SessionId('draft'))).toBe('standard') + }) + + it('recomposes a blank Session under the named preset', async () => { + const { remote, selections } = await harness({ presets: ['standard', 'minimal'] }) + await remote.create({ sessionId: SessionId('draft') }) + + const reused = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'minimal' } }) + expect(selections).toEqual([{ sessionId: 'draft', agentPreset: 'minimal' }]) + }) + + it('keeps a blank Session that already runs the requested preset', async () => { + const { ctx, remote, selections } = await harness({ presets: ['standard', 'minimal'] }) + await remote.create({ sessionId: SessionId('draft') }) + ctx.sessions.get(SessionId('draft'))?.append('agent-preset/selected', { agentPreset: 'minimal' }) + + const reused = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'minimal' } }) + expect(selections).toEqual([]) + }) + + it('validates the requested preset before touching the blank Session', async () => { + const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] }) + await remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' }) + + const response = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'deleted' }) + + expect(response).toMatchObject({ ok: false, error: { code: 'agent-preset/not-found' } }) + expect(selections).toEqual([]) + expect(presetOf(SessionId('draft'))).toBe('minimal') + }) + + it('keeps the blank Session unchanged when the requested preset fails to activate', async () => { + const { remote, selections, presetOf } = await harness({ + presets: ['standard', 'broken'], + broken: new Set(['broken']), + }) + await remote.create({ sessionId: SessionId('draft') }) + + const response = await remote.create({ sessionId: SessionId('draft'), agentPreset: 'broken' }) + + expect(response).toMatchObject({ ok: false, error: { code: 'agent-preset/invalid' } }) + expect(selections).toEqual([]) + expect(presetOf(SessionId('draft'))).toBe('standard') + }) + + it('creates a new Session instead of reusing one that has started', async () => { + const { ctx, remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] }) + await remote.create({ sessionId: SessionId('talk'), agentPreset: 'minimal' }) + const talk = ctx.sessions.get(SessionId('talk')) + talk?.append('turn/start', { turn: 1 }) + talk?.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + + const created = await remote.create({ sessionId: SessionId('talk') }) + + if (!created.ok) throw new Error(`create failed: ${created.error.message}`) + expect(created.value.sessionId).not.toBe('talk') + expect(created.value.agentPreset).toBe('standard') + expect(selections).toEqual([]) + expect(presetOf(SessionId('talk'))).toBe('minimal') + }) + + it('creates a new Session when a turn starts before the preset switch', async () => { + const { remote } = await harness({ + presets: ['standard', 'minimal'], + locked: new Set([SessionId('racing')]), + }) + await remote.create({ sessionId: SessionId('racing'), agentPreset: 'minimal' }) + + const created = await remote.create({ sessionId: SessionId('racing') }) + + if (!created.ok) throw new Error(`create failed: ${created.error.message}`) + expect(created.value.sessionId).not.toBe('racing') + }) + + it('serializes concurrent reuse of one Session in request order', async () => { + const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'] }) + await remote.create({ sessionId: SessionId('draft') }) + + const [first, second] = await Promise.all([ + remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' }), + remote.create({ sessionId: SessionId('draft') }), + ]) + + expect(first).toMatchObject({ ok: true, value: { sessionId: 'draft' } }) + expect(second).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'standard' } }) + expect(selections).toEqual([ + { sessionId: 'draft', agentPreset: 'minimal' }, + { sessionId: 'draft', agentPreset: 'standard' }, + ]) + expect(presetOf(SessionId('draft'))).toBe('standard') + }) + + it('claims one Session in arrival order when an earlier preset resolves later', async () => { + const minimal = Promise.withResolvers() + const { remote, selections, presetOf } = await harness({ + presets: ['standard', 'minimal'], resolving: new Map([['minimal', minimal.promise]]), + }) + await remote.create({ sessionId: SessionId('draft') }) + + const first = remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' }) + const second = remote.create({ sessionId: SessionId('draft') }) + await new Promise(resolve => setTimeout(resolve, 0)) + minimal.resolve(undefined) + + expect(await first).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'minimal' } }) + expect(await second).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'standard' } }) + expect(selections).toEqual([ + { sessionId: 'draft', agentPreset: 'minimal' }, + { sessionId: 'draft', agentPreset: 'standard' }, + ]) + expect(presetOf(SessionId('draft'))).toBe('standard') + }) + + it('shares one creation between concurrent callers of a new identity', async () => { + const { ctx, remote } = await harness({ presets: ['standard'] }) + + const results = await Promise.all([ + remote.create({ sessionId: SessionId('fresh') }), + remote.create({ sessionId: SessionId('fresh') }), + ]) + + expect(results).toMatchObject([ + { ok: true, value: { sessionId: 'fresh' } }, + { ok: true, value: { sessionId: 'fresh' } }, + ]) + expect(ctx.agents.list().map(agent => agent.id)).toEqual(['fresh']) + }) + + it('refuses a Session in another directory', async () => { + const { ctx, remote } = await harness({ presets: ['standard'] }) + const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-elsewhere-'))) + tempDirs.push(elsewhere) + await remote.create({ sessionId: SessionId('other'), cwd: elsewhere }) + + const response = await remote.create({ sessionId: SessionId('other') }) + + expect(response).toMatchObject({ + ok: false, + error: { code: 'session/conflict', details: { sessionId: 'other', existingCwd: elsewhere } }, + }) + expect(ctx.agents.list().map(agent => agent.id)).toEqual(['other']) + }) + + it('refuses a Session in another directory before resolving the requested preset', async () => { + const { remote } = await harness({ presets: ['standard'] }) + const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-elsewhere-'))) + tempDirs.push(elsewhere) + await remote.create({ sessionId: SessionId('other'), cwd: elsewhere }) + + const response = await remote.create({ sessionId: SessionId('other'), agentPreset: 'nope' }) + + expect(response).toMatchObject({ ok: false, error: { code: 'session/conflict', details: { sessionId: 'other' } } }) + }) + + it('leaves a subagent identity to subagent routing', async () => { + const { ctx, remote, cwd } = await harness({ presets: ['standard'] }) + ctx.sessions.create(SessionId('child'), { + meta: { cwd, parentSession: SessionId('parent'), origin: 'subagent' }, + }) + + const response = await remote.create({ sessionId: SessionId('child') }) + + expect(response).toMatchObject({ ok: false, error: { code: 'session/agent-busy' } }) + }) + + it('reuses a preset-less blank Session unchanged when no roster is composed', async () => { + const { ctx, remote } = await harness() + await remote.create({ sessionId: SessionId('s5') }) + + const reused = await remote.create({ sessionId: SessionId('s5') }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 's5' } }) + expect(ctx.sessions.get(SessionId('s5'))?.header.agentPreset).toBeUndefined() + }) it('explains why a preset-less Session cannot be adopted under one', async () => { const { remote } = await harness() @@ -177,6 +440,235 @@ describe('session.create Agent preset identity', () => { }) if (response.ok) throw new Error('unreachable') expect('existingPreset' in response.error.details).toBe(false) - expect(response.error.message).toContain('records no agent preset') + expect(response.error.message).toBe('the deployment composes no agent preset roster, so session "s7" cannot run preset "standard"') + }) +}) + +describe('session.create reuse of a stored blank Session', () => { + it('resumes a blank Session whose recorded preset is no longer declared under the default', async () => { + const draft = SessionId('stale-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { remote, resumed, presetOf, selectedEvents } = await harness({ + presets: ['standard', 'minimal'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'liangshen' }), events: [modelSelection(0)] }]]), + }) + + const reused = await remote.create({ sessionId: draft, cwd }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'stale-draft', agentPreset: 'standard' } }) + expect(resumed).toEqual(['stale-draft']) + expect(presetOf(draft)).toBe('standard') + expect(selectedEvents(draft)).toEqual([{ agentPreset: 'standard' }]) + }) + + it('resumes a blank Session under the default even when its previous choice is still declared', async () => { + const draft = SessionId('picked-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { remote, presetOf, selectedEvents } = await harness({ + presets: ['standard', 'minimal'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [presetSelection(0, 'minimal')] }]]), + }) + + const reused = await remote.create({ sessionId: draft, cwd }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'picked-draft', agentPreset: 'standard' } }) + expect(presetOf(draft)).toBe('standard') + expect(selectedEvents(draft)).toEqual([{ agentPreset: 'minimal' }, { agentPreset: 'standard' }]) + }) + + it('resumes a blank Session under its recorded preset when the caller names it', async () => { + const draft = SessionId('restored-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { remote, presetOf, selectedEvents } = await harness({ + presets: ['standard', 'minimal'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [presetSelection(0, 'minimal')] }]]), + }) + + const reused = await remote.create({ sessionId: draft, cwd, agentPreset: 'minimal' }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'restored-draft', agentPreset: 'minimal' } }) + expect(presetOf(draft)).toBe('minimal') + expect(selectedEvents(draft)).toEqual([{ agentPreset: 'minimal' }]) + }) + + it('rejects a named preset that is no longer declared without resuming the Session', async () => { + const draft = SessionId('stale-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { ctx, remote, resumed } = await harness({ + presets: ['standard'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'liangshen' }), events: [modelSelection(0)] }]]), + }) + + const response = await remote.create({ sessionId: draft, cwd, agentPreset: 'liangshen' }) + + expect(response).toMatchObject({ + ok: false, + error: { code: 'agent-preset/not-found', details: { agentPreset: 'liangshen', available: ['standard'] } }, + }) + expect(resumed).toEqual([]) + expect(ctx.agents.list()).toEqual([]) + }) + + it('creates a new Session instead of resuming one that has started', async () => { + const talk = SessionId('stored-talk') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { remote, resumed } = await harness({ + presets: ['standard'], + stored: new Map([[talk, { header: storedHeader(talk, cwd, { agentPreset: 'liangshen' }), events: completedTurn(0) }]]), + }) + + const created = await remote.create({ sessionId: talk, cwd }) + + if (!created.ok) throw new Error(`create failed: ${created.error.message}`) + expect(created.value.sessionId).not.toBe('stored-talk') + expect(created.value.agentPreset).toBe('standard') + expect(resumed).toEqual([]) + }) + + it('creates a new Session when another owner holds the blank Session', async () => { + const draft = SessionId('held-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { ctx, remote } = await harness({ + presets: ['standard'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [modelSelection(0)] }]]), + held: new Set([draft]), + }) + + const created = await remote.create({ sessionId: draft, cwd }) + + if (!created.ok) throw new Error(`create failed: ${created.error.message}`) + expect(created.value.sessionId).not.toBe('held-draft') + expect(ctx.sessions.get(draft)).toBeUndefined() + }) + + it('reuses the Agent another resume published while holding the writer', async () => { + const draft = SessionId('contended-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { remote, selections, presetOf } = await harness({ + presets: ['standard', 'minimal'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'minimal' }), events: [modelSelection(0)] }]]), + publishedByOtherResume: new Set([draft]), + }) + + const reused = await remote.create({ sessionId: draft, cwd }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'contended-draft', agentPreset: 'standard' } }) + expect(selections).toEqual([{ sessionId: 'contended-draft', agentPreset: 'standard' }]) + expect(presetOf(draft)).toBe('standard') + }) + + it('reports an unreadable Session instead of creating another one', async () => { + const { ctx, remote } = await harness({ presets: ['standard'] }) + vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValue(new Error('storage offline')) + + const response = await remote.create({ sessionId: SessionId('unreadable') }) + + expect(response).toMatchObject({ ok: false, error: { code: 'gateway/internal' } }) + expect(ctx.agents.list()).toEqual([]) + }) + + it('reports a storage failure instead of creating another Session', async () => { + const draft = SessionId('unreadable-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { ctx, remote } = await harness({ + presets: ['standard'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'standard' }), events: [modelSelection(0)] }]]), + unreadable: new Set([draft]), + }) + + const response = await remote.create({ sessionId: draft, cwd }) + + expect(response).toMatchObject({ ok: false, error: { code: 'gateway/internal' } }) + expect(ctx.agents.list()).toEqual([]) + }) + + it('creates a new Session when the blank Session started after it was observed', async () => { + const draft = SessionId('overtaken-draft') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { ctx, remote, resumed } = await harness({ + presets: ['standard', 'minimal'], + stored: new Map([[draft, { header: storedHeader(draft, cwd, { agentPreset: 'minimal' }), events: [modelSelection(0)] }]]), + writtenSinceObservation: new Map([[draft, completedTurn(1)]]), + }) + + const created = await remote.create({ sessionId: draft, cwd }) + + if (!created.ok) throw new Error(`create failed: ${created.error.message}`) + expect(created.value.sessionId).not.toBe('overtaken-draft') + expect(resumed).toEqual(['overtaken-draft']) + expect(ctx.sessions.get(draft)).toBeUndefined() + }) + + it('refuses a stored Session in another directory', async () => { + const other = SessionId('stored-other') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { remote, resumed } = await harness({ + presets: ['standard'], + stored: new Map([[other, { header: storedHeader(other, '/elsewhere'), events: [modelSelection(0)] }]]), + }) + + const response = await remote.create({ sessionId: other, cwd }) + + expect(response).toMatchObject({ + ok: false, + error: { code: 'session/conflict', details: { sessionId: 'stored-other', existingCwd: '/elsewhere' } }, + }) + expect(resumed).toEqual([]) + }) + + it('leaves a stored subagent identity to subagent routing', async () => { + const child = SessionId('stored-child') + const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-'))) + tempDirs.push(cwd) + const { remote, resumed } = await harness({ + presets: ['standard'], + stored: new Map([[child, { + header: storedHeader(child, cwd, { parentSession: SessionId('parent'), origin: 'subagent' }), + events: [modelSelection(0)], + }]]), + }) + + const response = await remote.create({ sessionId: child, cwd }) + + expect(response).toMatchObject({ ok: false, error: { code: 'session/agent-busy' } }) + expect(resumed).toEqual([]) + }) +}) + +describe('session.create Workspace placement', () => { + it('reuses a blank member of the requested Workspace', async () => { + const draft = SessionId('member-draft') + const { remote } = await harness({ presets: ['standard'], workspace: { members: [draft], archived: [] } }) + await remote.create({ sessionId: draft }) + + const reused = await remote.create({ sessionId: draft, workspaceId: WORKSPACE }) + + expect(reused).toMatchObject({ ok: true, value: { sessionId: 'member-draft' } }) + }) + + it.each([ + { name: 'outside the Workspace', members: [], archived: [] }, + { name: 'archived', members: [SessionId('placed-draft')], archived: [SessionId('placed-draft')] }, + ])('creates a new Session instead of reusing a blank Session $name', async ({ members, archived }) => { + const draft = SessionId('placed-draft') + const { remote, selections, presetOf } = await harness({ presets: ['standard', 'minimal'], workspace: { members, archived } }) + await remote.create({ sessionId: draft, agentPreset: 'minimal' }) + + const created = await remote.create({ sessionId: draft, workspaceId: WORKSPACE }) + + if (!created.ok) throw new Error(`create failed: ${created.error.message}`) + expect(created.value.sessionId).not.toBe('placed-draft') + expect(selections).toEqual([]) + expect(presetOf(draft)).toBe('minimal') }) }) diff --git a/packages/api/session-controller/tsdown.config.ts b/packages/api/session-controller/tsdown.config.ts index bc2abfa538..0e42a1163e 100644 --- a/packages/api/session-controller/tsdown.config.ts +++ b/packages/api/session-controller/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../../client/tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-api-session-controller', + import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }, ) diff --git a/packages/api/settings-controller/locale/en.json b/packages/api/settings-controller/locale/en.json new file mode 100644 index 0000000000..ccd029abde --- /dev/null +++ b/packages/api/settings-controller/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-settings-controller" + } +} diff --git a/packages/api/settings-controller/locale/zh.json b/packages/api/settings-controller/locale/zh.json new file mode 100644 index 0000000000..5e1155ba4d --- /dev/null +++ b/packages/api/settings-controller/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "设置读写接口", + "description": "向客户端提供各项设置的读取与修改能力。" + } +} diff --git a/packages/api/settings-controller/package.json b/packages/api/settings-controller/package.json index da78f22942..6c72102b61 100644 --- a/packages/api/settings-controller/package.json +++ b/packages/api/settings-controller/package.json @@ -31,9 +31,11 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", diff --git a/packages/api/terminal-controller/locale/en.json b/packages/api/terminal-controller/locale/en.json new file mode 100644 index 0000000000..a505798bad --- /dev/null +++ b/packages/api/terminal-controller/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-terminal-controller" + } +} diff --git a/packages/api/terminal-controller/locale/zh.json b/packages/api/terminal-controller/locale/zh.json new file mode 100644 index 0000000000..777c03f31c --- /dev/null +++ b/packages/api/terminal-controller/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "终端控制接口", + "description": "向客户端提供会话终端的创建、输入、读取和恢复能力。" + } +} diff --git a/packages/api/terminal-controller/package.json b/packages/api/terminal-controller/package.json index 05d21aeb4a..d9ade0d77a 100644 --- a/packages/api/terminal-controller/package.json +++ b/packages/api/terminal-controller/package.json @@ -35,7 +35,8 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -84,6 +85,7 @@ "@deepseek-ai/dsh-working-directory": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/terminal-controller/tsdown.config.ts b/packages/api/terminal-controller/tsdown.config.ts index cb9d252eb2..0e42a1163e 100644 --- a/packages/api/terminal-controller/tsdown.config.ts +++ b/packages/api/terminal-controller/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../../client/tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-api-terminal-controller', + import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }, ) diff --git a/packages/api/workspace-controller/locale/en.json b/packages/api/workspace-controller/locale/en.json new file mode 100644 index 0000000000..233cc2ae0c --- /dev/null +++ b/packages/api/workspace-controller/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-workspace-controller" + } +} diff --git a/packages/api/workspace-controller/locale/zh.json b/packages/api/workspace-controller/locale/zh.json new file mode 100644 index 0000000000..43275acd31 --- /dev/null +++ b/packages/api/workspace-controller/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区控制接口", + "description": "向客户端提供工作区操作和可在重连后恢复的状态。" + } +} diff --git a/packages/api/workspace-controller/package.json b/packages/api/workspace-controller/package.json index 70ccb57c74..ac9d45a3e1 100644 --- a/packages/api/workspace-controller/package.json +++ b/packages/api/workspace-controller/package.json @@ -39,7 +39,8 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -58,6 +59,7 @@ "watch": "tsdown --watch" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/workspace-controller/tsdown.config.ts b/packages/api/workspace-controller/tsdown.config.ts index a79662aebc..0e42a1163e 100644 --- a/packages/api/workspace-controller/tsdown.config.ts +++ b/packages/api/workspace-controller/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../../client/tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-api-workspace-controller', + import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }, ) diff --git a/packages/api/workspace-files/locale/en.json b/packages/api/workspace-files/locale/en.json new file mode 100644 index 0000000000..63caa3de7d --- /dev/null +++ b/packages/api/workspace-files/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "api-workspace-files" + } +} diff --git a/packages/api/workspace-files/locale/zh.json b/packages/api/workspace-files/locale/zh.json new file mode 100644 index 0000000000..eebfab4170 --- /dev/null +++ b/packages/api/workspace-files/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区文件接口", + "description": "提供工作区文件读取、目录列表和文件信息更新。" + } +} diff --git a/packages/api/workspace-files/package.json b/packages/api/workspace-files/package.json index b29114ae0a..f77a965ad0 100644 --- a/packages/api/workspace-files/package.json +++ b/packages/api/workspace-files/package.json @@ -35,7 +35,8 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -74,6 +75,7 @@ "@deepseek-ai/dsh-util-workspace-path": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/api/workspace-files/tsdown.config.ts b/packages/api/workspace-files/tsdown.config.ts index 6bf04a7409..0e42a1163e 100644 --- a/packages/api/workspace-files/tsdown.config.ts +++ b/packages/api/workspace-files/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../../client/tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-api-workspace-files', + import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }, ) diff --git a/packages/attachment/attachment-local/locale/en.json b/packages/attachment/attachment-local/locale/en.json new file mode 100644 index 0000000000..7d67c258a1 --- /dev/null +++ b/packages/attachment/attachment-local/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "attachment-local" + } +} diff --git a/packages/attachment/attachment-local/locale/zh.json b/packages/attachment/attachment-local/locale/zh.json new file mode 100644 index 0000000000..c0116cbbfe --- /dev/null +++ b/packages/attachment/attachment-local/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "本地附件存储", + "description": "保存会话中的图片等附件,并按内容标识读取。" + } +} diff --git a/packages/attachment/attachment-local/package.json b/packages/attachment/attachment-local/package.json index 27f50c5174..f40c826a40 100644 --- a/packages/attachment/attachment-local/package.json +++ b/packages/attachment/attachment-local/package.json @@ -14,11 +14,19 @@ "main": "lib/index.js", "types": "lib/types/index.d.ts", "exports": { - ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, - "files": ["lib/index.js", "lib/types/**/*.d.ts"], + "files": [ + "locale/*.json", + "lib/index.js", + "lib/types/**/*.d.ts" + ], "license": "MIT", "peerDependencies": { "@deepseek-ai/dsh-attachment": "workspace:*", diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 20dc764eec..4468b0fd9a 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -36,11 +36,8 @@ en: a9afb263b03d112c zh: 31f5e797cd953c15 /deepseek-ai-dsh-app-boot/use-this-package/startup-and-reload-failures: - en: 09890e218ab49c84 - zh: e3d86597e7fb1adb -/deepseek-ai-dsh-app-boot/use-this-package/telling-the-agent-where-the-harness-lives: - en: 07c459f26f4f8517 - zh: 210f1e4894731b1a + en: 206c9093965bc5e1 + zh: d8525e950595c399 /deepseek-ai-dsh-app-boot/understand-the-implementation: en: f4a2695cb4c8a570 zh: 89837235d2f376cf @@ -48,20 +45,20 @@ en: 25a0d1b46fd66d68 zh: 5cd8b4ac382dccdc /deepseek-ai-dsh-app-boot/understand-the-implementation/helper-behavior: - en: f7bc3a8dd4b00bdd - zh: 30098428aa769ad0 + en: 6fa850d1bb000d0e + zh: aa83a40a9d3db295 /deepseek-ai-dsh-app-boot/understand-the-implementation/source-map: - en: 3da01827e3354655 - zh: 06ccfaed83f65a76 + en: 541700d5c39e0ab4 + zh: 7522dbd9cd68c930 /deepseek-ai-dsh-app-boot/further-exploration: en: 401269cc5ea8593e zh: cd337c356b320565 /deepseek-ai-dsh-app-boot/model-experience: - en: 769777f1cb1a9408 - zh: f02b2834179df50d + en: d2d0a21502d88c50 + zh: 82a60c7a490a6834 /deepseek-ai-dsh-app-boot/model-experience/kv-cache-effect: - en: c4d49630b68ae896 - zh: 6f450ec6ba39bb81 + en: 5a1d9344c8fdc790 + zh: 0b32579f658b2ca1 /deepseek-ai-dsh-app-boot/known-limitations-and-deferred-work: en: bf1a49013cad8e9c zh: 41b2b010f8650ec3 diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 093c79252b..cba4c934e4 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -116,10 +116,6 @@ The [Web process matrix](../../../apps/cli/tests/profiles/web/tests/web-failure- If your app owns the terminal, it can hand the terminal back before the process exits, so your shell is never left in raw mode. The handoff is bounded: a stuck cleanup delays the fatal exit but never cancels it. -### Telling the agent where the harness lives - -When your app boots a model-backed agent, you can tell the agent where the DSH implementation checkout lives: it learns that path and that it must not infer the working directory from it — it should use `pwd`. The instruction appears once near the top of the system prompt. Apps without a system prompt service skip it; in development, reloading the system prompt drops it until the next boot. - ----- @@ -151,13 +147,13 @@ The startup error also retains inactive-entry metadata and raw startup warning/e ### Helper behavior -The exports each own one stage of the boot: config resolution and snapshot replay, layered environment loading, fail-loud reporting, activation auditing, patch parsing, root-include mounting, config dump rendering, profile composition, and the harness-source section. Per-export contracts live in the code, not this README — see [`src/index.ts`](src/index.ts) and [`src/profile.ts`](src/profile.ts). +The exports each own one stage of the boot: config resolution and snapshot replay, layered environment loading, fail-loud reporting, activation auditing, patch parsing, root-include mounting, config dump rendering, and profile composition. Per-export contracts live in the code, not this README — see [`src/index.ts`](src/index.ts) and [`src/profile.ts`](src/profile.ts). ### Source map | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | Boot helpers: config resolution, environment loading, fail-loud guard, activation audit, patch parsing, config dump, harness-source section | +| [`src/index.ts`](src/index.ts) | Boot helpers: config resolution, environment loading, fail-loud guard, activation audit, patch parsing, config dump | | [`src/profile.ts`](src/profile.ts) | Profile discovery, initialization, bundle resolution, runtime resolution construction | | [`src/profile-plugins.ts`](src/profile-plugins.ts) | Installed dependencies, bundle activation policy, and manifest updates | | [`src/profile-sanitize.ts`](src/profile-sanitize.ts) | Profile patch backup and recovery bundle activation | @@ -187,11 +183,11 @@ Read these pages when the package-level contract is not enough. They move from t ## Model Experience -Indirectly, through the loaded plugin tree, which alone contributes model context; the one export that adds model-visible text, `addHarnessSourceSection`, does so only when a consumer calls it after boot. +Indirectly, through the loaded plugin tree, which alone contributes model context; no export adds model-visible text. #### KV Cache effect -Boot itself changes no request prefix. `addHarnessSourceSection` places its source path after first-party reusable instructions, so different checkouts leave those preceding bytes unchanged when tools and configuration match. Provider cache reuse is not guaranteed. +Boot itself changes no request prefix. ## Known Limitations and Deferred Work diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 379d602176..cb383af462 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -116,10 +116,6 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 如果你的应用持有终端,它可以在进程退出前把终端交还,你的 shell 绝不会残留在 raw 模式。交还过程有界:卡住的清理只会延迟致命退出,而不会取消它。 -### 告诉 agent(智能体)harness 所在位置 - -当你的应用启动模型驱动的 agent 时,你可以告诉 agent DSH 实现代码 checkout 的位置:它得知该路径,也知道不得据此推断工作目录——它应使用 `pwd`。这条指示在系统提示词靠前位置出现一次。没有系统提示词服务的应用会跳过;开发环境中,重新加载系统提示词后它会消失,直至下次启动。 - ----- @@ -151,13 +147,13 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 ### Helper 行为 -每个导出各负责启动的一个阶段:配置解析与快照回放、分层环境加载、明确报错的保护机制、激活审计、patch 解析、根 include 挂载、配置 dump 渲染、profile 组合,以及 harness 源码段落。各导出的约定在代码中,不在本 README——见 [`src/index.ts`](src/index.ts) 与 [`src/profile.ts`](src/profile.ts)。 +每个导出各负责启动的一个阶段:配置解析与快照回放、分层环境加载、明确报错的保护机制、激活审计、patch 解析、根 include 挂载、配置 dump 渲染与 profile 组合。各导出的约定在代码中,不在本 README——见 [`src/index.ts`](src/index.ts) 与 [`src/profile.ts`](src/profile.ts)。 ### 源码地图 | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | 启动 helper:配置解析、环境加载、会明确报错的保护机制、激活审计、patch 解析、配置 dump、harness 源码段落 | +| [`src/index.ts`](src/index.ts) | 启动 helper:配置解析、环境加载、会明确报错的保护机制、激活审计、patch 解析、配置 dump | | [`src/profile.ts`](src/profile.ts) | profile 发现、初始化、组合包解析、runtime resolution 构造 | | [`src/profile-plugins.ts`](src/profile-plugins.ts) | 已安装依赖、bundle 启用策略与 manifest 更新 | | [`src/profile-sanitize.ts`](src/profile-sanitize.ts) | profile patch 备份与恢复 bundle 启用状态 | @@ -187,11 +183,11 @@ Loader 结算后,app-boot 在仅 optional 条目未激活时输出警告。如 ## 模型体验 -模型通过此包加载的插件树间接受影响——只有该树贡献模型上下文;唯一贡献模型可见文本的导出 `addHarnessSourceSection`,也只有在消费方启动后调用它时才会产生影响。 +模型通过此包加载的插件树间接受影响——只有该树贡献模型上下文;没有导出会添加模型可见文本。 #### KV Cache 影响 -启动本身不改变请求前缀。`addHarnessSourceSection` 将源码路径放在第一方可复用指令之后,因此工具与配置一致时,不同 checkout 不会改变前置字节。不保证提供方复用缓存。 +启动本身不改变请求前缀。 ## 已知限制与延期工作 diff --git a/packages/boot/app-boot/package.json b/packages/boot/app-boot/package.json index a7a8e5646e..5717ca71cc 100644 --- a/packages/boot/app-boot/package.json +++ b/packages/boot/app-boot/package.json @@ -47,7 +47,6 @@ "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-launch-environment": "workspace:*", "@deepseek-ai/dsh-home-paths": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/cordis": "workspace:~" }, "devDependencies": { diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index d02c5d554f..f5b08a4596 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -31,7 +31,6 @@ export { ON_DEMAND_BUNDLES, OFFICIAL_ON_DEMAND_CATALOG, type OfficialBundleCatal export { generateConfigSchema, type ConfigSchemaDump, type NativeConfigSchema } from './config-schema/index.ts' export { createConfigProjector, LOADER_EXPRESSION_SCHEMA, type ConfigProjection } from './config-schema/projector.ts' export { isNativeConfigSchema } from './config-schema/native.ts' -import type {} from '@deepseek-ai/dsh-system-prompt' export { readProfilePlugins, reconcileProfilePlugins, writeProfileBundles, @@ -1039,31 +1038,3 @@ export async function boot( await diagnostics.fiber.dispose() } } - -/** Prompt-section name for the harness-source location line an app bin adds after boot. */ -export const HARNESS_SOURCE_SECTION = 'harness:source' - -/** - * Add a global prompt section naming the on-disk harness source checkout while - * explicitly distinguishing it from the task workspace and current working - * directory. The self-referential `dsh-tool-cordis` toolset reads and edits this - * checkout. Call once on the settled boot context ({@link boot}); the section - * uses the shared first-party placement after reusable instructions - * and before the Web surface and persona suffix. A booted tree with no - * `systemPrompt` service has no prompt to augment, so this is then a no-op - * that returns `undefined`. The section is - * registered against the `systemPrompt` service's fiber, so a dev HMR reload of - * that plugin drops it until the next boot. - * @param ctx - the settled boot context whose global system prompt to augment. - * @param sourceRoot - the absolute path to the harness checkout root. - * @returns the section disposer, or `undefined` when no `systemPrompt` service is mounted. - */ -export function addHarnessSourceSection(ctx: Context, sourceRoot: string): (() => void) | undefined { - const systemPrompt = ctx.get('systemPrompt') - if (systemPrompt === undefined) return undefined - return systemPrompt.section({ - name: HARNESS_SOURCE_SECTION, - order: systemPrompt.getSectionOrder('HARNESS_SOURCE'), - text: `The DeepSeek Harness implementation checkout is at ${sourceRoot}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself.`, - }) -} diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index c1601313b6..826e4fa368 100644 --- a/packages/boot/app-boot/tests/app-boot.spec.ts +++ b/packages/boot/app-boot/tests/app-boot.spec.ts @@ -5,10 +5,10 @@ import { pathToFileURL } from 'node:url' import { inspect } from 'node:util' import { afterAll, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import SystemPrompt, { renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import type {} from '@deepseek-ai/dsh-system-prompt' import { - addHarnessSourceSection, auditStartupEntries, boot, StartupError, - FAIL_LOUD_RELEASE_TIMEOUT_MS, HARNESS_SOURCE_SECTION, + auditStartupEntries, boot, StartupError, + FAIL_LOUD_RELEASE_TIMEOUT_MS, installFailLoud, loadEnv, loadLayeredEnv, loadOverlayPatches, resolveConfigPath, type FailLoudEvent, type FailLoudProcess, } from '../src/index.ts' @@ -1266,61 +1266,3 @@ describe('boot', () => { }) }) - -describe('addHarnessSourceSection', () => { - const SOURCE_ROOT = `${sep}opt${sep}harness-src` - const EXPECTED = `The DeepSeek Harness implementation checkout is at ${SOURCE_ROOT}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself.` - - it('distinguishes the source path from the current workdir after reusable instructions', async () => { - const ctx = new Context() - try { - await ctx.plugin(SystemPrompt, { personaPrefix: 'You are a coding agent.' }) - ctx.systemPrompt.section({ - name: 'tools:sdk', order: ctx.systemPrompt.getSectionOrder('TOOLS_SDK'), text: 'Reusable tool SDK.', - }) - const dispose = addHarnessSourceSection(ctx, SOURCE_ROOT) - expect(dispose).toBeTypeOf('function') - const systemPrompt = ctx.get('systemPrompt')! - const rendered = renderPrompt(await systemPrompt.assemble()) - expect(rendered).toContain(EXPECTED) - // The >= 0 guards keep a drifted opener/persona string from a false pass - // through `-1 < n`. - const identityAt = rendered.indexOf('You are an AI agent powered by DeepSeek Harness.') - const sourceAt = rendered.indexOf(EXPECTED) - const personaAt = rendered.indexOf('You are a coding agent.') - expect(identityAt).toBeGreaterThanOrEqual(0) - expect(personaAt).toBeGreaterThanOrEqual(0) - const sdkAt = rendered.indexOf('Reusable tool SDK.') - expect(personaAt).toBeGreaterThan(identityAt) - expect(sdkAt).toBeGreaterThan(personaAt) - expect(sdkAt).toBeLessThan(sourceAt) - } finally { - await ctx.fiber.dispose() - } - }) - - it('is a no-op returning undefined when no systemPrompt service is mounted', async () => { - const ctx = new Context() - try { - expect(addHarnessSourceSection(ctx, SOURCE_ROOT)).toBeUndefined() - } finally { - await ctx.fiber.dispose() - } - }) - - it('disposes the section it added, so a systemPrompt reload leaves no residue', async () => { - const ctx = new Context() - try { - await ctx.plugin(SystemPrompt, {}) - const systemPrompt = ctx.get('systemPrompt')! - const dispose = addHarnessSourceSection(ctx, SOURCE_ROOT)! - const present = await systemPrompt.assemble() - expect(present.sections.some(section => section.name === HARNESS_SOURCE_SECTION)).toBe(true) - dispose() - const gone = await systemPrompt.assemble() - expect(gone.sections.some(section => section.name === HARNESS_SOURCE_SECTION)).toBe(false) - } finally { - await ctx.fiber.dispose() - } - }) -}) diff --git a/packages/boot/app-boot/tsconfig.json b/packages/boot/app-boot/tsconfig.json index e59c38f2ba..9c3e57c809 100644 --- a/packages/boot/app-boot/tsconfig.json +++ b/packages/boot/app-boot/tsconfig.json @@ -20,9 +20,6 @@ { "path": "../../../vendor/group" }, - { - "path": "../../core/system-prompt" - }, { "path": "../../util/launch-environment" }, diff --git a/packages/boot/config-editor/locale/en.json b/packages/boot/config-editor/locale/en.json new file mode 100644 index 0000000000..ac0e222f08 --- /dev/null +++ b/packages/boot/config-editor/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "config-editor" + } +} diff --git a/packages/boot/config-editor/locale/zh.json b/packages/boot/config-editor/locale/zh.json new file mode 100644 index 0000000000..11a55507d9 --- /dev/null +++ b/packages/boot/config-editor/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "插件配置编辑", + "description": "保存插件配置,并将变更应用到当前运行配置。" + } +} diff --git a/packages/boot/config-editor/package.json b/packages/boot/config-editor/package.json index 2c61a7583d..9d5e4dd44e 100644 --- a/packages/boot/config-editor/package.json +++ b/packages/boot/config-editor/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/boot/hmr/locale/en.json b/packages/boot/hmr/locale/en.json new file mode 100644 index 0000000000..47f242be8c --- /dev/null +++ b/packages/boot/hmr/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "hmr" + } +} diff --git a/packages/boot/hmr/locale/zh.json b/packages/boot/hmr/locale/zh.json new file mode 100644 index 0000000000..f216cf3442 --- /dev/null +++ b/packages/boot/hmr/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "插件热重载", + "description": "在应用运行期间重新加载插件代码和配置。" + } +} diff --git a/packages/boot/hmr/package.json b/packages/boot/hmr/package.json index 403fe5ed76..5c86376b65 100644 --- a/packages/boot/hmr/package.json +++ b/packages/boot/hmr/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/boot/plugin-manager/locale/en.json b/packages/boot/plugin-manager/locale/en.json new file mode 100644 index 0000000000..094967d50f --- /dev/null +++ b/packages/boot/plugin-manager/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "plugin-manager" + } +} diff --git a/packages/boot/plugin-manager/locale/tools/en.json b/packages/boot/plugin-manager/locale/tools/en.json new file mode 100644 index 0000000000..2fdfce031d --- /dev/null +++ b/packages/boot/plugin-manager/locale/tools/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "plugin-manager/tools" + } +} diff --git a/packages/boot/plugin-manager/locale/tools/zh.json b/packages/boot/plugin-manager/locale/tools/zh.json new file mode 100644 index 0000000000..ab001f0ccb --- /dev/null +++ b/packages/boot/plugin-manager/locale/tools/zh.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "插件管理工具" + } +} diff --git a/packages/boot/plugin-manager/locale/zh.json b/packages/boot/plugin-manager/locale/zh.json new file mode 100644 index 0000000000..e5ffb5869b --- /dev/null +++ b/packages/boot/plugin-manager/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "插件管理服务", + "description": "管理当前运行配置中的插件与插件包,支持安装、移除和启停。" + } +} diff --git a/packages/boot/plugin-manager/package.json b/packages/boot/plugin-manager/package.json index d75e0ce99f..756d5adb93 100644 --- a/packages/boot/plugin-manager/package.json +++ b/packages/boot/plugin-manager/package.json @@ -43,9 +43,13 @@ "./tools": { "types": "./lib/types/tools.d.ts", "default": "./lib/types/tools.js" - } + }, + "./tools/locale/*.json": "./locale/tools/*.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", + "locale/tools/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", diff --git a/packages/boot/plugin-manager/tests/tools.spec.ts b/packages/boot/plugin-manager/tests/tools.spec.ts index bc7da82dfe..dab620bff1 100644 --- a/packages/boot/plugin-manager/tests/tools.spec.ts +++ b/packages/boot/plugin-manager/tests/tools.spec.ts @@ -1,10 +1,11 @@ +import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' /** Agent controls use the same manager methods as the Web and bound inventory reads. */ import { Context } from '@deepseek-ai/cordis' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime from '@deepseek-ai/dsh-tools' import { ToolCallId } from '@deepseek-ai/dsh-llm' import type { Agent } from '@deepseek-ai/dsh-agent' -import SandboxPolicy, { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' +import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' import { Session, SessionId, SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import SessionProjections from '@deepseek-ai/dsh-session-projection' import ApprovalService, { type ApprovalOutcome } from '@deepseek-ai/dsh-user-approval' diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index 1c6e763915..2a9948d8dd 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -21,11 +21,11 @@ en: e3cac911f080d8ef zh: 60749e9f5c39c1bc /deepseek-ai-dsh-web-app/use-this-package/configuration: - en: 2b09528c8fc8d370 - zh: 7b374ebda8841172 + en: ad3bf2a8a2a8a99e + zh: cf24ef814a0352b9 /deepseek-ai-dsh-web-app/use-this-package/listening-trust-and-public-deployments: - en: 177400de33509826 - zh: dd88bc096accffc8 + en: e6ddea1d2fc40501 + zh: ff08b6fa3fc24136 /deepseek-ai-dsh-web-app/use-this-package/running-over-ssh: en: df205a26b6d49168 zh: e46ed7cf9e06248a @@ -33,38 +33,38 @@ en: ccd6fc264b51e44b zh: 3265c68477a89ec9 /deepseek-ai-dsh-web-app/understand-the-implementation: - en: 2ea88398028ebff8 - zh: 0e589c297aeb9d43 + en: 323742a00cfe67b2 + zh: eff5245a82fc16e7 /deepseek-ai-dsh-web-app/understand-the-implementation/patch-semantics: en: 8a2554b3d17daa1f zh: 66f18946791cabb6 /deepseek-ai-dsh-web-app/understand-the-implementation/advertised-application-url: - en: ca977d2b2bcf72c5 - zh: 2b81b377c133c1a8 + en: 0b22e03e28d41420 + zh: fd45a97dd4336c25 /deepseek-ai-dsh-web-app/understand-the-implementation/readiness: en: 973128fd346869df zh: 54e6792f9f82a192 /deepseek-ai-dsh-web-app/understand-the-implementation/source-map: - en: d4c7f39a9fd90683 - zh: ac2dbf75b2ceb255 + en: 58800b6f2142c34f + zh: 10bf512b16db1cb8 /deepseek-ai-dsh-web-app/further-exploration: en: f81694f7424e2988 zh: 6643f9227039e228 /deepseek-ai-dsh-web-app/model-experience: en: 215e7ba838619b7b zh: a311da3843709f90 -/deepseek-ai-dsh-web-app/model-experience/harness-source-and-web-surface-context: - en: e6febc53efe0f51d - zh: 9177816a8678d65d -/deepseek-ai-dsh-web-app/model-experience/harness-source-and-web-surface-context/what-the-model-sees: - en: 583592075e04687d - zh: 9defddfd77bab0f7 -/deepseek-ai-dsh-web-app/model-experience/harness-source-and-web-surface-context/token-effect: - en: 908fc84d6849a830 - zh: 56fe5e418bab60ba -/deepseek-ai-dsh-web-app/model-experience/harness-source-and-web-surface-context/kv-cache-effect: - en: 1d7d87f54b20b563 - zh: d150a51615d278e8 +/deepseek-ai-dsh-web-app/model-experience/web-runtime-variable: + en: 623bf8a0bf05599d + zh: 398ded2e7b20c1ea +/deepseek-ai-dsh-web-app/model-experience/web-runtime-variable/what-the-model-sees: + en: ebaddc153ad7a835 + zh: 21aa60f73d14f26c +/deepseek-ai-dsh-web-app/model-experience/web-runtime-variable/token-effect: + en: 449fbfa3986f98f0 + zh: a7d66333594ab2dd +/deepseek-ai-dsh-web-app/model-experience/web-runtime-variable/kv-cache-effect: + en: 37542a8b81a744f5 + zh: c0048aaadecae296 /deepseek-ai-dsh-web-app/known-limitations-and-deferred-work: en: 635c1336e2f4e821 zh: caabdecb02e2df14 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index b1bce71984..fb7a19c963 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -52,7 +52,7 @@ Saved model selections override the composition default. The settings card accep |---|---|---| | `openBrowser` | `true` | Open the default browser after startup; SSH launches suppress it | | `printUrl` | `true` | Print the `dsh web:` URL line at startup | -| `surfaceContext` | `true` | Give the agent GUI-orientation context and expose `DSH_WEB_URL` to its shell commands | +| `surfaceContext` | `true` | Expose `DSH_WEB_URL` to the agent's shell commands | | `publicUrl` | Unset | Advertised HTTP(S) application root; otherwise announce the bind-address URL | The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-web-app) lists this runtime plugin's accepted fields and their JSDoc. The shipped composition inserts the `schedule` service row and the `ui-schedule` task page row, while the clock reading and the four reminder tools belong to the `standard`, `cordis`, and `ptc` presets. The `tool-subagent` and `tool-subagent-fork` rows in those presets deny the four tools, so a delegated child's scope never lists them. @@ -74,7 +74,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- Without `--public-url`, mapped IPv6 loopback binds such as `::ffff:127.0.0.1` advertise their IPv4 form, `127.0.0.1`, so the browser recognizes a local, trustworthy origin. The listener keeps the configured bind address. A dotted-quad IPv6 tail names the address's own low 32 bits, exactly as `listen` reads it, so `::0.0.0.1` is IPv6 loopback and advertises `[::1]`, while `::127.0.0.1` is a non-loopback address, not IPv4 loopback. -`--public-url` advertises the HTTP(S) root browsers use — the printed and opened startup URL, `DSH_WEB_URL`, and the web-surface orientation. Advertisement grants no trust: the browser-visible authority must also be named with `--trusted-host`. The flag configures no listener, routing, or cookie scope, because the proxy owns the external leg: [Publish the Web UI behind a reverse proxy](../../../docs/user/guide/public-deployments.md) lists what such a deployment must provide. +`--public-url` advertises the HTTP(S) root browsers use — the printed and opened startup URL, `DSH_WEB_URL`, and the Web GUI URL in the agent's runtime context. Advertisement grants no trust: the browser-visible authority must also be named with `--trusted-host`. The flag configures no listener, routing, or cookie scope, because the proxy owns the external leg: [Publish the Web UI behind a reverse proxy](../../../docs/user/guide/public-deployments.md) lists what such a deployment must provide. Neither the advertised URL nor the browser-trust fence protects the port itself, so restrict the port to the trusted proxy or network. @@ -96,7 +96,7 @@ Each browser session selects a shipped preset (`standard` by default). The Agent
Implementation internals — click to expand -The bundle is one patch layer of five files plus one runtime glue plugin: `cordis.patch.yml` carries the host rows and the preset registry, and each `presets/.patch.yml` inserts one shipped preset declaration, applied in the order `dsh.bundle.patch` lists them. The storage stack and projection cache come from `dsh-base`; the web overlay's workspace and message-feedback rows consume that shared `storageDomain` service. The patch restates the surface-specific values the base deliberately omits, inserts the web-only host rows and browser roster, then moves the agent plane behind presets. The glue plugin owns dist serving, the advertised application URL, the plain-HTTP exposure warning, prompt sections, the bash variable, and the readiness announcements. The `office-to-pdf` row mounts one lazy [Office conversion provider](../../document/office-to-pdf/README.md) for Host consumers, including Desktop compositions using this bundle. The conversion service's Remote methods authorize preview reads, while Document Preview owns the Office viewer and Client cache. +The bundle is one patch layer of five files plus one runtime glue plugin: `cordis.patch.yml` carries the host rows and the preset registry, and each `presets/.patch.yml` inserts one shipped preset declaration, applied in the order `dsh.bundle.patch` lists them. The storage stack and projection cache come from `dsh-base`; the web overlay's workspace and message-feedback rows consume that shared `storageDomain` service. The patch restates the surface-specific values the base deliberately omits, inserts the web-only host rows and browser roster, then moves the agent plane behind presets. The glue plugin owns dist serving, the advertised application URL, the plain-HTTP exposure warning, the bash variable, and the readiness announcements. The `office-to-pdf` row mounts one lazy [Office conversion provider](../../document/office-to-pdf/README.md) for Host consumers, including Desktop compositions using this bundle. The conversion service's Remote methods authorize preview reads, while Document Preview owns the Office viewer and Client cache. ### Patch semantics @@ -104,7 +104,7 @@ A patch replaces the targeted row's whole `config`, so each web row restates eve ### Advertised application URL -Startup display and browser handoff receive the advertised root with its launch token; the web-surface prompt and `DSH_WEB_URL` receive it clean. The root itself is defined under [Listening, trust, and public deployments](#public-deployments). +Startup display and browser handoff receive the advertised root with its launch token; the agent's runtime context and `DSH_WEB_URL` receive it clean. The root itself is defined under [Listening, trust, and public deployments](#public-deployments). ### Readiness @@ -114,12 +114,12 @@ The URL line and browser handoff are readiness signals: supervisors RPC as soon | File | Role | |---|---| -| [`src/index.ts`](src/index.ts) | The `web-app` glue plugin: dist resolution, advertised application URL, prompt sections, bash variable, URL line, browser handoff | +| [`src/index.ts`](src/index.ts) | The `web-app` glue plugin: dist resolution, advertised application URL, bash variable, URL line, browser handoff | | [`src/public-url.ts`](src/public-url.ts) | Advertised-root validation and trailing-slash normalization; a leaf module for local imports, not package API | | [`src/startup.ts`](src/startup.ts) | The `web-startup` provider: `--host`, `--port`, `--tls-cert`, `--tls-key`, `--public-url`, `--trusted-host`, `--no-open`, `--help` | | [`cordis.patch.yml`](cordis.patch.yml) | The web patch: restated base values, web host rows, browser roster, preset registry | | [`presets/`](presets) | One `@deepseek-ai/dsh-agent-preset` declaration per shipped preset (`standard`, `ptc`, `minimal`, `cordis`), each its own patch file | -| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | Dist index anchoring, advertised-URL publication and warnings, prompt sections, readiness publication | +| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | Dist index anchoring, advertised-URL publication and warnings, bash variable, readiness publication | | [`tests/startup.spec.ts`](tests/startup.spec.ts) | Command-line parsing over a real Loader tree | | [`tests/public-url.spec.ts`](tests/public-url.spec.ts) | Advertised-root parsing and normalization | | [`tests/browser-open.spec.ts`](tests/browser-open.spec.ts) | Default-browser handoff after the page is reachable | @@ -144,19 +144,19 @@ Read these pages when you want to go deeper into the shared core, the browser re ## Model Experience -### Harness-source and Web-surface context +### Web runtime variable #### What the model sees -When `surfaceContext` is true, the `harness:source` section identifies the on-disk Harness implementation without claiming it is the working directory, and the `app:web-surface` global section (first-party order 10100, after reusable instructions) orients the model to the GUI: the advertised application URL (defined under Listening, trust, and public deployments above), the "this page" referent, the update contract (the reload receiver is always on; no-refresh reloads additionally need the `pnpm run dev:web` watcher), and the instruction not to start replacement servers. `DSH_WEB_URL` additionally appears in the managed bash environment with its description, resolved per invocation from the live server. When it is false, neither section nor the variable is registered. +When `surfaceContext` is true, `DSH_WEB_URL` appears in the managed bash environment with its description, resolved per invocation as the advertised application URL defined under Listening, trust, and public deployments above. When it is false, the variable is not registered. The GUI orientation, the implementation checkout, and the current GUI URL come from the [`dsh-harness-dev-context`](../../context/harness-dev-context/README.md) row this bundle mounts. #### Token effect -One source line and one prompt paragraph per session plus two managed-environment variable lines; constant per process. +Two managed-environment variable lines; constant per process. #### KV Cache effect -Source and Web sections follow first-party reusable instructions. Different checkout paths or application URLs leave that preceding prefix unchanged when tools and configuration match; provider cache reuse is not guaranteed. +None; the plugin contributes no system-prompt text. ## Known Limitations and Deferred Work diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index c74fd1ccc0..40930ff56b 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -52,7 +52,7 @@ dsh --profile web --no-open --port 8080 |---|---|---| | `openBrowser` | `true` | 启动后用默认浏览器打开;SSH 启动会抑制它 | | `printUrl` | `true` | 启动时打印 `dsh web:` URL 行 | -| `surfaceContext` | `true` | 给 agent 提供 GUI 定位上下文,并把 `DSH_WEB_URL` 暴露给其 shell 命令 | +| `surfaceContext` | `true` | 把 `DSH_WEB_URL` 暴露给 agent 的 shell 命令 | | `publicUrl` | 未设置 | 对外公告的 HTTP(S) 应用根;否则公告绑定地址 URL | 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-web-app)列出了本运行时插件接受的字段及其 JSDoc。随发行版交付的组合插入 `schedule` 服务行与 `ui-schedule` 任务页面行,时钟读数与四个提醒工具则属于 `standard`、`cordis` 与 `ptc` 三个 preset。这三个 preset 的 `tool-subagent` 与 `tool-subagent-fork` 两行都 deny 这四个工具,因此被委派子 agent 的作用域不会列出它们。 @@ -74,7 +74,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- 未设置 `--public-url` 时,`::ffff:127.0.0.1` 这样的 mapped IPv6 回环绑定会公告其 IPv4 形式 `127.0.0.1`,让浏览器将其识别为本地可信来源。监听器仍使用配置的绑定地址。点分四段式的 IPv6 尾部表示该地址自身的低 32 位,与 `listen` 的读法完全一致:`::0.0.0.1` 属于 IPv6 回环并公告 `[::1]`,而 `::127.0.0.1` 是非回环地址,并非 IPv4 回环。 -`--public-url` 公告浏览器使用的 HTTP(S) 根——打印与打开的启动 URL、`DSH_WEB_URL` 与 web 表层定位。公告不授予任何信任:浏览器可见的 authority 还必须用 `--trusted-host` 点名。该 flag 不配置监听器、路由或 cookie 作用域,因为外部链路归代理所有:[在反向代理之后发布 Web UI](../../../docs/user/guide/public-deployments.zh.md)列出了这样的部署必须提供什么。 +`--public-url` 公告浏览器使用的 HTTP(S) 根——打印与打开的启动 URL、`DSH_WEB_URL`,以及 agent 运行时上下文中的 Web GUI URL。公告不授予任何信任:浏览器可见的 authority 还必须用 `--trusted-host` 点名。该 flag 不配置监听器、路由或 cookie 作用域,因为外部链路归代理所有:[在反向代理之后发布 Web UI](../../../docs/user/guide/public-deployments.zh.md)列出了这样的部署必须提供什么。 无论是公告 URL 还是浏览器信任栅栏都不保护端口本身,因此请把端口限制在可信代理或网络内。 @@ -96,7 +96,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public-
实现细节——点击展开 -此 bundle 由一层五个文件的补丁和一个运行时胶水插件组成:`cordis.patch.yml` 承载宿主行和 preset 注册表,每个 `presets/.patch.yml` 插入一条随发行版交付的 preset 声明,按 `dsh.bundle.patch` 列出的顺序应用。存储栈与投影缓存来自 `dsh-base`;Web 叠加层的工作区和消息反馈条目消费共享的 `storageDomain` 服务。补丁重述 base 有意省略的界面专用值,插入 Web 专用宿主条目和浏览器插件列表,再将 Agent 层移到预设后面。胶水插件负责 dist 服务、公告应用 URL、明文 HTTP 暴露警告、提示词段落、bash 变量和就绪通知。`office-to-pdf` 条目为宿主消费者挂载一个延迟创建引擎的 [Office 转换提供方](../../document/office-to-pdf/README.zh.md),使用此 bundle 的 Desktop 组合也共享该提供方。 转换服务的 Remote 方法负责预览读取授权,Document Preview 负责 Office 查看器和客户端缓存。 +此 bundle 由一层五个文件的补丁和一个运行时胶水插件组成:`cordis.patch.yml` 承载宿主行和 preset 注册表,每个 `presets/.patch.yml` 插入一条随发行版交付的 preset 声明,按 `dsh.bundle.patch` 列出的顺序应用。存储栈与投影缓存来自 `dsh-base`;Web 叠加层的工作区和消息反馈条目消费共享的 `storageDomain` 服务。补丁重述 base 有意省略的界面专用值,插入 Web 专用宿主条目和浏览器插件列表,再将 Agent 层移到预设后面。胶水插件负责 dist 服务、公告应用 URL、明文 HTTP 暴露警告、bash 变量和就绪通知。`office-to-pdf` 条目为宿主消费者挂载一个延迟创建引擎的 [Office 转换提供方](../../document/office-to-pdf/README.zh.md),使用此 bundle 的 Desktop 组合也共享该提供方。 转换服务的 Remote 方法负责预览读取授权,Document Preview 负责 Office 查看器和客户端缓存。 ### patch 语义 @@ -104,7 +104,7 @@ patch 会替换目标行的整个 `config`,因此每个 Web 行都重述自己 ### 公告应用 URL -启动显示与浏览器交接接收附带启动 token 的公告根;web 表层提示词与 `DSH_WEB_URL` 接收不含凭据的形式。根本身由[监听、信任与公开部署](#public-deployments)定义。 +启动显示与浏览器交接接收附带启动 token 的公告根;agent 的运行时上下文与 `DSH_WEB_URL` 接收不含凭据的形式。根本身由[监听、信任与公开部署](#public-deployments)定义。 ### 就绪宣告 @@ -114,12 +114,12 @@ URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发 | 文件 | 职责 | |---|---| -| [`src/index.ts`](src/index.ts) | `web-app` 粘合插件:dist 解析、公告应用 URL、提示词段落、bash 变量、URL 行、浏览器交接 | +| [`src/index.ts`](src/index.ts) | `web-app` 粘合插件:dist 解析、公告应用 URL、bash 变量、URL 行、浏览器交接 | | [`src/public-url.ts`](src/public-url.ts) | 公告根的校验与尾斜杠归一化;供本地导入的叶子模块,不属于包 API | | [`src/startup.ts`](src/startup.ts) | `web-startup` 提供方:`--host`、`--port`、`--tls-cert`、`--tls-key`、`--public-url`、`--trusted-host`、`--no-open`、`--help` | | [`cordis.patch.yml`](cordis.patch.yml) | Web patch:重述的基础值、Web 宿主行、浏览器名录、preset 注册表 | | [`presets/`](presets) | 每个随发行版交付的 preset(`standard`、`ptc`、`minimal`、`cordis`)各一条 `@deepseek-ai/dsh-agent-preset` 声明,各自一个补丁文件 | -| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | dist index 锚定、公告 URL 发布与警告、提示词段落、就绪宣告发布 | +| [`tests/web-app.spec.ts`](tests/web-app.spec.ts) | dist index 锚定、公告 URL 发布与警告、bash 变量、就绪宣告发布 | | [`tests/startup.spec.ts`](tests/startup.spec.ts) | 在真实 Loader 树上的命令行解析 | | [`tests/public-url.spec.ts`](tests/public-url.spec.ts) | 公告根的解析与归一化 | | [`tests/browser-open.spec.ts`](tests/browser-open.spec.ts) | 页面可达后的默认浏览器交接 | @@ -144,19 +144,19 @@ URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发 ## 模型体验 -### Harness 源码与 Web 表层上下文 +### Web 运行时变量 #### 模型看到什么 -当 `surfaceContext` 为 true 时,`harness:source` 段落标明磁盘上的 Harness 实现,但不会声称它就是工作目录;全局段落 `app:web-surface`(first-party 顺序 10100,位于可复用指令之后)则向模型说明 GUI:公告应用 URL(定义见上文「监听、信任与公开部署」)、「this page」指代什么、更新约定(重载接收端始终开启;无刷新重载还需要 `pnpm run dev:web` watcher),以及不要启动替代服务器的指令。`DSH_WEB_URL` 还会连同描述出现在受管 bash 环境中,每次调用时从运行中的服务器解析。当它为 false 时,这两个段落和该变量都不会注册。 +当 `surfaceContext` 为 true 时,`DSH_WEB_URL` 连同描述出现在受管 bash 环境中,每次调用时解析为上文「监听、信任与公开部署」定义的公告应用 URL。为 false 时不注册该变量。GUI 定位、实现 checkout 与当前 GUI URL 由本 bundle 挂载的 [`dsh-harness-dev-context`](../../context/harness-dev-context/README.zh.md) 行提供。 #### Token 影响 -每个会话一行源码说明和一段提示词,外加两行受管环境变量;每个进程内保持恒定。 +两行受管环境变量;每个进程内保持恒定。 #### KV Cache 影响 -源码与 Web 段落位于第一方可复用指令之后。工具与配置一致时,不同 checkout 路径或应用 URL 不会改变前置前缀;不保证提供方复用缓存。 +无;该插件不贡献系统提示词文本。 ## 已知限制与延期工作 diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 987df7c3f7..a1ca0b5483 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -189,14 +189,11 @@ # Web glue owned by this bundle: resolves the built frontend dist (an # assembly fact of dsh-web-app, never user config), mounts the - # frontend-static fallback owner, registers the web-surface prompt - # section and the bash runtime variable, prints the URL line, and opens the - # canonical URL after the full Loader tree settles and the required- - # entry audit passes. Invocation-only values come from the webStartup - # provider; the advertised application URL is this row's `publicUrl`, - # otherwise the bind-address URL. A complete agent-preset persona - # suppresses the prompt section for that agent while retaining the - # host-owned shell variable. + # frontend-static fallback owner, registers the bash runtime variable, + # prints the URL line, and opens the canonical URL after the full Loader + # tree settles and the required-entry audit passes. Invocation-only values + # come from the webStartup provider; the advertised application URL is + # this row's `publicUrl`, otherwise the bind-address URL. - id: web-runtime name: '@deepseek-ai/dsh-web-app' inject: [webStartup] @@ -206,6 +203,14 @@ publicUrl: !!js ctx.webStartup.publicUrl surfaceContext: true + # Model context for an agent that inspects or extends the harness serving + # this GUI: value-free prompt sections plus the current checkout and GUI + # URL as optional runtime context. A complete agent-preset persona replaces + # the sections, and a persona that suppresses optional runtime context + # also drops the two value lines. + - id: harness-dev-context + name: '@deepseek-ai/dsh-harness-dev-context' + # The client-plugin reload chain, always mounted: it is idle until a # rebuild watcher (pnpm run dev:web) actually rewrites client bundles. It # is a row rather than a child of web-runtime because its node half is a @@ -378,6 +383,10 @@ - id: ui-reference name: '@deepseek-ai/dsh-client-ui-reference' + # Display masking for recognized credentials in sent user text; remove + # this entry to draw credentials as written. + - id: ui-secret-mask + name: '@deepseek-ai/dsh-client-ui-secret-mask' # Background jobs: the session-header roster with on-demand streaming # record panels over the session job-output service. diff --git a/packages/bundle/web-app/locale/en.json b/packages/bundle/web-app/locale/en.json new file mode 100644 index 0000000000..38435d75ce --- /dev/null +++ b/packages/bundle/web-app/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "web-app" + } +} diff --git a/packages/bundle/web-app/locale/startup/en.json b/packages/bundle/web-app/locale/startup/en.json new file mode 100644 index 0000000000..517b230f59 --- /dev/null +++ b/packages/bundle/web-app/locale/startup/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "web-app/startup" + } +} diff --git a/packages/bundle/web-app/locale/startup/zh.json b/packages/bundle/web-app/locale/startup/zh.json new file mode 100644 index 0000000000..71c9dfc066 --- /dev/null +++ b/packages/bundle/web-app/locale/startup/zh.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "Web 启动配置" + } +} diff --git a/packages/bundle/web-app/locale/zh.json b/packages/bundle/web-app/locale/zh.json new file mode 100644 index 0000000000..c224b7e344 --- /dev/null +++ b/packages/bundle/web-app/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Web 应用运行支持", + "description": "提供前端页面资源,并连接 Web 应用所需的运行配置。" + } +} diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index deb1a2ac05..f831a62741 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-web-app", - "description": "The dsh browser-surface bundle: the web patch layer over dsh-base plus the runtime glue plugin (frontend dist serving, web-surface prompt, bash runtime variables, URL line)", + "description": "The dsh browser-surface bundle: the web patch layer over dsh-base plus the runtime glue plugin (frontend dist serving, bash runtime variables, URL line)", "version": "0.2.1-alpha.2", "publishConfig": { "access": "public" @@ -25,9 +25,13 @@ "./cordis.patch.yml": "./cordis.patch.yml", "./presets/*.patch.yml": "./presets/*.patch.yml", "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./startup/locale/*.json": "./locale/startup/*.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", + "locale/startup/*.json", "lib/index.js", "lib/startup.js", "cordis.patch.yml", @@ -92,6 +96,7 @@ "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-client-ui-reference": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-secret-mask": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-schedule": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", @@ -180,13 +185,13 @@ "@deepseek-ai/dsh-client-ui-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", "@deepseek-ai/dsh-host-product-telemetry-otel": "workspace:*", - "@deepseek-ai/dsh-client-ui-settings-session-log": "workspace:*" + "@deepseek-ai/dsh-client-ui-settings-session-log": "workspace:*", + "@deepseek-ai/dsh-harness-dev-context": "workspace:*" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", - "@deepseek-ai/dsh-shell-env": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*" + "@deepseek-ai/dsh-shell-env": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -198,7 +203,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-shell-env": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-typert-registry": "workspace:*", "@deepseek-ai/libreoffice-kit": "^0.1.5", "@deepseek-ai/dsh-otel": "workspace:*" diff --git a/packages/bundle/web-app/src/index.ts b/packages/bundle/web-app/src/index.ts index 28e078bd31..b93b559620 100644 --- a/packages/bundle/web-app/src/index.ts +++ b/packages/bundle/web-app/src/index.ts @@ -4,9 +4,9 @@ * manifest field). The plugin owns the browser-surface glue: it resolves * the built frontend dist (workspace knowledge of this bundle, never user * config), mounts the `frontend-static` fallback owner over it, registers the - * harness-source and web-surface prompt sections, the bash-visible web runtime - * variable, the process-token URL line, and the default-browser handoff. An - * advertised `publicUrl` replaces the published bind-address URL. Non-loopback + * bash-visible web runtime variable, the process-token URL line, and the + * default-browser handoff, and provides the `webApp` service. An advertised + * `publicUrl` replaces the published bind-address URL. Non-loopback * HTTP binds trigger an exposure warning. App command-line values arrive * through the `webStartup` service expressions in the bundle patch. * @module @deepseek-ai/dsh-web-app @@ -14,26 +14,38 @@ import { spawn, type ChildProcess } from 'node:child_process' import { createRequire } from 'node:module' -import { isIP } from 'node:net' import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' import type { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { addHarnessSourceSection, auditStartupEntries } from '@deepseek-ai/dsh-app-boot' +import { auditStartupEntries } from '@deepseek-ai/dsh-app-boot' import type {} from '@deepseek-ai/dsh-client-connection' import * as FrontendStatic from '@deepseek-ai/dsh-host-frontend-static' -import { isLoopbackHost, normalizeBindAddress } from '@deepseek-ai/dsh-host-webserver' +import { bindUrlHost, isLoopbackHost } from '@deepseek-ai/dsh-host-webserver' import { launchedThroughSsh, launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment' import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess' import type {} from '@deepseek-ai/cordis-plugin-loader' import type {} from '@deepseek-ai/dsh-shell-env' import { parsePublicUrl } from './public-url.ts' +/** The Web GUI this process serves, provided by the `web-runtime` row. */ +export interface WebApp { + /** + * The URL this GUI advertises, also used for `DSH_WEB_URL` and the startup URL line. + * @returns the configured `publicUrl`, otherwise the listener origin. + */ + getAdvertisedUrl(): string +} + +declare module '@deepseek-ai/cordis' { + interface Context { + /** The Web GUI this process serves; absent when no Web runtime is mounted. */ + webApp: WebApp + } +} + /** Stable Cordis plugin name. */ export const name = 'web-app' -/** This dsh installation's root, from either this package's source or built entry. */ -const SOURCE_ROOT = fileURLToPath(new URL('../../../..', import.meta.url)) const ANNOUNCED_ROOTS = new WeakSet() /** Services required before the web runtime can mount. */ @@ -46,16 +58,14 @@ export interface Config { /** Print the URL line on activation; a non-interactive layer can turn it off. */ printUrl: boolean /** - * Register the model-visible surface context (the `app:web-surface` prompt - * section and the `DSH_WEB_URL` bash variable). A one-shot non-interactive - * layer can turn it off when its user is not in the GUI, so the - * orientation text would be false. + * Register the `DSH_WEB_URL` bash variable naming this GUI. A one-shot + * non-interactive layer can turn it off when its user is not in the GUI. */ surfaceContext: boolean /** * Canonical HTTP(S) root to advertise in the printed and opened URL, - * `DSH_WEB_URL`, and the web-surface orientation, e.g. - * `https://app.example/ui/`, normalized to end in `/`. Configures no routing + * `DSH_WEB_URL`, and `webApp.getAdvertisedUrl()`, which supplies the Web GUI + * URL in agent runtime context, e.g. `https://app.example/ui/`, normalized to end in `/`. Configures no routing * or authentication; see [public deployments](../README.md#public-deployments). * Absent or YAML `null` advertises the bind-address URL. */ @@ -103,65 +113,6 @@ try { } ` -/** - * Local root URL of the active Web server, using the browser-compatible form - * of its bind address and brackets for IPv6 literals. Non-loopback binds such - * as a container's Pod address advertise that address. - * @throws when the runtime resolves without a bound webServer, or when the bind - * address has no URL form (see {@link advertisedBindHost}). - */ -function localWebUrl(ctx: Context): string { - const webServer = ctx.get('webServer') - const port = webServer?.port - if (webServer === undefined || port === undefined) { - throw new Error('web-app: webServer service missing while resolving Web runtime') - } - const host = advertisedBindHost(webServer.host) - return `${webServer.protocol}//${isIP(host) === 6 ? `[${host}]` : host}:${String(port)}` -} - -/** - * Bind address in a URL. Loopback addresses use their canonical address text, - * so browsers treat them as local, trustworthy origins: a genuinely mapped - * literal such as `::ffff:127.0.0.1` reads as `127.0.0.1`, and a dotted-quad - * tail reads as the address it names, so `::0.0.0.1` reads as `::1` rather - * than as `0.0.0.1`. Interface zone IDs cannot appear in a URL; only a - * redundant loopback zone can be dropped. - * @param host - webserver bind address. - * @returns the zone-free URL host. - * @throws when a non-loopback zone requires an explicit public URL. - */ -function advertisedBindHost(host: string): string { - const zoneAt = host.indexOf('%') - const bare = zoneAt === -1 ? host : host.slice(0, zoneAt) - if (isLoopbackHost(bare)) return normalizeBindAddress(bare) - if (zoneAt === -1) return host - throw new Error( - `web-app: bind address ${JSON.stringify(host)} carries an interface zone id, which no URL can express;` - + ' pass --public-url with the root browsers actually reach it through', - ) -} - -/** Resolve the advertised root: this plugin's canonical `publicUrl`, or the bind-address URL (loopback when bound to loopback). */ -function appRootUrl(ctx: Context, publicUrl: string | undefined): string { - if (publicUrl !== undefined) return publicUrl - return localWebUrl(ctx) -} - -/** Model-visible orientation and acceptance boundary for sessions created through `dsh web`. */ -function webSurfacePrompt(webUrl: string): string { - const updateContract = 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while ' - + '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. ' - + 'Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. ' - return `You are interacting with the user through the DeepSeek Harness Web GUI at ${webUrl}. ` - + 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. ' - + 'The browser provides no implicit DOM, route, or screenshot context. ' - + updateContract - + 'Starting another server does not update this GUI. ' - + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. ' - + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.' -} - /** * Dist location is workspace knowledge of this bundle: anchored on the * frontend package manifest, not configured. Existence is a request-time @@ -227,8 +178,8 @@ export const internals: { } = { resolveDistIndex, openBrowser } /** - * Mount the Web runtime: dist serving, surface prompt, the bash runtime - * variable, the URL line, and the default-browser handoff. + * Mount the Web runtime: dist serving, the bash runtime variable, the URL + * line, and the default-browser handoff. * @param ctx - plugin context carrying the webServer service. * @param config - validated {@link Config}. */ @@ -237,30 +188,30 @@ export function apply(ctx: Context, config: Config): void { // the string transform and reaches here, meaning unset. const publicUrl = config.publicUrl ?? undefined const boundHost = ctx.webServer.host - if (publicUrl === undefined) advertisedBindHost(boundHost) + if (publicUrl === undefined && bindUrlHost(boundHost) === undefined) { + throw new Error( + `web-app: bind address ${JSON.stringify(boundHost)} carries an interface zone id, which no URL can express;` + + ' pass --public-url with the root browsers actually reach it through', + ) + } if (ctx.webServer.protocol === 'http:' && !isLoopbackHost(boundHost)) { console.warn(`dsh web: listening on ${boundHost} over plain HTTP; restrict this port to a trusted proxy or network`) } // The bind URL belongs to this host. Under SSH, the operator reaches it // through a local forwarding address that this process cannot derive. const handoffBrowser = config.openBrowser && !launchedThroughSsh(launchEnvironmentOf(ctx)) + /** The advertised root: the canonical `publicUrl`, or the listener's own origin. */ + const appRootUrl = (): string => publicUrl ?? ctx.webServer.getOrigin() + ctx.provide('webApp', { getAdvertisedUrl: appRootUrl } satisfies WebApp) ctx.plugin(FrontendStatic, { distIndex: internals.resolveDistIndex() }) if (config.surfaceContext) { - ctx.inject(['systemPrompt'], (promptCtx) => { - addHarnessSourceSection(promptCtx, SOURCE_ROOT) - promptCtx.systemPrompt.section({ - name: 'app:web-surface', - order: promptCtx.systemPrompt.getSectionOrder('WEB_SURFACE'), - text: () => webSurfacePrompt(appRootUrl(promptCtx, publicUrl)), - }) - }) ctx.inject(['shellEnv'], (runtimeCtx) => { runtimeCtx.shellEnv.register({ name: 'web-runtime', variables: { [DSH_WEB_URL]: { description: 'Advertised URL of the DeepSeek Harness Web GUI serving this session.' }, }, - resolve: () => ({ [DSH_WEB_URL]: appRootUrl(runtimeCtx, publicUrl) }), + resolve: () => ({ [DSH_WEB_URL]: appRootUrl() }), }) }) } @@ -273,7 +224,7 @@ export function apply(ctx: Context, config: Config): void { // hand-built tree without a Loader is already the complete tree. const announceReady = (): void => { if (ANNOUNCED_ROOTS.has(connectionCtx.root)) return - const webUrl = appRootUrl(connectionCtx, publicUrl) + const webUrl = appRootUrl() const authenticatedUrl = connectionCtx.connection.authenticatedUrl(webUrl) ANNOUNCED_ROOTS.add(connectionCtx.root) if (config.printUrl) { diff --git a/packages/bundle/web-app/src/startup.ts b/packages/bundle/web-app/src/startup.ts index f24e4ea386..3152e085fb 100644 --- a/packages/bundle/web-app/src/startup.ts +++ b/packages/bundle/web-app/src/startup.ts @@ -64,7 +64,7 @@ function webCommand(): Command { .option('--host ', 'bind address: one concrete IPv4 or IPv6 literal of a local interface; wildcard addresses are rejected') .option('--no-open', 'do not open the Web UI in the default browser') .option('--port ', 'listen port; pass 0 to let the OS pick a free one') - .option('--public-url ', 'advertise this HTTP(S) root in the printed, opened, web-surface, and DSH_WEB_URL forms; grants no trust') + .option('--public-url ', 'advertise this HTTP(S) root in the printed, opened, runtime-context, and DSH_WEB_URL forms; grants no trust') .option('--trusted-host ', 'extra authority the /api browser-trust fence accepts (host or host:port; repeatable)') .option('--tls-cert ', 'PEM server certificate chain; requires --tls-key') .option('--tls-key ', 'unencrypted PEM private key; requires --tls-cert') diff --git a/packages/bundle/web-app/tests/web-app.spec.ts b/packages/bundle/web-app/tests/web-app.spec.ts index e1c21573ac..67a350355d 100644 --- a/packages/bundle/web-app/tests/web-app.spec.ts +++ b/packages/bundle/web-app/tests/web-app.spec.ts @@ -11,8 +11,7 @@ import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' import * as AppBoot from '@deepseek-ai/dsh-app-boot' import { createLaunchEnvironmentSnapshot, DSH_LAUNCH_ENVIRONMENT_KEY } from '@deepseek-ai/dsh-launch-environment' -import SystemPrompt from '@deepseek-ai/dsh-system-prompt' -import type { WebServer } from '@deepseek-ai/dsh-host-webserver' +import { bindUrlHost, type WebServer } from '@deepseek-ai/dsh-host-webserver' import { apply, Config, internals } from '../src/index.ts' vi.mock('node:child_process', async importOriginal => ({ @@ -59,10 +58,11 @@ function stageDist(): string { /** Web carrier without a network listener. */ function fakeHttpServer(host = '127.0.0.1'): { server: WebServer } { - const server: Pick = { + const server: Pick = { host, port: 4567, protocol: 'http:', + getOrigin() { return `http://${bindUrlHost(host) ?? ''}:${String(this.port)}` }, registerFallback: () => () => {}, renderIndex: (html: string) => html, } @@ -126,7 +126,6 @@ describe('web-app runtime glue', () => { const openBrowser = vi.fn(async (url: string) => { lifecycle.push(`open:${url}`) }) internals.openBrowser = openBrowser apply(ctx, new Config({ openBrowser: true, printUrl: true, surfaceContext: true })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567/?token=test-token') @@ -137,15 +136,9 @@ describe('web-app runtime glue', () => { 'dsh web: opening the default browser; pass --no-open to disable', 'open:http://127.0.0.1:4567/?token=test-token', ]) - const assembly = await ctx.systemPrompt.assemble() - expect(assembly.sections.find(entry => entry.name === 'harness:source')?.text).toContain('DeepSeek Harness implementation checkout') - const section = assembly.sections.find(entry => entry.name === 'app:web-surface') - expect(section?.text).toContain('http://127.0.0.1:4567') - // The single update contract: the receiver is always on; no-refresh - // reloads additionally need the rebuild watcher. - expect(section?.text).toContain('pnpm run dev:web') const webRuntime = contributions.find(contribution => contribution.name === 'web-runtime') expect(webRuntime?.resolve()).toEqual({ DSH_WEB_URL: 'http://127.0.0.1:4567' }) + expect(ctx.webApp.getAdvertisedUrl()).toBe('http://127.0.0.1:4567') }) it('advertises and opens the configured public root behind a prefix-stripping proxy', async () => { @@ -173,7 +166,6 @@ describe('web-app runtime glue', () => { surfaceContext: true, publicUrl: 'https://proxy.example:8443/web', })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await vi.waitFor(() => { expect(openBrowser).toHaveBeenCalled() }) expect(lifecycle).toEqual([ @@ -181,12 +173,10 @@ describe('web-app runtime glue', () => { 'dsh web: opening the default browser; pass --no-open to disable', 'open:https://proxy.example:8443/web/?token=test-token', ]) - const assembly = await ctx.systemPrompt.assemble() - const section = assembly.sections.find(entry => entry.name === 'app:web-surface') - expect(section?.text).toContain('https://proxy.example:8443/web/') - expect(section?.text).not.toContain('127.0.0.1') const urlContribution = contributions.find(contribution => contribution.name === 'web-runtime') expect(urlContribution?.resolve()).toEqual({ DSH_WEB_URL: 'https://proxy.example:8443/web/' }) + // The service advertises the row's effective publicUrl, whether it came from --public-url or a profile override. + expect(ctx.webApp.getAdvertisedUrl()).toBe('https://proxy.example:8443/web/') }) it('publishes no readiness side effect when printing and browser opening are disabled', async () => { @@ -198,17 +188,13 @@ describe('web-app runtime glue', () => { const openBrowser = vi.fn(async () => {}) internals.openBrowser = openBrowser apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: true })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await new Promise(resolve => setTimeout(resolve, 0)) expect(log).not.toHaveBeenCalled() expect(openBrowser).not.toHaveBeenCalled() - const assembly = await ctx.systemPrompt.assemble() - expect(assembly.sections.find(entry => entry.name === 'app:web-surface')?.text) - .toContain('rebuilding the affected Web artifacts') await ctx.fiber.dispose() }) - it('skips the surface context when disabled (the one-shot layer): no prompt section, no bash variables', async () => { + it('skips the surface context when disabled (the one-shot layer): no bash variables', async () => { stageDist() const ctx = new Context() ctx.provide('webServer', fakeHttpServer().server) @@ -221,11 +207,7 @@ describe('web-app runtime glue', () => { }, } as never) apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: false })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) await new Promise(resolve => setTimeout(resolve, 0)) - const assembly = await ctx.systemPrompt.assemble() - expect(assembly.sections.some(entry => entry.name === 'app:web-surface')).toBe(false) - expect(assembly.sections.some(entry => entry.name === 'harness:source')).toBe(false) expect(contributions).toEqual([]) await ctx.fiber.dispose() }) @@ -465,22 +447,6 @@ describe('web-app runtime glue', () => { } }) - it('fails loud when the prompt section resolves against a portless webserver', async () => { - stageDist() - const ctx = new Context() - // A webserver whose bound port is gone (torn down mid-request): the - // section must throw, never render a URL with an undefined port. - const { server } = fakeHttpServer() - Object.defineProperty(server, 'port', { get: () => undefined }) - ctx.provide('webServer', server) - provideConnection(ctx) - apply(ctx, new Config({ openBrowser: false, printUrl: false, surfaceContext: true })) - await ctx.plugin(SystemPrompt, { personaPrefix: '' }) - await new Promise(resolve => setTimeout(resolve, 0)) - await expect(ctx.systemPrompt.assemble()).rejects.toThrow('webServer service missing') - await ctx.fiber.dispose() - }) - it('anchors the dist index on the frontend package manifest without requiring a built dist', () => { // The production resolver (not the test hook): the anchor resolves on any // checkout, built or not — dist existence is the fallback owner's diff --git a/packages/bundle/web-app/tsconfig.json b/packages/bundle/web-app/tsconfig.json index d4a74c09ba..2f7f148e60 100644 --- a/packages/bundle/web-app/tsconfig.json +++ b/packages/bundle/web-app/tsconfig.json @@ -35,9 +35,6 @@ { "path": "../../util/launch-environment" }, - { - "path": "../../core/system-prompt" - }, { "path": "../../shell/shell-env" }, diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index ddaad3c866..16956ca71d 100644 --- a/packages/client/AGENTS.md +++ b/packages/client/AGENTS.md @@ -8,7 +8,7 @@ Packages here are named with the directory prefix: `@deepseek-ai/dsh-client-..` (for example, `'tool.call.toolview'`). 3. **Component props are the five shares, all derived**: `PropsRuntime` (owner data plus scope/global seats), `PropsRenderSlots` (children), `PropsRenderFactories` (`renderFactorySlot`), `PropsStore` (store), and the inject face. Never hand-write or locally re-type a derived member. Factory props follow the corresponding `Factory*PropsOf` aliases. 4. **Hooks are framework-made only**: standing seats include `useSession`, `useSessions`, `useWorkspaces`, `useStore`, `renderSlot`, and `renderFactorySlot`; Factory definitions additionally receive `useFactorySlot`. The renderer also binds `use` hooks from provide contributions and inject `hooks` compartments. Business code never creates a hook or selector as a prop value — pass plain data and callbacks. (Component-internal behavioral hooks that subscribe to nothing external are fine.) @@ -69,6 +69,7 @@ Npm sections describe installation and development relationships; each build fac 5. **Only Host runtime libraries require installation dependencies.** Browser-only third-party implementations belong in `devDependencies`, whether inlined into `lib/client.js` or retained as bare imports in a static browser library. Static libraries are Web-shell build inputs; the final Vite build merges their imports and styles. Distributed browser code remains subject to runtime license disclosure ([reference](../../.agents/notes/implemented/process/2026-08-26-published-dependency-faces.md)). 6. **Browser and Node build faces declare externality independently.** A dynamic browser half uses the baseline plus `dsh.client.external`; a statically linked face externalizes every bare specifier; a Node face externalizes its production dependencies ([`tsdown.client.ts`](tsdown.client.ts)). Moving a name between npm sections must not silently change bundle contents. 7. **Keep the published payload closed.** Every relative runtime import and emitted asset must be covered by `files`; the repository publint pass checks the exact publication view. +8. **Only the root manifest declares React type packages.** `@types/react` and `@types/react-dom` belong only in the root `package.json` `devDependencies`, and `verify-package-dependencies` rejects them in every manifest under `apps/*`, `packages/*/*`, and `vendor/*`; packages still declare the `react` and `react-dom` they import. Each package-local pnpm link is one more location TypeScript scans when it computes module specifiers for every JSX file ([rationale](../../.agents/notes/implemented/process/2026-10-11-lossless-build-speedups.md#1-only-the-root-manifest-declares-react-type-packages)). ## Build-time browser environment @@ -142,7 +143,7 @@ If `test:gui` is red on code you did not touch, neither silently fix nor ignore Bringing up a new `packages/client/` plugin package (ui-workspace is a complete example; ui-sidebar/ui-user-questions are minimal skeletons): -1. **Package skeleton**: `package.json` (`@deepseek-ai/dsh-client-`, exports `.`/`./client`/`./src/*`/`./package.json`, `dsh.client` manifest, `files` list), `tsconfig.json` (extends `tsconfig.base.client.json`, one `references` entry per workspace dependency), `tsdown.config.ts` (`clientBundle(id, ['lib/types/index.js'])`), `src/index.ts` (empty node-half apply), `src/css-modules.d.ts` when using CSS Modules, and `README.md` with the Model Experience section. +1. **Package skeleton**: `package.json` (`@deepseek-ai/dsh-client-`, exports `.`/`./client`/`./src/*`/`./package.json`, `dsh.client` manifest, `files` list), `tsconfig.json` (extends `tsconfig.base.client.json`, one `references` entry per workspace dependency), `tsdown.config.ts` (`clientBundle(import.meta.dirname, ['lib/types/index.js'])`), `src/index.ts` (empty node-half apply), `src/css-modules.d.ts` when using CSS Modules, and `README.md` with the Model Experience section. 2. **Three registration surfaces, all required** (missing any one fails at a different, later point): the `tsconfig.client.json` aggregate `references` entry; a `dsh.client` row in `packages/bundle/web-app/cordis.patch.yml`; a `packages/bundle/web-app/package.json` dependency (profile boots resolve bare row names through the computed runtime resolution, which is installed as an interception on Node's resolvers — a row whose package no manifest declares fails to import). `pnpm-workspace.yaml` already globs `packages/*/*`. 3. **dsh.client manifest semantics**: `platform: 'web'` always, and the declaration requires a `./client` export (the scan throws without one); `immediately: true` only for stage-one-prefetch infrastructure rows. `inject` lists package-name dependency edges — they are **informational only** (preflight display, HMR diffing); they do not sequence entry activation or apply order. Activation order is Cordis fiber inject waiting on *services*, nothing else. A non-baseline `external` request sequences its dynamic supplier ahead of the consumer — see [shared modules](#shared-modules-and-the-module-graph). 4. **Registering into another package's slot**: apply order is unconstrained, and a business service is not a declaration barrier. Use `ctx.slots.inject(name, () => ctx.slots.register(...))`; it waits on the actual declaration, removes the contribution when that declaration collapses, reruns after redeclaration, and leaves with the caller's plugin fiber. Return a generator yielding each registration when several contributions must install and roll back atomically. A bare `slots.register` into an undeclared slot remains an error; keep service edges only for services the contribution actually reads. @@ -153,7 +154,7 @@ Bringing up a new `packages/client/` plugin package (ui-workspace is a com 1. **Check the [ui-primitives catalog](ui-primitives/README.md#component-catalog) before writing a control.** A plugin cannot import another plugin's component, so `ui-primitives` is the only place a control can be shared; the catalog states when to reuse, when to promote, and when your own package is the right home. -2. Compose through `register`: add the slot to `SlotMap`, declare it in its parent entry's `children`, and register your component. Use a Component Factory only for a reusable assembly rendered independently under unrelated parents; see the [Slots reference](../../docs/subsystems/slots.md). +2. Compose through `register`: add the slot to `SlotMap`, declare it in its parent entry's `children`, and register your component. A component or assembly designed for reuse may instead use a Component Factory; one-off components need not become Factories. See the [Slots reference](../../docs/subsystems/slots.md). 3. Type ordinary props from the five shares (`PropsRuntime` & `PropsRenderSlots` & `PropsRenderFactories` & `PropsStore` & inject face), and use the derived `Factory*PropsOf` aliases for Factory Components. Shared or remount-surviving state goes in a declared store; component-private state stays local. 4. Component tests feed props directly (`createXXXStore().create()` for the store data; plain stubs for framework hooks) and assert behavior without render machinery. 5. Tokens only in CSS; product copy follows the localization rule above; English comments. diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 766b7d16d0..f4e03603ff 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 1aa93b8088fb1962 - zh: 10feaed78bc6408c + en: e0bdfa58440be810 + zh: a006bb2e73f3f264 /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 04eb19d8f7..19ed68cdbc 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -63,6 +63,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-input-trigger/`](ui-input-trigger/README.md) | Coordinates inline command and reference suggestions | — | | [`ui-skill/`](ui-skill/README.md) | Adds skill references to inline suggestions | — | | [`ui-reference/`](ui-reference/README.md) | Unified Web `@file` / `@session` reference source | — | +| [`ui-secret-mask/`](ui-secret-mask/README.md) | Masks recognized credentials in sent user text | — | | [`ui-subagent/`](ui-subagent/README.md) | Provides subagent navigation, child transcript states, and inline references | — | | [`ui-jobs/`](ui-jobs/README.md) | Lists this session's background jobs with on-demand streaming record panels | — | | [`ui-schedule/`](ui-schedule/README.md) | Lists the current Session's active reminders in a read-only header catalog | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index 2ebc91a3e1..1ef85c42b5 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -63,6 +63,7 @@ kind: "package-group" | [`ui-input-trigger/`](ui-input-trigger/README.zh.md) | 协调内联命令与引用建议 | — | | [`ui-skill/`](ui-skill/README.zh.md) | 向内联建议添加 skill(技能)引用 | — | | [`ui-reference/`](ui-reference/README.zh.md) | 统一的 Web `@file` / `@session` 引用 source | — | +| [`ui-secret-mask/`](ui-secret-mask/README.zh.md) | 遮挡已发送用户文本中可识别的凭据 | — | | [`ui-subagent/`](ui-subagent/README.zh.md) | 提供 subagent 导航、子级 transcript(文本记录)状态与内联引用 | — | | [`ui-jobs/`](ui-jobs/README.zh.md) | 列出本会话的后台任务,并提供按需展开的流式输出面板 | — | | [`ui-schedule/`](ui-schedule/README.zh.md) | 在只读标题栏目录中列出当前会话中生效的提醒 | — | diff --git a/packages/client/connection/locale/en.json b/packages/client/connection/locale/en.json new file mode 100644 index 0000000000..85615ed94d --- /dev/null +++ b/packages/client/connection/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "connection" + } +} diff --git a/packages/client/connection/locale/zh.json b/packages/client/connection/locale/zh.json new file mode 100644 index 0000000000..642e58d1cd --- /dev/null +++ b/packages/client/connection/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "客户端连接", + "description": "建立已认证的客户端通信,并管理连接生命周期。" + } +} diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index bcd37df919..21e395fb6f 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -39,6 +40,7 @@ "zod": "4.4.3" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/connection/tsdown.config.ts b/packages/client/connection/tsdown.config.ts index 69cd7ce36d..7aa03cebc1 100644 --- a/packages/client/connection/tsdown.config.ts +++ b/packages/client/connection/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-connection', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/file-upload/locale/en.json b/packages/client/file-upload/locale/en.json new file mode 100644 index 0000000000..1a2719ee6c --- /dev/null +++ b/packages/client/file-upload/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "file-upload" + } +} diff --git a/packages/client/file-upload/locale/zh.json b/packages/client/file-upload/locale/zh.json new file mode 100644 index 0000000000..5a330e6b60 --- /dev/null +++ b/packages/client/file-upload/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文件上传", + "description": "将浏览器中的文件上传到当前会话,供消息和工具使用。" + } +} diff --git a/packages/client/file-upload/package.json b/packages/client/file-upload/package.json index 027de0b95a..7c5f43b873 100644 --- a/packages/client/file-upload/package.json +++ b/packages/client/file-upload/package.json @@ -35,7 +35,8 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -52,6 +53,7 @@ }, "license": "MIT", "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.js", diff --git a/packages/client/file-upload/tsdown.config.ts b/packages/client/file-upload/tsdown.config.ts index 97292cd3cc..7aa03cebc1 100644 --- a/packages/client/file-upload/tsdown.config.ts +++ b/packages/client/file-upload/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-file-upload', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/hmr/locale/en.json b/packages/client/hmr/locale/en.json new file mode 100644 index 0000000000..47f242be8c --- /dev/null +++ b/packages/client/hmr/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "hmr" + } +} diff --git a/packages/client/hmr/locale/zh.json b/packages/client/hmr/locale/zh.json new file mode 100644 index 0000000000..28262e2f7c --- /dev/null +++ b/packages/client/hmr/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Web 客户端热更新", + "description": "同步浏览器中的插件,并在代码重建后更新相关界面。" + } +} diff --git a/packages/client/hmr/package.json b/packages/client/hmr/package.json index f87c12fca4..3fd0ca2c4d 100644 --- a/packages/client/hmr/package.json +++ b/packages/client/hmr/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -48,6 +49,7 @@ "@deepseek-ai/cordis": "workspace:~" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/hmr/tsdown.config.ts b/packages/client/hmr/tsdown.config.ts index 69b96b4229..7aa03cebc1 100644 --- a/packages/client/hmr/tsdown.config.ts +++ b/packages/client/hmr/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-hmr', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/locale/locale/en.json b/packages/client/locale/locale/en.json new file mode 100644 index 0000000000..9f4e0d1c02 --- /dev/null +++ b/packages/client/locale/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "locale" + } +} diff --git a/packages/client/locale/locale/zh.json b/packages/client/locale/locale/zh.json new file mode 100644 index 0000000000..8fa3c8e462 --- /dev/null +++ b/packages/client/locale/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "界面语言", + "description": "管理界面语言偏好和各插件的翻译文案。" + } +} diff --git a/packages/client/locale/package.json b/packages/client/locale/package.json index 7027a879cb..6cc7ea6e2a 100644 --- a/packages/client/locale/package.json +++ b/packages/client/locale/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -51,7 +52,6 @@ "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-package-manifest": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-settings": "workspace:*" @@ -60,6 +60,7 @@ "@deepseek-ai/schemastery": "workspace:~" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/locale/tsdown.config.ts b/packages/client/locale/tsdown.config.ts index 8babf9f1eb..7aa03cebc1 100644 --- a/packages/client/locale/tsdown.config.ts +++ b/packages/client/locale/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-locale', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/modules/locale/en.json b/packages/client/modules/locale/en.json new file mode 100644 index 0000000000..cd77943573 --- /dev/null +++ b/packages/client/modules/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "modules" + } +} diff --git a/packages/client/modules/locale/zh.json b/packages/client/modules/locale/zh.json new file mode 100644 index 0000000000..d24fc0c1fd --- /dev/null +++ b/packages/client/modules/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "客户端模块加载", + "description": "管理浏览器插件模块及其加载依赖。" + } +} diff --git a/packages/client/modules/package.json b/packages/client/modules/package.json index c5235aa379..c9d0440c04 100644 --- a/packages/client/modules/package.json +++ b/packages/client/modules/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -45,6 +46,7 @@ "@deepseek-ai/dsh-client-store": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/modules/tsdown.config.ts b/packages/client/modules/tsdown.config.ts index 06db107f32..3a0694bdf9 100644 --- a/packages/client/modules/tsdown.config.ts +++ b/packages/client/modules/tsdown.config.ts @@ -1,6 +1,6 @@ import { clientBundle } from '../tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-client-modules', + import.meta.dirname, ['lib/types/index.js'], ) diff --git a/packages/client/product-analytics/locale/en.json b/packages/client/product-analytics/locale/en.json new file mode 100644 index 0000000000..0351b24e9f --- /dev/null +++ b/packages/client/product-analytics/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "product-analytics" + } +} diff --git a/packages/client/product-analytics/locale/zh.json b/packages/client/product-analytics/locale/zh.json new file mode 100644 index 0000000000..6740088981 --- /dev/null +++ b/packages/client/product-analytics/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "桌面端使用统计", + "description": "采集桌面端指定交互事件,并提交给产品统计服务。" + } +} diff --git a/packages/client/product-analytics/package.json b/packages/client/product-analytics/package.json index 0b35b21571..a8240ccc6b 100644 --- a/packages/client/product-analytics/package.json +++ b/packages/client/product-analytics/package.json @@ -34,7 +34,8 @@ }, "./types": { "types": "./lib/types/events.d.ts" - } + }, + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -66,6 +67,7 @@ "@deepseek-ai/dsh-otel": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts", diff --git a/packages/client/product-analytics/tsdown.config.ts b/packages/client/product-analytics/tsdown.config.ts index 4479f52fe2..620261533c 100644 --- a/packages/client/product-analytics/tsdown.config.ts +++ b/packages/client/product-analytics/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-product-analytics', ['lib/types/index.js'], { hostPhase: true }) +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/resources/locale/en.json b/packages/client/resources/locale/en.json new file mode 100644 index 0000000000..8350a2a390 --- /dev/null +++ b/packages/client/resources/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "resources" + } +} diff --git a/packages/client/resources/locale/zh.json b/packages/client/resources/locale/zh.json new file mode 100644 index 0000000000..4a9685490b --- /dev/null +++ b/packages/client/resources/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "客户端资源服务", + "description": "将文件等资源地址解析为可供界面读取的内容。" + } +} diff --git a/packages/client/resources/package.json b/packages/client/resources/package.json index 9664423589..1790c6ac68 100644 --- a/packages/client/resources/package.json +++ b/packages/client/resources/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -50,6 +51,7 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/resources/tsdown.config.ts b/packages/client/resources/tsdown.config.ts index a6e81e749c..7aa03cebc1 100644 --- a/packages/client/resources/tsdown.config.ts +++ b/packages/client/resources/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-resources', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/shortcuts/locale/en.json b/packages/client/shortcuts/locale/en.json new file mode 100644 index 0000000000..b79351a738 --- /dev/null +++ b/packages/client/shortcuts/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "shortcuts" + } +} diff --git a/packages/client/shortcuts/locale/zh.json b/packages/client/shortcuts/locale/zh.json new file mode 100644 index 0000000000..9bcdbae433 --- /dev/null +++ b/packages/client/shortcuts/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "快捷键服务", + "description": "注册应用快捷键,并将按键操作分发到对应功能。" + } +} diff --git a/packages/client/shortcuts/package.json b/packages/client/shortcuts/package.json index 0d9165439d..8bc13120c6 100644 --- a/packages/client/shortcuts/package.json +++ b/packages/client/shortcuts/package.json @@ -27,7 +27,8 @@ "./protocol": { "types": "./lib/types/protocol.d.ts", "default": "./lib/protocol.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,6 +56,7 @@ "@deepseek-ai/dsh-host-webserver": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/protocol.js", diff --git a/packages/client/shortcuts/tsdown.config.ts b/packages/client/shortcuts/tsdown.config.ts index 4f32cd61c0..bae160bb21 100644 --- a/packages/client/shortcuts/tsdown.config.ts +++ b/packages/client/shortcuts/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-client-shortcuts', + import.meta.dirname, ['lib/types/index.js', 'lib/types/protocol.js'], { hostPhase: true }, ) diff --git a/packages/client/store/tsdown.config.ts b/packages/client/store/tsdown.config.ts index b505d0388d..a6264e0b21 100644 --- a/packages/client/store/tsdown.config.ts +++ b/packages/client/store/tsdown.config.ts @@ -1,6 +1,6 @@ import { staticLinked } from '../tsdown.client.ts' export default staticLinked( - '@deepseek-ai/dsh-client-store', + import.meta.dirname, ['lib/types/index.js'], ) diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 9d9053ded3..888519a890 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -11,7 +11,7 @@ * inputs, including origins recorded by chained source maps. */ import { readFile, stat, utimes } from 'node:fs/promises' -import { existsSync, globSync, readFileSync } from 'node:fs' +import { existsSync, readFileSync } from 'node:fs' import { createRequire, isBuiltin } from 'node:module' import { basename, dirname, isAbsolute, relative, resolve as resolvePath, sep } from 'node:path' import { fileURLToPath } from 'node:url' @@ -100,22 +100,25 @@ function browserSourcePath(source: string, sourcemapPath: string): string { * the package without lib/index.js and the host Loader cannot import its node * half. The Client build consumes `lib/types` and chains those tsc maps, with * original source content, into the standalone plugin map. - * @param id - plugin id (package name), stamped into the __ModuleLoader__.load - * handoff and onto the injected style tags. + * @param packageDir - the package's own directory, normally the config's + * `import.meta.dirname`. Its `package.json` name is the plugin id stamped into + * the __ModuleLoader__.load handoff and onto the injected style tags. * @param libEntry - node-half entries. * @param options - phase placement, lib overrides, companion Node configs, and optional per-file Client banner. * @returns ENV-selected tsdown config for the current build face. + * @throws {Error} when `/package.json` is unreadable or declares no name. */ export function clientBundle( - id: string, + packageDir: string, libEntry: readonly string[], options: ClientBundleOptions = {}, ): BuildFaceConfig { - const lib = clientLibraryConfig(id, libEntry, options.lib) + const manifest = readPackageManifest(packageDir) + const lib = clientLibraryConfig(manifest, libEntry, options.lib) return ({ env }) => { const face = buildFace(env?.DSH_BUILD_FACE) const clientEntry = face === undefined ? 'src/client/index.ts' : 'lib/types/client/index.js' - const client = clientConfig(id, clientEntry, options.clientBanner) + const client = clientConfig(manifest, clientEntry, options.clientBanner) const node = [lib, ...(options.companions ?? [])] if (face === 'host') return options.hostPhase === true ? node : [SKIP_WORKSPACE_BUILD] if (face === 'client') { @@ -147,13 +150,16 @@ export function clientBundle( * 4. stylesheets ship with the package: a relative `.css` import survives as a * relative external and the sheet is emitted under `lib/` at its * `src`-relative path, so vite stays the only owner of class hashing. - * @param id - package name, used in tsdown diagnostics. + * @param packageDir - the package's own directory, normally the config's + * `import.meta.dirname`; its `package.json` name is used in tsdown diagnostics. * @param libEntry - emitted JavaScript entries consumed from `lib/types`, one * bundle each: a multi-entry build would emit a hash-named shared chunk that * the exact `files` list cannot publish. * @returns ENV-selected tsdown config for the Client build face. + * @throws {Error} when `/package.json` is unreadable or declares no name. */ -export function staticLinked(id: string, libEntry: readonly string[]): BuildFaceConfig { +export function staticLinked(packageDir: string, libEntry: readonly string[]): BuildFaceConfig { + const id = readPackageManifest(packageDir).name // Each entry names its own output file, so two entries with the same basename // would overwrite one artifact instead of emitting two. const names = new Set(libEntry.map(entry => basename(entry, '.js'))) @@ -177,12 +183,14 @@ export function isStaticLinkedConfig(configs: readonly UserConfig[]): boolean { /** * Build a Client-only Node library during the Client pass. - * @param id - Package name used in tsdown diagnostics. + * @param packageDir - The package's own directory, normally the config's + * `import.meta.dirname`; its `package.json` name is used in tsdown diagnostics. * @param libEntry - Emitted JavaScript entries consumed from `lib/types`. * @returns ENV-selected tsdown config for the Client build face. + * @throws {Error} when `/package.json` is unreadable or declares no name. */ -export function clientLibrary(id: string, libEntry: readonly string[]): BuildFaceConfig { - const lib = clientLibraryConfig(id, libEntry) +export function clientLibrary(packageDir: string, libEntry: readonly string[]): BuildFaceConfig { + const lib = clientLibraryConfig(readPackageManifest(packageDir), libEntry) return clientOnly([lib]) } @@ -218,14 +226,15 @@ function buildFace(value: unknown): BuildFace { } function clientLibraryConfig( - id: string, + manifest: PackageManifest, libEntry: readonly string[], overrides: UserConfig = {}, ): UserConfig { + let externals: readonly RegExp[] | undefined const isProductionDependency = (specifier: string): boolean => - matchesSpecifier(productionExternals(id), specifier) + matchesSpecifier(externals ??= productionExternals(manifest), specifier) return { - name: id, + name: manifest.name, entry: [...libEntry], outDir: 'lib', format: ['esm'], @@ -330,9 +339,10 @@ function stylesheetAsset(source: string, importer: string): { readonly file: str return { file, fileName: file.slice(boundary + SOURCE_MARKER.length).split(sep).join('/') } } -/** The manifest fields the build faces read to state their own module edges. */ -interface WorkspaceManifest { - readonly name?: string +/** The manifest fields the build faces read to name the package and state its own module edges. */ +interface PackageManifest { + /** Package name: the tsdown config name, the Client loader id, and the diagnostic subject. */ + readonly name: string /** Sections a real install materializes on disk next to the built package. */ readonly dependencies?: Record readonly peerDependencies?: Record @@ -340,52 +350,44 @@ interface WorkspaceManifest { readonly dsh?: { readonly client?: { readonly external?: unknown } } } -const manifestCache = new Map() -const productionExternalCache = new Map() -const clientExternalCache = new Map>() - /** - * Read one workspace package's manifest. Located by package name rather than by - * cwd, because tsdown evaluates every package config with the repository root as - * `process.cwd()` during a workspace build. Callers read it on the first - * resolveId of a build, not while a config is built, so selecting a build face - * never touches a manifest. - * @param id - package name, as spelled at the preset call site. + * Read the manifest of the package whose config calls a preset. The caller + * passes its directory because tsdown evaluates every package config with the + * repository root as `process.cwd()` during a workspace build. + * @param packageDir - the package's own directory. * @returns the parsed manifest. - * @throws {Error} when no workspace package declares that name. + * @throws {Error} when `package.json` is unreadable, is not JSON, or declares no string name. */ -function workspaceManifest(id: string): WorkspaceManifest { - const cached = manifestCache.get(id) - if (cached !== undefined) return cached - for (const manifestPath of globSync('packages/*/*/package.json', { cwd: REPOSITORY_ROOT })) { - const manifest = JSON.parse( - readFileSync(resolvePath(REPOSITORY_ROOT, manifestPath), 'utf8'), - ) as WorkspaceManifest - if (manifest.name !== id) continue - manifestCache.set(id, manifest) - return manifest +function readPackageManifest(packageDir: string): PackageManifest { + const manifestPath = resolvePath(packageDir, 'package.json') + let parsed: unknown + try { + parsed = JSON.parse(readFileSync(manifestPath, 'utf8')) + } catch (error) { + throw new Error( + `tsdown: cannot read ${manifestPath}; pass the package directory (the import.meta.dirname of its tsdown.config.ts)`, + { cause: error }, + ) } - throw new Error(`tsdown: no packages/*/*/package.json declares the name ${id}`) + if (typeof parsed !== 'object' || parsed === null || !('name' in parsed) || typeof parsed.name !== 'string') { + throw new Error(`tsdown: ${manifestPath} declares no string package name`) + } + return parsed as PackageManifest } /** * External patterns for one package's Node half: its own production sections, * subpaths included. - * @param id - package name, as spelled at the preset call site. + * @param manifest - the package's own manifest. * @returns one `^name(/|$)` pattern per production dependency, name-sorted. */ -function productionExternals(id: string): readonly RegExp[] { - const cached = productionExternalCache.get(id) - if (cached !== undefined) return cached - const manifest = workspaceManifest(id) +function productionExternals(manifest: PackageManifest): readonly RegExp[] { const names = new Set([ ...Object.keys(manifest.dependencies ?? {}), ...Object.keys(manifest.peerDependencies ?? {}), ...Object.keys(manifest.optionalDependencies ?? {}), ]) - const patterns = [...names].sort().map(name => new RegExp(`^${escapeSpecifier(name)}(/|$)`)) - productionExternalCache.set(id, patterns) - return patterns + return [...names].sort().map(name => new RegExp(`^${escapeSpecifier(name)}(/|$)`)) } /** @@ -408,19 +410,15 @@ export function requestedExternals( * Module-table specifiers one package requests. The shell baseline is implicit * for every dynamic bundle; `dsh.client.external` only adds package-specific * dynamic rows or subpaths. - * @param id - package name, as spelled at the preset call site. + * @param manifest - the package's own manifest, whose `dsh.client` declaration adds requests. * @returns the baseline plus the package's explicit requests. */ -function clientExternals(id: string): ReadonlySet { - const cached = clientExternalCache.get(id) - if (cached !== undefined) return cached - const externals = new Set([ +function clientExternals(manifest: PackageManifest): ReadonlySet { + return new Set([ ...PLATFORM_MODULES, ...PRELOADED_CLIENT_EXTERNALS, - ...requestedExternals(id, workspaceManifest(id).dsh?.client ?? {}), + ...requestedExternals(manifest.name, manifest.dsh?.client ?? {}), ]) - clientExternalCache.set(id, externals) - return externals } /** Escape a package name for literal use inside a RegExp source. */ @@ -469,8 +467,10 @@ function asyncChunkRequirePlugin(): TsdownPlugin { } } -function clientConfig(id: string, entry: string, clientBanner?: (fileName: string) => string | undefined): UserConfig { - const isRequested = (specifier: string): boolean => clientExternals(id).has(specifier) +function clientConfig(manifest: PackageManifest, entry: string, clientBanner?: (fileName: string) => string | undefined): UserConfig { + const id = manifest.name + let requested: ReadonlySet | undefined + const isRequested = (specifier: string): boolean => (requested ??= clientExternals(manifest)).has(specifier) const isolation = clientInputIsolation(id) return { name: `${id}/client`, diff --git a/packages/client/ui-agent-preset/README.i18n.yaml b/packages/client/ui-agent-preset/README.i18n.yaml index 4205a9cf81..889f6327b3 100644 --- a/packages/client/ui-agent-preset/README.i18n.yaml +++ b/packages/client/ui-agent-preset/README.i18n.yaml @@ -18,8 +18,8 @@ en: a21296842d6e18da zh: 75f3a6a79691884f /deepseek-ai-dsh-client-ui-agent-preset/understand-the-implementation: - en: b3221ef8bc6d8096 - zh: 68cb05566249da10 + en: a90bf7539dbce636 + zh: d77c1fecac2c6a4b /deepseek-ai-dsh-client-ui-agent-preset/further-exploration: en: bbae8d79844bc481 zh: 4302107fd1f460e6 diff --git a/packages/client/ui-agent-preset/README.md b/packages/client/ui-agent-preset/README.md index 75f778ff62..4108cc9231 100644 --- a/packages/client/ui-agent-preset/README.md +++ b/packages/client/ui-agent-preset/README.md @@ -45,7 +45,7 @@ Entering Creator selects `cordis` for the receiving blank Session without changi `agentPresets/list` supplies the roster and marks the current default, and `agentPresets/read` one declaration's YAML for the viewer; default changes write the `agent-preset-registry` settings namespace. The picker, blank-session synchronization and read-only session label use recorded preset identities. Connection resets and settings updates refresh the roster. -`CreatePluginMenuItem` contributes to `plugins.add.actions` using the shared roster store. Its selection calls the owner's `onDismiss()` before the same `startCreatorDraft` callback exposed to Settings as `creatorDraft`. That callback stages `cordis` through `AgentPresetSeatController` and opens the task through `uiWorkspace.startSession` with explicit draft preservation; it can reuse a blank Session and applies the staged choice when a Session binding becomes available. The choice is consumed once applied. Both Coding Tools states use the same picker and selection store, and `AgentPresetSeat` renders refusals through the shared `Toast` component. +`CreatePluginMenuItem` contributes to `plugins.add.actions` using the shared roster store. Its selection calls the owner's `onDismiss()` before the same `startCreatorDraft` callback exposed to Settings as `creatorDraft`. That callback stages `cordis` through `AgentPresetSeatController` and opens the task through `uiWorkspace.startSession` with explicit draft preservation and `agentPreset: 'cordis'`, so the Host composes the reused blank or new Session under Creator; without a target Workspace, the staged choice applies when a Session binding becomes available. The choice is consumed once applied. Both Coding Tools states use the same picker and selection store, and `AgentPresetSeat` renders refusals through the shared `Toast` component.
diff --git a/packages/client/ui-agent-preset/README.zh.md b/packages/client/ui-agent-preset/README.zh.md index 735d008239..256cc81182 100644 --- a/packages/client/ui-agent-preset/README.zh.md +++ b/packages/client/ui-agent-preset/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" `agentPresets/list` 提供列表并标记当前默认值,`agentPresets/read` 为查看器提供一条声明的 YAML;默认值的修改写入 `agent-preset-registry` settings 命名空间。选择器、空白会话同步和只读会话标签使用记录的 preset 标识。连接重置和设置更新会刷新列表。 -`CreatePluginMenuItem` 使用共享的预设列表 store,向 `plugins.add.actions` 贡献菜单项。选择时先调用页面传入的 `onDismiss()`,再调用与设置页 `creatorDraft` 相同的 `startCreatorDraft` 回调。该回调通过 `AgentPresetSeatController` 暂存 `cordis`,再通过显式保留草稿的 `uiWorkspace.startSession` 调用打开任务;它可以复用空白 Session,并在 Session 绑定可用时应用暂存选择。暂存选择应用后即清除。代码工作工具开启或关闭时均使用同一个选择器和选择 store,`AgentPresetSeat` 通过共享的 `Toast` 组件显示拒绝原因。 +`CreatePluginMenuItem` 使用共享的预设列表 store,向 `plugins.add.actions` 贡献菜单项。选择时先调用页面传入的 `onDismiss()`,再调用与设置页 `creatorDraft` 相同的 `startCreatorDraft` 回调。该回调通过 `AgentPresetSeatController` 暂存 `cordis`,再通过显式保留草稿并传入 `agentPreset: 'cordis'` 的 `uiWorkspace.startSession` 调用打开任务,由 Host 以创造模式组合被复用的空白 Session 或新 Session;没有目标工作区时,暂存选择在 Session 绑定可用时应用。暂存选择应用后即清除。代码工作工具开启或关闭时均使用同一个选择器和选择 store,`AgentPresetSeat` 通过共享的 `Toast` 组件显示拒绝原因。
diff --git a/packages/client/ui-agent-preset/locale/en.json b/packages/client/ui-agent-preset/locale/en.json new file mode 100644 index 0000000000..6cb010026a --- /dev/null +++ b/packages/client/ui-agent-preset/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-agent-preset" + } +} diff --git a/packages/client/ui-agent-preset/locale/zh.json b/packages/client/ui-agent-preset/locale/zh.json new file mode 100644 index 0000000000..4e8dd6b04d --- /dev/null +++ b/packages/client/ui-agent-preset/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Agent 预设界面", + "description": "选择当前及新会话的 Agent 预设,并编辑预设使用的插件。" + } +} diff --git a/packages/client/ui-agent-preset/package.json b/packages/client/ui-agent-preset/package.json index 10eab5b9d8..93a5319006 100644 --- a/packages/client/ui-agent-preset/package.json +++ b/packages/client/ui-agent-preset/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -67,10 +68,10 @@ "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-agent-preset/src/client/index.ts b/packages/client/ui-agent-preset/src/client/index.ts index 1abeb855be..6fa0e3e4ad 100644 --- a/packages/client/ui-agent-preset/src/client/index.ts +++ b/packages/client/ui-agent-preset/src/client/index.ts @@ -5,8 +5,8 @@ * the roster (selection, the new-task default, a read-only view of each * declared composition, and the way into Creator mode). * - * A running session keeps the composition it began with (the host refuses to - * adopt an existing session under a different preset). That is what splits + * A running session keeps the composition it began with (the host switches a + * session's preset only before its first turn). That is what splits * the choice from the display: the hero chip is before-the-fact, while the * header only reports what a session already runs. The default preset is * edited where the roster is visible — the settings section's "make default" @@ -198,10 +198,10 @@ export function apply(ctx: ClientContext): void { }) const startCreatorDraft = () => { + // The Host composes the reused draft or new Session; the stage only drives the chip's display and introduction. const seat = mainBlankSeat() ?? unboundSeat seat.stage('cordis', true) - scope.uiWorkspace.startSession(undefined, { clearPreviousDraft: false }) - void seat.apply() + scope.uiWorkspace.startSession(undefined, { clearPreviousDraft: false, agentPreset: 'cordis' }) } scope.effect(() => { diff --git a/packages/client/ui-agent-preset/src/client/seat-store.ts b/packages/client/ui-agent-preset/src/client/seat-store.ts index dfa2c69945..0a1860ba86 100644 --- a/packages/client/ui-agent-preset/src/client/seat-store.ts +++ b/packages/client/ui-agent-preset/src/client/seat-store.ts @@ -3,8 +3,10 @@ * * The new-session screen has no session, so a pick is staged rather than * applied. It reaches a session when one becomes current and is still blank — - * whether the workspace connect created it or reused an existing blank one, - * which is why staging cannot simply ride along on `sessions.create`. + * whether the workspace connect created it or reused an existing blank one. A + * flow that knows its preset before it starts (the settings section's creator + * entry) passes it to session creation instead, and its stage only drives the + * chip's display. * * The stage is forgotten once applied. The next new session starts from the * Host-effective default again. diff --git a/packages/client/ui-agent-preset/tests/apply.client.spec.ts b/packages/client/ui-agent-preset/tests/apply.client.spec.ts index aa52b2c3d7..c891d1d6d4 100644 --- a/packages/client/ui-agent-preset/tests/apply.client.spec.ts +++ b/packages/client/ui-agent-preset/tests/apply.client.spec.ts @@ -212,7 +212,7 @@ function declareConversation(slots: SlotRegistry): () => void { /** A Workspace UI double recording new-session starts. */ function uiWorkspaceDouble() { - const starts: unknown[] = [] + const starts: { workspaceId: unknown; options: unknown }[] = [] return { starts, startSession: (workspaceId?: unknown, options?: unknown) => { starts.push({ workspaceId, options }) }, @@ -1066,7 +1066,7 @@ describe('ui-agent-preset apply', () => { // new-session flow began. expect(section.startCreatorDraft).toBeDefined() expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis') - expect(uiWorkspace.starts).toHaveLength(1) + expect(uiWorkspace.starts).toEqual([{ workspaceId: undefined, options: { clearPreviousDraft: false, agentPreset: 'cordis' } }]) // A cross-screen stage carries the introduce cue; the chip acknowledges // it once, and a repeat acknowledgement leaves the snapshot untouched. @@ -1079,15 +1079,16 @@ describe('ui-agent-preset apply', () => { conversation() }) - it('applies the creator preset to an existing blank main Session', async () => { + it('lets the new-session flow compose the creator preset on a blank main Session', async () => { const { ctx, slots, calls } = await bench() declareRoot(slots) const conversation = declareConversation(slots) ctx.provide('conversation', {} as never) - const sessions = sessionsDouble(ctx, { + const state = { current: 's1', byId: { s1: { id: 's1', blank: true, projectionValues: { agentPreset: 'standard' } } }, - }) + } + const sessions = sessionsDouble(ctx, state) ctx.provide('sessions', sessions as never) const uiWorkspace = uiWorkspaceDouble() ctx.provide('uiWorkspace', uiWorkspace as never) @@ -1100,10 +1101,13 @@ describe('ui-agent-preset apply', () => { await seat.load() await section.load() section.startCreatorDraft?.() + expect(uiWorkspace.starts).toEqual([{ workspaceId: undefined, options: { clearPreviousDraft: false, agentPreset: 'cordis' } }]) - await vi.waitFor(() => { expect(calls).toContain('select:cordis') }) - expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis') - expect(uiWorkspace.starts).toEqual([{ workspaceId: undefined, options: { clearPreviousDraft: false } }]) + // The Host composes the reused Session; the chip only follows its projection. + state.byId.s1 = { id: 's1', blank: true, projectionValues: { agentPreset: 'cordis' } } + sessions.notify() + await vi.waitFor(() => { expect(seat.hooks.agentPresetSeat.getSnapshot().current).toBe('cordis') }) + expect(calls).not.toContain('select:cordis') conversation() }) diff --git a/packages/client/ui-agent-preset/tsdown.config.ts b/packages/client/ui-agent-preset/tsdown.config.ts index 3f5cc0a823..7aa03cebc1 100644 --- a/packages/client/ui-agent-preset/tsdown.config.ts +++ b/packages/client/ui-agent-preset/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-agent-preset', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-approval/locale/en.json b/packages/client/ui-approval/locale/en.json new file mode 100644 index 0000000000..48c1a5785f --- /dev/null +++ b/packages/client/ui-approval/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-approval" + } +} diff --git a/packages/client/ui-approval/locale/zh.json b/packages/client/ui-approval/locale/zh.json new file mode 100644 index 0000000000..e93a40b026 --- /dev/null +++ b/packages/client/ui-approval/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "操作审批界面", + "description": "展示待审批的操作,并将用户选择返回给运行中的任务。" + } +} diff --git a/packages/client/ui-approval/package.json b/packages/client/ui-approval/package.json index 3d34e53fbf..8c86cc1348 100644 --- a/packages/client/ui-approval/package.json +++ b/packages/client/ui-approval/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -59,11 +60,11 @@ "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "@deepseek-ai/dsh-client-shortcuts": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-approval/tsdown.config.ts b/packages/client/ui-approval/tsdown.config.ts index 4ddd1fdffe..7aa03cebc1 100644 --- a/packages/client/ui-approval/tsdown.config.ts +++ b/packages/client/ui-approval/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-approval', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-attachment/README.i18n.yaml b/packages/client/ui-attachment/README.i18n.yaml index fa658714af..123b686b4e 100644 --- a/packages/client/ui-attachment/README.i18n.yaml +++ b/packages/client/ui-attachment/README.i18n.yaml @@ -27,8 +27,8 @@ en: 836a62c8f73366ac zh: 35da7836eaf68a67 /deepseek-ai-dsh-client-ui-attachment/understand-the-implementation: - en: 415bd2b09bb84b6b - zh: 2e49a39fb3957b4f + en: 07204b7d538b7434 + zh: 705cc6b0c9387cce /deepseek-ai-dsh-client-ui-attachment/further-exploration: en: 733ac3e4df52d6e9 zh: 98a6a8cac7d66645 diff --git a/packages/client/ui-attachment/README.md b/packages/client/ui-attachment/README.md index 4c344a07d7..4fee29e123 100644 --- a/packages/client/ui-attachment/README.md +++ b/packages/client/ui-attachment/README.md @@ -49,7 +49,7 @@ While a file drag is over the page, the full-viewport overlay announces the drop
Implementation internals — click to expand -The plugin waits for `conversation.input.attachments`, `conversation.message.images`, `conversation.trajectory.images`, and `tool.call.images` through `ctx.slots.inject`. It then registers the composer rail, document drop target, shared history gallery for Chat, Trajectory, and Tool results, and original-image lightbox. The presentation components are driven entirely by props: the slot owner supplies attachment data, image loading, callbacks, and the locale translator; the package entry exports no components. +The plugin provides the root-scoped `conversation.images.content` Factory. Its official `MessageImages` entries fill `conversation.chat.user.images`, `conversation.chat.message.images`, `conversation.trajectory.images`, and `tool.call.images` at priority 100 through `ctx.slots.inject`. A lower-priority entry replaces only its own position; removing it restores the official entry. All defaults reuse one gallery with explicit image references, authorized loader, layout hints, and optional complete labels. The Factory owns gallery presentation and default copy, not Session state or read authorization. Each domain owns its Slot declaration. The composer attachment rail remains a separate entry, and the package entry exports no components. | File | Role | |---|---| diff --git a/packages/client/ui-attachment/README.zh.md b/packages/client/ui-attachment/README.zh.md index c9cc5e60f3..706a6d97c7 100644 --- a/packages/client/ui-attachment/README.zh.md +++ b/packages/client/ui-attachment/README.zh.md @@ -49,7 +49,7 @@ Trajectory 附件行使用 48px 方形缩略图,完整缩放图片而不裁剪
实现细节——点击展开 -插件通过 `ctx.slots.inject` 等待 `conversation.input.attachments`、`conversation.message.images`、`conversation.trajectory.images` 与 `tool.call.images`。随后它注册 composer rail、文档拖放目标、供 Chat、Trajectory 与工具结果共用的历史图片 gallery,以及原图灯箱。呈现组件仅依赖 props:slot 持有方提供附件数据、图片加载、回调与语言包翻译器;包入口不导出任何组件。 +插件提供 root 作用域的 `conversation.images.content` Factory。官方 `MessageImages` 条目通过 `ctx.slots.inject`,以优先级 100 填入 `conversation.chat.user.images`、`conversation.chat.message.images`、`conversation.trajectory.images` 和 `tool.call.images`。较低优先级的条目只替换自身所在位置,移除后恢复官方条目。各默认条目复用同一画廊,显式传入图片引用、授权 loader、布局参数和可选的完整 labels。Factory 负责画廊展示与默认文案,不拥有 Session 状态或读取授权。各领域拥有自己的 Slot 声明。Composer 附件栏仍为独立条目,包入口不导出任何组件。 | 文件 | 职责 | |---|---| diff --git a/packages/client/ui-attachment/locale/en.json b/packages/client/ui-attachment/locale/en.json new file mode 100644 index 0000000000..5d1be6fe24 --- /dev/null +++ b/packages/client/ui-attachment/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-attachment" + } +} diff --git a/packages/client/ui-attachment/locale/zh.json b/packages/client/ui-attachment/locale/zh.json new file mode 100644 index 0000000000..13fe1edf53 --- /dev/null +++ b/packages/client/ui-attachment/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "附件展示", + "description": "在消息输入、对话和运行记录中展示附件与图片。" + } +} diff --git a/packages/client/ui-attachment/package.json b/packages/client/ui-attachment/package.json index 8e18afbe65..3b2483a7e6 100644 --- a/packages/client/ui-attachment/package.json +++ b/packages/client/ui-attachment/package.json @@ -23,11 +23,13 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { "inject": [ + "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-ui-chat", "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-renderer", @@ -44,8 +46,7 @@ "license": "MIT", "devDependencies": { "@deepseek-ai/cordis": "workspace:~", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", + "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-ui-chat": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-trajectory": "workspace:*", @@ -59,6 +60,7 @@ "clsx": "^2.0.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-attachment/src/MessageImage.tsx b/packages/client/ui-attachment/src/MessageImage.tsx index 7f350bbc94..a067ffd446 100644 --- a/packages/client/ui-attachment/src/MessageImage.tsx +++ b/packages/client/ui-attachment/src/MessageImage.tsx @@ -2,9 +2,11 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import { IconLoadingOutlineRegular, IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { ImageLightbox } from '@deepseek-ai/dsh-client-ui-primitives' -import type { ImageLightboxLabels } from '@deepseek-ai/dsh-client-ui-primitives' +import type { MessageImageLabels } from '@deepseek-ai/dsh-client-ui-conversation/client' import css from './MessageImage.module.css' +export type { MessageImageLabels } from '@deepseek-ai/dsh-client-ui-conversation/client' + /** Loads a session-authorized durable image URL and may expose a cached URL synchronously. */ export type ImageLoader = ((attachment: ImageAttachmentRef) => Promise) & { peek?: (attachment: ImageAttachmentRef) => string | undefined @@ -26,22 +28,6 @@ export type MessageImageSpec = } } -/** Message-image strings the owner resolves from its own locale namespace. */ -export interface MessageImageLabels { - /** Fallback display name for an unnamed image. */ - image: string - /** Thumbnail tooltip inviting the original-image preview. */ - open: string - /** Accessible thumbnail label; receives the image's display name. */ - openNamed: (label: string) => string - /** Loading placeholder shown until bytes resolve. */ - loading: string - /** Retry-control label shown when the load fails. */ - loadFailed: string - /** Lightbox strings forwarded to the opened preview. */ - lightbox: ImageLightboxLabels -} - /** Display box for a lone image (DeepSeek Chat rule): long edge 240px with * the rendered aspect ratio clamped to [0.25, 4] — the overflow is cropped by * `object-fit: cover` — and never upscaled past the image's natural size. The diff --git a/packages/client/ui-attachment/src/client/MessageImages.tsx b/packages/client/ui-attachment/src/client/MessageImages.tsx index 192147f877..76a0718c1f 100644 --- a/packages/client/ui-attachment/src/client/MessageImages.tsx +++ b/packages/client/ui-attachment/src/client/MessageImages.tsx @@ -1,17 +1,33 @@ -import type { MessageImagesProps } from '@deepseek-ai/dsh-client-ui-chat/client' +/** Official image gallery Factory and default image Slot adapter. */ +import { useMemo } from 'react' +import type { FactoryComponentPropsOf, PropsRenderFactories } from '@deepseek-ai/dsh-client-ui-slots' +import type { MessageImagesOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client' import { ImageGallery } from '../MessageImage.tsx' import { messageImageLabels } from './labels.ts' -/** Historical message-image slot entry. */ -export function MessageImages({ images, loadImage, align, compact = false, thumbnail = false, t }: MessageImagesProps) { - return ( - - ) +type MessageImagesProps = MessageImagesOwnerProps & PropsRenderFactories + +/** + * Render a gallery with an authorized loader and caller-owned or default labels. + * @param props - image sources, authorized loader, layout hints, optional labels, and Factory locale seat. + * @returns the official gallery; no Session binding is needed by this component. + */ +export function MessageImagesContent({ images, loadImage, align, compact = false, thumbnail = false, labels, t }: +FactoryComponentPropsOf<'conversation.images.content'>) { + const resolved = useMemo(() => labels ?? messageImageLabels(t), [labels, t]) + return +} + +/** + * Fill a message, trajectory, or tool image position through the shared Content Factory. + * @param props - Slot owner image data, authorized loader, and framework Factory renderer. + * @returns the official gallery occurrence. + */ +export function MessageImages({ images, loadImage, align, compact, thumbnail, renderFactorySlot }: MessageImagesProps) { + return renderFactorySlot('conversation.images.content', { + images, loadImage, align, + ...compact === undefined ? {} : { compact }, + ...thumbnail === undefined ? {} : { thumbnail }, + }) } diff --git a/packages/client/ui-attachment/src/client/index.ts b/packages/client/ui-attachment/src/client/index.ts index 62deeebfc3..75059f84b3 100644 --- a/packages/client/ui-attachment/src/client/index.ts +++ b/packages/client/ui-attachment/src/client/index.ts @@ -1,4 +1,4 @@ -/** Browser attachment plugin: fills conversation's composer and image slots. */ +/** Browser attachment plugin: composer entries and independently replaceable image galleries. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' @@ -6,29 +6,33 @@ import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-tool/client' import type {} from '@deepseek-ai/dsh-client-ui-trajectory/client' import { ComposerAttachments } from './ComposerAttachments.tsx' -import { MessageImages } from './MessageImages.tsx' +import { MessageImages, MessageImagesContent } from './MessageImages.tsx' -/** Slot registry required by this presentation plugin. */ +/** Slot registry required by the attachment presentation plugin. */ export const inject = ['slots'] -/** Register attachment presentation without exporting React components as package values. */ +/** + * Register composer attachments and the shared gallery with its domain adapters. + * @param ctx - client plugin context with the Slot registry. + */ export function apply(ctx: ClientContext): void { + ctx.slots.registerFactory({ + name: 'conversation.images.content', scope: 'root', locale: 'conversation', + }, MessageImagesContent) ctx.slots.inject('conversation.input.attachments', () => ctx.slots.register({ name: 'conversation.input.attachments', locale: 'conversation', }, ComposerAttachments)) - ctx.slots.inject('conversation.message.images', () => ctx.slots.register({ - name: 'conversation.message.images', - locale: 'conversation', + ctx.slots.inject('conversation.chat.message.images', () => ctx.slots.register({ + name: 'conversation.chat.message.images', priority: 100, + }, MessageImages)) + ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({ + name: 'conversation.chat.user.images', priority: 100, }, MessageImages)) ctx.slots.inject('conversation.trajectory.images', () => ctx.slots.register({ - name: 'conversation.trajectory.images', - locale: 'conversation', + name: 'conversation.trajectory.images', priority: 100, }, MessageImages)) - // The tool image gallery reuses the message gallery renderer: its owner - // carries the same images/loadImage/align share the message arm does. ctx.slots.inject('tool.call.images', () => ctx.slots.register({ - name: 'tool.call.images', - locale: 'conversation', + name: 'tool.call.images', priority: 100, }, MessageImages)) } diff --git a/packages/client/ui-attachment/tests/image-slot-isolation.client.spec.tsx b/packages/client/ui-attachment/tests/image-slot-isolation.client.spec.tsx new file mode 100644 index 0000000000..04f83f3ba8 --- /dev/null +++ b/packages/client/ui-attachment/tests/image-slot-isolation.client.spec.tsx @@ -0,0 +1,76 @@ +// @vitest-environment jsdom +/** Independent domain image positions with one shared official gallery Factory. */ +import { act, cleanup, within } from '@testing-library/react' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { AttachmentId } from '@deepseek-ai/dsh-attachment' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { UiConversation } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/assembly.ts' +import { en, zh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts' +import type { MessageImagesOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import * as attachmentPlugin from '../src/client/index.ts' + +afterEach(cleanup) + +const SLOTS = [ + 'conversation.chat.user.images', 'conversation.chat.message.images', + 'conversation.trajectory.images', 'tool.call.images', +] as const + +async function bench() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + locale.register('conversation', { en, zh }) + locale.setLocale('en') + runtime.ctx.provide('locale', locale) + runtime.slots.installLocale(locale) + new UiConversation(runtime.ctx, runtime.sessions) + await runtime.mount(attachmentPlugin) + await runtime.sessions.add({ id: 'image-domains' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('image-domains')) + const input: MessageImagesOwnerProps = { + images: [{ attachment: { + attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), mediaType: 'image/png', + name: 'shared.png', width: 1, height: 1, bytes: 68, + } }], + loadImage: vi.fn(async () => 'blob:shared'), align: 'start', + } + await runtime.root.declare({ + 'conversation.chat.user.images': { kind: 'single', scope: 'session' }, + 'conversation.chat.message.images': { kind: 'single', scope: 'session' }, + 'conversation.trajectory.images': { kind: 'single', scope: 'session' }, + 'tool.call.images': { kind: 'single', scope: 'session' }, + }, ({ renderSlot, SessionProvider }) => + {SLOTS.map(name =>
{renderSlot(name, input)}
)} +
) + return { runtime, view: runtime.renderRoot() } +} + +describe('domain image Slots', () => { + it.each(SLOTS)('replaces only %s and restores the shared gallery on disposal', async (name) => { + const { runtime, view } = await bench() + expect(runtime.factoryOf('conversation.images.content').scope).toBe('root') + const images = new Map() + for (const slot of SLOTS) { + expect(runtime.slots.entries(slot)[0]?.options.priority).toBe(100) + images.set(slot, await within(view.getByTestId(slot)).findByAltText('shared.png')) + } + const override = await runtime.mount({ inject: ['slots'], apply(ctx) { + ctx.slots.register({ name, priority: 0 }, () => Domain override) + } }) + const target = within(view.getByTestId(name)) + expect(target.getByText('Domain override')).toBeTruthy() + expect(target.queryByAltText('shared.png')).toBeNull() + for (const other of SLOTS.filter(slot => slot !== name)) { + expect(within(view.getByTestId(other)).getByAltText('shared.png')).toBe(images.get(other)) + } + await act(async () => { await override.dispose() }) + expect(target.queryByText('Domain override')).toBeNull() + expect(await target.findByAltText('shared.png')).toBeTruthy() + for (const other of SLOTS.filter(slot => slot !== name)) { + expect(within(view.getByTestId(other)).getByAltText('shared.png')).toBe(images.get(other)) + } + }) +}) diff --git a/packages/client/ui-attachment/tests/message-image.client.spec.tsx b/packages/client/ui-attachment/tests/message-image.client.spec.tsx index 7fa2c0a980..d447df5fd9 100644 --- a/packages/client/ui-attachment/tests/message-image.client.spec.tsx +++ b/packages/client/ui-attachment/tests/message-image.client.spec.tsx @@ -1,18 +1,18 @@ // @vitest-environment jsdom -import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { useState } from 'react' +import type { PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react' import { AttachmentId } from '@deepseek-ai/dsh-attachment' -import { EMPTY_CHAT_SNAPSHOT, type MessageImagesProps } from '@deepseek-ai/dsh-client-ui-chat/client' -import { EMPTY_CONVERSATION_SNAPSHOT } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { en, zh } from '@deepseek-ai/dsh-client-ui-conversation/src/client/locales.ts' +import { UiConversation } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/assembly.ts' import { ImageGallery, MessageImage } from '../src/MessageImage.tsx' import type { MessageImageLabels } from '../src/MessageImage.tsx' -import { MessageImages } from '../src/client/MessageImages.tsx' - -// Every session-scope fixture carries the resource hook the resources plugin merges into GlobalStandardProps. -const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined, reload: () => {} })) as GlobalStandardProps['useResource'] -const usePanelInfo: GlobalStandardProps['usePanelInfo'] = selector => selector({ activePanelId: null }) +import * as attachmentPlugin from '../src/client/index.ts' afterEach(cleanup) @@ -34,23 +34,6 @@ const attachment = { name: 'history.png', } -type AttentionSnapshot = Parameters[0]>[0] -type TrajectorySnapshot = Parameters[0]>[0] - -const noAttention: AttentionSnapshot = new Map() -const emptyTrajectory: TrajectorySnapshot = { - eventNodes: [], - eventLocations: new Map(), - requests: [], - callSchemas: new Map(), - partial: null, - runningCalls: [], -} -const useSessionStatus: MessageImagesProps['useSessionStatus'] = selector => selector(noAttention) -const useConversation: MessageImagesProps['useConversation'] = selector => selector(EMPTY_CONVERSATION_SNAPSHOT) -const useChat: MessageImagesProps['useChat'] = selector => selector(EMPTY_CHAT_SNAPSHOT) -const useTrajectory: MessageImagesProps['useTrajectory'] = selector => selector(emptyTrajectory) - describe('MessageImage', () => { it('renders a cached URL on the first frame while refreshing it', () => { const load = Object.assign(vi.fn(() => new Promise(() => {})), { @@ -285,65 +268,77 @@ describe('ImageGallery', () => { expect(several.container.querySelectorAll('[data-variant="tile"]')).toHaveLength(3) }) + it('uses complete Factory labels unchanged and restores defaults without remounting the image', async () => { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + locale.register('conversation', { en, zh }) + locale.setLocale('en') + runtime.ctx.provide('locale', locale) + runtime.slots.installLocale(locale) + await runtime.mount(attachmentPlugin) + const images = [{ preview: { url: 'blob:labels', name: 'preview.png' } }] + const loadImage = vi.fn(async () => 'blob:unused') + await runtime.root.declare({}, ({ renderFactorySlot }: PropsRuntime<'root'> & PropsRenderFactories) => { + const [custom, setCustom] = useState(true) + return <> + + {renderFactorySlot('conversation.images.content', { + images, loadImage, align: 'start', ...(custom ? { labels } : {}), + })} + + }) + const view = runtime.renderRoot() + const image = view.getByAltText('preview.png') + const frame = view.getByRole('button', { name: 'preview.png,点击查看原图' }) + expect(frame.getAttribute('title')).toBe(labels.open) + fireEvent.click(frame) + expect(view.getByRole('dialog', { name: labels.lightbox.dialog })).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: labels.lightbox.close })) + fireEvent.click(view.getByRole('button', { name: 'Default labels' })) + const defaultFrame = view.getByRole('button', { name: 'preview.png, click to view original' }) + expect(defaultFrame).toBe(frame) + expect(view.getByAltText('preview.png')).toBe(image) + expect(defaultFrame.getAttribute('title')).toBe('View original') + fireEvent.click(defaultFrame) + expect(view.getByRole('dialog', { name: 'Original image preview' })).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: 'Close original image preview' })) + expect(loadImage).not.toHaveBeenCalled() + }) + it('renders the conversation slot entry with translated labels', async () => { - const t = ((key: string, params?: Readonly>) => { - const translated: Record = { - 'image.label': '图片', - 'image.openOriginal': '查看原图', - 'image.loading': '图片加载中…', - 'image.loadFailed': '图片加载失败,点击重试', - 'image.preview': '原图预览', - 'image.closePreview': '关闭原图预览', - } - if (key === 'image.openOriginalLabel') { - const label = params?.label - return `${typeof label === 'string' ? label : ''},点击查看原图` - } - return translated[key] ?? key - }) as MessageImagesProps['t'] + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + locale.register('conversation', { en, zh }) + locale.setLocale('zh') + runtime.ctx.provide('locale', locale) + new UiConversation(runtime.ctx, runtime.sessions) + runtime.slots.installLocale(locale) + await runtime.declare({ 'conversation.chat.message.images': { kind: 'single', scope: 'session' } }) + await runtime.mount(attachmentPlugin) + await runtime.sessions.add({ id: 'message-images-test' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('message-images-test')) const loadImage = vi.fn().mockResolvedValue('blob:slot-image') - const useSession: MessageImagesProps['useSession'] = () => { - throw new Error('MessageImages does not read the session snapshot') - } - const useInput: MessageImagesProps['useInput'] = () => { - throw new Error('MessageImages does not read the input snapshot') - } - const useSessions: MessageImagesProps['useSessions'] = () => { - throw new Error('MessageImages does not read the session list snapshot') - } - const useWorkspaces: MessageImagesProps['useWorkspaces'] = () => { - throw new Error('MessageImages does not read the workspace list snapshot') - } - const props: MessageImagesProps = { - sessionId: 'message-images-test' as MessageImagesProps['sessionId'], - useSession, - useSessions, - usePanelInfo, useSessionRetainInfo: () => undefined, useResource, - useSessionStatus, - useWorkspaces, - useProjection: () => undefined, - useConversation, - useChat, - useTrajectory, - useInput, - inputActions: { - captureInsertion: () => ({ start: 0, end: 0, draftRev: 0 }), - insertText: () => false, - setDraft: vi.fn(), - persistDraft: vi.fn(), - addAttachments: vi.fn(() => true), - removeAttachment: vi.fn(), - pruneAttachments: vi.fn(), - submit: vi.fn(), - }, - images: [{ attachment }], - loadImage, - align: 'end', - t, - } - const view = render() + const slot = runtime.renderSlot('conversation.chat.message.images', { + images: [{ attachment }], loadImage, align: 'end', + }, { session }) + const { view, container } = slot await waitFor(() => { expect(view.getByAltText('history.png')).toBeTruthy() }) expect(view.getByRole('button', { name: 'history.png,点击查看原图' })).toBeTruthy() - expect(view.container.querySelector('[data-align="end"]')).not.toBeNull() + expect(container.querySelector('[data-align="end"]')).not.toBeNull() + expect(loadImage).toHaveBeenCalledWith(attachment) + expect(view.getByRole('button', { name: 'history.png,点击查看原图' }).getAttribute('data-variant')).toBe('single') + for (const [compact, thumbnail, variant] of [ + [true, false, 'tile'], + [false, true, 'thumbnail'], + [false, false, 'single'], + ] as const) { + slot.update({ images: [{ attachment }], loadImage, align: 'end', compact, thumbnail }) + expect(view.getByRole('button', { name: 'history.png,点击查看原图' }).getAttribute('data-variant')).toBe(variant) + expect(view.getByAltText('history.png').getAttribute('src')).toBe('blob:slot-image') + expect(container.querySelector('[data-align="end"]')).not.toBeNull() + } + expect(loadImage).toHaveBeenCalledOnce() }) }) diff --git a/packages/client/ui-attachment/tests/plugin.client.spec.ts b/packages/client/ui-attachment/tests/plugin.client.spec.ts index a83b33e8e0..6181d8db35 100644 --- a/packages/client/ui-attachment/tests/plugin.client.spec.ts +++ b/packages/client/ui-attachment/tests/plugin.client.spec.ts @@ -1,26 +1,42 @@ import { Context } from '@deepseek-ai/cordis' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, onTestFinished, vi } from 'vitest' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { TestSessions } from '@deepseek-ai/dsh-client-test-runtime' import { apply as applyHost } from '../src/index.ts' import { apply, inject } from '../src/client/index.ts' import { ComposerAttachments } from '../src/client/ComposerAttachments.tsx' -import { MessageImages } from '../src/client/MessageImages.tsx' +import { MessageImages, MessageImagesContent } from '../src/client/MessageImages.tsx' + +const IMAGE_SLOTS = [ + 'conversation.chat.message.images', 'conversation.chat.user.images', + 'conversation.trajectory.images', 'tool.call.images', +] as const async function bench() { const ctx = new Context() + const sessions = new TestSessions(async (action) => { await action() }, ctx) + onTestFinished(async () => { + await sessions.disposeScopes() + await ctx.fiber.dispose() + }) + ctx.provide('sessions', sessions) + ctx.provide('locale', new LocaleRuntime(ctx)) await ctx.plugin(SlotRegistry).await() ctx.slots.register({ name: 'root', children: { 'conversation.input.attachments': { kind: 'single', scope: 'session-maybe' }, - 'conversation.message.images': { kind: 'single', scope: 'session' }, + 'conversation.chat.message.images': { kind: 'single', scope: 'session' }, + 'conversation.chat.user.images': { kind: 'single', scope: 'session' }, 'conversation.trajectory.images': { kind: 'single', scope: 'session' }, 'tool.call.images': { kind: 'single', scope: 'session' }, }, } as never, () => null) + const registerFactory = vi.spyOn(ctx.slots, 'registerFactory') const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() - return { ctx, fiber } + return { ctx, fiber, registerFactory } } describe('attachment plugin', () => { @@ -29,30 +45,21 @@ describe('attachment plugin', () => { }) it('registers all entries and removes them with the plugin fiber', async () => { - const { ctx, fiber } = await bench() + const { ctx, fiber, registerFactory } = await bench() expect(inject).toEqual(['slots']) + expect(registerFactory).toHaveBeenCalledWith({ + name: 'conversation.images.content', scope: 'root', locale: 'conversation', + }, MessageImagesContent) + expect(ctx.slots.snapshot('factory:conversation.images.content')).toHaveLength(1) expect(ctx.slots.entries('conversation.input.attachments')).toMatchObject([{ - locale: 'conversation', - component: ComposerAttachments, + locale: 'conversation', component: ComposerAttachments, }]) - expect(ctx.slots.entries('conversation.message.images')).toMatchObject([{ - locale: 'conversation', - component: MessageImages, - }]) - expect(ctx.slots.entries('conversation.trajectory.images')).toMatchObject([{ - locale: 'conversation', - component: MessageImages, - }]) - expect(ctx.slots.entries('tool.call.images')).toMatchObject([{ - locale: 'conversation', - component: MessageImages, - }]) - + for (const name of IMAGE_SLOTS) { + expect(ctx.slots.entries(name)).toMatchObject([{ component: MessageImages, options: { priority: 100 } }]) + } await fiber.dispose() - expect(ctx.slots.entries('conversation.input.attachments')).toHaveLength(0) - expect(ctx.slots.entries('conversation.message.images')).toHaveLength(0) - expect(ctx.slots.entries('conversation.trajectory.images')).toHaveLength(0) - expect(ctx.slots.entries('tool.call.images')).toHaveLength(0) + for (const name of IMAGE_SLOTS) expect(ctx.slots.entries(name)).toHaveLength(0) + expect(ctx.slots.snapshot('factory:conversation.images.content')).toHaveLength(0) }) }) diff --git a/packages/client/ui-attachment/tsconfig.json b/packages/client/ui-attachment/tsconfig.json index 1f5b771ac1..136e1ebb26 100644 --- a/packages/client/ui-attachment/tsconfig.json +++ b/packages/client/ui-attachment/tsconfig.json @@ -34,6 +34,9 @@ }, { "path": "../ui-primitives" + }, + { + "path": "../locale/tsconfig.client.json" } ] } diff --git a/packages/client/ui-attachment/tsdown.config.ts b/packages/client/ui-attachment/tsdown.config.ts index 2c903ce9af..3a0694bdf9 100644 --- a/packages/client/ui-attachment/tsdown.config.ts +++ b/packages/client/ui-attachment/tsdown.config.ts @@ -1,6 +1,6 @@ import { clientBundle } from '../tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-client-ui-attachment', + import.meta.dirname, ['lib/types/index.js'], ) diff --git a/packages/client/ui-brand-official/locale/en.json b/packages/client/ui-brand-official/locale/en.json new file mode 100644 index 0000000000..09781290d4 --- /dev/null +++ b/packages/client/ui-brand-official/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-brand-official" + } +} diff --git a/packages/client/ui-brand-official/locale/zh.json b/packages/client/ui-brand-official/locale/zh.json new file mode 100644 index 0000000000..479797b84e --- /dev/null +++ b/packages/client/ui-brand-official/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DeepSeek 品牌展示", + "description": "在应用侧栏等位置展示官方品牌元素。" + } +} diff --git a/packages/client/ui-brand-official/package.json b/packages/client/ui-brand-official/package.json index deadad2ad5..e21a4838eb 100644 --- a/packages/client/ui-brand-official/package.json +++ b/packages/client/ui-brand-official/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -48,11 +49,11 @@ "@deepseek-ai/dsh-client-ui-sidebar": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-brand-official/tsdown.config.ts b/packages/client/ui-brand-official/tsdown.config.ts index 9edc90cbc9..7aa03cebc1 100644 --- a/packages/client/ui-brand-official/tsdown.config.ts +++ b/packages/client/ui-brand-official/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-brand-official', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index b1a7cbaa67..62f04ab2b8 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -15,8 +15,8 @@ en: 41cd21266011d571 zh: 3172d1a2acbb27b7 /deepseek-ai-dsh-client-ui-chat/reference-previews: - en: 35907a97c3edfa79 - zh: 5423c6d41fac73d3 + en: aa6b1abec265bf1b + zh: 7260ce78afba2584 /deepseek-ai-dsh-client-ui-chat/hidden-chat-rows: en: cbf1f0a2205046a5 zh: 2e59d0815351349f @@ -24,20 +24,20 @@ en: 2157fcd6b0d100b5 zh: 9e865ac3953ebe30 /deepseek-ai-dsh-client-ui-chat/turn-token-usage: - en: 9f39ef2d8b3a70b4 - zh: 77b7ff326d24e1c1 + en: bb20da372b144302 + zh: 75a8c5ab7ec8d665 /deepseek-ai-dsh-client-ui-chat/completed-turn-footer: en: b4cd36e7ab91281e zh: 8ccf412b9dde61d5 /deepseek-ai-dsh-client-ui-chat/turn-process-folding: - en: 0c63ffa8f245050e - zh: f421d1a569b16c3d + en: 4cd7c81d70d2f365 + zh: 18eca6d16e44b6c2 /deepseek-ai-dsh-client-ui-chat/grouped-rendering: - en: 8b2586e6b9f188a7 - zh: 6687f9e67432d04f + en: bc8d1d786c9affea + zh: 3139f0228527a174 /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: 5bcd9284adc0e0a7 - zh: cf633bb13e2c63b2 + en: 3f4e6c161b4583bb + zh: e4265bb2bce8eb1c /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 7ad45dcdca..697efe25cf 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -33,7 +33,15 @@ File-mention providers receive the viewed Session ID with the closing-turn owner ## Reference previews -Chat supplies file and HTTP(S) navigation through one `MarkdownDelegateProvider` around its node list. Assistant Markdown file links open in the right Sidebar after the message settles, including references to unmodified files. Relative paths resolve in the viewed Session's workspace; absolute paths retain the same Session's filesystem access. `#L24` and `#L24-L30` navigate to the first specified line and reuse an existing file tab. Missing files show the preview's error state. +Sent generic-file attachments retain the draft's [file-card radius](../../../docs/ui-radius.md#radius-scale). + +`ChatView` supplies file and HTTP(S) navigation through the existing `MarkdownDelegateProvider` around its node list, passing `requestOpenFile`, `openExternalLink`, and `fileImages` directly. Its file opener retains Chat's failure feedback and retry handling. Assistant Markdown file links open in the right Sidebar after the message settles, including references to unmodified files. Relative paths resolve in the viewed Session's workspace; absolute paths retain the same Session's filesystem access. `#L24` and `#L24-L30` navigate to the first specified line and reuse an existing file tab. Missing files show the preview's error state. + +Native message images use separate user and output positions. The `conversation.chat.user.content` Factory declares `conversation.chat.user.images`, which `UserContent` renders; the Assistant node registration declares `conversation.chat.message.images`, which `AssistantMarkdown` renders. Both receive image sources, the authorized `loadImage`, and layout options through explicit props. Their official `MessageImages` entries call the shared root-scoped `conversation.images.content` Factory. Each position can be replaced independently without duplicating the gallery implementation. + +The session-scoped `conversation.chat.user.content` Factory renders only the user content stack: text, extra blocks, image/file attachments in input order, and reference summaries. Its [`UserContentInput`](src/client/contract/slots.ts) carries prepared `content`, transform `facts`, display props, and explicit `loadImage`; node-owned injections provide reference actions. It calls the shared `conversation.user.text` Factory for text and its own image Slot for images. Direct callers need a Session binding and supply their own row wrapper. + +`UserStyleBubble` and the [source-specific wrappers]() retain the user row, keys, pending/echo markers, timestamps, copy controls, and other message actions. The content Factory reads neither source-specific models nor private Context, and is not a global user-content override entry point. Standalone Markdown images show contained previews and open the shared image lightbox; local paths resolve against the viewed workspace after settlement. Image file links keep their sidebar activation and show a thumbnail after hover dwell or keyboard focus. Escape dismisses the thumbnail. Failed images retain a localized status and their description; no duplicate-image filtering is applied. @@ -60,7 +68,7 @@ A completed Turn shows an expandable usage row only when the loaded window inclu Settings → General → Performance & usage appears after Send behavior while busy and before Session Log upload, and stores `ui-chat.performanceUsage` as `detailed` (default) or `compact`. Compact shows only available output speed and cache-hit percentage beneath the composer, without interactive statistic dialogs or per-Turn usage. Detailed exposes session statistics and per-Turn token usage. Neither mode shows elapsed time in the completed-turn footer. The preference changes presentation only; accounting and Session events remain intact. -The composer statistics are two `conversation.composer.dock` list entries: `activity` (order 0, turn and step counts and output speed, with LLM time, tool time, and TTFT) and `usage` (order 1, token total and cache hit). Another plugin replaces one pill by registering the same id and the same `order`; the dock orders rows by `order`, while a lower `priority` picks the replacement: a dynamic plugin receives one automatically, and a statically composed plugin passes it explicitly. A new id adds a pill. Each pill carries its id in `data-composer-stat`. An open pill dialog closes on Escape or on a pointerdown or click outside it, so activating another pill by pointer or keyboard swaps dialogs instead of stacking them. +The composer statistics are two `conversation.composer.dock` list entries: `activity` (order 0, turn and step counts and output speed, with LLM time, tool time, and TTFT) and `usage` (order 1, token total and cache hit). The controls follow the shared [statistics-control radius](../../../docs/ui-radius.md#radius-scale). Another plugin replaces one control by registering the same id and the same `order`; the dock orders rows by `order`, while a lower `priority` picks the replacement: a dynamic plugin receives one automatically, and a statically composed plugin passes it explicitly. A new id adds a control. Each control carries its id in `data-composer-stat`. An open statistics dialog closes on Escape or on a pointerdown or click outside it, so activating another control by pointer or keyboard swaps dialogs instead of stacking them. Explicit selections update every consumer immediately; accepted Host settings reconcile the live value, so a refused or pending write keeps the selected mode until the Host answers. @@ -84,7 +92,7 @@ When Chat ends with an open Turn control and that Turn has no visible input, the Work-details modes control process-group display and reasoning previews. Compact, Standard, and Detailed fold eligible completed Turns without hiding the final answer; Verbose retains the duration/status header without a collapse action and shows historical process rows directly. The [business-rule reference](src/client/conversation-nodes/README.md#display-modes) contains the mode table, title behavior, whole-Turn eligibility, clocks, and disclosure resets. -The Settings row below Work details offers an [independent collapse-timing preference](src/client/conversation-nodes/README.md#collapse-timing). +The Settings row below Work details offers an [independent collapse-timing preference](src/client/conversation-nodes/README.md#collapse-timing), saved through the same Host profile configuration. ----- @@ -95,7 +103,7 @@ Chat registers its process Group Definition through `uiConversation.groups`. Rea `groupPart` selects reasoning or response in the Assistant renderer without copying Node payloads. A Tool node owns its preparing, dispatched, and result stages under one callId. Each part has a distinct DOM anchor for reading-position restoration; Turn navigation addresses the original Node key and lands on its first visible part. Group sources, member parents, and keys survive display-mode changes and newly loaded prefixes that extend an intact group. The source Node Store remains the only Node-data owner, and a replaced Builder rebinds keyed subscriptions without remounting seats. Mode changes retain size observers and reuse the Turn-state selector. -The Chat Builder publishes `bottomSource` per Node: true for visible Nodes belonging to the last Turn in the loaded timeline, not just the final row. Advancing the bottom Turn notifies only Nodes in the old and new bottom Turns. Groups read their first member's position. Pending-input deduplication and collapse decisions remain in the Chat view, outside the Builder. +The Chat Builder publishes `bottomSource` per Node: true for visible Nodes belonging to the latest loaded exchange, not just the final row. Nodes declare their group-tree position through `groupTree`; a Turn holding an `exchange` Node opens an exchange, and the exchange lasts until the next opening Turn. Moving the exchange start notifies only Nodes in Turns that entered or left it. Groups read their first member's position. Pending-input deduplication and collapse decisions remain in the Chat view, outside the Builder. Live tool deltas share reasoning's frame-batched publication; durable calls and results publish immediately. Native and nested results retain event presentation metadata, so historical file and command labels use the operation’s location. Repeated deltas retain the Tool node when observed argument answers, the anchor, location, and visibility are unchanged. The Definition supplies the same lazy argument reader to tool rows and group detail, without tool-specific registration. @@ -109,7 +117,7 @@ Scroll-edge fades initialize when `ResizeObserver` reports the open group's layo Each group owns local `useDisclosure` state that survives mode changes while its component stays mounted. -The session-scoped `conversation.chat.reasoning.body` single Slot offers the original reasoning text and streaming state only when its body is expanded. Its official entry registers at priority 100 and calls the `conversation.chat.reasoning.content` Factory. A replacement uses a lower priority number and may call that same Factory with original or derived text. The root-scoped Factory requires no Session and fixes compact typography. Its optional `labels` accepts complete `MarkdownLabels` unchanged; omission uses Chat's localized defaults. The host supplies no inline fallback or plugin action state. Display extensions must preserve access to the original text and own their controls inside their Body wrapper. Extensions do not replace the reasoning preview or its disclosure policy. +The session-scoped `conversation.chat.reasoning.body` single Slot offers the original reasoning text and streaming state only when its body is expanded. Its official entry registers at priority 100 and calls the `conversation.chat.reasoning.content` Factory. A replacement uses a lower priority number and may call that same Factory with original or derived text. The root-scoped Factory requires no Session and fixes compact typography. Its optional `labels` accepts complete `MarkdownLabels` unchanged; omission uses Chat's localized defaults. The host supplies no inline fallback or plugin action state. Display extensions must preserve access to the original text and own their controls inside their Body wrapper. Extensions do not replace the reasoning preview or its disclosure policy. The [reasoning display rules](src/client/conversation-nodes/README.md#display-modes) define which blocks produce rows. The Chat-node slot injects a reset-bound `useDisclosure` Hook for reasoning and tools. Intermediate renderers forward it without subscribing; each invocation owns independent open state. Source callbacks retain their receiver and stable identity. When an enclosing Turn actually hides a process member, its seat resets those disclosures without replacing component keys or changing the Hook reference. Display-mode changes preserve their open state. @@ -134,7 +142,7 @@ Next-message folding combines row closure and tail following in one cancellable Changing Work details clears reserved bottom space after active folds finish and reconciles the scroll range with the selected mode. Readers already following the tail stay at the new bottom; other readers are not forced to follow. -Fold coordination is viewport-local: reservations and idle callbacks never broadcast to other Chat views. ChatView supplies its motion capability once to `conversation.chat.flow` through the render's `hookContext`. Flow binds the group and header behavior hooks, owns node and image rendering, and shares the existing Chat store and Session node sources. Layout nodes and inline reasoning receive the bound hooks without receiving the motion controller or changing content parents. Generic searchable hiding applies before paint and owns focus protection and beforematch handling; pending-input reconciliation remains in ChatView. +Fold coordination is viewport-local: reservations and idle callbacks never broadcast to other Chat views. ChatView supplies its motion capability once to `conversation.chat.flow` through the render's `hookContext`. Flow binds the group and header behavior hooks, owns node dispatch, supplies Factory rendering for local echoes, and shares the existing Chat store and Session node sources. The image entry Factory owns the replaceable image Slot. Layout nodes and inline reasoning receive the bound hooks without receiving the motion controller or changing content parents. Generic searchable hiding applies before paint and owns focus protection and beforematch handling; pending-input reconciliation remains in ChatView. | Outer follows | Open group follows | Back-to-bottom button | New content | |---|---|---|---| diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index fb8d1dba8c..fd0bec6b81 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -33,7 +33,15 @@ kind: "package-reference" ## 引用预览 -Chat 在节点列表外通过一个 `MarkdownDelegateProvider` 提供文件及 HTTP(S) 导航。Assistant Markdown 文件链接在消息落定后可于右侧栏打开,包括未修改文件的引用。相对路径基于当前查看的 Session 工作区解析;绝对路径仍使用同一 Session 的文件系统访问。`#L24` 和 `#L24-L30` 定位到指定起始行,并复用现有文件标签。文件缺失时显示预览错误状态。 +已发送的普通文件附件保留草稿中的[文件卡片圆角](../../../docs/ui-radius.zh.md#radius-scale)。 + +`ChatView` 通过节点列表外围既有的 `MarkdownDelegateProvider` 提供文件及 HTTP(S) 导航,直接传入 `requestOpenFile`、`openExternalLink` 和 `fileImages`。文件打开动作保留 Chat 的失败反馈与重试处理。Assistant Markdown 文件链接在消息落定后可于右侧栏打开,包括未修改文件的引用。相对路径基于当前查看的 Session 工作区解析;绝对路径仍使用同一 Session 的文件系统访问。`#L24` 和 `#L24-L30` 定位到指定起始行,并复用现有文件标签。文件缺失时显示预览错误状态。 + +原生消息图片使用独立的用户与输出位置。`conversation.chat.user.content` Factory 声明 `conversation.chat.user.images`,由 `UserContent` 渲染;Assistant 节点注册声明 `conversation.chat.message.images`,由 `AssistantMarkdown` 渲染。两者通过显式 props 接收图片来源、授权 `loadImage` 和布局参数。官方 `MessageImages` 条目调用共享的 root 作用域 `conversation.images.content` Factory。每个位置均可独立替换,无需复制画廊实现。 + +Session 作用域的 `conversation.chat.user.content` Factory 只渲染用户内容区域:文本、额外内容块、按输入顺序排列的图片/文件附件及引用摘要。[`UserContentInput`](src/client/contract/slots.ts) 携带预处理的 `content`、变换 `facts`、显示 props 和显式 `loadImage`;引用动作由节点自己的 Injection 提供。正文调用共享 `conversation.user.text` Factory,图片调用自身拥有的图片 Slot。直接调用需要 Session 绑定,行包装层由调用方提供。 + +`UserStyleBubble` 和[各来源包装层]() 保留用户行、key、pending/echo 标记、时间、复制控件及其他消息操作。内容 Factory 不读取来源专属模型或私有 Context,也不是全局用户内容替换入口。 独立的 Markdown 图片以内嵌预览显示,点击打开共享图片浮层;本地路径在消息落定后基于当前查看的工作区解析。图片文件链接保持点击打开侧栏,鼠标停留或键盘聚焦时显示缩略图,Esc 关闭缩略图。图片加载失败时保留本地化状态与图片说明;不执行重复图片过滤。 @@ -60,7 +68,7 @@ Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node, 设置 → 通用设置 → 性能与用量位于繁忙时的发送行为之后、Session Log 上传之前,将 `ui-chat.performanceUsage` 保存为 `detailed`(默认)或 `compact`。简洁模式仅在输入框下方显示可用的输出速度和缓存命中率,不显示统计交互卡片或每轮用量。详细模式提供会话统计和每轮 token 用量。两种模式的已完成轮次页脚均不显示耗时。该偏好仅影响展示,记账和 Session 事件保持完整。 -输入框统计信息由两个 `conversation.composer.dock` 列表条目组成:`activity`(order 0,轮次数、步骤数与输出速度,以及 LLM 耗时、工具耗时与 TTFT)和 `usage`(order 1,token 总量与缓存命中)。其他插件以相同的 id 和相同的 `order` 注册即可替换某个胶囊;dock 按 `order` 排列各行,更低的 `priority` 决定由替换者渲染:动态插件会自动获得,静态组合的插件需显式传入。以新 id 注册则新增胶囊。每个胶囊在 `data-composer-stat` 中携带其 id。按下 Escape,或在已打开的对话框之外发生 pointerdown 或点击时,该对话框会关闭,因此用指针或键盘激活另一个胶囊会切换对话框,而不会叠加两个。 +输入框统计信息由两个 `conversation.composer.dock` 列表条目组成:`activity`(order 0,轮次数、步骤数与输出速度,以及 LLM 耗时、工具耗时与 TTFT)和 `usage`(order 1,token 总量与缓存命中)。这些控件遵循公共的[统计控件圆角规则](../../../docs/ui-radius.zh.md#radius-scale)。其他插件以相同的 id 和相同的 `order` 注册即可替换某个控件;dock 按 `order` 排列各行,更低的 `priority` 决定由替换者渲染:动态插件会自动获得,静态组合的插件需显式传入。以新 id 注册则新增控件。每个控件在 `data-composer-stat` 中携带其 id。按下 Escape,或在已打开的对话框之外发生 pointerdown 或点击时,该对话框会关闭,因此用指针或键盘激活另一个控件会切换对话框,而不会叠加两个。 明确选择会立即更新所有使用方;Host 接受的设置会校正实时值,因此写入被拒绝或尚未应答时保持所选模式,直到 Host 应答。 @@ -84,7 +92,7 @@ Chat 末尾为进行中的 Turn 控制行,且该轮尚无可见输入时,第 工作步骤展示模式控制过程组显示与推理预览。简洁、标准、详细模式收起符合条件的已完成轮次,不隐藏最终答案;完全展开模式保留时长或状态抬头,但不支持收起,历史过程行直接显示。[业务规则明细](src/client/conversation-nodes/README.zh.md#display-modes) 统一说明模式表、组头行为、整轮折叠资格、时钟与开合重置。 -工作步骤展示下方的设置行提供[独立的收起时机设置](src/client/conversation-nodes/README.zh.md#collapse-timing)。 +工作步骤展示下方的设置行提供[独立的收起时机设置](src/client/conversation-nodes/README.zh.md#collapse-timing),通过相同的 Host profile 配置保存。 ----- @@ -95,7 +103,7 @@ Chat 通过 `uiConversation.groups` 注册过程 Group Definition。React 通过 `groupPart` 在 Assistant 渲染器中选择推理或回复,不复制 Node 载荷。同一个 callId 的准备、派发与结果阶段由 Tool 节点自己拥有。每个部分有独立的 DOM 锚点用于恢复阅读位置;轮次导航使用原 Node key,落到它的第一个可见部分。展示模式切换以及为完整旧组补入更早成员时,保留组来源、成员父级及 key。原 Node Store 仍是唯一节点数据所有者,替换 Builder 时重新绑定按键订阅,不重挂载容器。模式变化保留尺寸观察器,并复用整轮状态选择器。 -Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载时间线的最后一轮时为 true,而不只是列表最后一行。底部轮次推进时,只有旧、新底部轮次的节点收到位置变化通知。Group 读取其首个成员的位置。待发送消息去重与收起判断仍由 Chat 视图处理,不进入 Builder。 +Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载的最新交互段时为 true,而不只是列表最后一行。节点通过 `groupTree` 声明自己在分组树中的位置;含 `exchange` 节点的轮次开启一个交互段,交互段持续到下一个开启轮次。交互段起点移动时,只有进入或离开该交互段的轮次中的节点收到通知。Group 读取其首个成员的位置。待发送消息去重与收起判断仍由 Chat 视图处理,不进入 Builder。 实时工具 delta 与推理共用按帧合并的发布节奏;持久调用和结果立即发布。原生与嵌套结果保留事件中的展示元数据,使历史文件与命令标签使用执行时的位置。当已读取参数的答案、锚点、位置及可见性均未变化时,重复 delta 保持 Tool 节点不变。Definition 向工具行和分组详情提供同一个懒计算参数读器,无需按工具注册。 @@ -109,7 +117,7 @@ Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载时 每个组拥有本地 `useDisclosure` 状态,组件保持挂载时,模式切换保留该状态。 -Session 作用域的 `conversation.chat.reasoning.body` single Slot 仅在思考正文展开时提供原始思考文本和流式状态。官方条目以优先级 100 注册,并调用 `conversation.chat.reasoning.content` Factory。替换项使用更小的优先级数值,可向同一个 Factory 传入原文或派生显示文本。root 作用域的 Factory 不要求 Session,并固定使用紧凑排版。其可选 `labels` 原样接受完整的 `MarkdownLabels`,省略时使用 Chat 的默认本地化文案。宿主不提供内联 fallback 或插件操作状态。显示扩展必须保留查看原文的能力,并在自己的 Body 包装内维护控件。扩展不替换思考预览或展开策略。 +Session 作用域的 `conversation.chat.reasoning.body` single Slot 仅在思考正文展开时提供原始思考文本和流式状态。官方条目以优先级 100 注册,并调用 `conversation.chat.reasoning.content` Factory。替换项使用更小的优先级数值,可向同一个 Factory 传入原文或派生显示文本。root 作用域的 Factory 不要求 Session,并固定使用紧凑排版。其可选 `labels` 原样接受完整的 `MarkdownLabels`,省略时使用 Chat 的默认本地化文案。宿主不提供内联 fallback 或插件操作状态。显示扩展必须保留查看原文的能力,并在自己的 Body 包装内维护控件。扩展不替换思考预览或展开策略。哪些块生成思考行由[思考展示规则](src/client/conversation-nodes/README.zh.md#display-modes)定义。 Chat 节点 slot 为推理与工具注入绑定重置来源的 `useDisclosure` 钩子。中间 renderer 只透传、不订阅,每次调用拥有独立展开状态。来源回调保留接收对象及稳定引用。外层轮次实际隐藏过程成员时,所在节点重置这些开合状态,不替换组件 key,也不改变钩子引用。展示模式切换保留展开状态。 @@ -134,7 +142,7 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 切换工作步骤展示档位时,当前折叠结束后清空底部预留空间,并按所选档位调整滚动范围。原本跟随底部的读者保持在新的底部;其他读者不会被强制拉回底部。 -折叠协调状态由各自的 viewport 持有,空间预留和空闲回调不会广播到其他 Chat 视图。ChatView 通过本次渲染的 `hookContext`,向 `conversation.chat.flow` 交接一次动画能力。Flow 绑定组内容与组头的行为 hook,负责节点和图片渲染,并共享既有 Chat store 与 Session 节点来源。布局节点和行内思考接收绑定后的 hook,不接收动画控制器,也不改变内容的父级。通用的可搜索隐藏在绘制前生效,并负责焦点保护及 beforematch;pending 输入对账仍留在 ChatView。 +折叠协调状态由各自的 viewport 持有,空间预留和空闲回调不会广播到其他 Chat 视图。ChatView 通过本次渲染的 `hookContext`,向 `conversation.chat.flow` 交接一次动画能力。Flow 绑定组内容与组头的行为 hook,负责节点分发,为本地回显提供 Factory renderer,并共享既有 Chat store 与 Session 节点来源。图片入口 Factory 拥有可替换的图片 Slot。布局节点和行内思考接收绑定后的 hook,不接收动画控制器,也不改变内容的父级。通用的可搜索隐藏在绘制前生效,并负责焦点保护及 beforematch;pending 输入对账仍留在 ChatView。 | 外层跟随 | 已展开小组跟随 | 回到底部按钮 | 新增内容 | |---|---|---|---| diff --git a/packages/client/ui-chat/locale/en.json b/packages/client/ui-chat/locale/en.json new file mode 100644 index 0000000000..a07944e34f --- /dev/null +++ b/packages/client/ui-chat/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-chat" + } +} diff --git a/packages/client/ui-chat/locale/zh.json b/packages/client/ui-chat/locale/zh.json new file mode 100644 index 0000000000..bece9e8048 --- /dev/null +++ b/packages/client/ui-chat/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "聊天内容展示", + "description": "渲染聊天消息、工具内容和相关详情。" + } +} diff --git a/packages/client/ui-chat/package.json b/packages/client/ui-chat/package.json index a738710edb..1eb2d42930 100644 --- a/packages/client/ui-chat/package.json +++ b/packages/client/ui-chat/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -88,8 +89,6 @@ "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@tanstack/react-virtual": "3.14.10", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "react": "^18.2.0", "react-dom": "^18.2.0", "@deepseek-ai/dsh-settings": "workspace:*", @@ -99,6 +98,7 @@ "@deepseek-ai/schemastery": "workspace:~" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-chat/src/chat-settings.ts b/packages/client/ui-chat/src/chat-settings.ts index c4c6ce3b95..8e76bb29ed 100644 --- a/packages/client/ui-chat/src/chat-settings.ts +++ b/packages/client/ui-chat/src/chat-settings.ts @@ -8,6 +8,18 @@ export const CHAT_SETTINGS_NAMESPACE = 'ui-chat' /** Field carrying the work-details presentation mode. */ export const TRANSCRIPT_VIEW_FIELD = 'transcriptView' +/** Field carrying the independent work-details collapse timing. */ +export const COLLAPSE_TIMING_FIELD = 'collapseTiming' + +/** Available points when a completed Turn returns to its historical presentation. */ +export const COLLAPSE_TIMINGS = ['completion', 'next-input'] as const + +/** When a completed Turn returns to its historical presentation. */ +export type CollapseTiming = typeof COLLAPSE_TIMINGS[number] + +/** Preserve completion-time folding when no timing preference is saved. */ +export const DEFAULT_COLLAPSE_TIMING: CollapseTiming = 'completion' + /** Work-details presentation modes a user can choose. */ export const TRANSCRIPT_VIEW_MODES = ['compact', 'standard', 'detailed', 'verbose'] as const @@ -50,6 +62,8 @@ export const DEFAULT_LINK_OPENING: LinkOpening = 'sidebar' export interface ChatSettings { /** Work-details preference; absence uses the client default, and legacy saved values remain accepted. */ transcriptView?: TranscriptViewMode | typeof LEGACY_TRANSCRIPT_VIEW_MODE | typeof LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE | null + /** Independent collapse timing; absence preserves completion-time folding. */ + collapseTiming?: CollapseTiming /** Detail level for composer statistics and completed-Turn usage. */ performanceUsage: PerformanceUsageMode /** Default destination for Chat HTTP(S) links. */ @@ -58,6 +72,7 @@ export interface ChatSettings { /** Durable Chat schema; also the wire envelope the browser scope validates against. */ export const ChatSettingsFields = { + [COLLAPSE_TIMING_FIELD]: z.union([...COLLAPSE_TIMINGS]).default(DEFAULT_COLLAPSE_TIMING), linkOpening: z.union(['sidebar', 'new-tab']).default(DEFAULT_LINK_OPENING), performanceUsage: z.union([...PERFORMANCE_USAGE_MODES]).default(DEFAULT_PERFORMANCE_USAGE), // Missing and unrecognized modes defer to the client's default. diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index eabd566256..8aa63aa1f7 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -31,6 +31,7 @@ import { ApprovalCommand } from './chat/ApprovalCommand.tsx' import { ChatView } from './chat/ChatView.tsx' import { ChatFlow } from './chat/ChatFlow.tsx' import { registerChatNodeRenderers } from './chat/register-node-renderers.ts' +import { UserContent } from './chat/UserContent.tsx' import { ActivityPill, UsagePill } from './chat/StatsPills.tsx' import { registerConversationNodes } from './conversation-nodes/register.ts' import { QuotaNoticeHost } from './chat/QuotaNoticeHost.tsx' @@ -169,6 +170,10 @@ export function apply(ctx: Context): void { ctx.effect(() => () => { transcriptView.dispose(); performancePolicy.dispose() }) const performanceUsage = performancePolicy.mode registerChatNodeRenderers(ctx, performanceUsage, presentation) + ctx.slots.registerFactory({ + name: 'conversation.chat.user.content', scope: 'session', locale: NS, + children: { 'conversation.chat.user.images': { kind: 'single', scope: 'session' } }, + }, UserContent) ctx.slots.inject('settings.general.item', () => ctx.slots.register({ name: 'settings.general.item', @@ -211,7 +216,6 @@ export function apply(ctx: Context): void { name: 'conversation.chat.flow', locale: NS, store: chatStore, children: { 'conversation.chat.node': { kind: 'keyed', scope: 'session', inject: CHAT_NODE_INJECT }, - 'conversation.message.images': { kind: 'single', scope: 'session' }, }, inject: (sessionId: SessionId): ChatFlowDataInjected => { const binding = ctx.sessions.binding(sessionId) @@ -258,11 +262,6 @@ export function apply(ctx: Context): void { else ctx.sidebarRight.openResource(url, { params: { line: options.line } }) await Promise.resolve() }, - openSkill: (name) => { - const scope = ctx.sessions.scope(sessionId) - if (scope === undefined) return - ctx.get('inputTriggers')?.sessionOf(scope).openReference('skill', { ref: `/${name}` }) - }, openExternalLink: (url) => { if (linkOpening.getSnapshot() === 'sidebar' && ctx.get('sidebarRightTabs')?.get('browser') !== undefined) { ctx.sidebarRight.openTab('browser', { params: { url } }) diff --git a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx index dcc1141b47..22ae5bac70 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantMarkdown.tsx @@ -27,7 +27,9 @@ export function localPathMediaUrl(base: string, value: string): string | undefin return fileMediaUrl(base, path) } -export interface AssistantMarkdownProps extends Pick, 'renderSlot'> { +export interface AssistantMarkdownProps extends + Pick, 'renderSlot'>, + Pick { /** Render only the requested business portion, preserving original block indexes. */ groupPart?: string | undefined /** Stable Hook forwarded to each independently expandable reasoning block. */ @@ -36,8 +38,6 @@ export interface AssistantMarkdownProps extends Pick - {renderMessageImages({ - images: group.map(({ attachment }) => ({ attachment })), - align: 'start', + {renderSlot('conversation.chat.message.images', { + images: group.map(({ attachment }) => ({ attachment })), loadImage, align: 'start', })} , ) diff --git a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx index b77dffb7f1..5f61fe7007 100644 --- a/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx +++ b/packages/client/ui-chat/src/client/chat/AssistantNodeView.tsx @@ -4,11 +4,11 @@ import type { ChatNodeViewProps, PresentationInjected, TurnTailOwnerProps } from import { AssistantMarkdown } from './AssistantMarkdown.tsx' type AssistantNodeViewProps = ChatNodeViewProps<'assistant-step'> & InjectFace - & PropsRenderSlots<'conversation.chat.reasoning.body'> + & PropsRenderSlots<'conversation.chat.reasoning.body' | 'conversation.chat.message.images'> /** Streaming, settled, and interrupted Assistant states share one keyed renderer instance. */ export const AssistantNodeView = memo(function AssistantNodeView({ - node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, renderMessageImages, fileMentions, + node, groupPart, useDisclosure, useGroupAction, useTurnData, turnProcess, openFile, loadImage, fileMentions, usePresentation, renderSlot, t, }: AssistantNodeViewProps) { const data = node.data @@ -38,7 +38,7 @@ export const AssistantNodeView = memo(function AssistantNodeView({ useDisclosure={useDisclosure} streaming={data.status === 'running'} interrupted={data.status === 'interrupted'} - renderMessageImages={renderMessageImages} + loadImage={loadImage} reasoningHidden={reasoningHidden} useGroupAction={useGroupAction} usePresentation={usePresentation} diff --git a/packages/client/ui-chat/src/client/chat/ChatFlow.tsx b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx index 1b8306ee5f..c54e8a108f 100644 --- a/packages/client/ui-chat/src/client/chat/ChatFlow.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatFlow.tsx @@ -1,6 +1,5 @@ /** Ordered Chat rows, local echoes, and running status share the flow slot's parent. */ -import { memo, useCallback } from 'react' -import type { RenderMessageImages } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { memo } from 'react' import { assertNever } from '@deepseek-ai/dsh-util-values' import type { ChatFlowSlotProps } from '../contract/slots.ts' import { ChatNodeSeat } from './ChatNodeSeat.tsx' @@ -13,8 +12,8 @@ import { RunningStatus } from './RunningStatus.tsx' export const ChatFlow = memo(function ChatFlow({ entries, pendingInputs, lastInputTurn, deferCollapse, useSession, useChat, useChatNode, useChatNodeBottom, useChatNodeProcess, useChatGroup, usePresentation, - useStore, actions, renderSlot, t, useGroupAction, useGroupHeaderAction, - cwd, openFile, openSkill, inspectCall, forkAt, loadImage, fileMentions, + useStore, actions, renderSlot, renderFactorySlot, t, useGroupAction, useGroupHeaderAction, + cwd, openFile, inspectCall, forkAt, loadImage, fileMentions, }: ChatFlowSlotProps) { const nodeStore = useChat(snapshot => snapshot.nodes) const running = useSession(snapshot => snapshot.running) @@ -25,14 +24,10 @@ export const ChatFlow = memo(function ChatFlow({ ? location.turn.status === 'open' ? location.turn.start?.time : undefined : undefined }) - const renderMessageImages = useCallback( - owner => renderSlot('conversation.message.images', { ...owner, loadImage }), - [loadImage, renderSlot], - ) const seatProps = { nodeStore, useChatNode, useChatNodeBottom, useChatNodeProcess, usePresentation, useStore, actions, renderSlot, t, useGroupAction, deferCollapse, - cwd, openFile, openSkill, inspectCall, forkAt, loadImage, renderMessageImages, fileMentions, + cwd, openFile, inspectCall, forkAt, loadImage, fileMentions, } const rows = entries.map((entry) => { switch (entry.kind) { @@ -48,10 +43,10 @@ export const ChatFlow = memo(function ChatFlow({ }) const pendingRows = pendingInputs.map(item => 'requestId' in item ? ( + loadImage={loadImage} renderFactorySlot={renderFactorySlot} t={t} /> ) : ( + loadImage={loadImage} renderFactorySlot={renderFactorySlot} t={t} /> )) const tail = entries.at(-1) const node = tail?.kind === 'node' ? nodeStore.get(tail.key) : undefined diff --git a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx index 4bc1947dca..9b076678a3 100644 --- a/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatNodeSeat.tsx @@ -47,8 +47,8 @@ function turnOf(node: ChatNode | undefined): number | undefined { */ export const ChatNodeSeat = memo(function ChatNodeSeat({ nodeKey, groupPart, useChatNode, useChatNodeProcess, usePresentation, - cwd, openFile, openSkill, inspectCall, forkAt, - loadImage, renderMessageImages, fileMentions, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction, + cwd, openFile, inspectCall, forkAt, + loadImage, fileMentions, useStore, actions, renderSlot, t, useChatNodeBottom, deferCollapse, useGroupAction, }: ChatNodeSeatProps) { const bottom = useChatNodeBottom(nodeKey) const node = useChatNode(nodeKey) @@ -127,16 +127,14 @@ export const ChatNodeSeat = memo(function ChatNodeSeat({ ...groupPart === undefined ? {} : { groupPart }, cwd, openFile, - openSkill, inspectCall, forkAt, loadImage, - renderMessageImages, fileMentions, turnProcess, }, [ - node, groupPart, cwd, openFile, openSkill, inspectCall, forkAt, - loadImage, renderMessageImages, fileMentions, turnProcess, + node, groupPart, cwd, openFile, inspectCall, forkAt, + loadImage, fileMentions, turnProcess, ]) if (routedNode === undefined || owner === null) return null // Runtime dispatch owns the correlation: every Node's discriminant is the diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 5ff669c1fb..6696330f0a 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -101,6 +101,11 @@ transition: margin-top 160ms cubic-bezier(0.4, 0, 0.2, 1); } +.column[data-input-fold] > :not([data-chat-motion]), +.column[data-input-fold] > :global([data-slot="conversation.chat.flow"]) > :not([data-chat-motion]) { + transition: none; +} + @media (prefers-reduced-motion: reduce) { .column[data-chat-motion] > :not([data-chat-motion]), .column[data-chat-motion] > :global([data-slot="conversation.chat.flow"]) > :not([data-chat-motion]) { diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index e3e4491672..3b528dc47a 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -59,7 +59,7 @@ const MOTION_TAIL_MS = 800 */ export function ChatView({ useSession, useChat, useConversation, useSessions, renderSlot, - sessionId, openFile, openSkill, openExternalLink, loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, fileMentions, + sessionId, openFile, openExternalLink, loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, fileMentions, usePresentation, useProjection, t, }: ChatViewSlotProps) { const order = useChat(s => s.order) @@ -223,10 +223,10 @@ export function ChatView({ )} - + {renderSlot('conversation.chat.flow', { entries, pendingInputs, lastInputTurn, deferCollapse, - cwd, openFile: requestOpenFile, openSkill, inspectCall, forkAt, loadImage, fileMentions, + cwd, openFile: requestOpenFile, inspectCall, forkAt, loadImage, fileMentions, }, { hookContext: flowContext })} {/* No pending placeholders: questions (ui-user-questions) and approvals diff --git a/packages/client/ui-chat/src/client/chat/MessageItem.module.css b/packages/client/ui-chat/src/client/chat/MessageItem.module.css index 5d19483335..3bacafab47 100644 --- a/packages/client/ui-chat/src/client/chat/MessageItem.module.css +++ b/packages/client/ui-chat/src/client/chat/MessageItem.module.css @@ -326,7 +326,7 @@ min-height: 64px; padding: 8px 12px; border: 0.5px solid var(--dsw-alias-border-l2, rgba(0, 0, 0, 0.12)); - border-radius: var(--dsw-radius-xl); + border-radius: var(--dsw-radius-lg); background: var(--dsw-specific-input-major, transparent); box-sizing: border-box; } diff --git a/packages/client/ui-chat/src/client/chat/MessageItem.tsx b/packages/client/ui-chat/src/client/chat/MessageItem.tsx index 9005150af0..a2d394c106 100644 --- a/packages/client/ui-chat/src/client/chat/MessageItem.tsx +++ b/packages/client/ui-chat/src/client/chat/MessageItem.tsx @@ -1,28 +1,29 @@ -import { Fragment, memo, useEffect, useMemo, useState } from 'react' +import { memo, useEffect, useMemo, useState } from 'react' import type { ReactNode } from 'react' import type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client' -import type { MessageImageSource } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { fileExtension, FileTypeIcon, fileSizeText, JsonBlock, projectUserText, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' -import type { ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps } from '../contract/slots.ts' +import type { PropsRenderFactories } from '@deepseek-ai/dsh-client-ui-slots' +import type { UserTextFacts } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { JsonBlock, StateDot, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' +import type { + ChatNodeOwnerProps, ChatNodeViewProps, ChatViewSlotProps, UserContentAttachment, UserContentData, UserContentInput, +} from '../contract/slots.ts' import type { ModelRetryNode, TurnErrorNode, UserMessageNode } from '../contract/snapshot.ts' import { CompactionItem } from './CompactionItem.tsx' import { ContextInjectionRow } from './ContextInjectionRow.tsx' import { MessageIconActions } from './MessageIconActions.tsx' import css from './MessageItem.module.css' +const EMPTY_TEXT_FACTS: Readonly> = {} + type UserImage = Extract type UserFile = Extract -type PresentedAttachment = - | { readonly type: 'image'; readonly image: MessageImageSource } - | { readonly type: 'file'; readonly file: UserFile['attachment'] } - function contentParts(content: readonly unknown[]): { text: string - attachments: PresentedAttachment[] + attachments: UserContentAttachment[] rest: unknown[] } { const texts: string[] = [] - const attachments: PresentedAttachment[] = [] + const attachments: UserContentAttachment[] = [] const rest: unknown[] = [] for (const block of content) { const b = block as { type?: string; text?: string; attachment?: unknown } @@ -160,11 +161,11 @@ function TurnMaxTokensItem({ t }: { /** Right-aligned bubble shared by user and steering rows. */ function UserStyleBubble({ - content, renderMessageImages, actions, pending = false, echo = false, referenceLabels = [], skillNames = [], - previewAttachments, references, t, + content, loadImage, renderFactorySlot, actions, pending = false, echo = false, referenceLabels, skillNames, + previewAttachments, facts: inputFacts = EMPTY_TEXT_FACTS, interactive = false, }: { content: readonly unknown[] - renderMessageImages: ChatNodeOwnerProps['renderMessageImages'] + renderFactorySlot: PropsRenderFactories['renderFactorySlot'] /** Optional IconActions (or similar) below the bubble; receives the joined text. */ actions?: (text: string) => ReactNode /** Whether this is the Host-authoritative pre-admission steering projection. */ @@ -176,59 +177,35 @@ function UserStyleBubble({ /** Skill names the step's `skill-invocation` injections loaded for this message. */ skillNames?: readonly string[] /** Local submission-echo attachments replacing the content-derived attachment sequence. */ - previewAttachments?: readonly PresentedAttachment[] - references?: Pick - t: ChatViewSlotProps['t'] -}): ReactNode { - const { text, attachments: contentAttachments, rest } = contentParts(content) - const attachments = previewAttachments ?? contentAttachments - const compactImages = attachments.length > 1 - const truncated = (total: number): string => t('json.truncated', { total }) - const showBubble = text !== '' || rest.length > 0 + previewAttachments?: readonly UserContentAttachment[] + /** Inputs used by text transforms, separate from row and rendering props. */ + facts?: Readonly> +} & Pick & Pick): ReactNode { + const parts = useMemo(() => contentParts(content), [content]) + const prepared = useMemo(() => ({ + text: parts.text, + attachments: previewAttachments ?? parts.attachments, + extraBlocks: parts.rest, + ...(referenceLabels === undefined ? {} : { referenceLabels }), + }), [parts, previewAttachments, referenceLabels]) + const facts = useMemo>>(() => ({ + ...inputFacts, + ...(referenceLabels === undefined ? {} : { sessionLabels: referenceLabels }), + ...(skillNames === undefined ? {} : { skillNames }), + }), [inputFacts, referenceLabels, skillNames]) return (
-
- {attachments.length > 0 && ( -
- {attachments.map((attachment, index) => attachment.type === 'image' - ? ( - - {renderMessageImages({ - images: [attachment.image], - align: 'end', - compact: compactImages, - })} - - ) - : ( - - - - {attachment.file.name} - - {[fileExtension(attachment.file.name).toUpperCase().slice(0, 8), fileSizeText(attachment.file.bytes)] - .filter(Boolean).join(' ')} - - - - ))} -
- )} - {showBubble &&
- {projectUserText(text, referenceLabels, skillNames, 'skill', references)} - {rest.map((block, i) => )} -
} - {referenceLabels.length > 0 && ( -
- {t('message.referenceSummary', { labels: referenceLabels.join(t('message.referenceSeparator')) })} -
- )} -
- {actions?.(text)} + {renderFactorySlot('conversation.chat.user.content', { + content: prepared, + loadImage, + facts, + interactive, + })} + {actions?.(prepared.text)}
) } @@ -236,20 +213,20 @@ function UserStyleBubble({ /** * Render one Host-authoritative pending steering item with the same visual * language as its eventual durable transcript node. - * @param props - Pending message content and conversation translator. + * @param props - pending content, authorized image loader, and Factory/locale seats. * @returns the pending steering bubble. */ -export function PendingSteeringBubble({ content, renderMessageImages, t }: { +export function PendingSteeringBubble({ content, loadImage, renderFactorySlot, t }: { content: readonly unknown[] - renderMessageImages: ChatNodeOwnerProps['renderMessageImages'] + renderFactorySlot: PropsRenderFactories['renderFactorySlot'] t: ChatViewSlotProps['t'] -}): ReactNode { +} & Pick): ReactNode { return ( ( ): ReactNode { const content = useMemo( () => (submission.text === '' ? [] : [{ type: 'text', text: submission.text }]), [submission.text], ) - const previewAttachments = useMemo( + const previewAttachments = useMemo( () => submission.attachments.map(attachment => attachment.type === 'image' ? { type: 'image', @@ -299,10 +276,10 @@ export function PendingSubmissionBubble({ submission, renderMessageImages, t }: ( ) { const data = node.data return ( ( ) { + const { text, attachments, extraBlocks, referenceLabels = EMPTY_LABELS } = content + const compactImages = attachments.length > 1 + const truncated = (total: number): string => t('json.truncated', { total }) + const showBubble = text !== '' || extraBlocks.length > 0 + return ( +
+ {attachments.length > 0 && ( +
+ {attachments.map((attachment, index) => attachment.type === 'image' + ? ( + + {renderSlot('conversation.chat.user.images', { + images: [attachment.image], loadImage, align: 'end', compact: compactImages, + })} + + ) + : ( + + + + {attachment.file.name} + + {[fileExtension(attachment.file.name).toUpperCase().slice(0, 8), fileSizeText(attachment.file.bytes)] + .filter(Boolean).join(' ')} + + + + ))} +
+ )} + {showBubble &&
+ {renderFactorySlot('conversation.user.text', { text, facts, interactive, ellipsis })} + {extraBlocks.map((block, index) => ( + + ))} +
} + {referenceLabels.length > 0 && ( +
+ {t('message.referenceSummary', { labels: referenceLabels.join(t('message.referenceSeparator')) })} +
+ )} +
+ ) +} diff --git a/packages/client/ui-chat/src/client/chat/flow-motion.ts b/packages/client/ui-chat/src/client/chat/flow-motion.ts index 2804a93b77..9705f1f22a 100644 --- a/packages/client/ui-chat/src/client/chat/flow-motion.ts +++ b/packages/client/ui-chat/src/client/chat/flow-motion.ts @@ -1,7 +1,7 @@ /** - * Fade-then-close transitions owned by one Chat viewport. Rows fade before their boxes close; - * the owner reserves removed height and holds scrolling until that viewport's folds finish. - * Motion is opt-in under `[data-chat-motion]`, respects reduced motion, and clears temporary styles. + * Fold transitions owned by one Chat viewport. Input folds coordinate box sizes and scrolling on + * one frame clock; other folds use CSS transitions. Motion is opt-in under `[data-chat-motion]`, + * respects reduced motion, and clears temporary styles. */ import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react' import { useSearchableHidden, type HiddenTransition } from './searchable-hidden.ts' @@ -24,12 +24,53 @@ export interface FlowMotionRows { cancelMotion(element: HTMLElement): void } +/** Geometry captured before one input-owned fold changes its boxes. */ +export interface InputFoldBox { + readonly element: HTMLElement + readonly height: number + readonly marginTop: number + readonly closing: boolean +} + +/** The viewport follows the same progress that changes the folded boxes. */ +export interface InputFoldDriver { + /** + * Capture geometry before the frame clock changes the boxes. + * @param boxes - non-nested boxes whose layout changes on this clock. + */ + begin(boxes: readonly InputFoldBox[]): void + /** + * Reserve scroll range before box writes; omit when the driver needs no pre-write compensation. + * @param progress - shared eased progress from zero to one. + * @param cancelled - automatic following has stopped; reader-position compensation still applies. + */ + prepare?(progress: number, cancelled: boolean): void + /** + * Apply viewport geometry after box writes, even when automatic following is cancelled. + * @param progress - shared eased progress from zero to one. + * @param cancelled - preserve the reader's position rather than applying the automatic target. + * @returns actual scrollTop displacement from the batch start, for closing-content visual compensation. + */ + frame(progress: number, cancelled: boolean): number + /** + * Release temporary geometry after the last frame or cancellation. + * @param cancelled - clean up without reacquiring follow ownership or committing an obsolete landing. + */ + finish(cancelled: boolean): void +} + /** Animation lifetime and fold coordination for one viewport. */ export interface FlowMotion extends FlowMotionRows { /** @returns whether a row owned by this viewport is closing. */ foldActive(): boolean /** @param listener - callback after the last fold. @returns cancellation for a pending callback. */ onFoldIdle(listener: () => void): () => void + /** @param driver - one input-owned viewport motion. @returns whether an active fold was adopted. */ + followInput(driver: InputFoldDriver): boolean + /** Stop input-owned scrolling while letting its closing rows finish. */ + cancelInput(): void + /** @returns whether a coordinated fold currently owns layout and scrolling. */ + inputActive(): boolean /** Cancel owned animations and pending work when the viewport detaches. */ clear(): void } @@ -66,6 +107,101 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: const pendingReserve = new Set() let pendingGrowth = 0 let reserveScheduled = false + const boxes = new Map void; finish: () => void }>() + let inputDriver: InputFoldDriver | null = null + let inputFrame: number | null = null + let inputBatch = false + let clearEpoch = 0 + let inputCleanup: (() => void) | null = null + let activeDriver: InputFoldDriver | null = null + let cancelEmptyBatch: (() => void) | null = null + + function cancelInput(): void { inputDriver = null } + + function followInput(driver: InputFoldDriver): boolean { + if (folding === 0) return false + if (inputBatch) { + inputDriver = activeDriver + return true + } + inputDriver = driver + scheduleReserve() + return true + } + + function runInputBatch(): void { + const driver = inputDriver + if (driver === null || inputBatch) return + const owned = [...boxes.values()] + const batch = owned.filter(box => box.element.parentElement?.closest('[data-chat-motion="collapse"]') === null) + .sort((left, right) => left.element.compareDocumentPosition(right.element) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1) + if (!batch.some(box => box.closing)) return + inputBatch = true + activeDriver = driver + driver.begin(batch) + inputCleanup = () => { driver.finish(true) } + for (const box of owned) box.take() + for (const box of batch) { + box.element.style.transition = 'none' + box.element.style.height = `${box.closing ? box.height : 0}px` + box.element.style.marginTop = `${box.closing ? box.marginTop : 0}px` + box.element.style.opacity = box.closing ? '1' : '0' + } + const reduced = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches + let started: number | undefined + let displacement = 0 + cancelEmptyBatch = () => { + if (batch.some(box => box.closing && boxes.get(box.element) === box)) return + if (inputFrame !== null) cancelAnimationFrame(inputFrame) + inputFrame = null + inputBatch = false + activeDriver = null + inputDriver = null + inputCleanup = null + cancelEmptyBatch = null + for (const box of owned) if (boxes.get(box.element) === box) box.finish() + driver.finish(true) + } + const tick = (now: number): void => { + inputFrame = null + started ??= now + const elapsed = reduced ? CLOSE_DELAY_MS + CLOSE_MS : now - started + const linear = Math.min(1, Math.max(0, (elapsed - CLOSE_DELAY_MS) / CLOSE_MS)) + const progress = linear * linear * (3 - 2 * linear) + driver.prepare?.(progress, inputDriver !== driver) + for (const box of batch) { + if (boxes.get(box.element) !== box) continue + const remaining = box.closing ? 1 - progress : progress + box.element.style.height = `${box.height * remaining}px` + box.element.style.marginTop = `${box.marginTop * remaining}px` + box.element.style.opacity = box.closing ? String(Math.max(0, 1 - elapsed / FADE_OUT_MS)) : String(progress) + } + displacement = driver.frame(progress, inputDriver !== driver) + let removedBefore = 0 + for (const box of batch) { + if (boxes.get(box.element) !== box) continue + if (box.closing) { + // Transforming the closing box changes its pixels, not its flow contribution. + box.element.style.translate = `0 ${displacement + removedBefore}px` + removedBefore += (box.height + box.marginTop) * progress + } else removedBefore -= (box.height + box.marginTop) * progress + } + if (linear < 1) { + inputFrame = requestAnimationFrame(tick) + return + } + for (const box of owned) box.finish() + inputBatch = false + activeDriver = null + inputCleanup = null + cancelEmptyBatch = null + const cancelled = inputDriver !== driver + if (!cancelled) inputDriver = null + driver.finish(cancelled) + } + if (reduced) tick(0) + else inputFrame = requestAnimationFrame(tick) + } function foldActive(): boolean { return folding > 0 } @@ -77,6 +213,18 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: function flushReserve(): void { reserveScheduled = false + if (inputDriver !== null && !inputBatch) { + pendingReserve.clear() + pendingGrowth = 0 + runInputBatch() + return + } + if (typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches) { + pendingReserve.clear() + pendingGrowth = 0 + for (const box of [...boxes.values()]) box.finish() + return + } let total = -pendingGrowth pendingGrowth = 0 for (const element of pendingReserve) { @@ -92,7 +240,8 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: if (reserveScheduled) return reserveScheduled = true // After the whole commit's collapses and reveals have started, before any box changes size. - queueMicrotask(flushReserve) + const epoch = clearEpoch + queueMicrotask(() => { if (epoch === clearEpoch) flushReserve() }) } function foldStarted(): void { @@ -113,18 +262,21 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: element.removeEventListener('transitionend', onEnd) clearTimeout(timer) running.delete(element) + boxes.delete(element) const { style } = element style.height = '' style.marginTop = '' style.opacity = '' style.overflow = '' style.transition = '' + style.translate = '' delete element.dataset.chatMotion } function cancelMotion(element: HTMLElement): void { pendingReserve.delete(element) running.get(element)?.() + cancelEmptyBatch?.() } function collapse(element: HTMLElement, done: () => void): void { @@ -168,6 +320,8 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: } element.addEventListener('transitionend', onEnd) running.set(element, cancel) + boxes.set(element, { element, height, marginTop, closing: true, finish, + take: () => { element.removeEventListener('transitionend', onEnd); clearTimeout(timer) } }) } function reveal(element: HTMLElement): void { @@ -200,16 +354,28 @@ export function createFlowMotion(reserve: (px: number) => void, foldingChanged: const timer = setTimeout(finish, CLOSE_DELAY_MS + CLOSE_MS + SETTLE_SLACK_MS) element.addEventListener('transitionend', onEnd) running.set(element, finish) + boxes.set(element, { element, height, marginTop, closing: false, finish, + take: () => { element.removeEventListener('transitionend', onEnd); clearTimeout(timer) } }) } function clear(): void { + clearEpoch++ + reserveScheduled = false + inputDriver = null + activeDriver = null + inputBatch = false + if (inputFrame !== null) cancelAnimationFrame(inputFrame) + inputFrame = null + inputCleanup?.() + inputCleanup = null + cancelEmptyBatch = null foldIdleListeners.clear() pendingReserve.clear() pendingGrowth = 0 for (const cancel of [...running.values()]) cancel() } - return { collapse, reveal, cancelMotion, foldActive, onFoldIdle, clear } + return { collapse, reveal, cancelMotion, foldActive, onFoldIdle, followInput, cancelInput, inputActive: () => inputBatch, clear } } function useFlowTransition(motion: FlowMotionRows | undefined, grow: boolean): HiddenTransition | undefined { @@ -219,11 +385,12 @@ function useFlowTransition(motion: FlowMotionRows | undefined, grow: boolean): H current.current = null }, [motion]) const transition = useCallback((element, hidden, commit) => { - const animate = current.current === element && motionEnabled(element) + const mounted = current.current === element + const animate = mounted && motionEnabled(element) current.current = element if (hidden) { if (hiddenOrCollapsing(element)) return - if (animate && motion !== undefined) motion.collapse(element, commit) + if (mounted && element.closest(MOTION_SCOPE) !== null && motion !== undefined) motion.collapse(element, commit) else commit() return } diff --git a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts index a5d4f9bc7a..7e58223287 100644 --- a/packages/client/ui-chat/src/client/chat/register-node-renderers.ts +++ b/packages/client/ui-chat/src/client/chat/register-node-renderers.ts @@ -51,7 +51,10 @@ export function registerChatNodeRenderers( name: 'conversation.chat.node', key: 'assistant-step', locale: NS, - children: { 'conversation.chat.reasoning.body': { kind: 'single', scope: 'session' } }, + children: { + 'conversation.chat.reasoning.body': { kind: 'single', scope: 'session' }, + 'conversation.chat.message.images': { kind: 'single', scope: 'session' }, + }, inject: () => ({ hooks: { presentation } }), }, AssistantNodeView)) ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({ diff --git a/packages/client/ui-chat/src/client/chat/use-chat-reading.ts b/packages/client/ui-chat/src/client/chat/use-chat-reading.ts index 85561c8fb8..3d3c6ae048 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-reading.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-reading.ts @@ -87,6 +87,17 @@ export class ChatReading { this.commit(landing, true, this.viewport.latestTurn) } + /** + * Follow submitted input on the active fold's animation clock. + * @returns whether this input joined a closing batch instead of starting another scroll animation. + */ + followInputFold(): boolean { + this.cancelPending() + return this.viewport.followInputFold(this.follow, (landing) => { + this.commit(landing, true, this.viewport.latestTurn) + }) + } + /** Stop a native follow animation where it is; the next sampled position decides follow intent. */ interruptFollow(): void { this.viewport.interruptFollow(this.follow) diff --git a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts index e233309669..8f867de148 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts @@ -64,6 +64,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { cancelFollow.current = null }, []) const cancelPendingFollow = useCallback(() => { + viewport.motion.cancelInput() clearPendingFollow() // Retain a cancelled wait until this fold ends, so resize cannot reacquire follow ownership. if (viewport.motion.foldActive()) { @@ -71,7 +72,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { } }, [clearPendingFollow, viewport]) const followAfterFold = useCallback(() => { - if (cancelFollow.current !== null) return + if (cancelFollow.current !== null || viewport.motion.inputActive()) return reading.interruptFollow() cancelFollow.current = viewport.motion.onFoldIdle(() => { cancelFollow.current = null @@ -100,8 +101,8 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { if (ownInput) { clearPendingFollow() navigation.cancel() - if (current.deferCompletedTurns && viewport.motion.foldActive()) followAfterFold() - else reading.followTail(current.deferCompletedTurns ? 'smooth' : 'instant') + if (current.deferCompletedTurns && reading.followInputFold()) return + reading.followTail(current.deferCompletedTurns ? 'smooth' : 'instant') return } if (navigation.contentCommitted()) { diff --git a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts index 5a81d63230..ad6de91901 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts @@ -160,6 +160,107 @@ export class ChatViewport { this.setSpacer(this.spacerHeight() + px) } + /** + * Join an input-caused fold and its tail movement on the fold's frame clock. + * @param follow - the existing reader's follow controller. + * @param settled - commits follow ownership after the final geometry is installed. + * @returns whether a closing batch owns this input. + */ + followInputFold(follow: ScrollFollow, settled: (landing: ViewportLanding) => void): boolean { + const elements = this.elements + if (elements === null) return false + this.interruptFollow(follow) + let start = 0 + let target = 0 + let removed = 0 + let initialHeight = 0 + let originalRoom = 0 + let finalRoom = 0 + let growth = 0 + let base = 0 + let previousColumnHeight = 0 + let previousProgress = 0 + let segmentProgress = 0 + let segmentTop = 0 + return this.motion.followInput({ + begin: (boxes) => { + const viewport = elements.scroller.getBoundingClientRect() + const metrics = scrollMetrics(elements.scroller) + start = metrics.top + originalRoom = this.spacerHeight() + initialHeight = Math.max(elements.column.offsetHeight, elements.scroller.scrollHeight - originalRoom) + let above = 0 + for (const box of boxes) { + const amount = box.height + box.marginTop + if (box.closing) { + removed += amount + const top = box.element.getBoundingClientRect().top - box.marginTop + above += Math.max(0, Math.min(amount, viewport.top - top)) + } else growth += amount + } + const finalHeight = initialHeight - removed + growth + base = Math.max(0, start - above) + segmentTop = start + previousColumnHeight = elements.column.offsetHeight + target = Math.max(base, Math.max(0, finalHeight - metrics.height)) + finalRoom = target === 0 ? 0 : Math.max(0, target + metrics.height - finalHeight) + elements.column.dataset.inputFold = '' + // This reserve only prevents an intermediate clamp; the final frame installs the exact deficit. + this.setSpacer(Math.max(originalRoom, finalRoom, removed)) + follow.setFollowing(true) + }, + prepare: (progress, cancelled) => { + if (this.elements !== elements) return + const added = elements.column.offsetHeight - previousColumnHeight + if (added !== 0) { + initialHeight += added + const finalHeight = initialHeight - removed + growth + target = Math.max(base, finalHeight - elements.scroller.clientHeight, 0) + finalRoom = target === 0 ? 0 : Math.max(0, target + elements.scroller.clientHeight - finalHeight) + segmentTop = elements.scroller.scrollTop + segmentProgress = previousProgress + } + const remaining = segmentProgress === 1 ? 1 : (progress - segmentProgress) / (1 - segmentProgress) + const top = cancelled ? elements.scroller.scrollTop : segmentTop + (target - segmentTop) * remaining + const currentHeight = initialHeight + (growth - removed) * progress + const room = Math.max(cancelled ? 0 : finalRoom, top + elements.scroller.clientHeight - currentHeight) + // Growing the room before shrinking boxes avoids a native clamp between writes. + this.setSpacer(Math.max(this.spacerHeight(), room)) + }, + frame: (progress, cancelled) => { + if (this.elements !== elements) return 0 + const remaining = segmentProgress === 1 ? 1 : (progress - segmentProgress) / (1 - segmentProgress) + const top = cancelled ? elements.scroller.scrollTop : segmentTop + (target - segmentTop) * remaining + const currentHeight = initialHeight + (growth - removed) * progress + const room = Math.max(cancelled ? 0 : finalRoom, top + elements.scroller.clientHeight - currentHeight) + elements.scroller.scrollTop = top + this.setSpacer(room) + if (!cancelled) this.observation = { top: elements.scroller.scrollTop, landing: null } + previousColumnHeight = elements.column.offsetHeight + previousProgress = progress + return elements.scroller.scrollTop - start + }, + finish: (cancelled) => { + if (this.elements !== elements) return + // Commit the final sibling margins while their input-fold transition override still applies. + void elements.column.offsetHeight + delete elements.column.dataset.inputFold + if (cancelled) { + const metrics = scrollMetrics(elements.scroller) + const height = elements.scroller.scrollHeight - this.spacerHeight() + this.setSpacer(metrics.top === 0 ? 0 : Math.max(0, metrics.top + metrics.height - height)) + this.invalidate() + return + } + this.setSpacer(finalRoom) + const metrics = scrollMetrics(elements.scroller) + const landing = { metrics, position: null, turn: this.latestTurn } + this.observation = { top: metrics.top, landing } + settled(landing) + }, + }) + } + /** Clear fold reservations after a display-mode change, allowing the scroll range to shrink. */ resetBelow(): void { this.setSpacer(0) diff --git a/packages/client/ui-chat/src/client/contract/chat-nodes.ts b/packages/client/ui-chat/src/client/contract/chat-nodes.ts index cade646b1c..c1cb6fad37 100644 --- a/packages/client/ui-chat/src/client/contract/chat-nodes.ts +++ b/packages/client/ui-chat/src/client/contract/chat-nodes.ts @@ -3,6 +3,7 @@ import type { ConversationLocation, ConversationViewNode, ModelRetryNode, RunningToolCall, ToolCallBlock, } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { ChatGroupTree } from './group-tree.ts' /** Final Chat render unit produced by a Chat business Definition. */ export interface ChatConversationViewNode extends ConversationViewNode { @@ -10,6 +11,13 @@ export interface ChatConversationViewNode extends ConversationViewNode { readonly anchorSeq: number readonly location: ConversationLocation readonly visibility: 'visible' | 'hidden' + /** + * Group-tree position, visible or hidden. An `exchange` Node's Turn and every + * later Turn before the next opening Turn form one exchange; the latest + * loaded exchange starts at the last loaded opening Turn, or at the first + * loaded Turn when none is loaded. + */ + readonly groupTree?: ChatGroupTree | undefined } /** Merge-extensible payload registry keyed by final Chat renderer kind. */ diff --git a/packages/client/ui-chat/src/client/contract/group-tree.ts b/packages/client/ui-chat/src/client/contract/group-tree.ts new file mode 100644 index 0000000000..efe1dabe3a --- /dev/null +++ b/packages/client/ui-chat/src/client/contract/group-tree.ts @@ -0,0 +1,27 @@ +import type { ChatConversationViewNode } from './chat-nodes.ts' + +/** + * Chat group-tree positions from the outermost grouping inward; a Node at a + * position also stands outside every inner grouping. + * - `exchange`: the Node's Turn opens an exchange, the run of Turns that lasts + * until the next opening Turn. + * - `turn`: the Node stays in its Turn outside the Turn's process disclosure. + * - `process`: the Node stays in the process disclosure outside step runs. + * + * Only `exchange` is read today; process disclosure and step runs still select + * independent Nodes by kind (`TURN_PROCESS_INDEPENDENT_KINDS`, the process-group + * `INDEPENDENT` set), so no Definition publishes `turn` or `process` yet. + */ +export type ChatGroupTree = 'exchange' | 'turn' | 'process' + +const DEPTH: Readonly> = { exchange: 0, turn: 1, process: 2 } + +/** + * Test whether a Node stands at a group-tree position or outside it. + * @param node - Chat Node. + * @param position - group-tree position to compare against. + * @returns whether the Node's position is `position` or an outer one. + */ +export function isAtOrOutside(node: Pick, position: ChatGroupTree): boolean { + return node.groupTree !== undefined && DEPTH[node.groupTree] <= DEPTH[position] +} diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index 52d7786e20..9bce65619b 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -3,15 +3,16 @@ import type { RefObject } from 'react' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' import type { SessionId, SessionSeq } from '@deepseek-ai/dsh-session/types' import type { PendingSubmission } from '@deepseek-ai/dsh-api-session-controller/client' +import type { FileAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { CommandNode, CompactionSummaryNode, ConversationLocationDataStore, ConversationTurnDataMap, ConversationGroupData, GroupSnapshot, - MessageImageLoader, MessageImagesOwnerProps, RenderEntry, RenderMessageImages, TurnLocation, + MessageImageLoader, MessageImageSource, MessageImagesOwnerProps, RenderEntry, TurnLocation, UserTextFacts, UserTextInput, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { HostObservable, InjectFace, KeyedSnapshotSelectorHook, PropsLocale, PropsRenderSlots, PropsRuntime, - PropsStore, SlotHookFactory, SnapshotSelectorHook, + PropsRenderFactories, PropsStore, SlotHookFactory, SnapshotSelectorHook, } from '@deepseek-ai/dsh-client-ui-slots' import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { MarkdownFileMentions, MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives' @@ -209,24 +210,39 @@ export interface ChatNodeOwnerProps { /** Renderer-owned Node portion selected by the grouping Definition. */ groupPart?: string cwd?: string | undefined - /** Open the current source file of a skill referenced by a sent message. */ - openSkill: (name: string) => void openFile: (path: string, options?: OpenFileOptions) => void inspectCall: ((callId: ToolCallId) => void) | undefined forkAt: (seq: number) => void - /** - * Session-authorized image loader, down-threaded from the Chat view so a - * chat-node renderer can render the attachment presentation slot directly - * with only the durable references plus this loader, instead of receiving a - * rendering closure. - */ + /** Session-authorized image loader supplied by the Chat view. */ loadImage: MessageImageLoader - renderMessageImages: RenderMessageImages fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined /** Turn-process state when this Node belongs to a projected Turn. */ turnProcess?: TurnProcessOwnerProps | undefined } +/** One attachment in the original user-message display order. */ +export type UserContentAttachment = + | { readonly type: 'image'; readonly image: MessageImageSource } + | { readonly type: 'file'; readonly file: FileAttachmentRef } + +/** Prepared user contents without row identity, admission state, time, or actions. */ +export interface UserContentData { + readonly text: string + readonly attachments: readonly UserContentAttachment[] + /** Blocks not represented by text or attachment presentation. */ + readonly extraBlocks: readonly unknown[] + /** Labels displayed in the caller-provided reference summary. */ + readonly referenceLabels?: readonly string[] +} + +/** Public content rendering input; reference renderers own their injected actions. */ +export interface UserContentInput extends Pick, + Pick { + readonly content: UserContentData + /** Transform inputs passed unchanged to UserText, separate from summary and rendering props. */ + readonly facts: Readonly> +} + /** Shared presentation state for one Turn-process answer generation. */ export interface TurnProcessOwnerProps { /** Process content eligible to share one Turn-level disclosure. */ @@ -247,7 +263,7 @@ export interface PresentationInjected { /** Full props of one keyed Chat renderer. */ export type ChatNodeViewProps = - PropsRuntime<'conversation.chat.node', Kind> & PropsLocale<'chat'> + PropsRuntime<'conversation.chat.node', Kind> & PropsLocale<'chat'> & PropsRenderFactories /** Command-row owner share. */ export interface CommandRowOwnerProps { @@ -292,8 +308,6 @@ export interface ChatViewInjected { /** Resolve one optional group without subscribing the root View to its data. */ chatGroup: (key: string) => ObservableSnapshot> | undefined> | undefined } - /** Open the current source file of a skill referenced by a sent message. */ - openSkill: (name: string) => void /** Open one HTTP(S) message link at the selected destination, using an external tab if Sidebar Browser is unavailable. */ openExternalLink: (url: string) => void openFile: (path: string, options?: OpenFileOptions) => Promise @@ -314,7 +328,7 @@ export type ChatFlowDataInjected = Pick { + 'cwd' | 'openFile' | 'inspectCall' | 'forkAt' | 'loadImage' | 'fileMentions'> { readonly entries: readonly RenderEntry[] readonly pendingInputs: readonly (PendingSubmission | InboxState['next-step'][number])[] readonly lastInputTurn: number | undefined @@ -324,7 +338,8 @@ export interface ChatFlowOwnerProps extends Pick - & PropsRenderSlots<'conversation.chat.node' | 'conversation.message.images'> + & PropsRenderSlots<'conversation.chat.node'> + & PropsRenderFactories & PropsStore & InjectFace & PropsLocale<'chat'> @@ -337,8 +352,9 @@ export type ChatViewSlotProps = & InjectFace & PropsLocale<'chat'> -/** Full props of the durable-message image renderer. */ -export type MessageImagesProps = PropsRuntime<'conversation.message.images'> & PropsLocale<'conversation'> +/** Full props shared by the user and output image entries. */ +export type MessageImagesProps = + PropsRuntime<'conversation.chat.user.images' | 'conversation.chat.message.images'> & PropsRenderFactories declare module '@deepseek-ai/dsh-client-ui-slots' { interface SessionStandardProps { @@ -352,6 +368,13 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { } interface SlotFactoryMap { + /** Prepared user text, attachments, and references inside a caller-owned message row. */ + 'conversation.chat.user.content': { + scope: 'session' + props: UserContentInput + locale: 'chat' + children: { 'conversation.chat.user.images': { kind: 'single'; scope: 'session' } } + } /** Session-independent reasoning Markdown with Chat labels and compact typography. */ 'conversation.chat.reasoning.content': { scope: 'root' @@ -387,7 +410,9 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * supplies image references, an authorized loader, and alignment. A * registration replaces the shipped gallery; without one, images are omitted. */ - 'conversation.message.images': { kind: 'single'; scope: 'session'; owner: MessageImagesOwnerProps } + 'conversation.chat.message.images': { kind: 'single'; scope: 'session'; owner: MessageImagesOwnerProps } + /** User-message images, including pending and local-echo previews, independently replaceable from output images. */ + 'conversation.chat.user.images': { kind: 'single'; scope: 'session'; owner: MessageImagesOwnerProps } /** * Command row keyed by the command name. The component receives the folded * command lifecycle and linked compaction when present. Reusing a key diff --git a/packages/client/ui-chat/src/client/contract/snapshot.ts b/packages/client/ui-chat/src/client/contract/snapshot.ts index b337c929bf..7e5f5038d3 100644 --- a/packages/client/ui-chat/src/client/contract/snapshot.ts +++ b/packages/client/ui-chat/src/client/contract/snapshot.ts @@ -35,7 +35,10 @@ export interface ChatNodeStore { get(key: string): ChatConversationViewNode | undefined /** @param key - stable Conversation Context key. @returns its identity-stable observable source. */ source(key: string): ChatNodeSource - /** @param key - Chat Node identity. @returns whether the visible Node belongs to the last Turn in the loaded timeline. */ + /** + * @param key - Chat Node identity. + * @returns whether the visible Node belongs to the latest loaded exchange (see `ChatConversationViewNode.groupTree`). + */ bottomSource(key: string): ObservableSnapshot /** * Observe one Turn's data for a single Node kind, including hidden Nodes, in anchor order. diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml b/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml index 2c402fade5..64ed556c17 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.i18n.yaml @@ -24,8 +24,8 @@ en: 91b35cbebe8c2a1d zh: a4fee6d7102bc874 /chat-conversation-node-rules/whole-turn-folding: - en: 6feeb1527191633f - zh: 401656a7b9a4a4ed + en: 8e0c0b62da18a24f + zh: f740809d0b7ff2f5 /chat-conversation-node-rules/display-modes: en: ada5a60d2c46f6a8 zh: f3eaeb5cb4d9b3de @@ -33,11 +33,11 @@ en: b25bf00ce3a6a119 zh: 0ab47a4014ea5e1e /chat-conversation-node-rules/display-modes/collapse-timing: - en: c31be5bb8cb77dc7 - zh: 9550ab598119076f + en: 03d744dd1c92bdd3 + zh: 19804eaf3234632a /chat-conversation-node-rules/display-modes/group-title-rules: - en: 5b40d65e660549b7 - zh: 09b6894aa00154e7 + en: 2392290662bc69e8 + zh: 8872d651c07a8f4c /chat-conversation-node-rules/process-grouping: en: c2650489ded57503 zh: f2554d74e75ae0f9 diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.md b/packages/client/ui-chat/src/client/conversation-nodes/README.md index 91c8b42ef6..a15f07a6a7 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.md +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.md @@ -70,7 +70,7 @@ If steering, a User message, or a trigger notice follows process output, the Tur Whole-Turn folding controls the loaded process range, independently of secondary groups, in Compact, Standard, and Detailed. Verbose keeps that range visible and retains the duration/status header without a collapse action. A recorded Turn end makes that range eligible even when paging has not loaded the Turn start. -The rules below use the default completion-time folding. The [collapse-timing preference](#collapse-timing) can defer the latest Turn's historical presentation without changing whole-Turn eligibility. +The rules below use the default completion-time folding. The [collapse-timing preference](#collapse-timing) can defer the latest exchange's historical presentation without changing whole-Turn eligibility. The Turn control follows all its opening inputs, including human steering and non-human trigger notices, while waiting for the first Assistant output and after that output arrives. Consecutive inputs before the first process evidence are opening inputs, anchored by the last one. Later inputs retain their positions: even when paging has not loaded their inbox insertions and they temporarily appear as ordinary User messages, preceding process content must not move after them. @@ -136,9 +136,11 @@ Reading a default does not automatically save configuration. When the user chang ### Collapse timing -Settings → General → Collapse work details appears directly below Work details and is independent of the display mode. On completion is the default and retains immediate folding and tail positioning. On next message enables delayed folding and its coordinated transitions. The choice lasts for the current Client instance: closing Settings preserves it; reloading or reopening the app resets it to On completion. It never writes Host settings, browser storage, or Session data. +Settings → General → Collapse work details appears directly below Work details and is independent of the display mode. On completion is the default and retains immediate folding and tail positioning. On next message enables delayed folding and its coordinated transitions. The choice is saved as `ui-chat.collapseTiming` through the same Host profile settings as Work details and is restored after reload or reopening the app. Profiles without a saved value use On completion without writing that default. It does not write browser storage or Session data. -With On next message, the latest Turn keeps its running presentation after completion: Compact and Standard retain their process headers, and Detailed retains its flat process rows. A pending ordinary transcript submission or a newer Turn ends this exemption without clearing the reader's manual whole-Turn choice. Inner disclosures reset only when their outer process actually hides. Queued input and steering alone do not end it. The latest Turn of a reopened Session also receives the exemption; manual whole-Turn choices still take precedence. Switching back to On completion ends the exemption immediately. +With On next message, the latest exchange keeps its running presentation after completion: Compact and Standard retain their process headers, and Detailed retains its flat process rows. An exchange starts with the Turn whose first Step admits human input and includes every later Turn until the next such Turn, so a Turn woken by a notice (a settled subagent, goal round, schedule, or job) leaves the preceding Turns of its exchange expanded. A pending ordinary transcript submission or a Turn that opens a newer exchange ends this exemption without clearing the reader's manual whole-Turn choice; a bare Turn start does not, because the host claims the waking input before it logs Step 1. Inner disclosures reset only when their outer process actually hides. Queued input and steering alone do not end it. The latest exchange of a reopened Session also receives the exemption, starting at the first loaded Turn when the loaded window holds no opening Turn; manual whole-Turn choices still take precedence. Switching back to On completion ends the exemption immediately. + +When a new message triggers a fold, process details close and the transcript follows the new message in one upward movement, without a second scroll after the fold. Off-screen steps do not add bottom space; only the space needed to preserve the visible movement remains when the retained answer and new message cannot fill it. Content added during the fold updates its remaining movement. Reopening every closing row cancels that movement and releases obsolete bottom space. A reading gesture interrupts automatic following; finishing the fold does not resume it. Verbose retains its flat process rows under either timing. Failed, stopped, and interleaved-input Turns retain their existing whole-Turn eligibility rules; delayed folding can still postpone Detailed's conversion from flat rows to historical groups. @@ -183,7 +185,7 @@ Group headers show a category icon, replace it with a down arrow on hover or key An open capped group follows content growth only while its own scroll position is at the bottom. Scrolling away pauses that group's following; returning to the bottom resumes it, independently of outer transcript following. Manually opening an unclosed group starts at the bottom and follows growth; manually opening a closed group starts at the top with following disabled, even when its initial content fits without scrolling. Closing the group in the data or restoring its height cap through a mode change does not reset an already-open reader's position. Browser find retains its own reveal position. -Individual reasoning starts collapsed, including while streaming. All modes preview the latest paragraph whose first line ends with a newline; an unfinished single line has no preview. Later text in that paragraph does not change the preview. After settlement, the mode table applies. Expanded reasoning uses compact Markdown typography. +Only reasoning blocks with non-whitespace text produce individual rows; each retains its original text and expands independently. A blank streaming tail produces no row and does not transfer its running state to an earlier block. Individual reasoning starts collapsed, including while streaming. All modes preview the latest paragraph whose first line ends with a newline; an unfinished single line has no preview. Later text in that paragraph does not change the preview. After settlement, the mode table applies. Expanded reasoning uses compact Markdown typography. Switching modes retains manually opened groups and inner disclosures. It changes visibility and sizing without recreating the message rows. Detailed and Verbose do not open every individual disclosure. Only Verbose keeps the whole Turn open. diff --git a/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md b/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md index d3b44f86c0..089a0b886a 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md +++ b/packages/client/ui-chat/src/client/conversation-nodes/README.zh.md @@ -70,7 +70,7 @@ description: "Chat 过程分组与活动摘要的明细业务规则。" 简洁、标准、详细模式的整轮折叠控制已加载的过程范围,独立于二级组。完全展开模式保持该范围可见,保留时长或状态抬头,但不支持收起。已经记录轮次结束时,即使向前分页尚未加载到轮次起点,也可以对该范围折叠。 -以下规则采用默认的完成时收起。[收起时机设置](#collapse-timing) 可以推迟最新轮次恢复历史呈现的时间,不改变整轮折叠资格。 +以下规则采用默认的完成时收起。[收起时机设置](#collapse-timing) 可以推迟最新交互段恢复历史呈现的时间,不改变整轮折叠资格。 整轮控件位于该轮所有起始输入之后,包括人工 steering 和非人工触发通知;等待首个 Assistant 输出及输出到达后均保持这一顺序。首个过程证据之前的连续输入都属于开场,以最后一条为准;过程证据之后的输入留在原位,即使分页尚未加载其入队记录、消息暂时归为普通 User,也不能把前面的过程移到它后面。 @@ -136,9 +136,11 @@ description: "Chat 过程分组与活动摘要的明细业务规则。" ### 收起时机 -设置 → 通用设置 → 过程收起时机位于工作步骤展示正下方,与展示模式独立。「完成时收起」是默认值,保留立即折叠和即时跟尾定位;「下次发送时收起」启用延后折叠及其协调过渡。选择仅在当前 Client 实例内有效:关闭设置面板后保留,刷新或重新打开应用时恢复为「完成时收起」。此偏好不写入 Host 设置、浏览器存储或 Session 数据。 +设置 → 通用设置 → 过程收起时机位于工作步骤展示正下方,与展示模式独立。「完成时收起」是默认值,保留立即折叠和即时跟尾定位;「下次发送时收起」启用延后折叠及其协调过渡。选择以 `ui-chat.collapseTiming` 保存到与工作步骤展示相同的 Host profile 设置,刷新或重新打开应用后会恢复。未保存此值的 profile 使用「完成时收起」,不会自动写入默认值。此偏好不写入浏览器存储或 Session 数据。 -选择「下次发送时收起」后,最新轮次完成时保留运行中的呈现:简洁和标准保留过程组头,详细保留平铺过程行。普通 transcript 输入进入待发送状态,或出现更新轮次时,取消这项例外,但保留用户对整轮的手动开合选择。只有外层过程实际隐藏时,才重置内部开合。排队输入和单独的 steering 不会取消例外。重新打开 Session 时,其最新轮次也享有例外;整轮的手动开合选择仍优先。切回「完成时收起」会立即取消例外。 +选择「下次发送时收起」后,最新交互段完成时保留运行中的呈现:简洁和标准保留过程组头,详细保留平铺过程行。交互段从首个 Step 接收真人输入的轮次开始,包含之后的所有轮次,直到下一个这样的轮次,因此由通知(子 agent 完成、Goal Round、定时任务或后台作业)唤醒的轮次不会收起同一交互段里更早的轮次。普通 transcript 输入进入待发送状态,或出现开启更新交互段的轮次时,取消这项例外,但保留用户对整轮的手动开合选择;仅出现新轮次的开始不会取消,因为 Host 先认领唤醒输入,再记录 Step 1。只有外层过程实际隐藏时,才重置内部开合。排队输入和单独的 steering 不会取消例外。重新打开 Session 时,其最新交互段也享有例外,已加载窗口中没有开启轮次时从第一个已加载轮次算起;整轮的手动开合选择仍优先。切回「完成时收起」会立即取消例外。 + +新消息触发折叠时,过程收起与跟随新消息合为一次向上运动,折叠结束后不再追加滚动。屏幕外的步骤不增加底部补白;只有保留的正文和新消息无法填满可见内容移动所需空间时,才保留必要差额。折叠期间新增的内容会更新剩余运动;重新展开全部正在收起的行时,取消该运动并释放失效的底部补白。阅读手势会中断自动跟随,折叠结束不会重新接管。 完全展开模式在两种时机下都保留平铺过程行。失败、停止和含插入输入的轮次沿用原有整轮折叠资格;延后折叠仍可推迟详细模式从平铺行转换为历史分组的时机。 @@ -183,7 +185,7 @@ description: "Chat 过程分组与活动摘要的明细业务规则。" 已展开的限高组仅在自己的滚动位置处于底部时跟随内容增长。滚离底部暂停该组跟随,滚回底部后恢复,与外层文本记录的跟随状态独立。手动展开未关闭的组时定位到底部并跟随增长;手动展开已关闭的组时从顶部开始且不启用跟随,即使初始内容无需滚动即可容纳。数据中的组变为已关闭,或通过模式切换恢复限高时,不重置已展开组的阅读位置。浏览器查找沿用自身的展开定位。 -单个推理初始收起,包括流式输出期间。四档都预览最近一个首行以换行结束的段落;未完成的单行没有预览,该段落后续文本不改变预览。结算后按上表展示。展开的推理使用紧凑 Markdown 排版。 +只有含非空白文本的推理块生成独立行,各自保留原文并独立展开。空白流式尾块不生成行,也不将运行状态转移给前面的块。单个推理初始收起,包括流式输出期间。四档都预览最近一个首行以换行结束的段落;未完成的单行没有预览,该段落后续文本不改变预览。结算后按上表展示。展开的推理使用紧凑 Markdown 排版。 切换模式保留手动展开的组和内部开合状态,只改变显隐与尺寸,不重建消息行。详细和完全展开都不表示自动打开每个内部控件;只有完全展开模式始终展开整轮。 diff --git a/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts b/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts index 0423e1ff20..dad0b6e51e 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/chat-snapshot-builder.ts @@ -12,7 +12,9 @@ import type { ChatTurnNavigationIndex, ChatTurnProcessPresentation, LegacyConversationSlice, TurnNavigationItem, } from '../contract/snapshot.ts' import { TURN_PROCESS_INDEPENDENT_KINDS } from '../contract/turn-process.ts' +import { locationCoordinates } from './common.ts' import { sessionRecallLabels, skillInvocationName } from './event-projection.ts' +import { GroupTreeSegments } from './group-tree-segments.ts' import { sameTurnNavigationItem, turnNavigationItem } from './turn-navigation.ts' import { ChatTurnProcessProjector } from './turn-process-presentation.ts' @@ -108,7 +110,8 @@ class MutableChatNodeStore implements ChatNodeStore { private readonly sources = new Map>() private readonly processSources = new Map>() private readonly bottomSources = new Map>() - private bottomTurn: number | undefined + /** Bottom membership: the latest loaded exchange. */ + private readonly exchanges = new GroupTreeSegments('exchange') private readonly dirtyKeys = new Set() private readonly dirtyBottomKeys = new Set() private readonly dirtyProcessKeys = new Set() @@ -131,19 +134,21 @@ class MutableChatNodeStore implements ChatNodeStore { bottomSource(key: string): ObservableSnapshot { return cachedSource(this.bottomSources, key, () => new MutableChatSource(() => { const node = this.get(key) as ChatNode | undefined - return this.bottomTurn !== undefined && node !== undefined && isVisibleChatNode(node) - && locationCoordinates(node.location).turn === this.bottomTurn + return node !== undefined && isVisibleChatNode(node) + && this.exchanges.inLatest(locationCoordinates(node.location).turn) }, `[ui-chat] node bottom source ${key}`)) } - setBottomTurn(turn: number | undefined, locations: ChatLocationNodeIndex): void { - if (turn === this.bottomTurn) return - for (const changed of [this.bottomTurn, turn]) { - if (changed !== undefined) { - for (const key of locations.getTurn(changed)) this.dirtyBottomKeys.add(key) - } + /** + * Settle the latest exchange for the loaded Turns and mark the Nodes of + * Turns that entered or left it. + * @param turnOrder - loaded Turns in ascending timeline order. + * @param locations - current Chat Location index. + */ + settleBottom(turnOrder: readonly number[], locations: ChatLocationNodeIndex): void { + for (const turn of this.exchanges.settle(turnOrder)) { + for (const key of locations.getTurn(turn)) this.dirtyBottomKeys.add(key) } - this.bottomTurn = turn } turnDataSource(turn: number, kind: Kind): ObservableSnapshot { @@ -196,6 +201,7 @@ class MutableChatNodeStore implements ChatNodeStore { this.byKey.set(node.key, node) if (previous.get(node.key) !== node) { this.updateTurnKind(previous.get(node.key), node) + this.exchanges.track(previous.get(node.key), node) this.dirtyKeys.add(node.key) this.dirtyProcessKeys.add(node.key) } @@ -203,6 +209,7 @@ class MutableChatNodeStore implements ChatNodeStore { } for (const key of previous.keys()) { this.updateTurnKind(previous.get(key), undefined) + this.exchanges.track(previous.get(key), undefined) this.dirtyKeys.add(key) this.dirtyProcessKeys.add(key) } @@ -215,6 +222,7 @@ class MutableChatNodeStore implements ChatNodeStore { for (const node of nodes) { if (this.byKey.get(node.key) === node) continue this.updateTurnKind(this.byKey.get(node.key), node) + this.exchanges.track(this.byKey.get(node.key), node) this.byKey.set(node.key, node) this.dirtyKeys.add(node.key) this.dirtyProcessKeys.add(node.key) @@ -408,12 +416,6 @@ function stepKey(turn: number, step: number): string { return `${turn}:${step}` } -function locationCoordinates(location: ConversationLocation): { turn?: number; step?: number } { - if (location.kind === 'step') return { turn: location.turn.turn, step: location.step.step } - if (location.kind === 'turn') return { turn: location.turn.turn } - return {} -} - function locationTurnStatus(location: ConversationLocation): string | undefined { return location.kind === 'turn' || location.kind === 'step' ? location.turn.status : undefined } @@ -1114,7 +1116,7 @@ export class ChatSnapshotBuilder implements ConversationViewBuilder node.key) this.locations.rebuild(this.order, this.store) this.store.replaceProcesses(this.order, this.locations) - this.store.setBottomTurn(input.timeline.turnOrder.at(-1), this.locations) + this.store.settleBottom(input.timeline.turnOrder, this.locations) this.navigation.rebuild(input.timeline, this.locations, this.store) this.timeline = input.timeline this.latestGroupInput = { @@ -1165,7 +1167,7 @@ export class ChatSnapshotBuilder implements ConversationViewBuilder( @@ -45,6 +57,7 @@ export function chatNode( options: { readonly location?: ConversationLocation readonly visibility?: 'visible' | 'hidden' + readonly groupTree?: ChatGroupTree | undefined } = {}, ): ChatNode { return { @@ -55,6 +68,7 @@ export function chatNode( anchorSeq, location: options.location ?? contextLocation(context), visibility: options.visibility ?? 'visible', + groupTree: options.groupTree, data, } } diff --git a/packages/client/ui-chat/src/client/conversation-nodes/group-tree-segments.ts b/packages/client/ui-chat/src/client/conversation-nodes/group-tree-segments.ts new file mode 100644 index 0000000000..738b79ef29 --- /dev/null +++ b/packages/client/ui-chat/src/client/conversation-nodes/group-tree-segments.ts @@ -0,0 +1,91 @@ +import type { ChatConversationViewNode } from '../contract/chat-nodes.ts' +import { isAtOrOutside, type ChatGroupTree } from '../contract/group-tree.ts' +import { locationCoordinates } from './common.ts' + +const NO_TURNS: readonly number[] = [] + +/** + * Loaded Turns split into consecutive segments at the Turns holding a Node at + * one group-tree position, visible or hidden. The latest segment starts at the + * last such Turn, or at the first loaded Turn when none is loaded. Node changes + * update per-Turn counts without scanning the loaded Nodes; `settle` returns at + * once while the start holds and otherwise reads loaded Turns only from the + * earlier of the previous and new starts. + */ +export class GroupTreeSegments { + /** Opening Node count by owning Turn. */ + private readonly openings = new Map() + private latestOpening: number | undefined + private latestStart: number | undefined + + /** @param position - group-tree position whose Nodes open a segment. */ + constructor(private readonly position: ChatGroupTree) {} + + /** + * Account one Node change. + * @param previous - replaced Node; absent for an addition. + * @param next - replacing Node; absent for a removal. + */ + track(previous: ChatConversationViewNode | undefined, next: ChatConversationViewNode | undefined): void { + const before = this.openingTurn(previous) + const after = this.openingTurn(next) + if (before === after) return + if (before !== undefined && this.adjust(before, -1) === 0 && before === this.latestOpening) { + this.latestOpening = this.lastOpeningTurn() + } + if (after !== undefined) { + this.adjust(after, 1) + if (this.latestOpening === undefined || after > this.latestOpening) this.latestOpening = after + } + } + + /** + * Test latest-segment membership as of the last `settle`. + * @param turn - owning Turn, when resolved. + * @returns whether the Turn belongs to the latest segment. + */ + inLatest(turn: number | undefined): boolean { + return turn !== undefined && this.latestStart !== undefined && turn >= this.latestStart + } + + /** + * Move the latest segment start for the currently loaded Turns. + * @param turnOrder - loaded Turns in ascending timeline order. + * @returns loaded Turns that entered or left the latest segment, in ascending order. + */ + settle(turnOrder: readonly number[]): readonly number[] { + const previous = this.latestStart + const start = this.latestOpening ?? turnOrder[0] + if (start === previous) return NO_TURNS + this.latestStart = start + const bounded = previous !== undefined && start !== undefined + const low = bounded ? Math.min(previous, start) : Number.NEGATIVE_INFINITY + const high = bounded ? Math.max(previous, start) : Number.POSITIVE_INFINITY + const changed: number[] = [] + for (const turn of turnOrder.slice(turnOrder.findLastIndex(turn => turn < low) + 1)) { + if (turn >= high) break + changed.push(turn) + } + return changed + } + + private openingTurn(node: ChatConversationViewNode | undefined): number | undefined { + return node !== undefined && isAtOrOutside(node, this.position) ? locationCoordinates(node.location).turn : undefined + } + + private lastOpeningTurn(): number | undefined { + let last: number | undefined + for (const turn of this.openings.keys()) { + if (last === undefined || turn > last) last = turn + } + return last + } + + /** @returns the Turn's opening count after the change; zero removes the Turn. */ + private adjust(turn: number, delta: number): number { + const next = (this.openings.get(turn) ?? 0) + delta + if (next > 0) this.openings.set(turn, next) + else this.openings.delete(turn) + return next + } +} diff --git a/packages/client/ui-chat/src/client/conversation-nodes/message.ts b/packages/client/ui-chat/src/client/conversation-nodes/message.ts index ddfffb0cca..d5ef45f93c 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/message.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/message.ts @@ -4,7 +4,7 @@ import type { } from '@deepseek-ai/dsh-client-ui-conversation/client' import { isAppendSurfaceEvent, isReplacementSurfaceEvent } from '@deepseek-ai/dsh-session/surface' import type { InboxState } from './inbox.ts' -import { chatNode } from './common.ts' +import { chatNode, contextLocation } from './common.ts' import { contextForm, contextProducer } from './event-projection.ts' interface ReferencedUserMessageNode extends UserMessageNode { @@ -115,7 +115,18 @@ export const messageDefinition: ConversationNodeDefinition = { const waking = context.state.kind === 'context' && context.start?.event.type === 'user/message' && context.state.waking === true - return chatNode(context, waking ? 'turn-trigger' : context.state.kind, context.state.seq, context.state) + // Human input claimed for Step 1 opens an exchange; Notice-woken Turns and + // later steering stay in the current exchange, so they never fold earlier Turns. + const location = contextLocation(context) + const opensExchange = (context.state.kind === 'user' || context.state.kind === 'steering') + && location.kind === 'step' && location.step.step === 1 + return chatNode( + context, + waking ? 'turn-trigger' : context.state.kind, + context.state.seq, + context.state, + { location, groupTree: opensExchange ? 'exchange' : undefined }, + ) }, } diff --git a/packages/client/ui-chat/src/client/index.ts b/packages/client/ui-chat/src/client/index.ts index a725061f89..275d76b96b 100644 --- a/packages/client/ui-chat/src/client/index.ts +++ b/packages/client/ui-chat/src/client/index.ts @@ -27,6 +27,7 @@ export type { FinalAssistantChatData, ManualCompactionChatData, RetryChatData, ToolChatData, TurnProcessChatData, TurnTailChatData, } from './contract/chat-nodes.ts' +export type { ChatGroupTree } from './contract/group-tree.ts' export type { ChatStoreState, ToolCallId, TurnProcessViewEntry } from './contract/store.ts' export type { TranscriptViewRowInjected, TranscriptViewRowProps } from './settings/TranscriptViewRow.tsx' export type { TranscriptViewMode } from '../chat-settings.ts' @@ -37,7 +38,7 @@ export type { ChatFlowDataInjected, ChatFlowHookContext, ChatFlowInjected, ChatFlowOwnerProps, ChatFlowSlotProps, UseGroupHeaderAction, CommandRowOwnerProps, CommandRowProps, MessageImagesProps, OpenFileOptions, PresentationInjected, QuotaNoticeCode, QuotaNoticeHostProps, QuotaNoticeInjected, QuotaNoticeOwnerProps, QuotaNoticeState, - ReasoningBodyOwnerProps, ReasoningContentInput, + ReasoningBodyOwnerProps, ReasoningContentInput, UserContentAttachment, UserContentData, UserContentInput, TurnProcessOwnerProps, TurnTailOwnerProps, UseChat, UseChatNodeTurnData, UseDisclosure, UsePresentation, UseGroupAction, } from './contract/slots.ts' export type { diff --git a/packages/client/ui-chat/src/client/presentation-policy.ts b/packages/client/ui-chat/src/client/presentation-policy.ts index eb5d15f39b..0bb38c7cdd 100644 --- a/packages/client/ui-chat/src/client/presentation-policy.ts +++ b/packages/client/ui-chat/src/client/presentation-policy.ts @@ -1,19 +1,14 @@ -/** Chat presentation derived from Host-backed detail and in-memory collapse timing. */ +/** Chat presentation derived from Host-backed detail and collapse timing. */ import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store' -import type { TranscriptViewMode } from '../chat-settings.ts' - -/** Available points when a completed Turn returns to its historical presentation. */ -export const COLLAPSE_TIMINGS = ['completion', 'next-input'] as const - -/** When a completed Turn returns to its historical presentation. */ -export type CollapseTiming = typeof COLLAPSE_TIMINGS[number] +import type { CollapseTiming, TranscriptViewMode } from '../chat-settings.ts' +export { COLLAPSE_TIMINGS, type CollapseTiming } from '../chat-settings.ts' /** Presentation capabilities that one work-details mode enables. */ export interface ChatPresentationPolicy { /** Preference identity for layout resets and diagnostics; renderers select the capabilities below. */ readonly mode: TranscriptViewMode - /** Browser-local experiment; completion retains the default immediate folding and scrolling. */ + /** Saved collapse timing; completion retains the default immediate folding and scrolling. */ readonly collapseTiming: CollapseTiming /** Whether a normally completed Turn folds its process rows behind the whole-Turn control. */ readonly foldCompletedTurns: boolean @@ -73,7 +68,7 @@ const TIMING_POLICIES = { /** * Resolve a stable policy for one detail mode and collapse timing. * @param mode - persisted work-details mode. - * @param collapseTiming - in-memory timing; defaults to immediate completion folding. + * @param collapseTiming - persisted timing; defaults to immediate completion folding. * @returns the same policy object for the same pair of choices. */ export function presentationPolicyFor( @@ -84,9 +79,9 @@ export function presentationPolicyFor( } /** - * Combine Host-backed detail and in-memory timing without owning subscriptions. + * Combine Host-backed detail and persisted timing without owning subscriptions. * @param mode - live work-details mode. - * @param collapseTiming - live, in-memory collapse timing. + * @param collapseTiming - live Host-backed collapse timing. * @returns observable policy whose subscriptions follow both preferences. */ export function derivePresentationPolicy( diff --git a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx index a770217041..d438e25c1d 100644 --- a/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx +++ b/packages/client/ui-chat/src/client/settings/TranscriptViewRow.tsx @@ -12,12 +12,12 @@ export interface TranscriptViewRowInjected { hooks: { /** Persisted work-details preference bound as useTranscriptView. */ transcriptView: SnapshotStore - /** Browser-local timing bound as useCollapseTiming. */ + /** Persisted collapse timing bound as useCollapseTiming. */ collapseTiming: SnapshotStore } /** Change the work-details presentation. */ setTranscriptView: (mode: TranscriptViewMode) => void - /** Retain collapse timing for this Client lifetime without changing Host settings. */ + /** Persist collapse timing independently of the work-details mode. */ setCollapseTiming: (timing: CollapseTiming) => void } @@ -40,7 +40,7 @@ const COLLAPSE_LABELS = { } as const satisfies Record /** - * Render work-details and browser-local collapse-timing selectors. + * Render the independent, Host-backed work-details and collapse-timing selectors. * @param props - composed Settings slot props. * @returns the preference row. */ diff --git a/packages/client/ui-chat/src/client/transcript-view.ts b/packages/client/ui-chat/src/client/transcript-view.ts index 4e311ff076..83928e2e8f 100644 --- a/packages/client/ui-chat/src/client/transcript-view.ts +++ b/packages/client/ui-chat/src/client/transcript-view.ts @@ -1,9 +1,10 @@ -/** Host-backed work details and independent, in-memory collapse timing. */ +/** Independent work-details preferences backed by the same Host configuration form. */ import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ConfigForm } from '@deepseek-ai/dsh-client-ui-settings/client' import type { CollapseTiming } from './presentation-policy.ts' import { + COLLAPSE_TIMING_FIELD, DEFAULT_COLLAPSE_TIMING, DEFAULT_TRANSCRIPT_VIEW_MODE, LEGACY_TRANSCRIPT_VIEW_MODE, LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE, TRANSCRIPT_VIEW_FIELD, type ChatSettings, type TranscriptViewMode, } from '../chat-settings.ts' @@ -13,8 +14,8 @@ export class TranscriptViewPolicy { private readonly unsubscribe: () => void /** Reactive current mode, including the client default before Host settings arrive. */ readonly mode: SnapshotStore - /** Independent Client-lifetime choice; each new instance starts with completion-time folding. */ - readonly collapseTiming: SnapshotStore = createSnapshotStore('completion') + /** Reactive collapse timing, defaulting to completion until Host settings arrive. */ + readonly collapseTiming: SnapshotStore = createSnapshotStore(DEFAULT_COLLAPSE_TIMING) /** * @param host - durable Chat settings scope. @@ -43,11 +44,13 @@ export class TranscriptViewPolicy { } /** - * Keep collapse timing in memory without writing Host or browser storage. + * Publish and persist collapse timing without changing the work-details mode. * @param timing - immediate completion folding or deferred folding at the next input. */ setCollapseTiming(timing: CollapseTiming): void { + if (this.collapseTiming.getSnapshot() === timing) return this.collapseTiming.set(timing) + void this.host.set(COLLAPSE_TIMING_FIELD, timing) } /** Adopt the latest accepted Host section without writing it back. */ @@ -58,5 +61,7 @@ export class TranscriptViewPolicy { const mode = saved === LEGACY_TRANSCRIPT_VIEW_MODE || saved === LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE ? 'detailed' : saved ?? this.defaultMode if (this.mode.getSnapshot() !== mode) this.mode.set(mode) + const timing = section.collapseTiming ?? DEFAULT_COLLAPSE_TIMING + if (this.collapseTiming.getSnapshot() !== timing) this.collapseTiming.set(timing) } } diff --git a/packages/client/ui-chat/src/index.ts b/packages/client/ui-chat/src/index.ts index 2380110127..e5876b8392 100644 --- a/packages/client/ui-chat/src/index.ts +++ b/packages/client/ui-chat/src/index.ts @@ -2,7 +2,7 @@ import type {} from '@deepseek-ai/dsh-settings' import type { Volatile, Context } from '@deepseek-ai/cordis' -import type { ChatSettings, LinkOpening, PerformanceUsageMode } from './chat-settings.ts' +import type { ChatSettings, CollapseTiming, LinkOpening, PerformanceUsageMode } from './chat-settings.ts' import z from '@deepseek-ai/schemastery' import { TRANSCRIPT_VIEW_FIELD } from './chat-settings.ts' @@ -18,6 +18,8 @@ export { export interface Config { /** Completed turn transcript presentation. */ transcriptView: Volatile + /** When completed work details return to their historical presentation. */ + collapseTiming: Volatile /** Performance and usage detail level. */ performanceUsage: Volatile /** Default destination for Chat HTTP(S) links. */ @@ -27,6 +29,7 @@ export interface Config { /** Live preferences projected to the browser. */ export const Config = z.object({ [TRANSCRIPT_VIEW_FIELD]: ChatSettingsFields[TRANSCRIPT_VIEW_FIELD].volatile(), + collapseTiming: ChatSettingsFields.collapseTiming.volatile(), performanceUsage: ChatSettingsFields['performanceUsage'].volatile(), linkOpening: ChatSettingsFields.linkOpening.volatile(), }) diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 13bb94398b..2898fab578 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -137,7 +137,7 @@ async function bench(initialSettings?: ChatSettings, withBrowserRegistry = true, } describe('Chat inject API', () => { - it('projects independent Settings choices without saving timing to Host settings', async () => { + it('projects independent Settings choices and saves timing to Host settings', async () => { const b = await bench() try { const row = b.runtime.slots.entries('settings.general.item') @@ -149,12 +149,12 @@ describe('Chat inject API', () => { expect(presentation.getSnapshot()).toMatchObject({ mode: 'detailed', collapseTiming: 'completion' }) setCollapseTiming('next-input') expect(presentation.getSnapshot()).toMatchObject({ mode: 'detailed', collapseTiming: 'next-input' }) - expect(b.chatSettings.set).not.toHaveBeenCalled() - b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true }) + expect(b.chatSettings.set).toHaveBeenCalledWith('collapseTiming', 'next-input') + b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true }) expect(presentation.getSnapshot()).toMatchObject({ mode: 'standard', collapseTiming: 'next-input' }) setCollapseTiming('completion') expect(presentation.getSnapshot()).toMatchObject({ mode: 'standard', collapseTiming: 'completion' }) - expect(b.chatSettings.set).not.toHaveBeenCalled() + expect(b.chatSettings.set).toHaveBeenLastCalledWith('collapseTiming', 'completion') expect(b.session.prompt).not.toHaveBeenCalled() expect(b.session.cancel).not.toHaveBeenCalled() } finally { @@ -387,20 +387,14 @@ describe('Chat inject API', () => { } }) - it('routes sent skill previews through the viewed Session source and tolerates an absent provider', async () => { + it('leaves skill preview injection to the skill reference owner', async () => { const b = await bench() - const { injected } = b.chatViewApi(b.rootReference) - injected.openSkill('review') - const openReference = vi.fn(() => true) - const sessionOf = vi.fn(() => ({ openReference })) - b.runtime.ctx.provide('inputTriggers', { sessionOf } as never) - injected.openSkill('review') - expect(sessionOf).toHaveBeenCalledWith(b.runtime.sessions.scope(ROOT)) - expect(openReference).toHaveBeenCalledWith('skill', { ref: '/review' }) - vi.spyOn(b.runtime.sessions, 'scope').mockReturnValueOnce(undefined) - injected.openSkill('review') - expect(openReference).toHaveBeenCalledTimes(1) - await b.runtime.dispose() + try { + const { injected } = b.chatViewApi(b.rootReference) + expect(injected).not.toHaveProperty('openSkill') + } finally { + await b.runtime.dispose() + } }) it('keeps a relative path under the Session without a cwd, and addresses a path outside the workspace absolutely', async () => { diff --git a/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx b/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx index e37c569f03..c366be70e6 100644 --- a/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx +++ b/packages/client/ui-chat/tests/assistant-markdown-path-images.client.spec.tsx @@ -3,15 +3,15 @@ import { cleanup, render } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' import { AssistantMarkdown, localPathMediaUrl } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' -import type { ChatNodeOwnerProps, ChatViewSlotProps } from '../src/client/contract/slots.ts' +import type { ChatViewSlotProps } from '../src/client/contract/slots.ts' import type { AssistantBlock } from '../src/client/contract/snapshot.ts' afterEach(() => { cleanup(); vi.restoreAllMocks() }) const t = ((_key: string) => 'label') as ChatViewSlotProps['t'] -const renderMessageImages = (() => null) as ChatNodeOwnerProps['renderMessageImages'] function textBlock(text: string): AssistantBlock { return { kind: 'text', text } @@ -63,7 +63,7 @@ describe('AssistantMarkdown local-path images', () => { usePresentation={useDetailedPresentation} blocks={[textBlock('See ![diagram](/tmp/graph.png) for the layout.')]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} t={t} />, ) @@ -81,7 +81,7 @@ describe('AssistantMarkdown local-path images', () => { usePresentation={useDetailedPresentation} blocks={[textBlock('See ![diagram](relative.png).')]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} t={t} />, ) diff --git a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx index 46c0bda457..c449d30d89 100644 --- a/packages/client/ui-chat/tests/chat-apply.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-apply.client.spec.tsx @@ -30,6 +30,7 @@ import { CHAT_SETTINGS_NAMESPACE, type ChatSettings } from '../src/chat-settings import { ActivityPill, UsagePill } from '../src/client/chat/StatsPills.tsx' import { createFlowMotion } from '../src/client/chat/flow-motion.ts' import { CHAT_FLOW_INJECT, CHAT_NODE_INJECT } from '../src/client/apply.ts' +import { UserContent } from '../src/client/chat/UserContent.tsx' declare module '@deepseek-ai/dsh-client-ui-conversation/client' { interface ConversationTurnDataMap { @@ -101,6 +102,7 @@ describe('Chat apply wiring', () => { expect(entry).not.toHaveProperty('CHAT_FLOW_INJECT') expect(entry).not.toHaveProperty('CHAT_NODE_INJECT') expect(entry).not.toHaveProperty('ChatFlow') + expect(entry).not.toHaveProperty('UserContent') }) it('registers the frame-wide quota notice host and keeps the failure row injection-free', async () => { @@ -140,23 +142,37 @@ describe('Chat apply wiring', () => { await b.runtime.dispose() }) - it('owns node and image rendering through the flow slot with the shared Chat store', async () => { + it('owns node dispatch in the shared flow and image Slots in their domain renderers', async () => { const b = await bench() onTestFinished(() => b.runtime.dispose()) + b.runtime.renderRoot() expect(b.runtime.slots.spec('conversation.chat.flow')).toMatchObject({ kind: 'single', scope: 'session' }) const view = b.runtime.slots.entries('conversation.view')[0] const flow = b.runtime.slots.entries('conversation.chat.flow')[0] + const assistant = b.runtime.slots.entries('conversation.chat.node').find(entry => entry.options.key === 'assistant-step') + const userContent = b.runtime.factoryOf('conversation.chat.user.content') + expect(userContent).toMatchObject({ scope: 'session', locale: 'chat', component: UserContent }) + expect(userContent.children?.['conversation.chat.user.images']).toMatchObject({ kind: 'single', scope: 'session' }) + expect(assistant?.children?.['conversation.chat.message.images']).toMatchObject({ kind: 'single', scope: 'session' }) + expect(userContent.store).toBeUndefined() + expect(userContent.inject).toBeUndefined() expect(view?.children?.['conversation.chat.flow']).toBeDefined() expect(view?.children?.['conversation.chat.node']).toBeUndefined() - expect(view?.children?.['conversation.message.images']).toBeUndefined() + expect(view?.children?.['conversation.chat.message.images']).toBeUndefined() + expect(view?.children?.['conversation.chat.user.images']).toBeUndefined() expect(flow?.children?.['conversation.chat.node']).toBeDefined() - expect(flow?.children?.['conversation.message.images']).toBeDefined() + expect(flow?.children?.['conversation.chat.message.images']).toBeUndefined() + expect(flow?.children?.['conversation.chat.user.images']).toBeUndefined() + expect(userContent.children?.['conversation.chat.message.images']).toBeUndefined() + expect(assistant?.children?.['conversation.chat.user.images']).toBeUndefined() expect(flow?.store).toBeDefined() expect(flow?.store).toBe(view?.store) await b.chat.dispose() expect(b.runtime.slots.spec('conversation.chat.flow')).toBeUndefined() expect(b.runtime.slots.spec('conversation.chat.node')).toBeUndefined() - expect(b.runtime.slots.spec('conversation.message.images')).toBeUndefined() + expect(b.runtime.slots.spec('conversation.chat.message.images')).toBeUndefined() + expect(b.runtime.slots.spec('conversation.chat.user.images')).toBeUndefined() + expect(() => b.runtime.factoryOf('conversation.chat.user.content')).toThrow('no definition') }) it('lets another registrant replace one composer stats pill by id', async () => { @@ -200,7 +216,7 @@ describe('Chat apply wiring', () => { expect(face.hooks.transcriptView.getSnapshot()).toBe('compact') }) - it('resets in-memory collapse timing when the Chat plugin remounts', async () => { + it('restores saved collapse timing when the Chat plugin remounts', async () => { const b = await bench() try { const row = b.runtime.slots.entries('settings.general.item') @@ -211,8 +227,8 @@ describe('Chat apply wiring', () => { expect(hooks.collapseTiming.getSnapshot()).toBe('completion') setCollapseTiming('next-input') expect(hooks.collapseTiming.getSnapshot()).toBe('next-input') - expect(b.chatSettings.set).not.toHaveBeenCalled() - b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true }) + expect(b.chatSettings.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input') + b.chatSettings.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true }) expect(hooks.transcriptView.getSnapshot()).toBe('standard') expect(hooks.collapseTiming.getSnapshot()).toBe('next-input') expect(b.runtime.slots.entries('settings.general.item').map(entry => entry.options.id)) @@ -226,9 +242,9 @@ describe('Chat apply wiring', () => { const remounted = remountedRow.inject!() const remountedHooks = remounted.hooks as TranscriptViewRowInjected['hooks'] expect(remountedHooks.collapseTiming).not.toBe(hooks.collapseTiming) - expect(remountedHooks.collapseTiming.getSnapshot()).toBe('completion') + expect(remountedHooks.collapseTiming.getSnapshot()).toBe('next-input') expect(remountedHooks.transcriptView.getSnapshot()).toBe('standard') - expect(b.chatSettings.set).not.toHaveBeenCalled() + expect(b.chatSettings.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input') expect(b.runtime.slots.entries('settings.general.item').map(entry => entry.options.id)) .toEqual(['transcript-view', 'link-opening', 'composer-enter', 'performance-usage']) } finally { diff --git a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx index 7954e2cb45..fa922ee1e1 100644 --- a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx @@ -7,7 +7,7 @@ import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts import type { ChatConversationViewNode, ConversationNode, } from '@deepseek-ai/dsh-client-ui-chat/client' -import type { ChatNodeViewProps } from '../src/client/contract/slots.ts' +import type { ChatNodeViewProps, UserContentInput } from '../src/client/contract/slots.ts' import { formatMessageClock, msUntilNextLocalMidnight, startOfLocalDay, } from '../src/client/chat/message-chrome.ts' @@ -15,8 +15,10 @@ import { CompactionNodeView, ContextMessageNodeView, RetryNodeView, UnknownNodeView, UserMessageNodeView, } from '../src/client/chat/MessageItem.tsx' -import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' +import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' +import { createUserContentFixture } from './user-content-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' import { ActivityPill, UsagePill, type StatPillProps } from '../src/client/chat/StatsPills.tsx' @@ -30,7 +32,9 @@ afterEach(() => { }) const t: ChatNodeViewProps['t'] = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null +const renderUserImages: Parameters>[1] = () => null +let renderUserContent: ReturnType +beforeEach(() => { renderUserContent = createUserContentFixture() }) const RETRY_ID = 'retry-fixture' as Extract['retryId'] // Recency scans the whole transcript; a detached fixture is its own latest row. @@ -67,9 +71,14 @@ function MessageItem({ node, t: translate, referenceLabels, skillNames }: Messag } : node, } - const props = { - node: viewNode, t: translate, renderMessageImages, openFile: vi.fn(), openSkill: vi.fn(), useChat: useDetachedChat, - } as unknown as ChatNodeViewProps + const renderUserFactory: ChatNodeViewProps['renderFactorySlot'] = (name, input) => { + if (name !== 'conversation.chat.user.content') throw new Error(`Unexpected user Factory: ${name}`) + return renderUserContent(input as UserContentInput, renderUserImages, translate) + } + const props: Partial> & { node: ChatConversationViewNode } = { + node: viewNode, t: translate, loadImage: unusedImageLoader, renderFactorySlot: renderUserFactory, + openFile: vi.fn(), useChat: useDetachedChat, + } switch (node.kind) { case 'user': case 'steering': @@ -168,16 +177,21 @@ describe('MessageItem arms', () => { // Same-day clock: construct "today at 14:24" so the label stays `HH:mm`. const now = new Date() const time = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 14, 24).getTime() - render( + const view = render( , ) expect(screen.getByText('14:24')).toBeTruthy() expect(screen.getByRole('button', { name: '复制' })).toBeTruthy() + const stack = view.getByText('hello bubble').closest('div')?.parentElement + expect(stack?.parentElement).toBe(view.container.firstElementChild) + expect(stack?.contains(screen.getByText('14:24'))).toBe(false) + expect(stack?.contains(screen.getByRole('button', { name: '复制' }))).toBe(false) + expect(stack?.nextElementSibling?.contains(screen.getByRole('button', { name: '复制' }))).toBe(true) expect(screen.queryByRole('button', { name: '在新对话中分支' })).toBeNull() expect(screen.queryByRole('button', { name: '编辑' })).toBeNull() fireEvent.click(screen.getByRole('button', { name: '复制' })) @@ -1051,7 +1065,7 @@ describe('small branch tails', () => { t={t} blocks={[{ kind: 'reasoning', text: 'one-liner' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('one-liner')).toBeTruthy() diff --git a/packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts b/packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts index ef52f7a258..d72295e212 100644 --- a/packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts +++ b/packages/client/ui-chat/tests/chat-node-bottom.client.spec.ts @@ -18,15 +18,20 @@ function node(index: number, owner = turn(index), text = ''): ChatConversationVi } } +/** A Node whose Turn opens an exchange. */ +function opening(index: number, owner = turn(index), text = ''): ChatConversationViewNode { + return { ...node(index, owner, text), groupTree: 'exchange' } +} + function timeline(turns: readonly TurnLocation[]): ConversationTimelineSnapshot { return { turnOrder: turns.map(value => value.turn), turns: new Map(turns.map(value => [value.turn, value])) } } describe('assembler-owned Chat bottom membership', () => { - it('notifies only old and new bottom keys among 4,000 observed historical Nodes', () => { + it('notifies only the Turns leaving or entering the latest exchange among 4,000 observed historical Nodes', () => { const builder = new ChatSnapshotBuilder() const turns = Array.from({ length: 4_000 }, (_, index) => turn(index + 1)) - const nodes = turns.map(value => node(value.turn, value)) + const nodes = turns.map(value => opening(value.turn, value)) const snapshot = builder.replace({ nodes, timeline: timeline(turns) }) builder.publish() const sources = nodes.map(value => snapshot.nodes.bottomSource(value.key)) @@ -36,7 +41,7 @@ describe('assembler-owned Chat bottom membership', () => { return listener }) const nextTurn = turn(4_001) - const nextNode = node(4_001, nextTurn) + const nextNode = opening(4_001, nextTurn) const nextSource = snapshot.nodes.bottomSource(nextNode.key) const nextChanged = vi.fn() nextSource.subscribe(nextChanged) @@ -55,17 +60,17 @@ describe('assembler-owned Chat bottom membership', () => { expect(snapshot.nodes.bottomSource(nextNode.key)).toBe(nextSource) nextChanged.mockClear() - builder.apply({ upserts: [node(4_001, nextTurn, 'updated')], timeline: timeline([...turns, nextTurn]) }) + builder.apply({ upserts: [opening(4_001, nextTurn, 'updated')], timeline: timeline([...turns, nextTurn]) }) builder.publish() expect(nextChanged).not.toHaveBeenCalled() expect(listeners.at(-1)).toHaveBeenCalledOnce() }) - it('advances on a Turn boundary before its Node materializes and retains source identity across replacement', () => { + it('keeps a bare Turn boundary and continuation Turns in the latest exchange until an opening Node arrives', () => { const builder = new ChatSnapshotBuilder() const first = turn(1) const second = turn(2) - const initial = builder.replace({ nodes: [node(1, first)], timeline: timeline([first]) }) + const initial = builder.replace({ nodes: [opening(1, first)], timeline: timeline([first]) }) builder.publish() const oldBottom = initial.nodes.bottomSource('user:1') const nextBottom = initial.nodes.bottomSource('user:2') @@ -73,26 +78,92 @@ describe('assembler-owned Chat bottom membership', () => { const unsubscribe = oldBottom.subscribe(changed) builder.apply({ upserts: [], timeline: timeline([first, second]) }) builder.publish() - expect(changed).toHaveBeenCalledOnce() - expect(oldBottom.getSnapshot()).toBe(false) - expect(nextBottom.getSnapshot()).toBe(false) + expect(changed).not.toHaveBeenCalled() + expect(oldBottom.getSnapshot()).toBe(true) + builder.apply({ upserts: [node(2, second)], timeline: timeline([first, second]) }) builder.publish() - expect(nextBottom.getSnapshot()).toBe(true) + expect(changed).not.toHaveBeenCalled() + expect([oldBottom.getSnapshot(), nextBottom.getSnapshot()]).toEqual([true, true]) + + builder.apply({ upserts: [opening(2, second)], timeline: timeline([first, second]) }) + builder.publish() + expect(changed).toHaveBeenCalledOnce() + expect([oldBottom.getSnapshot(), nextBottom.getSnapshot()]).toEqual([false, true]) unsubscribe() - const replaced = builder.replace({ nodes: [node(1, first)], timeline: timeline([first]) }) + + const replaced = builder.replace({ nodes: [opening(1, first)], timeline: timeline([first]) }) builder.publish() expect(replaced.nodes.bottomSource('user:1')).toBe(oldBottom) - expect(oldBottom.getSnapshot()).toBe(true) - expect(nextBottom.getSnapshot()).toBe(false) - expect(changed).toHaveBeenCalledOnce() + expect([oldBottom.getSnapshot(), nextBottom.getSnapshot()]).toEqual([true, false]) + + builder.replace({ nodes: [node(1, first), node(2, second)], timeline: timeline([first, second]) }) + builder.publish() + expect([oldBottom.getSnapshot(), nextBottom.getSnapshot()]).toEqual([true, true]) + }) + + it('starts the latest exchange at the first loaded Turn while no opening Node is loaded', () => { + const builder = new ChatSnapshotBuilder() + const turns = [turn(3), turn(4), turn(5)] + const initial = builder.replace({ nodes: turns.map(value => node(value.turn, value)), timeline: timeline(turns) }) + builder.publish() + const bottoms = ['user:3', 'user:4', 'user:5'].map(key => initial.nodes.bottomSource(key)) + expect(bottoms.map(source => source.getSnapshot())).toEqual([true, true, true]) + + const older = [turn(1), turn(2), ...turns] + const loaded = builder.replace({ nodes: older.map(value => node(value.turn, value)), timeline: timeline(older) }) + builder.publish() + expect(['user:1', 'user:2'].map(key => loaded.nodes.bottomSource(key).getSnapshot())).toEqual([true, true]) + + builder.replace({ nodes: [], timeline: timeline([]) }) + builder.publish() + expect(bottoms.map(source => source.getSnapshot())).toEqual([false, false, false]) + }) + + it('follows the latest remaining opening Turn when opening Nodes leave, move, or repeat in one Turn', () => { + const builder = new ChatSnapshotBuilder() + const turns = [turn(1), turn(2), turn(3), turn(4)] + const second: ChatConversationViewNode = { ...opening(22, turns[1]), key: 'user:2b' } + const nodes = [opening(1, turns[0]), opening(2, turns[1]), second, node(3, turns[2]), opening(4, turns[3])] + const initial = builder.replace({ nodes, timeline: timeline(turns) }) + builder.publish() + const bottom = (key: string): boolean => initial.nodes.bottomSource(key).getSnapshot() + const membership = (): boolean[] => ['user:1', 'user:2', 'user:3', 'user:4'].map(bottom) + expect(membership()).toEqual([false, false, false, true]) + + const before = vi.fn() + const unchanged = vi.fn() + initial.nodes.bottomSource('user:2').subscribe(before) + initial.nodes.bottomSource('user:1').subscribe(unchanged) + builder.apply({ upserts: [node(4, turns[3])], timeline: initial.timeline }) + builder.publish() + expect(membership()).toEqual([false, true, true, true]) + expect(before).toHaveBeenCalledOnce() + expect(unchanged).not.toHaveBeenCalled() + + builder.apply({ upserts: [node(2, turns[1])], timeline: initial.timeline }) + builder.publish() + expect(membership()).toEqual([false, true, true, true]) + + builder.apply({ upserts: [{ ...second, location: { kind: 'session' } }], timeline: initial.timeline }) + builder.publish() + expect(membership()).toEqual([true, true, true, true]) + + builder.apply({ upserts: [{ ...opening(3, turns[2]), visibility: 'hidden' }], timeline: initial.timeline }) + builder.publish() + expect(membership()).toEqual([false, false, false, true]) + expect(bottom('user:2b')).toBe(false) + + builder.replace({ nodes: [opening(1, turns[0]), node(2, turns[1]), node(4, turns[3])], timeline: initial.timeline }) + builder.publish() + expect(membership()).toEqual([true, true, false, true]) }) it('updates same-key Turn moves without changing root order and excludes unplaced or hidden Nodes', () => { const builder = new ChatSnapshotBuilder() const first = turn(1) const second = turn(2) - const initial = builder.replace({ nodes: [node(1, first)], timeline: timeline([first, second]) }) + const initial = builder.replace({ nodes: [node(1, first), opening(2, second)], timeline: timeline([first, second]) }) builder.publish() const bottom = initial.nodes.bottomSource('user:1') expect(bottom.getSnapshot()).toBe(false) diff --git a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx index 748b8fadfe..b212f91940 100644 --- a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx @@ -100,6 +100,219 @@ function mountScroll(deferCompletedTurns = true, initial: Partial { motion = value } + let input: ChatScrollInput = { + ready: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + steeringId: null, submissionId: null, running: false, deferCompletedTurns: true, + transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, + loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, + } + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: reduced }))) + const view = render() + const scroller = within(view.container).getByTestId('scrollport') + const column = within(view.container).getByTestId('column') + const spacer = scroller.querySelector('[data-chat-turn-spacer]')! + const row = document.createElement('div') + const glyph = document.createElement('span') + glyph.textContent = 'step text' + row.append(glyph) + column.append(row) + const rowHeight = () => row.hidden ? 0 : (row.style.transition !== '' && row.style.transition !== 'none') || row.style.height === '' + ? test.steps : Number.parseFloat(row.style.height) + const room = () => Number.parseFloat(spacer.style.height) || 0 + const contentHeight = () => test.earlier + rowHeight() + test.body + inputHeight + const floor = () => Math.max(0, contentHeight() + room() - test.viewport) + const scrollTo = vi.fn((options: ScrollToOptions) => { + scroller.scrollTop = options.top ?? scroller.scrollTop + }) + Object.defineProperties(scroller, { + clientHeight: { get: () => test.viewport }, + scrollHeight: { get: () => Math.max(test.viewport, contentHeight() + room()) }, + scrollTop: { + get: () => { top = Math.max(0, Math.min(top, floor())); return top }, + set: (value: number) => { top = Math.max(0, Math.min(value, floor())) }, + }, + scrollTo: { value: scrollTo }, + getBoundingClientRect: { value: () => ({ top: 0, bottom: test.viewport, height: test.viewport }) }, + }) + Object.defineProperties(row, { + offsetHeight: { get: rowHeight }, + getBoundingClientRect: { value: () => ({ top: test.earlier - top, bottom: test.earlier - top + rowHeight(), height: rowHeight() }) }, + }) + Object.defineProperties(column, { + offsetHeight: { get: contentHeight }, + getBoundingClientRect: { value: () => ({ top: -top, bottom: contentHeight() - top, height: contentHeight() }) }, + }) + input = { ...input, ready: true } + view.rerender() + top = test.top + scrollTo.mockClear() + return { + scroller, row, room, scrollTo, + reopenAll(verbose = false) { + act(() => { motion?.cancelMotion(row) }) + row.hidden = false + if (verbose) { + input = { ...input, transcriptView: 'verbose' } + view.rerender() + } + }, + growDuringFold(height: number, newSubmission: boolean) { + inputHeight += height + input = newSubmission + ? { ...input, submissionId: 'second-distinct-input' } + : { ...input, order: ['new-stream-content'], running: true } + view.rerender() + }, + cancelReading() { + fireEvent.wheel(scroller, { deltaY: -20 }) + scroller.scrollTop -= 20 + fireEvent.scroll(scroller) + return scroller.scrollTop + }, + updateInput() { + input = { ...input, submissionId: null, lastKey: 'durable-input', lastIsUser: true } + view.rerender() + }, + bodyTop: () => test.earlier + rowHeight() - top, + submit() { + inputHeight += test.input + row.hidden = false + submission++ + act(() => { + motion?.collapse(row, () => { row.hidden = true }) + }) + input = { ...input, submissionId: `visible-fold-input-${submission}` } + view.rerender() + }, + } +} + +describe.each([false, true])('visible input-fold matrix (reduced=%s)', (reduced) => { + it.each(visibleFoldCases)('$name lands with only the required visible room', async (test) => { + const h = mountVisibleFold(test, reduced) + const positions = [h.bodyTop()] + h.submit() + await act(async () => { await Promise.resolve() }) + for (let frame = 0; frame < 24; frame++) { + act(() => { vi.advanceTimersByTime(16) }) + positions.push(h.bodyTop()) + } + expect(h.scroller.scrollTop).toBeCloseTo(test.target, 5) + expect(h.room()).toBeCloseTo(test.room, 5) + if (test.steps > 0) expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) + for (let i = 1; i < positions.length; i++) expect(positions[i]!).toBeLessThanOrEqual(positions[i - 1]! + 0.01) + const end = h.bodyTop() + act(() => { vi.advanceTimersByTime(500) }) + expect(h.bodyTop()).toBe(end) + }) +}) + +it('consumes a prior legal fold deficit instead of accumulating whole steps on the next input', async () => { + const test = visibleFoldCases.find(test => test.name === 'T/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.room()).toBe(320) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(500) + expect(h.room()).toBe(240) + expect(h.scrollTo).not.toHaveBeenCalled() +}) + +it('retains the reader position without clamping after an input fold is interrupted', async () => { + const test = visibleFoldCases.find(test => test.name === 'B/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(112) }) + const readingTop = h.cancelReading() + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(readingTop) + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + +it.each([false, true])('stops obsolete viewport writes when every closing row reopens (verbose=%s)', async (verbose) => { + const test = visibleFoldCases.find(test => test.name === 'T/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(112) }) + h.reopenAll(verbose) + await act(async () => { await Promise.resolve() }) + const position = h.scroller.scrollTop + act(() => { vi.advanceTimersByTime(400) }) + expect(h.room()).toBe(0) + expect(h.scroller.scrollTop).toBe(position) + expect(h.row.hidden).toBe(false) + expect(h.row.style.height).toBe('') + expect(h.scroller.querySelector('[data-input-fold]')).toBeNull() + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + +it.each([false, true])('absorbs new height before the active fold finishes (new submission=%s)', async (newSubmission) => { + const test = visibleFoldCases.find(test => test.name === 'B/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(112) }) + h.growDuringFold(320, newSubmission) + await act(async () => { await Promise.resolve() }) + const positions = [h.bodyTop()] + for (let frame = 0; frame < 12; frame++) { + act(() => { vi.advanceTimersByTime(16) }) + positions.push(h.bodyTop()) + } + expect(h.scroller.scrollTop).toBe(test.target + 320) + expect(h.room()).toBe(0) + for (let i = 1; i < positions.length; i++) expect(positions[i]!).toBeLessThanOrEqual(positions[i - 1]! + 0.01) + const settled = h.scroller.scrollTop + act(() => { vi.advanceTimersByTime(500) }) + expect(h.scroller.scrollTop).toBe(settled) + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + +it('keeps one active fold when the local echo becomes its durable input', async () => { + const test = visibleFoldCases.find(test => test.name === 'B/B')! + const h = mountVisibleFold(test, false) + h.submit() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(96) }) + const halfway = h.bodyTop() + h.updateInput() + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(test.target) + expect(h.room()).toBe(0) + expect(h.bodyTop()).toBeLessThanOrEqual(halfway) + expect(h.scrollTo.mock.calls.some(([options]) => options.behavior === 'smooth')).toBe(false) +}) + describe('Chat scroll collapse timing', () => { it.each(['resize', 'scroll', 'history', 'input', 'preference'] as const)( 'waits for initial history before initializing a running view after %s', (change) => { @@ -148,37 +361,29 @@ describe('Chat scroll collapse timing', () => { } }) - it('coalesces submitted inputs into one follow after the last row closes', () => { + it('coalesces submitted inputs into one frame-owned fold', async () => { const h = mountScroll() h.startFold() h.update({ submissionId: 'first' }) h.update({ submissionId: 'second' }) expect(h.scrollTo).not.toHaveBeenCalled() expect(h.scroller.scrollTop).toBe(0) - h.finishFold() - expect(h.scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 600, behavior: 'smooth' }) + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scrollTo).not.toHaveBeenCalled() + expect(h.scroller.scrollTop).toBe(520) expect(h.scroller.style.overflowAnchor).toBe('') }) - it('keeps excess collapse as bottom room without reversing the scrollport', async () => { - const h = mountScroll() - h.scroller.scrollTop = 600 - h.startFold() + it('keeps only the visible deficit when submitted input is smaller than the fold', async () => { + const test = visibleFoldCases.find(test => test.name === 'T/B')! + const h = mountVisibleFold(test, false) + h.submit() await act(async () => { await Promise.resolve() }) - h.grow(1_060) - h.update({ submissionId: 'new-input' }) - h.grow(1_020) - act(() => { vi.advanceTimersByTime(20) }) - expect(h.scroller.scrollTop).toBe(600) - h.grow(980) - act(() => { vi.advanceTimersByTime(20) }) - expect(h.scroller.scrollTop).toBe(600) - fireEvent.scroll(h.scroller) - expect(h.scroller.scrollTop).toBe(600) - h.finishFold() - expect(h.scroller.scrollTop).toBe(600) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(500) + expect(h.room()).toBe(320) expect(h.scrollTo).not.toHaveBeenCalled() - expect(h.scroller.querySelector('[data-chat-turn-spacer]')?.style.height).toBe('20px') }) it.each([false, true])('clears mode-change bottom space after the fold (reader interrupts=%s)', async (interrupt) => { @@ -231,18 +436,15 @@ describe('Chat scroll collapse timing', () => { expect(h.scroller.scrollTop).toBe(520) }) - it('follows only the distance left after a smaller fold', async () => { - const h = mountScroll() - h.scroller.scrollTop = 600 - h.startFold() + it('combines the remaining input distance with the smaller fold', async () => { + const test = visibleFoldCases.find(test => test.name === 'larger input')! + const h = mountVisibleFold(test, false) + h.submit() await act(async () => { await Promise.resolve() }) - h.grow(1_200) - h.update({ submissionId: 'new-input' }) - h.grow(1_120) - act(() => { vi.advanceTimersByTime(20) }) - expect(h.scroller.scrollTop).toBe(600) - h.finishFold() - expect(h.scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 720, behavior: 'smooth' }) + act(() => { vi.advanceTimersByTime(400) }) + expect(h.scroller.scrollTop).toBe(2200) + expect(h.room()).toBe(0) + expect(h.scrollTo).not.toHaveBeenCalled() }) it.each(['wheel', 'touchstart', 'pointerdown', 'keydown'] as const)( @@ -275,7 +477,9 @@ describe('Chat scroll collapse timing', () => { h.update({ order: ['streaming-change'], running: true }) if (newInput) h.update({ submissionId: 'second' }) h.finishFold() - if (newInput) expect(h.scrollTo).toHaveBeenCalledExactlyOnceWith({ top: 600, behavior: 'smooth' }) + await act(async () => { await Promise.resolve() }) + act(() => { vi.advanceTimersByTime(400) }) + if (newInput) expect(h.scroller.scrollTop).toBe(520) else { expect(h.scrollTo).not.toHaveBeenCalled() expect(h.scroller.scrollTop).toBe(420) diff --git a/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts b/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts index 1a0ed20d21..ad4d4357a4 100644 --- a/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts +++ b/packages/client/ui-chat/tests/chat-snapshot-fixture.client.ts @@ -19,6 +19,7 @@ import { isSubagentDelegationTool, sameTurnProcessSpec, TURN_PROCESS_INDEPENDENT_KINDS, type TurnProcessSpec, } from '../src/client/contract/turn-process.ts' +import { isAtOrOutside } from '../src/client/contract/group-tree.ts' const EMPTY: readonly never[] = [] @@ -106,7 +107,8 @@ class FixtureNodeStore implements ChatNodeStore { private readonly sources = new Map>() private readonly processSources = new Map>() private readonly bottomSources = new Map>() - bottomTurn: number | undefined + /** First Turn of the latest loaded exchange. */ + bottomStart: number | undefined private readonly dirtyKeys = new Set() private readonly dirtyProcessKeys = new Set() private list: readonly ChatConversationViewNode[] = EMPTY @@ -122,8 +124,8 @@ class FixtureNodeStore implements ChatNodeStore { bottomSource(key: string): ReturnType { return cachedSource(this.bottomSources, key, () => new FixtureSource(() => { const location = this.get(key)?.location - return this.bottomTurn !== undefined && (location?.kind === 'turn' || location?.kind === 'step') - && location.turn.turn === this.bottomTurn + return this.bottomStart !== undefined && (location?.kind === 'turn' || location?.kind === 'step') + && location.turn.turn >= this.bottomStart })) } @@ -270,6 +272,8 @@ function settledNode( ? { kind: 'session' as const } : { kind: 'turn' as const, turn }, visibility: 'visible' as const, + // A fixture user message inside a Turn stands for its opening human input. + groupTree: node.kind === 'user' && turn !== undefined ? 'exchange' as const : undefined, } switch (node.kind) { case 'assistant': @@ -527,7 +531,11 @@ export function chatSnapshotFixture(input: { && previous.legacy.turnEnds === legacy.turnEnds ? previous.timeline : { turnOrder: [...turns.keys()], turns } - store.bottomTurn = timeline.turnOrder.at(-1) + const openingTurns = store.values().flatMap((node) => { + const location = node.location + return isAtOrOutside(node, 'exchange') && (location.kind === 'turn' || location.kind === 'step') ? [location.turn.turn] : [] + }) + store.bottomStart = openingTurns.length === 0 ? timeline.turnOrder[0] : Math.max(...openingTurns) const derived = timeline.turnOrder .map(turn => turnNavigationItem(turn, locations, store)) .filter((item): item is TurnNavigationItem => item !== undefined) diff --git a/packages/client/ui-chat/tests/chat-view.client.spec.tsx b/packages/client/ui-chat/tests/chat-view.client.spec.tsx index 2357acedc9..d248901ed5 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -2,7 +2,8 @@ import type { ProcessGroupData } from '../src/client/contract/process-groups.ts' import type { InboxState } from '@deepseek-ai/dsh-agent/types' -import type { GlobalStandardProps, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import { MessageId } from '@deepseek-ai/dsh-llm/brand' +import type { GlobalStandardProps, PropsRenderFactories, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { useEffect, useMemo } from 'react' @@ -12,7 +13,7 @@ import type { ChatViewSlotProps, CommandNode, CompactionSummaryNode, ContextMessageNode, ConversationNode, LegacyConversationSlice, ModelRetryNode, StartedToolCall, SteeringMessageNode, ToolCallBlock, ToolResultNode, TurnErrorNode, TurnMaxTokensNode, - TranscriptViewMode, UserMessageNode, + TranscriptViewMode, UserContentInput, UserMessageNode, } from '@deepseek-ai/dsh-client-ui-chat/client' import type { SessionListState, SessionSnapshot, @@ -54,6 +55,7 @@ import type { TurnProcessSpec } from '../src/client/contract/turn-process.ts' import { chatSnapshotFixture } from './chat-snapshot-fixture.client.ts' import { installTurnNavigatorObserver } from './turn-navigator-fixture.ts' import { renderReasoningSlot } from './reasoning-component-fixture.tsx' +import { createUserContentFixture } from './user-content-component-fixture.tsx' import { ConversationGroupStore } from '../../ui-conversation/src/client/conversation/group-store.ts' function installGroupedSnapshot( @@ -261,6 +263,13 @@ declare const flowDispatch: ChatViewSlotProps['renderSlot'] type NodeRenderer = typeof nodeDispatch<'conversation.chat.node'> type FlowRenderer = typeof flowDispatch<'conversation.chat.flow'> type ImageRenderer = (owner: MessageImagesOwnerProps) => React.ReactNode +type HarnessStandardProps = ChatViewSlotProps & PropsRenderFactories + +function isImageOwner(owner: object): owner is MessageImagesOwnerProps { + return 'images' in owner && Array.isArray(owner.images) + && 'loadImage' in owner && typeof owner.loadImage === 'function' + && 'align' in owner && (owner.align === 'start' || owner.align === 'end') +} type ToolOwner = Pick & { readonly callId: string readonly toolName: string @@ -270,12 +279,9 @@ type ToolOwner = Pick & { const renderCommandSlot: React.ComponentProps['renderSlot'] = (_key, _owner, opts) => opts?.fallback ?? null const renderTurnTailSlot: React.ComponentProps['renderSlot'] = () => null -const assistantSlots: Pick, 'renderSlot'> = { - renderSlot: renderReasoningSlot, -} function HarnessChatFlow({ standard, owner, hookContext, renderSlot }: { - readonly standard: ChatViewSlotProps + readonly standard: HarnessStandardProps readonly owner: ChatFlowOwnerProps readonly hookContext: ChatFlowHookContext readonly renderSlot: ChatFlowSlotProps['renderSlot'] @@ -288,13 +294,14 @@ function HarnessChatFlow({ standard, owner, hookContext, renderSlot }: { return } -function HarnessChatNode({ standard, owner, hookContext, usePerformanceUsage, toolOwners, fallback }: { - readonly standard: ChatViewSlotProps +function HarnessChatNode({ standard, owner, hookContext, usePerformanceUsage, toolOwners, fallback, renderAssistantSlot }: { + readonly standard: HarnessStandardProps readonly owner: RoutedChatNodeOwner readonly hookContext: ChatNodeHookContext readonly usePerformanceUsage: React.ComponentProps['usePerformanceUsage'] readonly toolOwners: ToolOwner[] readonly fallback: React.ReactNode + readonly renderAssistantSlot: React.ComponentProps['renderSlot'] }) { const hooks = useMemo(() => ({ useTurnData: CHAT_NODE_INJECT.hooks.turnData(standard, hookContext), @@ -311,7 +318,7 @@ function HarnessChatNode({ standard, owner, hookContext, usePerformanceUsage, to case 'context': return case 'assistant-step': - return + return case 'command': return case 'manual-compaction': @@ -392,7 +399,8 @@ function makeHarness( key => grouped?.groupSource(key as GroupKey) ?? absentGroup, ) const openFile = vi.fn<(path: string) => Promise>().mockResolvedValue(undefined) - const openSkill = vi.fn<(name: string) => void>() + const openUserFile = vi.fn<(path: string) => void>() + const renderUserContent = createUserContentFixture({ openFile: openUserFile }) const loadOlder = vi.fn() const loadThrough = vi.fn<(seq: number) => Promise>().mockResolvedValue(undefined) // Mutable outline holder: tests swap the value and drive a re-render via set(). @@ -415,11 +423,19 @@ function makeHarness( const usePerformanceUsage = bindSnapshotSelector(performanceUsage) let nodeSlotOverride: NodeRenderer | undefined let imageSlotOverride: ImageRenderer | undefined + const renderImages = (name: string, owner: object, options?: { fallback?: React.ReactNode }) => { + if ((name !== 'conversation.chat.user.images' && name !== 'conversation.chat.message.images') || !isImageOwner(owner)) { + throw new Error(`Unexpected Chat image Slot: ${name}`) + } + return imageSlotOverride?.(owner) ?? options?.fallback ?? null + } + const renderAssistantSlot: React.ComponentProps['renderSlot'] = (name, owner, options) => + name === 'conversation.chat.message.images' ? renderImages(name, owner, options) : renderReasoningSlot(name, owner, options) const renderNodeSlot: NodeRenderer = (key, owner, opts) => { if (nodeSlotOverride !== undefined) return nodeSlotOverride(key, owner, opts) return + toolOwners={toolOwners} fallback={opts.fallback} renderAssistantSlot={renderAssistantSlot} /> } const renderFlowSlot: ChatFlowSlotProps['renderSlot'] = (key: string, owner: object, opts?: { fallback?: React.ReactNode @@ -428,11 +444,12 @@ function makeHarness( if (key === 'conversation.chat.node') { return renderNodeSlot(key, owner as RoutedChatNodeOwner, opts as Parameters[2]) } - if (key === 'conversation.message.images') { - return imageSlotOverride?.(owner as MessageImagesOwnerProps) ?? opts?.fallback ?? null - } throw new Error(`Undeclared flow child: ${key}`) } + const renderFactorySlot: PropsRenderFactories['renderFactorySlot'] = (name, owner) => { + if (name !== 'conversation.chat.user.content') throw new Error(`Unexpected Chat Factory: ${name}`) + return renderUserContent(owner as UserContentInput, renderImages, props.t) + } const renderSlot: FlowRenderer = (key, owner, opts) => { if (key !== 'conversation.chat.flow') throw new Error(`Undeclared ChatView child: ${key}`) if ('renderSlot' in owner || 'useStore' in owner || 'actions' in owner) { @@ -443,7 +460,8 @@ function makeHarness( // SessionProvider seat arrives with the session-scope child declaration; // ChatView never invokes it (pass-through stub). const SessionProviderStub: ChatViewSlotProps['SessionProvider'] = ({ children }) => <>{children} - const props: ChatViewSlotProps = { + const props: HarnessStandardProps = { + renderFactorySlot, usePanelInfo: selector => selector({ activePanelId: null }), sessionId: SID, useSession: bindSnapshotSelector(session.source), @@ -487,7 +505,6 @@ function makeHarness( openView, completeViewRequest: () => {}, openFile, - openSkill, openExternalLink: vi.fn(), loadOlder, loadThrough, @@ -518,7 +535,7 @@ function makeHarness( } return { set, setSession: session.set, setChat: chatSource.set, ChatView, props, - openFile, openSkill, loadOlder, loadThrough, openView, + openFile, openUserFile, loadOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, chatScroll, forkAt, toolOwners, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, @@ -1851,6 +1868,32 @@ describe('ChatView', () => { expect(h.forkAt).toHaveBeenCalledWith(3) })) + it('keeps pending file mentions non-interactive until admission enables the reference injector', () => { + const pending: InboxState['next-step'][number] = { + id: MessageId('pending-file-mention'), role: 'user', source: { kind: 'user' }, + content: [{ type: 'text', text: 'Read @src/review.ts' }], + } + const h = makeHarness({}, { testInbox: { 'next-turn': [], 'next-step': [pending] }, running: true }) + const view = render() + const mention = view.getByText('review.ts') + expect(mention.closest('[data-pending-steering]')).not.toBeNull() + expect(view.queryByRole('button', { name: 'review.ts' })).toBeNull() + fireEvent.click(mention) + expect(h.openUserFile).not.toHaveBeenCalled() + expect(h.openFile).not.toHaveBeenCalled() + act(() => { + h.setSession({ testInbox: { 'next-turn': [], 'next-step': [] } }) + h.setChat({ nodes: [{ + kind: 'steering', messageId: pending.id, seq: 1, time: 1_000, + content: pending.content, source: pending.source, + }] }) + }) + expect(view.container.querySelector('[data-pending-steering]')).toBeNull() + fireEvent.click(view.getByRole('button', { name: 'review.ts' })) + expect(h.openUserFile).toHaveBeenCalledWith('src/review.ts') + expect(h.openFile).not.toHaveBeenCalled() + }) + it('keeps a later pending occurrence visible when it reuses a durable MessageId', () => { const pending = { id: 'steer-occurrence-later' as never, diff --git a/packages/client/ui-chat/tests/config.host.spec.ts b/packages/client/ui-chat/tests/config.host.spec.ts index a7fa8fa80a..b3ebb9b698 100644 --- a/packages/client/ui-chat/tests/config.host.spec.ts +++ b/packages/client/ui-chat/tests/config.host.spec.ts @@ -14,9 +14,9 @@ describe('ui-chat Host settings', () => { const configuration = await liveConfig(ctx, { Config, apply }) const { fiber } = configuration - expect(plainConfig(configuration.fiber.config)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar' }) + expect(plainConfig(configuration.fiber.config)).toEqual({ performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) await configuration.update({ transcriptView: 'normal' }) - expect(plainConfig(configuration.fiber.config)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar' }) + expect(plainConfig(configuration.fiber.config)).toEqual({ transcriptView: 'normal', performanceUsage: 'detailed', linkOpening: 'sidebar', collapseTiming: 'completion' }) for (const mode of ['expanded', 'compact', 'standard', 'detailed', 'verbose']) { await configuration.update({ transcriptView: mode }) expect(plainConfig(configuration.fiber.config)).toMatchObject({ transcriptView: mode }) @@ -35,6 +35,21 @@ describe('ui-chat Host settings', () => { await fiber.dispose() }) + it('validates collapse timing and restores its saved config independently of work details', async () => { + const ctx = new Context() + const configuration = await liveConfig(ctx, { Config, apply }) + expect(plainConfig(configuration.fiber.config)).toMatchObject({ collapseTiming: 'completion' }) + await configuration.update({ transcriptView: 'compact', collapseTiming: 'next-input' }) + const saved = plainConfig(configuration.fiber.config) + if (typeof saved !== 'object' || saved === null) throw new Error('expected saved configuration object') + expect(saved).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' }) + await expect(configuration.update({ collapseTiming: 'never' })).rejects.toThrow() + await configuration.fiber.dispose() + const restored = await liveConfig(ctx, { Config, apply }, saved) + expect(plainConfig(restored.fiber.config)).toMatchObject({ transcriptView: 'compact', collapseTiming: 'next-input' }) + await restored.fiber.dispose() + }) + it('loads without a settings provider', async () => { const ctx = new Context() await expect(ctx.plugin({ Config, apply }).await()).resolves.toBeDefined() diff --git a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts index 3823a0dbd5..3dc8c784db 100644 --- a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts +++ b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts @@ -659,6 +659,62 @@ describe('built-in conversation node Definitions', () => { } }) + it('opens exchanges only for human input claimed for Step 1', () => { + const human = textMessage('block-human', 'first task') + const steer = textMessage('block-steer', 'adjust course') + const notice = { ...textMessage('block-notice', 'background work finished'), source: { kind: 'schedule' } } + const idle = textMessage('block-idle', 'next task') + const bottomTurns = (current: ChatSnapshot): number[] => [...new Set(current.order.flatMap((key) => { + const location = current.nodes.get(key)?.location + return current.nodes.bottomSource(key).getSnapshot() && (location?.kind === 'turn' || location?.kind === 'step') + ? [location.turn.turn] + : [] + }))] + const inputs = (current: ChatSnapshot) => current.order + .map(key => current.nodes.get(key)) + .filter(candidate => candidate?.kind === 'user' || candidate?.kind === 'steering' || candidate?.kind === 'turn-trigger') + .map(candidate => [candidate?.kind, candidate?.groupTree ?? null]) + const value = assembler([ + at(1, 'agent/inbox/spliced', { target: 'next-turn', start: 0, inserted: [human] }), + at(2, 'turn/start', { turn: 1 }), + at(3, 'agent/inbox/spliced', { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }), + at(4, 'step/start', { turn: 1, step: 1 }), + at(5, 'user/message', human, { surfaceOp: 'append' }), + at(6, 'step/end', { turn: 1, step: 1 }), + at(7, 'agent/inbox/spliced', { target: 'next-step', start: 0, inserted: [steer] }), + at(8, 'agent/inbox/spliced', { target: 'next-step', start: 0, removedCount: 1, inserted: [] }), + at(9, 'step/start', { turn: 1, step: 2 }), + at(10, 'user/message', steer, { surfaceOp: 'append' }), + at(11, 'assistant/message', { turn: 1, step: 2, message: assistantMessage('block-answer-1', 'done') }, { surfaceOp: 'append' }), + at(12, 'step/end', { turn: 1, step: 2 }), + at(13, 'turn/end', { turn: 1, reason: { kind: 'completed' } }), + // The host assembles the system prompt between the waking claim and Step 1. + at(14, 'agent/inbox/spliced', { target: 'next-turn', start: 0, inserted: [notice] }), + at(15, 'turn/start', { turn: 2 }), + at(16, 'agent/inbox/spliced', { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }), + ]) + expect(inputs(snapshot(value))).toEqual([['user', 'exchange'], ['steering', null]]) + expect(bottomTurns(snapshot(value))).toEqual([1, 2]) + + value.append(at(17, 'step/start', { turn: 2, step: 1 })) + value.append(at(18, 'user/message', notice, { surfaceOp: 'append' })) + value.append(at(19, 'assistant/message', { turn: 2, step: 1, message: assistantMessage('block-answer-2', 'noted') }, { surfaceOp: 'append' })) + value.append(at(20, 'step/end', { turn: 2, step: 1 })) + value.append(at(21, 'turn/end', { turn: 2, reason: { kind: 'completed' } })) + value.flush() + expect(inputs(snapshot(value))).toEqual([['user', 'exchange'], ['steering', null], ['turn-trigger', null]]) + expect(bottomTurns(snapshot(value))).toEqual([1, 2]) + + value.append(at(22, 'agent/inbox/spliced', { target: 'next-step', start: 0, inserted: [idle] })) + value.append(at(23, 'turn/start', { turn: 3 })) + value.append(at(24, 'agent/inbox/spliced', { target: 'next-step', start: 0, removedCount: 1, inserted: [] })) + value.append(at(25, 'step/start', { turn: 3, step: 1 })) + value.append(at(26, 'user/message', idle, { surfaceOp: 'append' })) + value.flush() + expect(inputs(snapshot(value)).at(-1)).toEqual(['steering', 'exchange']) + expect(bottomTurns(snapshot(value))).toEqual([3]) + }) + it('replays pending splice chains and scopes steering to the current claim', () => { const first = textMessage('claim-first', 'first') const second = textMessage('claim-second', 'second') diff --git a/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx b/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx index cf7b24532c..241a0faded 100644 --- a/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/coverage-tails.client.spec.tsx @@ -6,12 +6,12 @@ import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' import { zh } from '../src/client/locale.ts' const t: AssistantMarkdownProps['t'] = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null afterEach(cleanup) @@ -27,7 +27,7 @@ describe('tails', () => { { kind: 'other', block: { type: 'mystery' } }, ]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('思考')).toBeTruthy() @@ -40,7 +40,7 @@ describe('tails', () => { blocks={[{ kind: 'text', text: 'partial words' }]} streaming={false} interrupted - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(stopped.getByText('已停止')).toBeTruthy() @@ -55,14 +55,14 @@ describe('tails', () => { t={t} blocks={[{ kind: 'tool-call', callId: 'c', name: 'todo_write', argsRaw: '{}' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(empty.container.firstChild).toBeNull() const blank = render( null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} usePresentation={useDetailedPresentation} - t={t} blocks={[]} streaming={false} renderMessageImages={renderMessageImages} />, + t={t} blocks={[]} streaming={false} loadImage={unusedImageLoader} />, ) expect(blank.container.firstChild).toBeNull() }) diff --git a/packages/client/ui-chat/tests/flow-motion.client.spec.tsx b/packages/client/ui-chat/tests/flow-motion.client.spec.tsx index 38c771bdbc..5eb8c2f853 100644 --- a/packages/client/ui-chat/tests/flow-motion.client.spec.tsx +++ b/packages/client/ui-chat/tests/flow-motion.client.spec.tsx @@ -210,6 +210,22 @@ describe('flow motion', () => { expect(reserve).toHaveBeenCalledExactlyOnceWith(200) }) + it('does not rewrite a reopened row after its input-fold ownership is cancelled', async () => { + vi.useFakeTimers() + const row = rowWithHeight(180) + const done = vi.fn() + motion.collapse(row, done) + motion.followInput({ begin: vi.fn(), frame: () => -20, finish: vi.fn() }) + await Promise.resolve() + vi.advanceTimersByTime(96) + motion.cancelMotion(row) + expectCleared(row) + vi.advanceTimersByTime(400) + expectCleared(row) + expect(row.style.translate).toBe('') + expect(done).not.toHaveBeenCalled() + }) + it('clears pending reservations and idle work with its owner', async () => { const row = rowWithHeight(80) const idle = vi.fn() @@ -307,13 +323,14 @@ describe.each([ expect(vi.getTimerCount()).toBe(0) }) - it.each([false, true])('hides immediately without motion when reduced motion is %s', (reduced) => { + it.each([false, true])('hides before the next paint when reduced motion is %s', async (reduced) => { vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: reduced }))) const onReveal = vi.fn() const view = render(
) const row = view.getByTestId('motion-row') Object.defineProperty(row, 'offsetHeight', { value: 80 }) view.rerender(
) + await act(async () => { await Promise.resolve() }) expect(row.getAttribute('hidden')).toBe(hiddenValue) expectCleared(row) expect(motion.foldActive()).toBe(false) diff --git a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx index 801bc01176..a15de80592 100644 --- a/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/gate-branch-tails.client.spec.tsx @@ -6,6 +6,7 @@ import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-tes import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' +import { unusedImageLoader } from './reasoning-component-fixture.tsx' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' import { ActivityPill, UsagePill, type StatPillProps } from '../src/client/chat/StatsPills.tsx' @@ -13,7 +14,6 @@ import { zh } from '../src/client/locale.ts' import { chatSnapshotFixture } from './chat-snapshot-fixture.client.ts' const t: AssistantMarkdownProps['t'] = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null afterEach(() => { cleanup() @@ -29,7 +29,7 @@ describe('render branch tails', () => { t={t} blocks={[{ kind: 'reasoning', text: 'done thinking' }, { kind: 'text', text: 'answer' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) // reasoning at index 0 with a later block: running is false → ok state. @@ -72,7 +72,7 @@ describe('render branch tails', () => { t={t} blocks={[{ kind: 'reasoning', text: 'still thinking' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.container.querySelector('[data-state="running"]')).not.toBeNull() diff --git a/packages/client/ui-chat/tests/group-tree-segments.client.spec.ts b/packages/client/ui-chat/tests/group-tree-segments.client.spec.ts new file mode 100644 index 0000000000..377ca9c7d2 --- /dev/null +++ b/packages/client/ui-chat/tests/group-tree-segments.client.spec.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest' +import type { TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { ChatConversationViewNode } from '../src/client/contract/chat-nodes.ts' +import { isAtOrOutside, type ChatGroupTree } from '../src/client/contract/group-tree.ts' +import { GroupTreeSegments } from '../src/client/conversation-nodes/group-tree-segments.ts' + +function turn(index: number): TurnLocation { + return { + turn: index, start: undefined, end: undefined, status: 'closed', steps: [], + data: { get: () => undefined, source: () => ({ getSnapshot: () => undefined, subscribe: () => () => {} }) }, + } +} + +function node(key: string, owner: number | undefined, groupTree?: ChatGroupTree): ChatConversationViewNode { + return { + key, id: key, kind: 'user', target: 'chat', anchorSeq: 0, visibility: 'hidden', groupTree, + location: owner === undefined ? { kind: 'session' } : { kind: 'turn', turn: turn(owner) }, + data: null, + } +} + +function members(segments: GroupTreeSegments, turns: readonly number[]): number[] { + return turns.filter(value => segments.inLatest(value)) +} + +describe('Chat group tree', () => { + it('orders positions from the outermost exchange inward', () => { + const at = (groupTree?: ChatGroupTree) => (['exchange', 'turn', 'process'] as const) + .map(position => isAtOrOutside({ groupTree }, position)) + expect(at('exchange')).toEqual([true, true, true]) + expect(at('turn')).toEqual([false, true, true]) + expect(at('process')).toEqual([false, false, true]) + expect(at(undefined)).toEqual([false, false, false]) + }) + + it('starts the latest segment at the last opening Turn and reports only the Turns that moved', () => { + const segments = new GroupTreeSegments('exchange') + const order = [1, 2, 3, 4, 5] + expect(segments.inLatest(1)).toBe(false) + expect(segments.settle(order)).toEqual(order) + expect(members(segments, order)).toEqual(order) + + segments.track(undefined, node('a', 2, 'exchange')) + expect(segments.settle(order)).toEqual([1]) + expect(members(segments, order)).toEqual([2, 3, 4, 5]) + expect(segments.settle(order)).toEqual([]) + + segments.track(undefined, node('b', 4, 'exchange')) + expect(segments.settle(order)).toEqual([2, 3]) + expect(members(segments, order)).toEqual([4, 5]) + expect(segments.inLatest(undefined)).toBe(false) + + segments.track(node('b', 4, 'exchange'), undefined) + expect(segments.settle(order)).toEqual([2, 3]) + expect(members(segments, order)).toEqual([2, 3, 4, 5]) + }) + + it('counts every opening Node of a Turn and falls back as openings leave', () => { + const segments = new GroupTreeSegments('exchange') + const order = [1, 2, 3] + const first = node('first', 1, 'exchange') + const twin = node('twin', 3, 'exchange') + const late = node('late', 3, 'exchange') + for (const value of [late, first, twin]) segments.track(undefined, value) + segments.settle(order) + expect(members(segments, order)).toEqual([3]) + + segments.track(late, node('late', 3)) + segments.settle(order) + expect(members(segments, order)).toEqual([3]) + + segments.track(first, undefined) + segments.settle(order) + expect(members(segments, order)).toEqual([3]) + + segments.track(twin, { ...twin, location: { kind: 'session' } }) + expect(segments.settle(order)).toEqual([1, 2]) + expect(members(segments, order)).toEqual(order) + }) + + it('falls back to the latest remaining opening Turn whatever order the openings arrived in', () => { + const segments = new GroupTreeSegments('exchange') + const order = [1, 2, 3, 4, 5] + const latest = node('latest', 5, 'exchange') + for (const value of [node('middle', 3, 'exchange'), node('earliest', 1, 'exchange'), latest]) { + segments.track(undefined, value) + } + segments.settle(order) + expect(members(segments, order)).toEqual([5]) + + segments.track(latest, undefined) + expect(segments.settle(order)).toEqual([3, 4]) + expect(members(segments, order)).toEqual([3, 4, 5]) + }) + + it('opens segments at Nodes of the configured position or an outer one', () => { + const segments = new GroupTreeSegments('turn') + const order = [1, 2, 3] + segments.track(undefined, node('process', 3, 'process')) + segments.track(undefined, node('turn', 2, 'turn')) + segments.track(undefined, node('exchange', 1, 'exchange')) + segments.track(node('none', 3), node('none', 3)) + segments.settle(order) + expect(members(segments, order)).toEqual([2, 3]) + }) + + it('clears the latest segment when no Turn is loaded', () => { + const segments = new GroupTreeSegments('exchange') + segments.track(undefined, node('a', 1, 'exchange')) + segments.settle([1]) + segments.track(node('a', 1, 'exchange'), undefined) + expect(segments.settle([])).toEqual([]) + expect(segments.inLatest(1)).toBe(false) + }) +}) diff --git a/packages/client/ui-chat/tests/image-labels.client.spec.tsx b/packages/client/ui-chat/tests/image-labels.client.spec.tsx index 9fdf281e40..e37b5ec2c6 100644 --- a/packages/client/ui-chat/tests/image-labels.client.spec.tsx +++ b/packages/client/ui-chat/tests/image-labels.client.spec.tsx @@ -1,12 +1,13 @@ // @vitest-environment jsdom -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { cleanup, render } from '@testing-library/react' import { AttachmentId } from '@deepseek-ai/dsh-attachment' -import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import type { RenderMessageImages } from '@deepseek-ai/dsh-client-ui-conversation/client' -import { AssistantMarkdown } from '../src/client/chat/AssistantMarkdown.tsx' +import type { MessageImagesOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { AssistantMarkdown, type AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' import { useDetailedPresentation } from './presentation-fixture.client.ts' import { useDisclosure } from '../src/client/chat/use-disclosure.ts' import { useSearchableHidden } from '../src/client/chat/searchable-hidden.ts' @@ -25,10 +26,11 @@ const attachment = { name: 'history.png', } -type MessageImagesRenderOwner = Parameters[0] - -function imageRenderer(calls: MessageImagesRenderOwner[]): RenderMessageImages { - return (owner) => { +async function renderImages(blocks: AssistantMarkdownProps['blocks'], calls: MessageImagesOwnerProps[]) { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const loadImage = vi.fn(async () => 'blob:history') + runtime.slots.inject('conversation.chat.message.images', () => runtime.slots.register({ name: 'conversation.chat.message.images' }, (owner: MessageImagesOwnerProps) => { calls.push(owner) return (
@@ -39,63 +41,94 @@ function imageRenderer(calls: MessageImagesRenderOwner[]): RenderMessageImages { })}
) - } + })) + await runtime.sessions.add({ id: 'image-labels' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('image-labels')) + await runtime.root.declare({ + 'conversation.chat.reasoning.body': { kind: 'single', scope: 'session' }, + 'conversation.chat.message.images': { kind: 'single', scope: 'session' }, + }, ({ renderSlot, SessionProvider }) => ( + + + + )) + return { view: runtime.renderRoot(), loadImage } } describe('assistant image slot handoff', () => { - it('passes one image group and its message alignment to the renderer', () => { - const calls: MessageImagesRenderOwner[] = [] - const view = render( - null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} - usePresentation={useDetailedPresentation} - t={t} - blocks={[{ kind: 'image', attachment }]} - streaming={false} - renderMessageImages={imageRenderer(calls)} - />, - ) + it('passes one image group and its message alignment to the renderer', async () => { + const calls: MessageImagesOwnerProps[] = [] + const { view, loadImage } = await renderImages([{ kind: 'image', attachment }], calls) expect(view.getByTestId('message-images').getAttribute('data-align')).toBe('start') expect(calls).toHaveLength(1) expect(calls[0]?.images).toEqual([{ attachment }]) + expect(calls[0]?.loadImage).toBe(loadImage) + expect(view.getByText('history.png')).toBeTruthy() }) - it('merges consecutive image blocks into one group and splits groups at text', () => { - const calls: MessageImagesRenderOwner[] = [] - const view = render( - null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} - usePresentation={useDetailedPresentation} - t={t} - blocks={[ - { kind: 'image', attachment }, - { kind: 'image', attachment }, - { kind: 'text', text: 'between' }, - { kind: 'image', attachment }, - ]} - streaming={false} - renderMessageImages={imageRenderer(calls)} - />, + it('updates one message loader without changing its sibling or remounting either gallery', () => { + const firstLoader = vi.fn(async () => 'blob:first') + const nextLoader = vi.fn(async () => 'blob:next') + const siblingLoader = vi.fn(async () => 'blob:sibling') + const firstRenderer = vi.fn((_key: string, _owner: object) => first gallery) + const siblingRenderer = vi.fn((_key: string, _owner: object) => sibling gallery) + const props = { + blocks: [{ kind: 'image', attachment }], streaming: false, t, + useDisclosure, useGroupAction: useSearchableHidden, + usePresentation: useDetailedPresentation, + } satisfies Omit + const content = (loadImage: AssistantMarkdownProps['loadImage']) => ( + <> + + + ) + const view = render(content(firstLoader)) + const firstGallery = view.getByText('first gallery') + const siblingGallery = view.getByText('sibling gallery') + const owner = { images: [{ attachment }], align: 'start' } + expect(firstRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: firstLoader, + }) + expect(siblingRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: siblingLoader, + }) + + view.rerender(content(nextLoader)) + + expect(firstRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: nextLoader, + }) + expect(siblingRenderer).toHaveBeenLastCalledWith('conversation.chat.message.images', { + ...owner, loadImage: siblingLoader, + }) + expect(view.getByText('first gallery')).toBe(firstGallery) + expect(view.getByText('sibling gallery')).toBe(siblingGallery) + }) + + it('merges consecutive image blocks into one group and splits groups at text', async () => { + const calls: MessageImagesOwnerProps[] = [] + const { view } = await renderImages([ + { kind: 'image', attachment }, + { kind: 'image', attachment }, + { kind: 'text', text: 'between' }, + { kind: 'image', attachment }, + ], calls) const galleries = view.getAllByTestId('message-images') expect(galleries).toHaveLength(2) expect(galleries.map(gallery => gallery.getAttribute('data-count'))).toEqual(['2', '1']) expect(calls.map(call => call.images.length)).toEqual([2, 1]) }) - it('keeps the renderer output at the image block position between text blocks', () => { - const calls: MessageImagesRenderOwner[] = [] - const view = render( - null} useDisclosure={useDisclosure} useGroupAction={useSearchableHidden} - usePresentation={useDetailedPresentation} - t={t} - blocks={[ - { kind: 'text', text: 'before' }, - { kind: 'image', attachment }, - { kind: 'text', text: 'after' }, - ]} - streaming={false} - renderMessageImages={imageRenderer(calls)} - />, - ) + it('keeps the renderer output at the image block position between text blocks', async () => { + const calls: MessageImagesOwnerProps[] = [] + const { view } = await renderImages([ + { kind: 'text', text: 'before' }, + { kind: 'image', attachment }, + { kind: 'text', text: 'after' }, + ], calls) const image = view.getByTestId('message-images') const before = view.getByText('before') const after = view.getByText('after') diff --git a/packages/client/ui-chat/tests/reasoning-component-fixture.tsx b/packages/client/ui-chat/tests/reasoning-component-fixture.tsx index fb2f6ea879..c2e0543f3c 100644 --- a/packages/client/ui-chat/tests/reasoning-component-fixture.tsx +++ b/packages/client/ui-chat/tests/reasoning-component-fixture.tsx @@ -10,15 +10,21 @@ import { zh } from '../src/client/locale.ts' const t = makeTranslate(zh, commonZh) +/** Reject attachment loads in component fixtures without durable images. */ +export const unusedImageLoader: AssistantMarkdownProps['loadImage'] = async () => { + throw new Error('This component fixture has no durable image attachments') +} + function content(input: ReasoningContentInput) { // The component only reads these inputs; unused framework seats are exercised in assembly tests. return createElement(ReasoningContent, { ...input, t } as ComponentProps) } /** Render the production child component without emulating a registry or its dispatch. */ -export const renderReasoningSlot = ( - (_key: 'conversation.chat.reasoning.body', input: ReasoningContentInput) => content(input) -) as AssistantMarkdownProps['renderSlot'] +export const renderReasoningSlot: AssistantMarkdownProps['renderSlot'] = (key: string, input: object) => { + if (key !== 'conversation.chat.reasoning.body') throw new Error(`Unexpected reasoning Slot: ${key}`) + return content(input as ReasoningContentInput) +} /** Supply the official component at the Factory call seam of a standalone component unit. */ export const renderReasoningFactory: PropsRenderFactories['renderFactorySlot'] = (name, input) => { diff --git a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx index fbd21baf11..29ad9a4e4d 100644 --- a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' -import { renderReasoningSlot as renderSlot } from './reasoning-component-fixture.tsx' +import { renderReasoningSlot as renderSlot, unusedImageLoader } from './reasoning-component-fixture.tsx' import { act, cleanup, fireEvent, render } from '@testing-library/react' import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -19,7 +19,119 @@ afterEach(() => { }) const t = makeTranslate(zh, commonZh) -const renderMessageImages: AssistantMarkdownProps['renderMessageImages'] = () => null + +describe('AssistantMarkdown reasoning blocks', () => { + const props = { + renderSlot, useDisclosure, useGroupAction: useSearchableHidden, + usePresentation: useDetailedPresentation, loadImage: unusedImageLoader, t, + } + + it.each([false, true])('omits blank blocks without trimming body text when streaming=%s', (streaming) => { + const text = '\n **Visible reasoning**\n\nOriginal body \n' + const texts = ['', ' \t\r\n', text, ''] + const blocks = Object.freeze(texts.map(text => Object.freeze({ kind: 'reasoning' as const, text }))) + const calls = vi.fn() + const extension: AssistantMarkdownProps['renderSlot'] = (key, owner, options) => { + calls(key, owner) + return renderSlot(key, owner, options) + } + const view = render() + expect(view.getAllByRole('button')).toHaveLength(1) + expect(view.container.querySelectorAll('[data-variant="think"]')).toHaveLength(1) + fireEvent.click(view.getByRole('button')) + expect(calls).toHaveBeenCalledWith('conversation.chat.reasoning.body', { text, running: false }) + expect(view.getByText('Visible reasoning').tagName).toBe('STRONG') + expect(blocks.map(block => block.text)).toEqual(texts) + }) + + it.each([false, true])('waits for non-whitespace reasoning when streaming=%s', (streaming) => { + const view = render() + expect(view.queryAllByRole('button')).toHaveLength(0) + for (const text of [' ', '\t', '\r\n', ' \t\r\n', '\u00a0']) { + view.rerender() + expect(view.queryAllByRole('button')).toHaveLength(0) + } + view.rerender() + expect(view.getAllByRole('button')).toHaveLength(1) + }) + + it('retains an expanded earlier row when a blank streaming tail receives text', () => { + const first = { kind: 'reasoning' as const, text: 'First thought\n\nEarlier body' } + const blank = { kind: 'reasoning' as const, text: ' \t\r\n' } + const view = render() + const earlierToggle = view.getByRole('button') + const earlierRow = earlierToggle.closest('[data-variant="think"]') + expect(earlierRow?.getAttribute('data-state')).toBe('ok') + expect(view.queryByText('运行中')).toBeNull() + fireEvent.click(earlierToggle) + const earlierBody = view.getByText('Earlier body') + + const tail = { kind: 'reasoning' as const, text: 'An unfinished tail' } + const blocks = [first, blank, tail] + view.rerender() + const toggles = view.getAllByRole('button') + expect(toggles).toHaveLength(2) + expect(toggles[0]).toBe(earlierToggle) + expect(view.getByText('Earlier body')).toBe(earlierBody) + expect(earlierToggle.getAttribute('aria-expanded')).toBe('true') + expect(earlierRow?.getAttribute('data-state')).toBe('ok') + const tailToggle = toggles[1]! + const tailRow = tailToggle.closest('[data-variant="think"]') + expect(tailRow?.getAttribute('data-state')).toBe('running') + expect(view.queryByText(tail.text)).toBeNull() + fireEvent.click(tailToggle) + expect(view.getByText(tail.text)).toBeTruthy() + expect(earlierToggle.getAttribute('aria-expanded')).toBe('true') + + view.rerender() + const settledToggles = view.getAllByRole('button') + expect(settledToggles).toHaveLength(2) + expect(settledToggles[0]).toBe(earlierToggle) + expect(settledToggles[1]).toBe(tailToggle) + expect(view.getByText('Earlier body')).toBe(earlierBody) + expect(tailRow?.getAttribute('data-state')).toBe('ok') + expect(tailToggle.getAttribute('aria-expanded')).toBe('true') + fireEvent.click(tailToggle) + expect(earlierToggle.getAttribute('aria-expanded')).toBe('true') + expect(tailToggle.getAttribute('aria-expanded')).toBe('false') + }) + + it.each(['Partial thought', '', ' \t\r\n'])('retains the stopped marker with blank reasoning around %j', (text) => { + const blocks = ['', text, ' \t\r\n'].map(text => ({ kind: 'reasoning' as const, text })) + const view = render() + expect(view.queryAllByRole('button')).toHaveLength(text.trim() === '' ? 0 : 1) + expect(view.getByText(t('message.stopped'))).toBeTruthy() + expect(view.queryByText('运行中')).toBeNull() + }) + + it('keeps non-blank rows and their expanded bodies across modes, excluding them from the response part', () => { + const mode = createSnapshotStore('compact') + const usePresentation = bindSnapshotSelector(derivePresentationPolicy(mode, createSnapshotStore('completion'))) + const blocks: AssistantMarkdownProps['blocks'] = [ + { kind: 'reasoning', text: '' }, + { kind: 'reasoning', text: 'Mode thought\n\nMode body' }, + { kind: 'reasoning', text: ' \t\r\n' }, + { kind: 'text', text: 'Answer' }, + ] + const view = render() + const toggle = view.getByRole('button') + fireEvent.click(toggle) + const body = view.getByText('Mode body') + for (const next of ['standard', 'detailed', 'verbose', 'compact'] as const) { + act(() => { mode.set(next) }) + expect(view.getAllByRole('button')).toHaveLength(1) + expect(view.getByRole('button')).toBe(toggle) + expect(toggle.getAttribute('aria-expanded')).toBe('true') + expect(view.getByText('Mode body')).toBe(body) + expect(view.queryByText('Answer')).toBeNull() + } + view.rerender() + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(view.getByText('Answer')).toBeTruthy() + }) +}) describe('ReasoningRow', () => { it('offers only text and streaming state to the standard Body Slot after expansion', () => { @@ -111,20 +223,20 @@ describe('ReasoningRow', () => { const view = render( , + t={t} blocks={[reasoning]} streaming loadImage={unusedImageLoader} />, ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('false') fireEvent.click(view.getByText('思考')) view.rerender( , + t={t} blocks={[reasoning, nextBlock]} streaming loadImage={unusedImageLoader} />, ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') view.rerender( , + t={t} blocks={[reasoning, nextBlock]} streaming={false} loadImage={unusedImageLoader} />, ) expect(view.getByRole('button').getAttribute('aria-expanded')).toBe('true') expect(view.getByText(/Check persistence/)).toBeTruthy() @@ -139,7 +251,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nDetails\n\nNewest reasoning tokens\n' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('运行中')).toBeTruthy() @@ -153,7 +265,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nDetails\n\nNewest reasoning tokens\nMore details\n\nChecking boundaries' }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('Newest reasoning tokens').closest('[data-streaming]') @@ -167,7 +279,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByText('Checking boundaries')).toBeTruthy() @@ -179,7 +291,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) const settledSummary = view.getByText('Inspect the session') @@ -195,7 +307,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nCheck persistence' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) const row = view.getByRole('button') @@ -226,7 +338,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming={streaming} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) @@ -247,7 +359,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) const summary = view.getByText('# Section 1') @@ -273,7 +385,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: first }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) fireEvent.click(view.getByText('思考')) @@ -286,7 +398,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text }]} streaming - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) expect(view.getByRole('heading', { name: 'Investigation' })).toBe(heading) @@ -301,7 +413,7 @@ describe('ReasoningRow', () => { t={t} blocks={[{ kind: 'reasoning', text: 'Inspect the session\nCheck persistence' }]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) fireEvent.click(view.getByText('思考')) @@ -321,7 +433,7 @@ describe('ReasoningRow', () => { { kind: 'text', text: 'Answer' }, ]} streaming={false} - renderMessageImages={renderMessageImages} + loadImage={unusedImageLoader} />, ) // Collapsed: no `data-open`, so the sticky rule's gate never matches. diff --git a/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts b/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts index e7c84f9a42..05fc6401ed 100644 --- a/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts +++ b/packages/client/ui-chat/tests/transcript-view-policy.client.spec.ts @@ -7,7 +7,7 @@ import { TranscriptViewPolicy } from '../src/client/transcript-view.ts' afterEach(() => { vi.restoreAllMocks() }) describe('TranscriptViewPolicy', () => { - it('defaults to completion and changes timing without reading or writing browser storage', () => { + it('defaults to completion and persists explicit timing without reading or writing browser storage', () => { const storageReads = vi.spyOn(Storage.prototype, 'getItem').mockReturnValue('"next-input"') const storageWrites = vi.spyOn(Storage.prototype, 'setItem') const storageRemovals = vi.spyOn(Storage.prototype, 'removeItem') @@ -32,7 +32,9 @@ describe('TranscriptViewPolicy', () => { expect(timingChanged).toHaveBeenCalledTimes(2) expect(policy.mode.getSnapshot()).toBe('detailed') expect(modeChanged).not.toHaveBeenCalled() - expect(host.set).not.toHaveBeenCalled() + expect(host.set).toHaveBeenCalledTimes(2) + expect(host.set).toHaveBeenNthCalledWith(1, 'collapseTiming', 'next-input') + expect(host.set).toHaveBeenNthCalledWith(2, 'collapseTiming', 'completion') expect(storageReads).not.toHaveBeenCalled() expect(storageWrites).not.toHaveBeenCalled() expect(storageRemovals).not.toHaveBeenCalled() @@ -44,18 +46,19 @@ describe('TranscriptViewPolicy', () => { } }) - it('starts each instance with completion timing while adopting the accepted Host mode', () => { + it('restores both saved preferences in each new instance', () => { const host = stubConfigForm() host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 1, writable: true }) const first = new TranscriptViewPolicy(host.scope) try { first.setCollapseTiming('next-input') + host.publish({ value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 2 }) const second = new TranscriptViewPolicy(host.scope) try { expect(first.collapseTiming.getSnapshot()).toBe('next-input') - expect(second.collapseTiming.getSnapshot()).toBe('completion') + expect(second.collapseTiming.getSnapshot()).toBe('next-input') expect(second.mode.getSnapshot()).toBe('standard') - expect(host.set).not.toHaveBeenCalled() + expect(host.set).toHaveBeenCalledExactlyOnceWith('collapseTiming', 'next-input') } finally { second.dispose() } @@ -65,21 +68,21 @@ describe('TranscriptViewPolicy', () => { expect(host.listenerCount()).toBe(0) }) - it('adopts Host mode updates without overriding the local timing choice', () => { + it('adopts independent Host mode and timing updates without writing them back', () => { const host = stubConfigForm() const policy = new TranscriptViewPolicy(host.scope) try { policy.setCollapseTiming('next-input') - host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed' }, revision: 1, writable: true }) + host.publish({ status: 'ready', value: { linkOpening: 'sidebar', transcriptView: 'compact', performanceUsage: 'detailed', collapseTiming: 'next-input' }, revision: 1, writable: true }) expect(policy.mode.getSnapshot()).toBe('compact') expect(policy.collapseTiming.getSnapshot()).toBe('next-input') policy.setMode('verbose') expect(policy.collapseTiming.getSnapshot()).toBe('next-input') - expect(host.set).toHaveBeenCalledExactlyOnceWith('transcriptView', 'verbose') + expect(host.set).toHaveBeenNthCalledWith(2, 'transcriptView', 'verbose') host.publish({ value: { linkOpening: 'sidebar', transcriptView: 'standard', performanceUsage: 'detailed' }, revision: 2 }) expect(policy.mode.getSnapshot()).toBe('standard') - expect(policy.collapseTiming.getSnapshot()).toBe('next-input') - expect(host.set).toHaveBeenCalledTimes(1) + expect(policy.collapseTiming.getSnapshot()).toBe('completion') + expect(host.set).toHaveBeenCalledTimes(2) } finally { policy.dispose() } diff --git a/packages/client/ui-chat/tests/user-content-component-fixture.tsx b/packages/client/ui-chat/tests/user-content-component-fixture.tsx new file mode 100644 index 0000000000..eb6670fb33 --- /dev/null +++ b/packages/client/ui-chat/tests/user-content-component-fixture.tsx @@ -0,0 +1,27 @@ +/** Production user content for component units; registry integration uses SlotTestRuntime. */ +import { createElement, type ComponentProps } from 'react' +import type { PropsLocale, PropsRenderFactories, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import type { UserTextInput } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { createUserTextFixture } from '../../ui-conversation/tests/user-text-component-fixture.client.tsx' +import type { UserContentInput } from '../src/client/contract/slots.ts' +import { UserContent } from '../src/client/chat/UserContent.tsx' + +/** + * Bind real text parsing and business renderers for one component-test lifetime. + * @param actions - reference operations supplied by the test's node-injection fixture. + * @returns renderer accepting prepared content, the user-image Slot seat, and Chat locale. + */ +export function createUserContentFixture(actions?: Parameters[0]) { + const renderUserText = createUserTextFixture(actions) + return ( + input: UserContentInput, + renderSlot: PropsRenderSlots<'conversation.chat.user.images'>['renderSlot'], + t: PropsLocale<'chat'>['t'], + ) => { + const renderFactory: PropsRenderFactories['renderFactorySlot'] = (name, owner) => { + if (name !== 'conversation.user.text') throw new Error(`Unexpected user content Factory: ${name}`) + return renderUserText(owner as UserTextInput) + } + return createElement(UserContent, { ...input, renderSlot, renderFactorySlot: renderFactory, t } as ComponentProps) + } +} diff --git a/packages/client/ui-chat/tests/user-content.client.spec.tsx b/packages/client/ui-chat/tests/user-content.client.spec.tsx new file mode 100644 index 0000000000..1a93864a41 --- /dev/null +++ b/packages/client/ui-chat/tests/user-content.client.spec.tsx @@ -0,0 +1,279 @@ +// @vitest-environment jsdom +import { useState, type ReactNode } from 'react' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { act, cleanup, fireEvent, type RenderResult, within } from '@testing-library/react' +import { AttachmentId, type FileAttachmentRef, type ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' +import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' +import type { PropsRenderFactories, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { UserContentAttachment, UserContentData, UserContentInput } from '../src/client/contract/slots.ts' +import { UserContent } from '../src/client/chat/UserContent.tsx' +import { en, NS, zh } from '../src/client/locale.ts' +import type { UserTextInjected } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '../../ui-conversation/src/client/conversation/user-text-registry.ts' +import { UserText, PlainUserText, SessionReference } from '../../ui-conversation/src/client/user-text/UserText.tsx' +import { sessionReferenceRule } from '../../ui-conversation/src/client/user-text/session-reference-rule.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from '../../ui-conversation/src/client/user-text/whitespace-rules.ts' +import { fileReferenceRule, folderReferenceRule } from '../../ui-reference/src/client/user-text-rules.ts' +import { FileReference, FolderReference } from '../../ui-reference/src/client/FileReference.tsx' +import { en as referenceEn, zh as referenceZh } from '../../ui-reference/src/client/locales.ts' +import { skillReferenceRule } from '../../ui-skill/src/client/user-text-rules.ts' +import { SkillReference } from '../../ui-skill/src/client/SkillReference.tsx' + +afterEach(cleanup) + +const image: ImageAttachmentRef = { + attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 68, width: 640, height: 320, name: 'history.png', +} +const file: FileAttachmentRef = { + attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), name: 'notes.txt', bytes: 23, +} +const durable: UserContentAttachment = { type: 'image', image: { attachment: image } } +const preview: UserContentAttachment = { + type: 'image', image: { preview: { url: 'blob:local-preview', name: 'preview.png', width: 4, height: 3 } }, +} +const filePart: UserContentAttachment = { type: 'file', file } +const empty: UserContentData = { text: '', attachments: [], extraBlocks: [] } +type RenderSeats = PropsRenderSlots<'conversation.approval.detail'> & PropsRenderFactories + +async function bench() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + runtime.ctx.provide('locale', locale) + locale.register('common', { en: commonEn, zh: commonZh }) + locale.register(NS, { en, zh }) + locale.register('reference', { en: referenceEn, zh: referenceZh }) + locale.setLocale('en') + runtime.slots.installLocale(locale) + const imageCalls: PropsRuntime<'conversation.chat.user.images'>[] = [] + const openFile = vi.fn<(path: string) => void>() + const openSkill = vi.fn<(name: string) => void>() + await runtime.mount({ inject: ['slots'], apply: (ctx) => { + const userText = new UserTextRegistry(ctx) + for (const rule of [ + sessionReferenceRule, fileReferenceRule, folderReferenceRule, skillReferenceRule, + collapseWhitespaceRule, trimWhitespaceRule, + ]) { + userText.register(rule) + } + ctx.slots.registerFactory({ + name: 'conversation.user.text', scope: 'session', + children: { 'conversation.user.text.node': { kind: 'keyed', scope: 'session', inline: true } }, + inject: (): UserTextInjected => ({ + hooks: { userTextRevision: { + getSnapshot: () => userText.getSnapshot(), subscribe: listener => userText.subscribe(listener), + } }, + createUserTextEvaluator: () => userText.createEvaluator(), + reportTransformFailure: (error: unknown): never => { throw error }, + }), + }, UserText) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'text' }, PlainUserText) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'session' }, SessionReference) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', locale: 'reference', + inject: () => ({ openFile }) }, FileReference) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder' }, FolderReference) + ctx.slots.register({ name: 'conversation.user.text.node', key: 'skill', inject: () => ({ openSkill }) }, SkillReference) + ctx.slots.inject('conversation.chat.user.images', () => ctx.slots.register({ name: 'conversation.chat.user.images' }, function ImageProbe(props) { + imageCalls.push(props) + const source = props.images[0] + if (source === undefined) throw new Error('User content must pass one image to the image Slot') + const name = 'attachment' in source ? source.attachment.name : source.preview.name + return snapshot.sessionId)}>{name} + })) + } }) + const mountContent = () => runtime.mount({ inject: ['slots'], apply: (ctx) => { + ctx.slots.registerFactory({ + name: 'conversation.chat.user.content', scope: 'session', locale: NS, + children: { 'conversation.chat.user.images': { kind: 'single', scope: 'session' } }, + }, UserContent) + } }) + const owner = await mountContent() + await runtime.sessions.add({ id: 'user-content' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('user-content')) + const captured: { seats?: RenderSeats; setContent?: (content: ReactNode) => void } = {} + await runtime.root.declare({ + 'conversation.approval.detail': { kind: 'single', scope: 'session' }, + }, function TestRoot(props) { + const [content, setContent] = useState(null) + captured.seats = props + captured.setContent = setContent + return content + }) + const view = runtime.renderRoot() + const { seats, setContent } = captured + if (seats === undefined || setContent === undefined) throw new Error('User content fixture root did not render') + const { SessionProvider } = seats + const factory = (input: UserContentInput) => seats.renderFactorySlot('conversation.chat.user.content', input) + const render = (content: ReactNode, scoped = true): RenderResult => { + const update = (next: ReactNode): void => { + act(() => { setContent(scoped ? {next} : next) }) + } + update(content) + return { ...view, rerender: update } + } + const loadImage = vi.fn(async () => 'blob:loaded') + return { runtime, locale, owner, mountContent, factory, render, loadImage, imageCalls, SessionProvider, openFile, openSkill } +} + +describe('user Content Factory', () => { + it('renders prepared text directly without a row, admission markers, time, or copy controls', async () => { + const b = await bench() + const text = '**literal user text**\nsecond line' + const view = b.render(b.factory({ content: { ...empty, text }, facts: {}, loadImage: b.loadImage })) + const textNode = view.getByText('**literal user text** second line') + expect(textNode.textContent).toBe(text) + const root = view.container.querySelector('[data-slot="root"]') + expect(textNode.closest('div')?.parentElement).toBe(root?.firstElementChild) + expect(root?.children).toHaveLength(1) + expect(view.container.querySelector('strong, time, [role="status"], [data-pending-steering], [data-submission-echo]')).toBeNull() + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(view.container.querySelector('[data-message-attachments]')).toBeNull() + expect(b.runtime.factoryOf('conversation.chat.user.content')).toMatchObject({ + component: UserContent, scope: 'session', locale: 'chat', + }) + }) + + it('keeps mixed files, durable images, and local previews in their prepared order through its user-image Slot', async () => { + const b = await bench() + const content: UserContentData = { + ...empty, text: 'Prepared text', attachments: [filePart, durable, { type: 'file', file: { ...file, name: 'last.md' } }, preview], + } + const view = b.render(b.factory({ content, facts: {}, loadImage: b.loadImage })) + const attachments = view.container.querySelector('[data-message-attachments]') + expect([...attachments?.children ?? []].map(child => child.textContent)).toEqual([ + 'notes.txtTXT 23B', 'history.png', 'last.mdMD 23B', 'preview.png', + ]) + expect(view.getByTitle('notes.txt')).toBeTruthy() + expect(view.getByText('Prepared text')).toBeTruthy() + const durableCall = b.imageCalls.find(call => call.images[0] === durable.image) + const previewCall = b.imageCalls.find(call => call.images[0] === preview.image) + expect(durableCall?.images).toEqual([durable.image]) + expect(previewCall?.images).toEqual([preview.image]) + for (const call of [durableCall, previewCall]) { + expect(call).toMatchObject({ align: 'end', compact: true, loadImage: b.loadImage }) + } + expect(b.loadImage).not.toHaveBeenCalled() + }) + + it.each([ + { label: 'one durable image', attachments: [durable], compact: false }, + { label: 'one preview', attachments: [preview], compact: false }, + { label: 'one file and one image', attachments: [filePart, durable], compact: true }, + { label: 'one preview and one file', attachments: [preview, filePart], compact: true }, + ])('uses all attachments to choose compact images: $label', async ({ attachments, compact }) => { + const b = await bench() + const view = b.render(b.factory({ content: { ...empty, attachments }, facts: {}, loadImage: b.loadImage })) + expect(view.getAllByTestId('image')).toHaveLength(1) + expect(b.imageCalls[0]).toMatchObject({ compact, align: 'end', loadImage: b.loadImage }) + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(view.container.querySelector('[data-slot="root"]')?.firstElementChild?.children).toHaveLength(1) + }) + + it('reuses one prepared value in unrelated parents while nested images inherit each Session', async () => { + const b = await bench() + await b.runtime.sessions.add({ id: 'other-user-content' }) + const other = b.runtime.sessions.retainFor(b.runtime.ctx, SessionId('other-user-content')) + const content: UserContentData = Object.freeze({ + text: 'Already prepared', attachments: Object.freeze([preview]), extraBlocks: Object.freeze([]), + }) + const input: UserContentInput = { content, facts: {}, loadImage: b.loadImage } + const { SessionProvider } = b + const view = b.render(<> +
{b.factory(input)}
+ + ) + for (const [parent, sessionId] of [['first', 'user-content'], ['second', 'other-user-content']] as const) { + const section = within(view.getByTestId(parent)) + expect(section.getByText('Already prepared')).toBeTruthy() + expect(section.getByTestId('image').getAttribute('data-session')).toBe(sessionId) + expect(section.getByTestId('image').getAttribute('data-current-session')).toBe(sessionId) + } + expect(b.imageCalls.every(call => call.images[0] === preview.image)).toBe(true) + }) + + it('binds live Chat locale labels for reference summaries and opaque extra blocks', async () => { + const b = await bench() + const block = { type: 'future-block', value: 'x'.repeat(20_001) } + const content: UserContentData = { ...empty, extraBlocks: [block], referenceLabels: ['Alpha', 'Beta'] } + const view = b.render(b.factory({ content, facts: {}, loadImage: b.loadImage })) + expect(view.getByText('Referenced session · Alpha, Beta')).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: '▸ Extra content block' })) + expect(view.container.querySelector('pre')?.textContent).toContain('"type": "future-block"') + expect(view.container.querySelector('pre')?.textContent).toContain( + `… truncated, ${JSON.stringify(block, null, 2).length} characters total`, + ) + act(() => { b.locale.setLocale('zh') }) + expect(view.getByText('引用会话 · Alpha、Beta')).toBeTruthy() + expect(view.getByRole('button', { name: '▾ 附加内容块' })).toBeTruthy() + expect(view.container.querySelector('pre')?.textContent).toContain( + `… 已截断,共 ${JSON.stringify(block, null, 2).length} 字符`, + ) + }) + + it('opens file and skill references through their own injectors only in interactive content', async () => { + const b = await bench() + const labels = ['Alpha'] + const content: UserContentData = { + ...empty, text: 'Read @"src/my file.ts" with /review and @Alpha', referenceLabels: labels, + } + const facts = { sessionLabels: labels, skillNames: ['review'] } + const view = b.render(b.factory({ content, facts, loadImage: b.loadImage, interactive: true })) + fireEvent.click(view.getByRole('button', { name: 'my file.ts' })) + fireEvent.click(view.getByRole('button', { name: '/review' })) + expect(b.openFile).toHaveBeenCalledWith('src/my file.ts') + expect(b.openSkill).toHaveBeenCalledWith('review') + expect(view.queryByRole('button', { name: 'Alpha' })).toBeNull() + view.rerender(b.factory({ content, facts, loadImage: b.loadImage })) + expect(view.queryAllByRole('button')).toHaveLength(0) + for (const label of ['my file.ts', '/review', 'Alpha']) fireEvent.click(view.getByText(label, { exact: true })) + expect(b.openFile).toHaveBeenCalledTimes(1) + expect(b.openSkill).toHaveBeenCalledTimes(1) + expect(view.container.querySelectorAll('[data-ref-chip]')).toHaveLength(3) + }) + + it('keeps an empty prepared value empty', async () => { + const b = await bench() + const view = b.render(b.factory({ content: empty, facts: {}, loadImage: b.loadImage })) + expect(view.container.textContent).toBe('') + const root = view.container.querySelector('[data-slot="root"]') + expect(root?.children).toHaveLength(1) + expect(root?.firstElementChild?.children).toHaveLength(0) + expect(view.container.querySelector('[data-message-attachments]')).toBeNull() + expect(view.queryAllByRole('button')).toHaveLength(0) + expect(b.imageCalls).toHaveLength(0) + }) + + it('removes live content on owner disposal and renders it again after registration', async () => { + const b = await bench() + const view = b.render(b.factory({ content: { ...empty, text: 'Reusable content' }, facts: {}, loadImage: b.loadImage })) + expect(view.getByText('Reusable content')).toBeTruthy() + await b.owner.dispose() + expect(view.queryByText('Reusable content')).toBeNull() + expect(() => b.runtime.factoryOf('conversation.chat.user.content')).toThrow('no definition') + await b.mountContent() + expect(view.getByText('Reusable content')).toBeTruthy() + }) + + it('requires a Session binding even when the prepared value has no images', async () => { + const b = await bench() + const message = "strict session factory 'conversation.chat.user.content' rendered without a scope binding" + const suppressExpectedError = (event: ErrorEvent): void => { + if (event.error instanceof Error && event.error.message === message) event.preventDefault() + } + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + window.addEventListener('error', suppressExpectedError) + try { + expect(() => b.render(b.factory({ content: { ...empty, text: 'Unbound content' }, facts: {}, loadImage: b.loadImage }), false)) + .toThrow(message) + } finally { + window.removeEventListener('error', suppressExpectedError) + error.mockRestore() + } + }) +}) diff --git a/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx b/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx index 5fe31820f6..44ac8f2362 100644 --- a/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx +++ b/packages/client/ui-chat/tests/views-type-chain.client.spec.tsx @@ -17,8 +17,8 @@ describe('Chat View type chain', () => { void chat.openFile({ turnSeq: 1, callId: 'c' }) // @ts-expect-error ChatView renders only its flow child. chat.renderSlot('conversation.chat.node', {}, { hookContext: nodeContext }) - // @ts-expect-error Image rendering belongs to the flow. - chat.renderSlot('conversation.message.images', {}) + // @ts-expect-error Output images belong to the Assistant node entry. + chat.renderSlot('conversation.chat.message.images', {}) // @ts-expect-error Flow owner data cannot override the flow's render authority. void flowOwner.renderSlot // @ts-expect-error Node renderers receive the bound hook, not the viewport controller. diff --git a/packages/client/ui-chat/tsdown.config.ts b/packages/client/ui-chat/tsdown.config.ts index 7787b8fe34..0364805433 100644 --- a/packages/client/ui-chat/tsdown.config.ts +++ b/packages/client/ui-chat/tsdown.config.ts @@ -2,7 +2,7 @@ import { clientBundle } from '../tsdown.client.ts' import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' -const bundle = clientBundle('@deepseek-ai/dsh-client-ui-chat', ['lib/types/index.js']) +const bundle = clientBundle(import.meta.dirname, ['lib/types/index.js']) const stylesheet = fileURLToPath(new URL('./src/client/chat/ChatView.module.css', import.meta.url)).replaceAll('\\', '/') const whaleImage = fileURLToPath(new URL('./src/client/chat/running-whale@2x.png', import.meta.url)) diff --git a/packages/client/ui-commands/README.i18n.yaml b/packages/client/ui-commands/README.i18n.yaml index 6177afb95c..97fd762cc1 100644 --- a/packages/client/ui-commands/README.i18n.yaml +++ b/packages/client/ui-commands/README.i18n.yaml @@ -27,8 +27,8 @@ en: 4feecdbec0c3f39e zh: 618944ecade8a3a2 /deepseek-ai-dsh-client-ui-commands/understand-the-implementation: - en: 3aeeba6c91c3ef19 - zh: d3afb3df6d15e17b + en: dbd2d83fb5e57ff3 + zh: 6e2e837f6a08f2fb /deepseek-ai-dsh-client-ui-commands/further-exploration: en: 409c04f534d23de7 zh: 165022d7a0a554eb diff --git a/packages/client/ui-commands/README.md b/packages/client/ui-commands/README.md index 8bf2cdc958..a3f56ab147 100644 --- a/packages/client/ui-commands/README.md +++ b/packages/client/ui-commands/README.md @@ -59,6 +59,8 @@ Popup selection panels fill the composer overlay's width, matching the slash men Each command-directory fetch requires an existing retained Client Session and waits for its initial history open to succeed before sending `commands.list`. A temporary `commandCatalog` reference holds that Session until the fetch settles. An unretained Session or a failed open rejects without sending the RPC, so background catalog refreshes do not reopen closed Sessions. +Popup selection uses the [standard menu inset and item radii](../../../docs/ui-radius.md#nested-hover). +
----- diff --git a/packages/client/ui-commands/README.zh.md b/packages/client/ui-commands/README.zh.md index 792611b54e..8c36427041 100644 --- a/packages/client/ui-commands/README.zh.md +++ b/packages/client/ui-commands/README.zh.md @@ -59,6 +59,8 @@ composer 携带图片或通用文件提交时,只有声明了 `input.attachmen 每次命令目录拉取都要求客户端已持有该会话,并等待首次历史打开成功后才发送 `commands.list`。临时的 `commandCatalog` 引用持续持有会话,直到拉取结束。未被持有的会话或打开失败会直接拒绝,不发送 RPC,因此后台目录刷新不会重新打开已关闭的会话。 +弹出选择面板使用[标准菜单的内缩与菜单项圆角](../../../docs/ui-radius.zh.md#nested-hover)。 +
----- diff --git a/packages/client/ui-commands/locale/en.json b/packages/client/ui-commands/locale/en.json new file mode 100644 index 0000000000..e7d16ed4e8 --- /dev/null +++ b/packages/client/ui-commands/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-commands" + } +} diff --git a/packages/client/ui-commands/locale/zh.json b/packages/client/ui-commands/locale/zh.json new file mode 100644 index 0000000000..ea7b9303f5 --- /dev/null +++ b/packages/client/ui-commands/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "命令选择界面", + "description": "在输入框中提供斜杠命令菜单和相关操作界面。" + } +} diff --git a/packages/client/ui-commands/package.json b/packages/client/ui-commands/package.json index 8fc1e03aea..d7bfa638d8 100644 --- a/packages/client/ui-commands/package.json +++ b/packages/client/ui-commands/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -54,7 +55,6 @@ "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "@deepseek-ai/dsh-api-session-controller": "workspace:*", @@ -66,6 +66,7 @@ "clsx": "^2.0.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-commands/src/client/PopupSelectView.module.css b/packages/client/ui-commands/src/client/PopupSelectView.module.css index f500af280b..bf44e4afa8 100644 --- a/packages/client/ui-commands/src/client/PopupSelectView.module.css +++ b/packages/client/ui-commands/src/client/PopupSelectView.module.css @@ -9,7 +9,7 @@ right: 0; box-sizing: border-box; z-index: 100; - padding: 3px; + padding: 4px; display: flex; flex-direction: column; min-width: min(220px, 100%); diff --git a/packages/client/ui-commands/tsdown.config.ts b/packages/client/ui-commands/tsdown.config.ts index 83f95f8a8c..7aa03cebc1 100644 --- a/packages/client/ui-commands/tsdown.config.ts +++ b/packages/client/ui-commands/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-commands', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 8b555526ad..720a609bd5 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -12,14 +12,17 @@ en: bac0bf0d7330f3b1 zh: 84a895f4b26d8490 /deepseek-ai-dsh-client-ui-conversation/table-of-contents: - en: 9c1c4905952fea5e - zh: d1506dd6fc1018d1 + en: eef4f18c3972ccc4 + zh: 6be65c6ac84ce497 /deepseek-ai-dsh-client-ui-conversation/conversation-assembly: - en: 1d2a3a7f98c2cc9b - zh: f895dd5e9f91e0a9 + en: 6aefa09bb22fdf81 + zh: 0641c4196437cf53 +/deepseek-ai-dsh-client-ui-conversation/sent-user-text: + en: 9912b286384c41d7 + zh: 3e994887c1948677 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 51c7c9e2537aa4be - zh: c4084541a776689e + en: ddabf2f192114e62 + zh: 31370ed6d5149409 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: bb1244310f5c0382 zh: 824b84077432b559 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 980340048f..76e507caa8 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -16,6 +16,7 @@ Desktop product events use the optional [product analytics service](../product-a ## Table of Contents - [Conversation assembly](#conversation-assembly) +- [Sent user text](#sent-user-text) - [Shell and standard props](#shell-and-standard-props) - [Temporary composer entries](#temporary-composer-entries) - [Model Experience](#model-experience) @@ -49,13 +50,24 @@ Group registration rejects a missing View target. Removing an already registered Target packages declaration-merge their snapshot and Location data maps, then register with `ctx.uiConversation.events.register(...)` and `ctx.uiConversation.views.register(...)`. A target reads its Session-owned source with `ctx.uiConversation.binding(binding).target(targetId)`. Registrations are Cordis effects and their returned disposers remove the contribution from the same registry. The shared request inspection serves every target: `ctx.uiConversation.inspectSystemPrompt(previous, event)` interprets system messages and positional replacements as immutable loaded-surface state. It selects the last nonempty surviving system node in surface order, retains only surviving replacement positions for chained rewrites, and withholds the prompt after an unindexed older endpoint until prepend replay supplies its order. Target-owned Definitions retain historical cards independently. `ctx.uiConversation.inspectRequestPrompt(previous, header, system)` classifies request changes against that effective prompt; ordinary messages and stream chunks require no system-state work. + +## Sent user text + +`UiConversation.userText` registers synchronous `match(text, from, context)` rules. Each call offers one business or Text candidate; the evaluator selects the earliest start and uses `order` and stable ID only for same-start ties. Each caller owns its query cache. `Context.read(key)` invalidates only readers of changed Facts, while future candidates and no-match results are reused within their recorded search ranges. Inputs and outputs use readonly types without runtime freezing. See the [UserText types](src/client/contract/user-text.ts) and [design decision](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md). + +Businesses extend `UserTextDataMap` and `UserTextFacts` on this package's `/client` entry, register a matcher through `ctx.uiConversation.userText`, and contribute their renderer to `conversation.user.text.node`. The session-scoped `conversation.user.text` Factory owns this inline keyed Slot. Whitespace rules also return ordinary Text candidates through the same scheduler; trim wins same-start edge collisions with collapse. Node registrations supply their own actions; `interactive` and CSS `ellipsis` remain React Props. Missing renderers display the original fragment; matching failures retain the complete original text and report the rule error. + +Queue previews enable whitespace collapsing and document-edge trimming, retain emoji, and use CSS ellipsis without truncating the input. Editing and copying retain the original text; native attachments use their separate presentation. + ## Shell and standard props -The shared image slot props keep display choices separate from durable references: `thumbnail` requests a contained attachment-list thumbnail, while `compact` requests a cropped gallery tile. An optional per-image `label` supplies the accessible display name; loading and cache identity still use the original attachment reference. [ui-attachment](../ui-attachment/README.md) owns rendering and the lightbox. +The shared image slot props keep display choices separate from durable references: `thumbnail` requests a contained attachment-list thumbnail, while `compact` requests a cropped gallery tile. An optional per-image `label` supplies the accessible display name; loading and cache identity still use the original attachment reference. `MessageImagesContentInput` adds optional complete `MessageImageLabels` for the root-scoped `conversation.images.content` Factory. Message, tool, and Factory inputs carry the view's authorized `loadImage` callback explicitly; loading and URL caching remain with the resource owner. [ui-attachment](../ui-attachment/README.md) provides this Factory and owns rendering and the lightbox. The composer measures its expanded control groups after size, content, visibility, or font-loading changes. If they cannot share a line, the row sets `--dsh-composer-model-text-display: none` and `--dsh-composer-model-icon-display: block` for the model seat; their defaults are `block` and `none`. Wrapping remains available if even the icon cannot fit. +The context meter follows the [statistics-control radius](../../../docs/ui-radius.md#radius-scale). + The context-occupancy button shows a ring and percentage below the input card, after the Session statistics. Clicking it opens the token breakdown in a panel kept inside the viewport, including when no statistics are shown; the button stays hidden until context usage and capacity are available. With Coding Tools off, the shell hides only Trajectory; other plugin-contributed Views remain available. The View tab bar is hidden when fewer than two Views are available. Turning Coding Tools off while Trajectory is active returns to Chat; stored View preferences and recorded Session data remain intact. Turning it on makes Trajectory available again. View owners receive the available roster so their navigation actions can follow the same visibility. @@ -82,7 +94,7 @@ Active transcripts in the main occurrence expose content-width drag handles in t The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged. -The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews render sent text through the shared inline reference projection from `ui-primitives` (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in the ui-primitives `InlineEditor`, so line breaks survive re-editing. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. +The resident composer survives no-Session and Session transitions. Whitespace hides its placeholder; a whitespace-only draft without attachments cannot be sent. The no-Session state keeps the same composer surface mounted but inert while the Workspace picker connects a blank Session. The surface is a shell-owned Lexical editor: reference chips are atomic decorator nodes carrying the owner's serialization identity (submission expands them through the owner codec), claimed slash commands stay styled leading text, folder text references carry the folder glyph as an icon prefix, and the draft's text and semantic references are persisted by the per-Session Conversation store. QueueDock reads `next-turn` from the Session `inbox` projection, including cold recovered messages, and excludes only requestIds still owned by local transcript submissions. Other queued rows retain their normal display and actions. Queue operations address exact queue occurrences through the scoped `ctx.conversation` service; queue previews use the [UserText Factory](#sent-user-text) (wire session forms fold to their label) and show local or durable images and files in original attachment order. Images use thumbnails; files use compact name-and-size cards. An edit exposes the literal sent text in the ui-primitives `InlineEditor`, so line breaks survive re-editing. Durable thumbnails resolve through the session image URL cache. Busy Enter behavior is stored in the Host-backed `ui-conversation` settings namespace. The composer keymap arbitrates the trigger menu's keys through the slash pipeline — Tab settles the highlighted completion (or drills a drillable one), Escape and Shift+Tab leave the menu without settling — and leaves every other key to the editor. An overlay that takes the keyboard hands it back through `SessionInput.focus()`, which rides Lexical's own focus so the caret returns where the draft left it rather than at the start. Plain Enter uses the configured delivery mode, exactly Ctrl+Enter or Cmd+Enter uses its complement, and Shift+Enter inserts a line break. Enter with Alt, AltGraph, both Ctrl and Cmd, or Shift plus Ctrl/Cmd leaves the draft and command menu unchanged and keeps the DOM event available to application shortcuts. The Conversation plugin registers the fixed send, newline, complementary-delivery, command-menu, and reference-menu rows and reserves their bindings until it unloads. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index d4a100e7dd..0f5afe0458 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -16,6 +16,7 @@ kind: "package-reference" ## 目录 - [Conversation 组装](#conversation-assembly) +- [已发送用户文本](#sent-user-text) - [Shell 与标准 props](#shell-and-standard-props) - [临时 composer entry](#temporary-composer-entries) - [模型体验](#model-experience) @@ -49,13 +50,24 @@ Group 注册时缺少 View 目标会报错。已注册的 View Definition 被移 target package 通过 declaration merge 扩展 snapshot 与 Location data map,再调用 `ctx.uiConversation.events.register(...)` 和 `ctx.uiConversation.views.register(...)`。target 通过 `ctx.uiConversation.binding(binding).target(targetId)` 读取其 Session-owned source。注册属于 Cordis effect,返回的 disposer 从同一个 registry 移除 contribution。共享的请求检查服务于每个 target:`ctx.uiConversation.inspectSystemPrompt(previous, event)` 将系统消息与位置替换解释为不可变的已加载 surface 状态。它按 surface 顺序选择最后一个非空的存活系统节点,为连续重写只保留存活的替换位置;遇到未建立索引的更早端点后,提示词保持不可用,直到向前补页回放提供其顺序。target 自有的 Definition 独立保留历史卡片。`ctx.uiConversation.inspectRequestPrompt(previous, header, system)` 根据该有效提示词分类请求变更;普通消息与流式分片无需处理系统状态。 + +## 已发送用户文本 + +`UiConversation.userText` 注册同步 `match(text, from, context)` 规则。每次调用提供一个业务或 Text 候选;计算器选择起点最早的候选,仅在同起点时使用 `order` 和稳定 ID。每个调用者拥有自己的查询缓存。`Context.read(key)` 只使变化 Facts 的读取者失效,未来候选和无匹配结果在已记录的搜索范围内复用。输入和输出使用 readonly 类型,不在运行时冻结。详见 [UserText 类型](src/client/contract/user-text.ts)与[设计决策](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.zh.md)。 + +业务扩展本包 `/client` 入口的 `UserTextDataMap` 和 `UserTextFacts`,通过 `ctx.uiConversation.userText` 注册匹配器,并向 `conversation.user.text.node` 贡献 renderer。Session 作用域的 `conversation.user.text` Factory 拥有这个行内 keyed Slot。空白规则也通过同一调度器返回普通 Text 候选,trim 在同起点的边缘空白冲突中胜过 collapse。节点注册自行提供动作,`interactive` 和 CSS `ellipsis` 仍为 React Props。缺少 renderer 时显示原文片段,匹配失败时保留完整原文并报告规则错误。 + +Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CSS 省略而不截断输入。编辑和复制保留原文;原生附件使用独立的展示路径。 + ## Shell 与标准 props -共享图片插槽属性将展示选择与持久化引用分开:`thumbnail` 请求完整缩放的附件列表缩略图,`compact` 请求裁剪的图片方块。每张图片可通过可选的 `label` 提供无障碍展示名称;加载和缓存标识仍使用原始附件引用。[ui-attachment](../ui-attachment/README.zh.md) 负责渲染与灯箱。 +共享图片插槽属性将展示选择与持久化引用分开:`thumbnail` 请求完整缩放的附件列表缩略图,`compact` 请求裁剪的图片方块。每张图片可通过可选的 `label` 提供无障碍展示名称;加载和缓存标识仍使用原始附件引用。`MessageImagesContentInput` 为 root 作用域的 `conversation.images.content` Factory 增加可选的完整 `MessageImageLabels`。消息、工具及 Factory 输入显式携带视图提供的授权 `loadImage` 回调;读取和 URL 缓存仍由资源所有者负责。[ui-attachment](../ui-attachment/README.zh.md) 提供该 Factory,负责渲染与灯箱。 控件组的尺寸、内容、可见性或字体加载状态变化后,composer 测量展开状态下的控件组。若无法排在同一行,控制栏为模型位设置 `--dsh-composer-model-text-display: none` 和 `--dsh-composer-model-icon-display: block`;两者默认值分别为 `block` 和 `none`。若连图标也放不下,仍允许换行。 +上下文占用率入口遵循[统计控件圆角规则](../../../docs/ui-radius.zh.md#radius-scale)。 + 上下文占用按钮在输入卡片下方、会话统计右侧显示圆环和百分比。点击按钮可在视口内的面板查看 token 构成,没有统计项时面板也不会越界;上下文用量和容量尚不可用时,按钮保持隐藏。 关闭代码工作工具时,外壳仅隐藏 Trajectory;其他插件贡献的 View 仍然可用。可用 View 少于两个时隐藏 View 标签栏。在 Trajectory 激活时关闭代码工作工具会返回 Chat;已保存的 View 偏好和 Session 记录保持不变。开启后,Trajectory 恢复可用。View 所有者接收可用列表,使导航操作跟随相同的可见性。 @@ -82,7 +94,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。 -常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览经 `ui-primitives` 的共享行内引用投影渲染已发送文本(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 +常驻 composer 在无 Session 与有 Session 之间保持挂载。输入空白字符会隐藏占位提示;没有附件的纯空白草稿无法发送。无 Session 时,同一个编辑器表面保持 inert,Workspace picker 连接 blank Session。该表面是 shell 所有的 Lexical 编辑器:引用 chip 是携带 owner 序列化身份的原子 decorator 节点(提交时经 owner codec 展开),已认领的 slash command 保持为带样式的行首文本,文件夹文本引用以图标前缀携带文件夹图形,草稿文字和引用语义字段由逐 Session Conversation store 持久化。QueueDock 从 Session 的 `inbox` 投影读取 `next-turn`,包含从冷状态恢复的消息,仅排除仍由本地 transcript 提交承接的 requestId。其他排队行保留正常展示和操作。Queue 操作通过 scoped `ctx.conversation` service 寻址准确的 queue occurrence;queue 预览使用 [UserText Factory](#sent-user-text)(wire 会话形式折叠为其标签),并按原始附件顺序展示本地或持久化的图片和文件。图片使用缩略图,文件使用紧凑的名称与大小卡片。编辑态在 ui-primitives 的 `InlineEditor` 中展示字面发送文本,因此重新编辑不会丢失换行。持久化缩略图通过会话图片 URL 缓存解析。繁忙时 Enter 行为保存在 Host-backed `ui-conversation` settings namespace。 composer 键盘映射经斜杠流水线裁决触发菜单的按键——Tab 确认高亮补全项(可下钻项则下钻),Escape 与 Shift+Tab 离开菜单且不选定——其余按键交给编辑器自身。 接管键盘的浮层通过 `SessionInput.focus()` 把键盘还回来,该路径走 Lexical 自己的 focus,因此光标回到草稿原来的位置而不是开头。 普通 Enter 使用已配置的投递模式,严格的 Ctrl+Enter 或 Cmd+Enter 使用互补模式,Shift+Enter 插入换行。带 Alt、AltGraph、同时带 Ctrl 与 Cmd,或 Shift 与 Ctrl/Cmd 的 Enter 保持草稿和指令菜单不变,并将 DOM 事件留给应用快捷键。Conversation 插件注册发送、换行、互补投递、命令菜单和引用菜单的固定条目,并在卸载前保留这些键位。 diff --git a/packages/client/ui-conversation/locale/en.json b/packages/client/ui-conversation/locale/en.json new file mode 100644 index 0000000000..918f717ecd --- /dev/null +++ b/packages/client/ui-conversation/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-conversation" + } +} diff --git a/packages/client/ui-conversation/locale/zh.json b/packages/client/ui-conversation/locale/zh.json new file mode 100644 index 0000000000..a48a705f37 --- /dev/null +++ b/packages/client/ui-conversation/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话界面框架", + "description": "组织对话内容、输入框、消息队列和视图导航。" + } +} diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index 20d6dd56b6..48a3f73af5 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -82,11 +83,9 @@ "@deepseek-ai/dsh-workspace": "workspace:*", "@deepseek-ai/dsh-file-reference": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "@lexical/headless": "^0.49.0", "react-dom": "^18.2.0", - "@types/react-dom": "~18.3.0", "zod": "4.4.3", "lexical": "^0.49.0", "clsx": "^2.0.0", @@ -100,6 +99,7 @@ "@deepseek-ai/dsh-client-product-analytics": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 9994c4e9ae..3e34d83b4b 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -14,10 +14,13 @@ import type {} from '@deepseek-ai/dsh-client-ui-session/client' import type {} from '@deepseek-ai/dsh-client-ui-settings/client' import type { ShortcutCommandId, ShortcutFixedCommand } from '@deepseek-ai/dsh-client-shortcuts/client' import { UiConversation } from './conversation/assembly.ts' +import { UserText, PlainUserText, SessionReference } from './user-text/UserText.tsx' +import { sessionReferenceRule } from './user-text/session-reference-rule.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from './user-text/whitespace-rules.ts' import type { ViewTab } from './contract/views.ts' import type { ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, - ConversationSessionInjected, DraftFileUploads, + ConversationSessionInjected, DraftFileUploads, UserTextInjected, } from './contract/slots.ts' import type { InputNotice } from './contract/input.ts' import type { ReferenceInsert } from './contract/draft-editor.ts' @@ -156,6 +159,30 @@ export function apply(ctx: Context, config: Config = Config({})): void { const maxConcurrentFileUploads = config.maxConcurrentFileUploads as number const workspaceNavigation = ctx.get('uiWorkspace') as unknown as WorkspaceNavigation const uiConversation = new UiConversation(ctx, sessions) + uiConversation.userText.register(sessionReferenceRule) + uiConversation.userText.register(collapseWhitespaceRule) + uiConversation.userText.register(trimWhitespaceRule) + slots.registerFactory({ + name: 'conversation.user.text', + scope: 'session', + children: { + 'conversation.user.text.node': { kind: 'keyed', scope: 'session', inline: true }, + }, + inject: (): UserTextInjected => ({ + hooks: { + userTextRevision: { + getSnapshot: () => uiConversation.userText.getSnapshot(), + subscribe: listener => uiConversation.userText.subscribe(listener), + }, + }, + createUserTextEvaluator: () => uiConversation.userText.createEvaluator(), + reportTransformFailure: (error) => { console.error('[ui-conversation] user-text transformation failed:', error) }, + }), + }, UserText) + slots.inject('conversation.user.text.node', function* () { + yield slots.register({ name: 'conversation.user.text.node', key: 'text', priority: 100 }, PlainUserText) + yield slots.register({ name: 'conversation.user.text.node', key: 'session', priority: 100 }, SessionReference) + }) ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-conversation: dictionaries') const t = ctx.locale.bind(NS) diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 5564aea9b6..9abf5afb1c 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -3,6 +3,7 @@ import type { ReactNode, RefObject } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import type { FileUploadReceiptId } from '@deepseek-ai/dsh-client-file-upload/client' +import type { ImageLightboxLabels } from '@deepseek-ai/dsh-client-ui-primitives' import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { MaybeSnapshotSelectorHook, ObservableSnapshot, SnapshotSelectorHook, @@ -22,6 +23,7 @@ import type { createConversationStore } from '../stores.ts' import type { BusyEnterBehavior } from './composer-submission.ts' import type { ConversationSnapshot } from './snapshot.ts' import type { ViewTab } from './views.ts' +import type { UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode } from './user-text.ts' /** Browser-owned draft attachment that has not crossed the durable Host boundary. */ export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment @@ -117,8 +119,53 @@ export interface MessageImagesOwnerProps { thumbnail?: boolean } -/** Slot-backed renderer used by Conversation targets without importing an attachment implementation. */ -export type RenderMessageImages = (owner: Omit) => ReactNode +/** Message-image strings the owner resolves from its own locale namespace. */ +export interface MessageImageLabels { + /** Fallback display name for an unnamed image. */ + image: string + /** Thumbnail tooltip inviting the original-image preview. */ + open: string + /** Accessible thumbnail label; receives the image's display name. */ + openNamed: (label: string) => string + /** Loading placeholder shown until bytes resolve. */ + loading: string + /** Retry-control label shown when the load fails. */ + loadFailed: string + /** Lightbox strings forwarded to the opened preview. */ + lightbox: ImageLightboxLabels +} + +/** Root-scoped image gallery input with explicit reading authority and optional caller copy. */ +export interface MessageImagesContentInput extends MessageImagesOwnerProps { + readonly labels?: MessageImageLabels +} + +/** Transform inputs and independently controlled rendering behavior. */ +export interface UserTextInput extends UserTextDocumentInput { + /** Enable renderer-owned reference actions; omitted values keep references read-only. */ + readonly interactive?: boolean + /** Use CSS single-line overflow ellipsis without shortening source text. */ + readonly ellipsis?: boolean +} + +/** Rule invalidation and document evaluation supplied by the data layer. */ +export interface UserTextInjected { + hooks: { userTextRevision: ObservableSnapshot } + /** Each invocation creates a caller-owned data-layer cache without registry subscriptions. */ + createUserTextEvaluator: () => UserTextEvaluator + /** Report a failed rule while the original text remains visible. */ + reportTransformFailure: (error: unknown) => void +} + +/** JSON-only owner data common to every business text node. */ +export interface UserTextNodeOwnerProps { + readonly raw: string + readonly interactive: boolean +} + +/** Complete props for the selected business node, including its Session scope. */ +export type UserTextNodeProps = + PropsRuntime<'conversation.user.text.node', Id> /** Selector hook over the current Session's assembled Conversation. */ export type UseConversation = SnapshotSelectorHook @@ -126,7 +173,33 @@ export type UseConversation = SnapshotSelectorHook export type UseConversationViews = SnapshotSelectorHook declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotFactoryMap { + /** Parse one original text and render its business nodes through the owned keyed Slot. */ + 'conversation.user.text': { + scope: 'session' + props: UserTextInput + inject: UserTextInjected + children: { + 'conversation.user.text.node': { kind: 'keyed'; scope: 'session'; inline: true } + } + } + /** Official reusable gallery, with explicit authorized loading and optional caller copy. */ + 'conversation.images.content': { + scope: 'root' + props: MessageImagesContentInput + locale: 'conversation' + } + } + interface SlotMap { + /** One business-owned inline renderer for a pure JSON text node. */ + 'conversation.user.text.node': { + kind: 'keyed' + scope: 'session' + inline: true + owner: UserTextNodeOwnerProps + keyProps: { [Id in UserTextId]: { node: UserTextNode } } + } /** Conversation shell beneath its root-scoped main-panel entry. */ 'main.conversation': { kind: 'single'; scope: 'session-maybe' } /** Strict per-Session Conversation body. */ diff --git a/packages/client/ui-conversation/src/client/contract/user-text.ts b/packages/client/ui-conversation/src/client/contract/user-text.ts new file mode 100644 index 0000000000..4b6f68e621 --- /dev/null +++ b/packages/client/ui-conversation/src/client/contract/user-text.ts @@ -0,0 +1,63 @@ +/** Readonly JSON candidates, forward matching, and tracked caller Facts. */ +import type { UserTextDataMap, UserTextFacts } from '../index.ts' + +/** Registered business IDs plus the document-owned `text` ID. */ +export type UserTextId = Extract + +type JsonPayload = T extends string | number | boolean | null ? T + : T extends (...args: never[]) => unknown ? never + : T extends readonly unknown[] ? { readonly [K in keyof T]: JsonPayload } + : T extends object ? { readonly [K in keyof T]: JsonPayload } + : never + +/** Original UTF-16 text and readonly Facts; absence is observable through `context.read`. */ +export interface UserTextDocumentInput { + readonly text: string + readonly facts: Readonly> +} + +/** Discriminated JSON node over a nonempty half-open UTF-16 range in the original text. */ +export type UserTextNode = { + [Id in K]: { + readonly id: Id + readonly start: number + readonly end: number + readonly data: JsonPayload + } +}[K] + +/** Facts reader valid only during its owning synchronous query; never retain it. */ +export interface UserTextTransformContext { + /** + * Record a field dependency, including an absent value; throws after the call returns or throws. + * @param key - field of the caller's readonly Facts snapshot. + * @returns the borrowed readonly value, or undefined when absent. + */ + read(key: K): UserTextFacts[K] | undefined +} + +/** One forward matcher for business references or Text replacements; order only resolves same-start candidates. */ +export interface UserTextRule { + readonly id: Id + /** Finite ascending priority; equal values use stable ID ordering, never plugin load order. */ + readonly order: number + /** + * Find one nearest original-text candidate at or after `from`, resolving own same-start alternatives deterministically. + * Search uses original lexical boundaries, not the beginning of a sliced suffix. Queries are independent of accepted nodes. + * @param text - complete original text; neither this string nor caller Facts may be mutated. + * @param from - inclusive original UTF-16 start offset, advancing within one reconciliation. + * @param context - synchronous Facts reader; all retained queries contribute dependencies. + * @returns one nonempty node using this rule's ID or `text`, or undefined when no later candidate exists. + * Text candidates preserve the exact source substring and may supply `data.display`. + */ + match(this: void, text: string, from: number, context: UserTextTransformContext): (UserTextNode & { readonly id: Id }) | UserTextNode<'text'> | undefined +} + +/** + * Reconcile one document using current rules and independently cached candidate queries. + * Reentrant calls throw. Failures carry ruleId and cause without publishing partial output; + * failed queries retry when their offset, definition, original text, or read Facts change. + * @param input - original text and readonly JSON Facts; fields are compared with Object.is. + * @returns readonly nodes covering the text, or [] for empty text; equivalent results retain identities. + */ +export type UserTextEvaluator = (input: UserTextDocumentInput) => readonly UserTextNode[] diff --git a/packages/client/ui-conversation/src/client/conversation/assembly.ts b/packages/client/ui-conversation/src/client/conversation/assembly.ts index edc182f530..b6cfcd6318 100644 --- a/packages/client/ui-conversation/src/client/conversation/assembly.ts +++ b/packages/client/ui-conversation/src/client/conversation/assembly.ts @@ -24,6 +24,7 @@ import { ConversationEventRegistry } from './event-registry.ts' import { HistoricalImageCache } from './historical-images.ts' import { ConversationViewRegistry } from './view-registry.ts' import { ConversationGroupRegistry } from './group-registry.ts' +import { UserTextRegistry } from './user-text-registry.ts' /** Observable faces published for one Session's Conversation assembly. */ export interface ConversationBinding { @@ -190,6 +191,8 @@ export class UiConversation extends Service { readonly views: ConversationViewRegistry /** Business grouping rules over already materialized target Nodes. */ readonly groups: ConversationGroupRegistry + /** Pure text rules and parser snapshots, independent of durable Session assembly. */ + readonly userText: UserTextRegistry private readonly bindings = new WeakMapWithValues() private readonly images: HistoricalImageCache @@ -202,6 +205,7 @@ export class UiConversation extends Service { this.events = new ConversationEventRegistry(ctx) this.views = new ConversationViewRegistry(ctx) this.groups = new ConversationGroupRegistry(ctx, this.views) + this.userText = new UserTextRegistry(ctx) this.images = new HistoricalImageCache(ctx, sessions) const rebuild = (): void => { for (const record of this.bindings.values) record.binding.rebuild() diff --git a/packages/client/ui-conversation/src/client/conversation/user-text-document.ts b/packages/client/ui-conversation/src/client/conversation/user-text-document.ts new file mode 100644 index 0000000000..e8c6b19b8a --- /dev/null +++ b/packages/client/ui-conversation/src/client/conversation/user-text-document.ts @@ -0,0 +1,244 @@ +/** Per-document candidate reconciliation, query coverage, tracked Facts and JSON identity reuse. */ +import type { UserTextFacts } from '../index.ts' +import type { + UserTextDocumentInput, UserTextNode, UserTextRule, UserTextTransformContext, +} from '../contract/user-text.ts' + +type FactKey = keyof UserTextFacts + +class UserTextTransformError extends Error { + constructor(readonly ruleId: string, cause: unknown) { + super(`user-text rule "${ruleId}" failed to evaluate`, { cause }) + this.name = 'UserTextTransformError' + } +} + +interface Query { + readonly from: number + readonly node: UserTextNode | undefined + readonly error: UserTextTransformError | undefined +} + +interface Matcher { + readonly definition: UserTextRule + readonly reads: Map + queries: readonly Query[] +} + +interface Traversal { + readonly matcher: Matcher + readonly added: Query[] + index: number + head: Query | undefined +} + +/** Data-layer cache owned by one caller; initialization and refresh share one reconciliation. */ +export class UserTextDocument { + private text: string | undefined + private rules: readonly UserTextRule[] | undefined + private initial: readonly UserTextNode[] = [] + private output: readonly UserTextNode[] = [] + private readonly matchers = new Map() + private complete = false + private evaluating = false + + /** + * Reconcile original text using current rule definitions and valid query records. + * @param input - original text and readonly Facts, compared by fields actually read. + * @param rules - unique definitions ordered by ascending order and stable ID. + * @returns complete readonly nodes; failures retain caches but publish no partial result. + */ + evaluate(input: UserTextDocumentInput, rules: readonly UserTextRule[]): readonly UserTextNode[] { + if (this.evaluating) throw new Error('user-text document evaluation cannot be reentrant') + this.evaluating = true + try { + const { changed, matchers } = this.prepare(input, rules) + if (!changed && this.complete) return this.output + this.complete = false + this.output = alignNodes(this.reconcile(input, matchers), this.output, this.initial) + this.complete = true + return this.output + } finally { + this.evaluating = false + } + } + + private prepare(input: UserTextDocumentInput, rules: readonly UserTextRule[]): { changed: boolean; matchers: Matcher[] } { + let changed = this.rules !== rules + if (this.text !== input.text) { + changed = true + this.text = input.text + this.matchers.clear() + this.initial = input.text.length === 0 ? [] : [textNode(input.text, 0, input.text.length)] + this.output = this.initial + } + const ids = new Set(rules.map(rule => rule.id)) + const matchers: Matcher[] = [] + for (const definition of rules) { + let matcher = this.matchers.get(definition.id) + if (matcher === undefined || matcher.definition !== definition || factsChanged(matcher.reads, input)) { + matcher = { definition, queries: [], reads: new Map() } + this.matchers.set(definition.id, matcher) + changed = true + } + matchers.push(matcher) + } + for (const id of this.matchers.keys()) if (!ids.has(id)) this.matchers.delete(id) + this.rules = rules + return { changed, matchers } + } + + private reconcile(input: UserTextDocumentInput, matchers: readonly Matcher[]): readonly UserTextNode[] { + const traversals: Traversal[] = matchers.map(matcher => ({ matcher, added: [], index: -1, head: undefined })) + const nodes: UserTextNode[] = [] + let cursor = 0 + try { + while (true) { + let winner: UserTextNode | undefined + for (const traversal of traversals) { + const node = nextCandidate(traversal, input, cursor) + // Definitions arrive in stable priority order; earlier starts always take precedence. + if (node !== undefined && (winner === undefined || node.start < winner.start)) winner = node + } + if (winner === undefined) { + if (cursor < input.text.length) nodes.push(textNode(input.text, cursor, input.text.length)) + return nodes + } + if (cursor < winner.start) nodes.push(textNode(input.text, cursor, winner.start)) + nodes.push(winner) + cursor = winner.end + } + } finally { + for (const { matcher, added } of traversals) { + if (added.length > 0) matcher.queries = mergeQueries(matcher.queries, added) + } + } + } + +} + +function factsChanged(reads: ReadonlyMap, input: UserTextDocumentInput): boolean { + for (const [key, value] of reads) if (!Object.is(value, input.facts[key])) return true + return false +} + +function withFacts(input: UserTextDocumentInput, reads: Map, run: (context: UserTextTransformContext) => T): T { + let active = true + try { + return run({ + read: (key: K): UserTextFacts[K] | undefined => { + if (!active) throw new Error('user-text transform context is closed; read is synchronous only') + const value = input.facts[key] + reads.set(key, value) + return value + }, + }) + } finally { + active = false + } +} + +function nextCandidate(traversal: Traversal, input: UserTextDocumentInput, cursor: number): UserTextNode | undefined { + const { matcher } = traversal + if (traversal.head === undefined || (traversal.head.node !== undefined && traversal.head.node.start < cursor)) { + let next = matcher.queries[traversal.index + 1] + while (next !== undefined && next.from <= cursor) { + traversal.index++ + next = matcher.queries[traversal.index + 1] + } + const recorded = matcher.queries[traversal.index] + if (recorded !== undefined && (recorded.error !== undefined + ? recorded.from === cursor : recorded.node === undefined || recorded.node.start >= cursor)) { + traversal.head = recorded + } else { + let node: UserTextNode | undefined + let error: UserTextTransformError | undefined + try { + node = withFacts(input, matcher.reads, context => matcher.definition.match(input.text, cursor, context)) + if (node !== undefined) validateCandidate(input.text, matcher.definition.id, cursor, node) + } catch (cause) { + error = new UserTextTransformError(matcher.definition.id, cause) + } + traversal.head = { from: cursor, node, error } + traversal.added.push(traversal.head) + } + } + if (traversal.head.error !== undefined) throw traversal.head.error + return traversal.head.node +} + +function validateCandidate(text: string, ruleId: string, from: number, node: UserTextNode): void { + if (!Number.isInteger(node.start) || !Number.isInteger(node.end) + || node.start < from || node.end <= node.start || node.end > text.length) { + throw new Error(`invalid candidate range [${node.start}, ${node.end}); expected a nonempty range from ${from} to ${text.length}`) + } + if (node.id === 'text') { + if (node.data.text !== text.slice(node.start, node.end)) throw new Error('text candidate must preserve its original substring') + } else if (node.id !== ruleId) { + throw new Error(`candidate must use rule ID "${ruleId}" or text`) + } +} + +function mergeQueries(previous: readonly Query[], added: readonly Query[]): readonly Query[] { + if (previous.length === 0) return added + const merged: Query[] = [] + const remaining = previous.values() + let old = remaining.next().value + // New queries only fill offsets not covered by retained records. + for (const query of added) { + while (old !== undefined && old.from < query.from) { + merged.push(old) + old = remaining.next().value + } + merged.push(query) + } + while (old !== undefined) { + merged.push(old) + old = remaining.next().value + } + return merged +} + +function textNode(text: string, start: number, end: number): UserTextNode<'text'> { + return { id: 'text', start, end, data: { text: text.slice(start, end) } } +} + +function alignNodes( + output: readonly UserTextNode[], previous: readonly UserTextNode[], input: readonly UserTextNode[], +): readonly UserTextNode[] { + let previousIndex = 0 + let inputIndex = 0 + let aligned: UserTextNode[] | undefined + for (const [index, node] of output.entries()) { + let inputNode = input[inputIndex] + while (inputNode && inputNode.start < node.start) inputNode = input[++inputIndex] + let previousNode = previous[previousIndex] + while (previousNode && previousNode.start < node.start) previousNode = previous[++previousIndex] + const reused = inputNode && equalNode(node, inputNode) ? inputNode + : previousNode && equalNode(node, previousNode) ? previousNode : node + if (reused !== node && !aligned) aligned = output.slice(0, index) + aligned?.push(reused) + } + const nodes = aligned ?? output + if (equalElements(nodes, previous)) return previous + return equalElements(nodes, input) ? input : nodes +} + +function equalElements(left: readonly UserTextNode[], right: readonly UserTextNode[]): boolean { + return left === right || (left.length === right.length && left.every((node, index) => node === right[index])) +} + +function equalNode(left: UserTextNode, right: UserTextNode): boolean { + return Object.is(left, right) || (left.id === right.id && left.start === right.start && left.end === right.end + && equalJson(left.data, right.data)) +} + +function equalJson(left: unknown, right: unknown): boolean { + if (Object.is(left, right)) return true + if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') return false + if (Array.isArray(left) !== Array.isArray(right)) return false + const keys = Object.keys(left) + if (keys.length !== Object.keys(right).length) return false + return keys.every(key => Object.hasOwn(right, key) + && equalJson(Reflect.get(left, key), Reflect.get(right, key))) +} diff --git a/packages/client/ui-conversation/src/client/conversation/user-text-registry.ts b/packages/client/ui-conversation/src/client/conversation/user-text-registry.ts new file mode 100644 index 0000000000..3dd1f04c61 --- /dev/null +++ b/packages/client/ui-conversation/src/client/conversation/user-text-registry.ts @@ -0,0 +1,51 @@ +/** Effect-owned user-text rules and their revision; document caches belong only to evaluator callers. */ +import type { UserTextEvaluator, UserTextRule } from '../contract/user-text.ts' +import { ConversationDefinitionRegistry } from './definition-registry.ts' +import { UserTextDocument } from './user-text-document.ts' + +/** Observable rule revision with no retained documents or document subscriptions. */ +export class UserTextRegistry extends ConversationDefinitionRegistry { + private rules: readonly UserTextRule[] = [] + private revision = 0 + + /** + * Register a uniquely named rule; invalid IDs, duplicate IDs and non-finite order throw before publication. + * @param rule - readonly synchronous candidate matcher with a nonempty ID other than the reserved `text` ID. + * @returns idempotent disposer; removal synchronously publishes a new revision. + */ + register(rule: UserTextRule): () => void { + if (rule.id.length === 0) throw new Error('user-text rule ID must not be empty') + if (rule.id === 'text') throw new Error('user-text rule "text" is reserved for original text') + if (!Number.isFinite(rule.order)) throw new Error(`user-text rule "${rule.id}" order must be finite`) + return this.registerDefinition( + rule.id, + rule, + `user-text rule "${rule.id}" is already registered`, + `uiConversation.userText.register(${JSON.stringify(rule.id)})`, + ) + } + + /** + * Create an independent document evaluator; it reads current rules at each call and never subscribes. + * @returns callback owning its document cache, released when the caller releases the callback. + */ + createEvaluator(): UserTextEvaluator { + const document = new UserTextDocument() + return input => document.evaluate(input, this.rules) + } + + /** + * Read the observable rule revision. + * @returns monotonic revision, stable until a successful registration or disposal. + */ + getSnapshot(): number { + return this.revision + } + + protected override refresh(): void { + this.rules = [...this.definitions.values()].sort((a, b) => + a.order - b.order || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) + this.revision++ + super.refresh() + } +} diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index 2b9e30d332..229aea31cc 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -1,4 +1,28 @@ -/** Browser Conversation assemble core, React adapter, shell, and input plugin. */ +/** Browser Conversation assemble core, React adapter, shell, input, and text projection plugin. */ +export type {} from './user-text/session-reference-rule.ts' + +/** Declaration-merged node payloads; IDs also identify the corresponding keyed renderer. */ +export interface UserTextDataMap { + text: { + /** Exact original substring; display transforms never change source text or UTF-16 coordinates. */ + readonly text: string + /** Optional display-only text; absence renders the original substring, while an empty string hides it. */ + readonly display?: string + } +} + +/** Caller-supplied JSON business facts and text-transform flags, never services or actions; absent flags are disabled. */ +export interface UserTextFacts { + /** Collapse whitespace runs in ordinary display text to one space. */ + readonly collapseWhitespace: boolean + /** Remove display whitespace only at the document's outer edges, without crossing business nodes. */ + readonly trimWhitespace: boolean +} + +export type { + UserTextDocumentInput, UserTextEvaluator, UserTextId, UserTextNode, UserTextRule, UserTextTransformContext, +} from './contract/user-text.ts' +export type { UserTextRegistry } from './conversation/user-text-registry.ts' export { apply, Config, inject } from './apply.ts' export type { Config as ConversationConfig } from './apply.ts' export { UiConversation } from './conversation/assembly.ts' @@ -67,7 +91,8 @@ export type { ConversationWidthControlsInputProps, ConversationWidthControlsProps, ConversationStore, ConvViewOwnerProps, ConvViewProps, EmptyWorkspaceOwnerProps, HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, InputControlOwnerProps, InputZone, - MessageImageLoader, MessageImageSource, MessageImagesOwnerProps, RenderMessageImages, UseConversation, + MessageImageLabels, MessageImageLoader, MessageImageSource, MessageImagesContentInput, MessageImagesOwnerProps, UseConversation, + UserTextInput, UserTextInjected, UserTextNodeOwnerProps, UserTextNodeProps, UseConversationViews, } from './contract/slots.ts' export type { diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index 4703ae3440..f1f708073b 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -312,6 +312,8 @@ export const zh = { 'row.input': '输入', 'row.output': '输出', 'row.inspect': '查看', + 'row.imageSize': '{width}x{height}px,{bytes} 字节', + 'row.imageSizeDownscaled': '{width}x{height}px(由 {originalWidth}x{originalHeight}px 缩小),{bytes} 字节', 'tool.title.search': '搜索', 'tool.title.read': '读取', 'tool.title.bash': '运行命令', @@ -690,6 +692,8 @@ export const en = { 'row.input': 'IN', 'row.output': 'OUT', 'row.inspect': 'Inspect', + 'row.imageSize': '{width}x{height}px, {bytes} bytes', + 'row.imageSizeDownscaled': '{width}x{height}px (downscaled from {originalWidth}x{originalHeight}px), {bytes} bytes', 'tool.title.search': 'Search', 'tool.title.read': 'Read', 'tool.title.bash': 'Bash', diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css index f5c12385d0..59d0bfdf6a 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css @@ -199,14 +199,7 @@ min-width: 0; font: var(--dsw-font-xs-13); font-family: Inter, var(--dsw-font-family); -} - -.preview { - overflow: hidden; color: var(--dsw-alias-label-primary-dimmed); - text-overflow: ellipsis; - white-space: nowrap; - word-break: break-word; } .actions { diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx index e98187bb1d..2ce7a20eef 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.tsx +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.tsx @@ -1,29 +1,24 @@ import type { Context } from '@deepseek-ai/cordis' import { useEffect, useId, useMemo, useState } from 'react' import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' -import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { PropsLocale, PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { IconCheckOutlineRegular, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular, IconCloseOutlineRegular, FileTypeIcon, fileSizeText, IconEditOutlineRegular, InlineEditor, IconQueueOutlineRegular, IconSendOutlineRegular, - IconTrashOutlineRegular, projectUserText, Tooltip, + IconTrashOutlineRegular, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { InboxState } from '@deepseek-ai/dsh-agent/types' import type { QueueAction } from '@deepseek-ai/dsh-api-session-controller/types' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' +import type { UserTextFacts } from '../index.ts' import { NS } from '../locales.ts' import css from './QueueDock.module.css' const EMPTY_QUEUE = [] as const -const QUEUE_PREVIEW_CHARS = 200 - -function previewOf(content: InboxState['next-turn'][number]['content']): string { - const flat = content - .filter(block => block.type !== 'image' && block.type !== 'file') - .map(block => (block.type === 'text' ? block.text : `[${block.type}]`)) - .join(' ').replace(/\s+/g, ' ').trim() - const chars = Array.from(flat) - return chars.length > QUEUE_PREVIEW_CHARS ? `${chars.slice(0, QUEUE_PREVIEW_CHARS).join('')}…` : flat +const QUEUE_TEXT_FACTS: Readonly> = { + collapseWhitespace: true, + trimWhitespace: true, } function textOf(content: InboxState['next-turn'][number]['content']): string | null { @@ -100,13 +95,14 @@ function QueueThumb({ attachment, loadImage, label }: { /** Full props of a dock entry: InputZone owner share + session standard kit + global seat + the locale seat. */ export type QueueDockProps = PropsRuntime<'conversation.input.dock'> & QueueDockInjected & PropsLocale<'conversation'> + & PropsRenderFactories /** * Queue strip: one item renders directly; multiple items default to a * collapsible count header; an empty queue renders nothing. Local queued submissions * show sending status and disabled actions until their Host queue rows arrive. */ -export function QueueDock({ useSession, useProjection, updateQueue, notify, loadImage, t }: QueueDockProps) { +export function QueueDock({ useSession, useProjection, updateQueue, notify, loadImage, renderFactorySlot, t }: QueueDockProps) { const inbox = useProjection('inbox') as unknown as InboxState | undefined const pendingSubmissions = useSession(s => s.pendingSubmissions) const queue = useMemo(() => { @@ -231,7 +227,10 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load ))} )} - {projectUserText(previewOf(row.content), [])} + {renderFactorySlot('conversation.user.text', { + text: row.content.filter(block => block.type === 'text').map(block => block.text).join(''), + facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, + })} )} {queueMutable &&
@@ -345,7 +344,9 @@ export function QueueDock({ useSession, useProjection, updateQueue, notify, load ))} )} - {projectUserText(submission.text, [])} + {renderFactorySlot('conversation.user.text', { + text: submission.text, facts: QUEUE_TEXT_FACTS, interactive: false, ellipsis: true, + })} {t('queue.sending')} {queueMutable &&
diff --git a/packages/client/ui-primitives/src/index.ts b/packages/client/ui-primitives/src/index.ts index 36e56125bf..cb95776fa6 100644 --- a/packages/client/ui-primitives/src/index.ts +++ b/packages/client/ui-primitives/src/index.ts @@ -59,7 +59,7 @@ export { FileTypeIcon, classifyFileType, fileExtension } from './FileTypeIcon.ts export type { CodeFileType, FileType, FileTypeIconProps, FileTypeKind, FileTypeProjectContext, } from './FileTypeIcon.tsx' -export { projectUserText, type UserTextReferences } from './user-text.tsx' +export { UserTextRun, ReferenceChip, type UserTextRunProps, type ReferenceChipProps } from './user-text.tsx' export { Tooltip } from './Tooltip.tsx' export type { TooltipSide } from './Tooltip.tsx' export { pointerModality } from './input-modality.ts' diff --git a/packages/client/ui-primitives/src/user-text.tsx b/packages/client/ui-primitives/src/user-text.tsx index 01289a4334..20d29f3b84 100644 --- a/packages/client/ui-primitives/src/user-text.tsx +++ b/packages/client/ui-primitives/src/user-text.tsx @@ -1,156 +1,56 @@ -/** - * Display projection of reference forms in sent user text (bubble and queue - * rows). The logged model text remains the single truth; this is presentation - * only. Inline references follow the consumer's wrapping policy and keep long - * labels within its width. Four decoration sources, by precedence: the wire session form - * `@[label](dsh-session:...)` folds to its label; exact session labels - * supplied by an adjacent recall decorate their bare `@label` mention; plain - * `@name` word-boundary tokens decorate by shape alone; and a plain `/name` - * token decorates only when the caller names it — a skill the host actually - * loaded for that message (ui-chat reads the step's `skill-invocation` - * injections) or the command a command-input bubble echoes — so `/123` or a - * stray `/word` stays plain text. A `/name` token is whitespace-bounded like - * the host skill gesture (`dsh-tool-skill`): it ends at whitespace or the - * text end, so slash paths (`/nfs-hg/xxx`, `/plan.md`) and punctuation-glued - * tokens (`/plan。`) stay plain even for a loaded name. - */ +/** Inline text and reference presentation; business rules supply resolved JSON data and actions. */ import type { ReactNode } from 'react' import clsx from 'clsx' -import { ReferenceIconRegular } from './ReferenceIcon.tsx' +import { ReferenceIconRegular, type ReferenceIconKind } from './ReferenceIcon.tsx' import css from './user-text.module.css' import markdownCss from './markdown/MarkdownText.module.css' -/** The wire form a session chip serializes to; label is the display text. */ -const SESSION_WIRE_RE = /@\[([^\]\n]+)\]\(dsh-session:[^)\s]+\)/gu - -/** Sentence punctuation a bare `@name` token may carry without being part of the reference. */ -const TRAILING_PUNCTUATION_RE = /[.,;:!?,。;:!?]+$/u - -interface DecorationRange { - readonly start: number - readonly end: number - /** Matched source text (hover title). */ - readonly label: string - readonly kind: 'session' | 'plain' - /** Pre-resolved display text (wire folds); derived from label when absent. */ - readonly display?: string -} - -/** Optional navigation supplied by consumers that can preview references. */ -export interface UserTextReferences { - /** Open a file path decoded from an `@` mention. */ - openFile: (path: string) => void - /** Open the source of a skill loaded for this message. */ - openSkill: (name: string) => void +/** Plain text follows the wrapping and typography of its host. */ +export interface UserTextRunProps { + readonly text: string } /** - * Split one sent text into inline plain runs and reference chips. - * @param text - the logged model text of the message or queue row. - * @param sessionLabels - exact session mention labels associated by an adjacent recall. - * @param slashNames - names a `/name` token may decorate as: the skills the - * host loaded for this message, or the command a command bubble echoes - * (unsent queue rows pass none). - * @param slashKind - the chip kind those tokens render as. - * @param references - optional file and skill preview actions; session and command tokens stay labels. - * @returns inline nodes covering the whole text. + * Render an uninterpreted inline text run. + * @param props - text retained verbatim from the caller's document. + * @returns one inline run without Markdown or reference recognition. */ -export function projectUserText( - text: string, - sessionLabels: readonly string[], - slashNames: readonly string[] = [], - slashKind: 'skill' | 'command' = 'skill', - references?: UserTextReferences, -): ReactNode { - const ranges: DecorationRange[] = [] - SESSION_WIRE_RE.lastIndex = 0 - let wire: RegExpExecArray | null - while ((wire = SESSION_WIRE_RE.exec(text)) !== null) { - ranges.push({ - start: wire.index, - end: wire.index + wire[0].length, - label: wire[0], - kind: 'session', - display: wire[1] as string, // non-optional capture in SESSION_WIRE_RE - }) - } - for (const rawLabel of [...new Set(sessionLabels)].sort((a, b) => b.length - a.length)) { - const label = `@${rawLabel}` - let start = text.indexOf(label) - while (start >= 0) { - ranges.push({ start, end: start + label.length, label, kind: 'session' }) - start = text.indexOf(label, start + label.length) - } - } - // A `/` token ends at whitespace or the text end like the host skill - // gesture; only `@` tokens shed sentence punctuation below. - const re = /(^|\s)(\/[\w-]+(?=\s|$)|@"[^"\n]+"|@[^\s]+)/gu - let m: RegExpExecArray | null - while ((m = re.exec(text)) !== null) { - const tokenStart = m.index + (m[1] as string).length // (^|\s) captures '' at line start - const rawLabel = m[2] as string // non-optional alternation capture - const label = rawLabel.startsWith('@"') - ? rawLabel - : rawLabel.replace(TRAILING_PUNCTUATION_RE, '') - if (label.length <= 1) continue - if (label.startsWith('/') && !slashNames.includes(label.slice(1))) continue - ranges.push({ start: tokenStart, end: tokenStart + label.length, label, kind: 'plain' }) - } - const rankOf = (range: DecorationRange): number => range.kind === 'session' ? 0 : 1 - ranges.sort((a, b) => a.start - b.start || rankOf(a) - rankOf(b) || b.end - a.end) - const parts: ReactNode[] = [] - let cursor = 0 - const pushPlain = (from: number, to: number): void => { - parts.push({text.slice(from, to)}) - } - for (const range of ranges) { - if (range.start < cursor) continue - const { start: tokenStart, end, label, kind } = range - if (tokenStart > cursor) pushPlain(cursor, tokenStart) - const referenceKind = kind === 'session' - ? 'session' - : label.startsWith('@') - ? label.replace(/^@"|"$/gu, '').endsWith('/') ? 'folder' : 'file' - : undefined - const displayLabel = range.display - ?? (referenceKind === undefined - ? label - : referenceKind === 'session' - ? label.slice(1) - : label.slice(1).replace(/^"|"$/gu, '').split(/[\\/]/u).filter(Boolean).at(-1) ?? label.slice(1)) - const contents = <> - {referenceKind !== undefined && ( - - )} - {displayLabel} - - const open = references === undefined ? undefined - : referenceKind === 'file' - ? () => { references.openFile(label.slice(1).replace(/^"|"$/gu, '')) } - : referenceKind === undefined && slashKind === 'skill' - ? () => { references.openSkill(label.slice(1)) } - : undefined - const className = clsx(css.refChip, referenceKind === undefined && css.slashChip) - parts.push(open === undefined - ? - {contents} - - : ) - cursor = end - } - if (parts.length === 0) return {text} - if (cursor < text.length) pushPlain(cursor, text.length) - return <>{parts} +export function UserTextRun({ text }: UserTextRunProps): ReactNode { + return {text} +} + +/** Presentation selected by a reference renderer, independent of its matching grammar. */ +export interface ReferenceChipProps { + readonly appearance: ReferenceIconKind | 'skill' | 'command' + readonly label: string + readonly title: string + /** Absent for display-only references and previews. */ + readonly onActivate?: () => void +} + +/** + * Render a reference label or its explicitly supplied activation action. + * Text selection and repeated pointer clicks do not activate the reference. + * @param props - resolved visual fields and optional action from the owning renderer. + * @returns an inline label, or a keyboard-accessible button when activation is supplied. + */ +export function ReferenceChip({ appearance, label, title, onActivate }: ReferenceChipProps): ReactNode { + const slash = appearance === 'skill' || appearance === 'command' + const contents = <> + {!slash && } + {label} + + const className = clsx(css.refChip, slash && css.slashChip) + return onActivate === undefined + ? {contents} + : } diff --git a/packages/client/ui-primitives/tests/terminal-block-styles.client.spec.ts b/packages/client/ui-primitives/tests/terminal-block-styles.client.spec.ts new file mode 100644 index 0000000000..0a809a7fa4 --- /dev/null +++ b/packages/client/ui-primitives/tests/terminal-block-styles.client.spec.ts @@ -0,0 +1,17 @@ +/** Terminal status positioning relative to the command's first visual line. */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/TerminalBlock.module.css', import.meta.url)), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, ' ') + +it('centers the status dot on one command line rather than the wrapped prompt height', () => { + const state = /\.runState\s*\{([^{}]*)\}/.exec(css)?.[1] + const prompt = /\.promptLine\s*\{([^{}]*)\}/.exec(css)?.[1] + expect(state).toBeDefined() + expect(prompt).toBeDefined() + expect(state).toContain('top: calc(var(--dsl-terminal-line-height) / 2)') + expect(state).toContain('transform: translateY(-50%)') + expect(prompt).toContain('line-height: var(--dsl-terminal-line-height)') +}) diff --git a/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx index 432a20fde2..b801dd6e91 100644 --- a/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx @@ -89,6 +89,42 @@ describe('TerminalBlock prompt label', () => { }) describe('TerminalBlock states', () => { + it.each([ + { output: undefined, running: false, exitCode: undefined }, + { output: 'launch acknowledgement', running: false, exitCode: 7, signal: 'SIGTERM' }, + { output: 'launch acknowledgement', running: false, exitCode: 0 }, + { output: '', running: false, exitCode: 0 }, + ])('background suppresses execution presentation for %j', (execution) => { + const view = render() + expect(promptRows(view.container)).toEqual(['appworker --watch', '$printf ready']) + expect(runStateOf(view.container)).toEqual({ state: null, label: undefined }) + expect(outputLines(view.container)).toEqual([]) + expect(view.queryByText('launch acknowledgement')).toBeNull() + expect(view.queryByText('无输出')).toBeNull() + expect(view.queryByText('信号 SIGTERM')).toBeNull() + expect(view.queryByRole('button')).toBeNull() + expect(view.container.firstElementChild?.hasAttribute('data-running')).toBe(false) + expect(view.container.firstElementChild?.hasAttribute('data-body')).toBe(false) + }) + + it('keeps command and prompt DOM when a background launch returns', () => { + const view = render() + const command = view.container.querySelector('[data-command-text]') + expect(runStateOf(view.container).state).toBe('ongoing') + view.rerender() + expect(view.container.querySelector('[data-command-text]')).toBe(command) + expect(runStateOf(view.container)).toEqual({ state: null, label: undefined }) + expect(view.queryByText('无输出')).toBeNull() + expect(view.queryByRole('button')).toBeNull() + }) + + it('keeps an explicit copyText override available in background mode', () => { + const view = render() + expect(view.getByRole('button', { name: '复制' })).toBeTruthy() + expect(view.queryByText('无输出')).toBeNull() + expect(runStateOf(view.container)).toEqual({ state: null, label: undefined }) + }) + it('running with no output shows the command line only: no output box, no placeholder, no copy', () => { const view = render() expect(view.getByText('sleep 5')).toBeTruthy() diff --git a/packages/client/ui-primitives/tsdown.config.ts b/packages/client/ui-primitives/tsdown.config.ts index 7f6262ae9f..a6264e0b21 100644 --- a/packages/client/ui-primitives/tsdown.config.ts +++ b/packages/client/ui-primitives/tsdown.config.ts @@ -1,6 +1,6 @@ import { staticLinked } from '../tsdown.client.ts' export default staticLinked( - '@deepseek-ai/dsh-client-ui-primitives', + import.meta.dirname, ['lib/types/index.js'], ) diff --git a/packages/client/ui-reference/README.i18n.yaml b/packages/client/ui-reference/README.i18n.yaml index e96368df0e..a6706a5349 100644 --- a/packages/client/ui-reference/README.i18n.yaml +++ b/packages/client/ui-reference/README.i18n.yaml @@ -30,8 +30,8 @@ en: 6c77da1e946f72e1 zh: b7b8e1e1d4f5a102 /deepseek-ai-dsh-client-ui-reference/understand-the-implementation/serialization: - en: dce929ccd4f0e349 - zh: e68bc0f79e184057 + en: c3fe8963ed80e403 + zh: ba3e057cd63e9189 /deepseek-ai-dsh-client-ui-reference/further-exploration: en: 157b1bcf84b5c11b zh: 6b7e4f3326b19036 diff --git a/packages/client/ui-reference/README.md b/packages/client/ui-reference/README.md index b39bf52141..50a711758b 100644 --- a/packages/client/ui-reference/README.md +++ b/packages/client/ui-reference/README.md @@ -59,6 +59,8 @@ Candidate requests require an existing retained Client Session and share one tem File picks preserve the natural text defined by the shared `@path` grammar as the hidden serialized and clipboard form. Session picks use the canonical `@[label](dsh-session:…)` mention; serialization never reconstructs identity from the visible title. +The plugin also registers file and folder matchers with [UserText](../ui-conversation/README.md#sent-user-text) and owns their `conversation.user.text.node` renderers. Each query returns the next complete reference at an original-text offset without file discovery; the shared evaluator resolves overlaps by source position. Interactive file nodes receive a Session-bound `openFile` injection; navigation failures keep the reference visible and offer a local retry/close dialog. Folder nodes remain labels. + ----- diff --git a/packages/client/ui-reference/README.zh.md b/packages/client/ui-reference/README.zh.md index b291958195..0ccf954688 100644 --- a/packages/client/ui-reference/README.zh.md +++ b/packages/client/ui-reference/README.zh.md @@ -59,6 +59,8 @@ Web 用户需要从同一个 `@` 补全菜单提及文件、文件夹或会话 文件选择把共享 `@path` 语法所定义的自然文本保留为隐藏的序列化与剪贴板形式。会话选择使用规范的 `@[label](dsh-session:…)` mention;序列化永远不会根据可见标题重建身份。 +插件还向 [UserText](../ui-conversation/README.zh.md#sent-user-text) 注册文件和目录匹配器,并拥有它们的 `conversation.user.text.node` renderer。每次查询返回原文偏移之后的下一个完整引用,不执行文件发现;共享计算器按原文位置裁定重叠。可交互的文件节点通过 Injection 接收绑定 Session 的 `openFile`;导航失败时保留引用,提供局部重试/关闭对话框。目录节点仍为标签。 + ----- diff --git a/packages/client/ui-reference/locale/en.json b/packages/client/ui-reference/locale/en.json new file mode 100644 index 0000000000..983a68eb3c --- /dev/null +++ b/packages/client/ui-reference/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-reference" + } +} diff --git a/packages/client/ui-reference/locale/zh.json b/packages/client/ui-reference/locale/zh.json new file mode 100644 index 0000000000..c42cc948b1 --- /dev/null +++ b/packages/client/ui-reference/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文件与会话引用界面", + "description": "通过 @ 在输入框中引用文件或其他会话。" + } +} diff --git a/packages/client/ui-reference/package.json b/packages/client/ui-reference/package.json index 6c9a63bffd..10b52588aa 100644 --- a/packages/client/ui-reference/package.json +++ b/packages/client/ui-reference/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -32,6 +33,8 @@ "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-connection", "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-input-trigger", "@deepseek-ai/dsh-client-ui-sidebar-right" ], @@ -52,8 +55,11 @@ "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "react": "^18.2.0", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-file-reference": "workspace:*", "@deepseek-ai/dsh-session-reference": "workspace:*", @@ -63,6 +69,7 @@ "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-reference/src/client/FileReference.tsx b/packages/client/ui-reference/src/client/FileReference.tsx new file mode 100644 index 0000000000..7e0e4ffa52 --- /dev/null +++ b/packages/client/ui-reference/src/client/FileReference.tsx @@ -0,0 +1,62 @@ +/** File navigation feedback belongs to the individual inline reference that requested it. */ +import { useState } from 'react' +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { InjectFace, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import { Button, Modal, ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives' +import type { NS } from './locales.ts' +import type {} from './user-text-rules.ts' + +/** Session-authorized synchronous navigation; document reading belongs to the preview host. */ +export interface FileReferenceInjected { + /** + * Open or reveal a file in the current Sidebar using the originating Session's authority. + * @param path - decoded path from the reference. + * @throws if navigation fails; the reference keeps a local retry/close dialog. + */ + readonly openFile: (path: string) => void +} + +type FileReferenceProps = UserTextNodeProps<'file'> & InjectFace & PropsLocale + +/** + * Render a file chip and contain synchronous navigation failures without hiding the reference. + * @param props - JSON node, interaction policy, Session-authorized navigation, and locale seat. + * @returns an inline chip and, after a navigation failure, its body-portaled dialog. + */ +export function FileReference({ node, raw, interactive, openFile, t }: FileReferenceProps) { + const [failedPath, setFailedPath] = useState(null) + const { path, label } = node.data + const close = () => { setFailedPath(null) } + const open = () => { + try { + openFile(path) + } catch { + setFailedPath(path) + return + } + setFailedPath(null) + } + return <> + + {interactive && failedPath === path && + + + } + />} + +} + +/** + * Render a directory as a label, even when the containing text permits file navigation. + * @param props - resolved directory data and the original reference spelling. + * @returns an inline non-interactive chip. + */ +export function FolderReference({ node, raw }: UserTextNodeProps<'folder'>) { + return +} diff --git a/packages/client/ui-reference/src/client/index.ts b/packages/client/ui-reference/src/client/index.ts index 6204478f75..6bc52b59d7 100644 --- a/packages/client/ui-reference/src/client/index.ts +++ b/packages/client/ui-reference/src/client/index.ts @@ -18,9 +18,14 @@ import type {} from '@deepseek-ai/dsh-api-remotes/client' // Type-only: pulls the locale plugin's Context merge (ctx.locale). import type {} from '@deepseek-ai/dsh-client-locale/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client' import { relativeTime } from '@deepseek-ai/dsh-client-ui-primitives' +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { FileReference, FolderReference, type FileReferenceInjected } from './FileReference.tsx' +import { fileReferenceRule, folderReferenceRule } from './user-text-rules.ts' +export type {} from './user-text-rules.ts' import type { ClientSessionContext, InputTriggerCrumb, InputTriggerServiceContract, InputTriggerSource, } from '@deepseek-ai/dsh-client-ui-input-trigger/client' @@ -40,17 +45,31 @@ declare module '@deepseek-ai/dsh-api-session-controller/client' { /** Required services: the trigger registry, the Remote namespaces, and the copy. */ export const inject = [ 'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences', - 'remote.sessionReferenceResolver', 'sidebarRight', + 'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation', ] /** - * Register the combined `@file` / `@session` source. + * Register the combined `@file` / `@session` source and independent file/folder text providers. * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-reference: dictionaries') const t = ctx.locale.bind(NS) const sessions = ctx.get('sessions') as ISessions + ctx.uiConversation.userText.register(fileReferenceRule) + ctx.uiConversation.userText.register(folderReferenceRule) + ctx.slots.inject('conversation.user.text.node', function* () { + yield ctx.slots.register({ + name: 'conversation.user.text.node', key: 'file', priority: 100, locale: NS, + inject: (sessionId: UserTextNodeProps<'file'>['sessionId']): FileReferenceInjected => ({ + openFile: (path) => { + const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd + ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path)) + }, + }), + }, FileReference) + yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'folder', priority: 100 }, FolderReference) + }) const source: InputTriggerSource = { trigger: '@', name: 'reference', diff --git a/packages/client/ui-reference/src/client/locales.ts b/packages/client/ui-reference/src/client/locales.ts index 7d185550cc..2d48030d5e 100644 --- a/packages/client/ui-reference/src/client/locales.ts +++ b/packages/client/ui-reference/src/client/locales.ts @@ -1,4 +1,4 @@ -/** `reference` namespace dictionaries for the unified `@` source. */ +/** `reference` dictionaries for the unified `@` source and inline file navigation. */ import type {} from '@deepseek-ai/dsh-client-ui-slots' @@ -18,6 +18,10 @@ export const zh = { 'section.sessions': '对话', 'candidate.noCwd': '(无工作目录)', 'crumb.root': '工作区', + 'fileOpen.title': '无法打开文件', + 'fileOpen.failed': '无法打开“{path}”,请重试或关闭此提示', + 'fileOpen.close': '关闭', + 'fileOpen.retry': '重试', 'time.now': '刚刚', 'time.minutes': '{n}分钟', 'time.hours': '{n}小时', @@ -31,7 +35,7 @@ export type ReferenceKey = keyof typeof zh declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { - /** The unified `@` reference menu's copy. */ + /** Reference menu and per-file navigation feedback. */ reference: ReferenceKey } } @@ -43,6 +47,10 @@ export const en = { 'section.sessions': 'Sessions', 'candidate.noCwd': '(no cwd)', 'crumb.root': 'Workspace', + 'fileOpen.title': 'Couldn’t open file', + 'fileOpen.failed': 'Couldn’t open “{path}”. Try again or close this message.', + 'fileOpen.close': 'Close', + 'fileOpen.retry': 'Retry', 'time.now': 'now', 'time.minutes': '{n}min', 'time.hours': '{n}h', diff --git a/packages/client/ui-reference/src/client/user-text-rules.ts b/packages/client/ui-reference/src/client/user-text-rules.ts new file mode 100644 index 0000000000..b227660c86 --- /dev/null +++ b/packages/client/ui-reference/src/client/user-text-rules.ts @@ -0,0 +1,49 @@ +/** Forward file and folder recognition in original text, without Facts or discovery. */ +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' + +interface PathReferenceData { + readonly path: string + readonly label: string +} + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + file: PathReferenceData + folder: PathReferenceData + } +} + +function nextPath(text: string, from: number, folder: boolean) { + const tokens = /(? = { + id: 'file', + order: 30, + match(text, from) { + const candidate = nextPath(text, from, false) + return candidate === undefined ? undefined : { id: 'file', ...candidate } + }, +} + +/** Return the nearest trailing-slash directory using the file-reference grammar. */ +export const folderReferenceRule: UserTextRule<'folder'> = { + id: 'folder', + order: 30, + match(text, from) { + const candidate = nextPath(text, from, true) + return candidate === undefined ? undefined : { id: 'folder', ...candidate } + }, +} diff --git a/packages/client/ui-reference/tests/browser-plugin.client.spec.ts b/packages/client/ui-reference/tests/browser-plugin.client.spec.ts index b0cb5ebeef..1ebd8d0f72 100644 --- a/packages/client/ui-reference/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-reference/tests/browser-plugin.client.spec.ts @@ -6,6 +6,10 @@ import { Context, Service } from '@deepseek-ai/cordis' import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import { UiConversation } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/assembly.ts' +import { FileReference, FolderReference, type FileReferenceInjected } from '../src/client/FileReference.tsx' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { RemoteError, TestSessions } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionFixture } from '@deepseek-ai/dsh-client-test-runtime' @@ -56,6 +60,19 @@ function request( } } +function TextSlotDeclaration(_props: PropsRenderSlots<'conversation.user.text.node'>): null { + return null +} + +async function installTextSlots(ctx: Context, sessions: TestSessions): Promise { + new UiConversation(ctx, sessions) + await ctx.plugin(SlotRegistry).await() + ctx.slots.register({ + name: 'root', + children: { 'conversation.user.text.node': { kind: 'keyed', scope: 'session' } }, + }, TextSlotDeclaration) +} + async function bench( files: RemoteLookup = vi.fn(() => Promise.resolve({ ok: true as const, @@ -114,6 +131,7 @@ async function bench( for (const [id, summary] of Object.entries(listed)) { if (id !== session.sessionId) await sessionStore.add({ id, summary }) } + await installTextSlots(ctx, sessionStore) const owner = sessionStore.retainFor(ctx, session.sessionId) const fiber = ctx.plugin({ inject: [...inject], apply }) await fiber.await() @@ -125,11 +143,12 @@ describe('apply', () => { it('declares its services and releases the @ reference registration on disposal', async () => { expect(inject).toEqual([ 'inputTriggers', 'locale', 'sessions', 'remote', 'remote.fileReferences', - 'remote.sessionReferenceResolver', 'sidebarRight', + 'remote.sessionReferenceResolver', 'sidebarRight', 'slots', 'uiConversation', ]) const { fiber } = await bench() let registered: InputTriggerSource | undefined const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) ctx.provide('sidebarRight', { openResource: vi.fn() }) ctx.provide('inputTriggers', { registerSource(source: InputTriggerSource) { @@ -148,12 +167,23 @@ describe('apply', () => { ctx.provide('remote.fileReferences', { list: () => Promise.resolve({ ok: true, value: [] }) }) ctx.provide('remote.sessionReferenceResolver', { candidates: () => Promise.resolve({ ok: true, value: [] }) }) ctx.provide('locale', new LocaleRuntime(ctx)) - ctx.provide('sessions', { list: { getSnapshot: () => ({ byId: {} }) } }) + const sessions = new TestSessions(async (action) => { await action() }, ctx) + onTestFinished(() => sessions.disposeScopes()) + ctx.provide('sessions', sessions) + await installTextSlots(ctx, sessions) const ownFiber = ctx.plugin({ inject: [...inject], apply }) await ownFiber.await() expect(registered).toMatchObject({ trigger: '@', name: 'reference', showGroupTitle: false }) + expect(ctx.uiConversation.userText.entries().map(rule => rule.id)).toEqual(['file', 'folder']) + expect(ctx.slots.entries('conversation.user.text.node')).toMatchObject([ + { options: { key: 'file' }, component: FileReference }, + { options: { key: 'folder' }, component: FolderReference }, + ]) + expect(ctx.slots.entries('conversation.user.text.node')[0]?.inject).toBeTypeOf('function') await ownFiber.dispose() expect(registered).toBeUndefined() + expect(ctx.uiConversation.userText.entries()).toHaveLength(0) + expect(ctx.slots.entries('conversation.user.text.node')).toHaveLength(0) await fiber.dispose() }) @@ -648,6 +678,19 @@ describe('pick and codec', () => { }) describe('reference preview', () => { + it('binds each inline file action to its originating Session', async () => { + const { ctx } = await bench() + const entry = ctx.slots.entries('conversation.user.text.node').find(candidate => candidate.options.key === 'file')! + const factory = entry.inject as NonNullable & ((id: SessionId) => FileReferenceInjected) + const openResource = vi.spyOn(ctx.sidebarRight, 'openResource') + factory(session.sessionId).openFile('docs/a b.md') + factory(sid('other')).openFile('notes.md') + expect(openResource.mock.calls).toEqual([ + ['dsh-resource://file/session/target/docs/a%20b.md'], + ['dsh-resource://file/session/other/notes.md'], + ]) + }) + it('opens plain and quoted file references without treating folders or sessions as files', async () => { const { ctx, source, fiber } = await bench() const openResource = vi.spyOn(ctx.sidebarRight, 'openResource') diff --git a/packages/client/ui-reference/tests/file-reference.client.spec.tsx b/packages/client/ui-reference/tests/file-reference.client.spec.tsx new file mode 100644 index 0000000000..b3e6eba6f3 --- /dev/null +++ b/packages/client/ui-reference/tests/file-reference.client.spec.tsx @@ -0,0 +1,57 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render } from '@testing-library/react' +import type { ComponentProps } from 'react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { FileReference, FolderReference } from '../src/client/FileReference.tsx' +import { en } from '../src/client/locales.ts' + +afterEach(cleanup) + +type Props = ComponentProps + +function props(openFile: Props['openFile']): Props { + return { + node: { id: 'file', start: 0, end: 14, data: { path: 'docs/a b.md', label: 'a b.md' } }, + raw: '@"docs/a b.md"', interactive: true, openFile, t: makeTranslate(en), + } as Props +} + +describe('FileReference', () => { + it('opens the decoded path and leaves summaries and folders non-interactive', () => { + const openFile = vi.fn() + const input = props(openFile) + const view = render() + fireEvent.click(view.getByRole('button', { name: 'a b.md' })) + expect(openFile).toHaveBeenCalledWith('docs/a b.md') + expect(view.queryByRole('dialog')).toBeNull() + view.rerender() + expect(view.getByText('a b.md').getAttribute('title')).toBe('@"docs/a b.md"') + expect(view.queryByRole('button')).toBeNull() + view.rerender() + expect(view.getByText('docs').getAttribute('title')).toBe('@docs/') + expect(view.queryByRole('button')).toBeNull() + }) + + it('keeps a navigation failure local and retries or closes without losing the reference', () => { + const openFile = vi.fn() + .mockImplementationOnce(() => { throw new Error('unavailable') }) + .mockImplementationOnce(() => { throw new Error('still unavailable') }) + .mockImplementationOnce(() => {}) + .mockImplementationOnce(() => { throw new Error('unavailable again') }) + const view = render() + fireEvent.click(view.getByRole('button', { name: 'a b.md' })) + expect(view.getByRole('dialog', { name: 'Couldn’t open file' }).textContent).toContain('Couldn’t open “docs/a b.md”') + fireEvent.click(view.getByRole('button', { name: 'Retry' })) + expect(view.getByRole('dialog')).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: 'Retry' })) + expect(view.queryByRole('dialog')).toBeNull() + expect(openFile.mock.calls).toEqual([['docs/a b.md'], ['docs/a b.md'], ['docs/a b.md']]) + fireEvent.click(view.getByRole('button', { name: 'a b.md' })) + fireEvent.click(view.getAllByRole('button', { name: 'Close' }).at(-1)!) + expect(view.queryByRole('dialog')).toBeNull() + expect(view.getByRole('button', { name: 'a b.md' })).toBeTruthy() + }) +}) diff --git a/packages/client/ui-reference/tests/user-text-rules.client.spec.ts b/packages/client/ui-reference/tests/user-text-rules.client.spec.ts new file mode 100644 index 0000000000..49c0af04ab --- /dev/null +++ b/packages/client/ui-reference/tests/user-text-rules.client.spec.ts @@ -0,0 +1,76 @@ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/user-text-registry.ts' +import { fileReferenceRule, folderReferenceRule } from '../src/client/user-text-rules.ts' + +function setup(rules: readonly UserTextRule[] = [folderReferenceRule, fileReferenceRule]) { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const registry = new UserTextRegistry(ctx) + for (const rule of rules) registry.register(rule) + return registry.createEvaluator() +} + +describe('fileReferenceRule and folderReferenceRule', () => { + it('reads no facts and reuses the entire result across fact updates', () => { + const read = vi.fn() + const file = vi.fn['match']>((text, from, context) => fileReferenceRule.match(text, from, { + read: (key) => { read(key); return context.read(key) }, + })) + const folder = vi.fn['match']>((text, from, context) => folderReferenceRule.match(text, from, { + read: (key) => { read(key); return context.read(key) }, + })) + const evaluate = setup([{ ...fileReferenceRule, match: file }, { ...folderReferenceRule, match: folder }]) + const text = '@src/a.ts @docs/' + const before = evaluate({ text, facts: {} }) + expect(before.filter(node => node.id !== 'text').map(node => node.id)).toEqual(['file', 'folder']) + expect(evaluate({ text, facts: { sessionLabels: ['new label'] } })).toBe(before) + expect(read).not.toHaveBeenCalled() + expect(file.mock.calls.map(([, from]) => from)).toEqual([0, text.indexOf(' ')]) + expect(folder.mock.calls.map(([, from]) => from)).toEqual([0, text.length]) + }) + + it('separates ordinary files from directories and decodes quoted paths', () => { + const evaluate = setup() + const text = '@src/deep/file.txt 与 @dir/ 与 @"a b.md" 与 @"dir a/" 与 @C:\\src\\a.ts' + const input = Object.freeze({ text, facts: Object.freeze({}) }) + const nodes = evaluate(input) + expect(nodes.filter(node => node.id === 'file').map(node => ({ raw: text.slice(node.start, node.end), data: node.data }))).toEqual([ + { raw: '@src/deep/file.txt', data: { path: 'src/deep/file.txt', label: 'file.txt' } }, + { raw: '@"a b.md"', data: { path: 'a b.md', label: 'a b.md' } }, + { raw: '@C:\\src\\a.ts', data: { path: 'C:\\src\\a.ts', label: 'a.ts' } }, + ]) + expect(nodes.filter(node => node.id === 'folder').map(node => ({ raw: text.slice(node.start, node.end), data: node.data }))).toEqual([ + { raw: '@dir/', data: { path: 'dir/', label: 'dir' } }, + { raw: '@"dir a/"', data: { path: 'dir a/', label: 'dir a' } }, + ]) + expect(JSON.parse(JSON.stringify(nodes))).toEqual(nodes) + }) + + it('leaves trailing sentence punctuation outside ranges without stripping quoted filename punctuation', () => { + const evaluate = setup() + const text = '@a.ts,。;:!? @b.md.,;:!? @"a!.md", @dir/。' + const nodes = evaluate({ text, facts: {} }) + expect(nodes.filter(node => node.id === 'file').map(node => ({ raw: text.slice(node.start, node.end), data: node.data }))) + .toEqual([ + { raw: '@a.ts', data: { path: 'a.ts', label: 'a.ts' } }, + { raw: '@b.md', data: { path: 'b.md', label: 'b.md' } }, + { raw: '@"a!.md"', data: { path: 'a!.md', label: 'a!.md' } }, + ]) + expect(nodes.filter(node => node.id === 'folder').map(node => text.slice(node.start, node.end))).toEqual(['@dir/']) + }) + + it('keeps root-directory display fallback and requires a token boundary', () => { + const evaluate = setup() + const text = '@"/" @/ mail@host prefix@a.ts @。 @' + const nodes = evaluate({ text, facts: {} }) + expect(nodes.filter(node => node.id === 'folder').map(node => node.data)).toEqual([ + { path: '/', label: '"/"' }, { path: '/', label: '/' }, + ]) + expect(nodes.filter(node => node.id === 'file')).toEqual([]) + expect(evaluate({ text: '@name', facts: {} })).toEqual([ + { id: 'file', start: 0, end: 5, data: { path: 'name', label: 'name' } }, + ]) + }) +}) diff --git a/packages/client/ui-reference/tsconfig.json b/packages/client/ui-reference/tsconfig.json index 88de84671c..5c126676ae 100644 --- a/packages/client/ui-reference/tsconfig.json +++ b/packages/client/ui-reference/tsconfig.json @@ -41,6 +41,12 @@ { "path": "../ui-primitives" }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, + { + "path": "../ui-renderer" + }, { "path": "../ui-slots" }, diff --git a/packages/client/ui-reference/tsdown.config.ts b/packages/client/ui-reference/tsdown.config.ts index f306d4db44..7aa03cebc1 100644 --- a/packages/client/ui-reference/tsdown.config.ts +++ b/packages/client/ui-reference/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-reference', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-renderer/locale/en.json b/packages/client/ui-renderer/locale/en.json new file mode 100644 index 0000000000..9b397064bb --- /dev/null +++ b/packages/client/ui-renderer/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-renderer" + } +} diff --git a/packages/client/ui-renderer/locale/zh.json b/packages/client/ui-renderer/locale/zh.json new file mode 100644 index 0000000000..8616d95117 --- /dev/null +++ b/packages/client/ui-renderer/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "界面渲染", + "description": "将各插件提供的界面组件组装到应用中。" + } +} diff --git a/packages/client/ui-renderer/package.json b/packages/client/ui-renderer/package.json index 9831527fa9..12ce753757 100644 --- a/packages/client/ui-renderer/package.json +++ b/packages/client/ui-renderer/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -43,14 +44,13 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "@types/use-sync-external-store": "^1.5.0", "react": "^18.2.0", "react-dom": "^18.2.0", "use-sync-external-store": "1.6.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-renderer/src/client/scoped-slots.tsx b/packages/client/ui-renderer/src/client/scoped-slots.tsx index 24bb7f6bd3..89ab67fb19 100644 --- a/packages/client/ui-renderer/src/client/scoped-slots.tsx +++ b/packages/client/ui-renderer/src/client/scoped-slots.tsx @@ -10,7 +10,7 @@ import { SlotOwnershipError, StaleAuthorizationError, standardHookPropName, type ChainRenderOpts, type HostObservable, type KeyedStandardSource, type LocaleFace, type RenderFactorySlot, type RenderOpts, type ScopedStandardSourceBinding, type SessionAreaProps, type SessionProviderComponent, type SlotRenderer, - type SlotRendererHost, type SlotScope, type SlotScopeAdapter, type StandardSourceBinding, + type SlotEntryDef, type SlotRendererHost, type SlotScope, type SlotScopeAdapter, type SlotSpec, type StandardSourceBinding, type StoredEntry, type StoredFactory, type Translate, } from '@deepseek-ai/dsh-client-ui-slots' import { @@ -21,6 +21,7 @@ import { import { SlotAssemblyError } from './errors.ts' type InjectedProps = Record +type SlotAnchorTag = 'div' | 'span' type SlotHookFactory = (standard: InjectedProps, hookContext: unknown) => unknown type SlotHookFactories = Readonly> @@ -79,7 +80,7 @@ function boundRenderSlot(host: SlotRendererHost, entry: StoredEntry): RenderSlot if (declared.kind === 'chain') { throw new SlotOwnershipError(`slot '${key}' is declared 'chain' — use renderSlotChain`) } - return + return } renderSlotCache.set(entry, binding) } @@ -108,7 +109,7 @@ function boundRenderSlotChain(host: SlotRendererHost, entry: StoredEntry): Rende if (declared.kind !== 'chain') { throw new SlotOwnershipError(`slot '${key}' is declared '${declared.kind}', not 'chain' — use renderSlot`) } - return + return } renderSlotChainCache.set(entry, binding) } @@ -128,7 +129,7 @@ function boundFactoryRenderSlot(host: SlotRendererHost, definition: StoredFactor const declared = definition.children?.[key] if (declared === undefined) throw new SlotOwnershipError(`slot '${key}' is not declared by this Factory`) if (declared.kind === 'chain') throw new SlotOwnershipError(`slot '${key}' is declared 'chain' — use renderSlotChain`) - return + return } factoryRenderSlotCache.set(definition, binding) return binding @@ -146,7 +147,7 @@ function boundFactoryRenderSlotChain(host: SlotRendererHost, definition: StoredF if (declared.kind !== 'chain') { throw new SlotOwnershipError(`slot '${key}' is declared '${declared.kind}', not 'chain' — use renderSlot`) } - return + return } factoryRenderSlotChainCache.set(definition, binding) return binding @@ -402,7 +403,7 @@ function sessionGenerationKeyOf(binding: ScopedStandardSourceBinding): number { * the outlet then owns the crash face). */ class SlotErrorBoundary extends Component< - { slotKey: string; onEntryError: (error: unknown) => void; children: ReactNode }, { failed: boolean } + { slotKey: string; anchor?: SlotAnchorTag; onEntryError: (error: unknown) => void; children: ReactNode }, { failed: boolean } > { override state = { failed: false } static getDerivedStateFromError(error: unknown): { failed: boolean } { @@ -414,7 +415,8 @@ class SlotErrorBoundary extends Component< this.props.onEntryError(error) } override render(): ReactNode { - if (this.state.failed) return
+ const Anchor = this.props.anchor ?? 'div' + if (this.state.failed) return return this.props.children } } @@ -1024,8 +1026,9 @@ function FactoryOutlet({ name, inputProps, slots: selected = EMPTY_FACTORY_SELEC ) } -function StrictSessionEntry({ slotKey, entry, ownerProps, slotInjected, hookContext, hasHookContext, onEntryError }: { +function StrictSessionEntry({ slotKey, anchor, entry, ownerProps, slotInjected, hookContext, hasHookContext, onEntryError }: { slotKey: string + anchor: SlotAnchorTag entry: StoredEntry ownerProps: object slotInjected: BoundSlotInject @@ -1041,7 +1044,7 @@ function StrictSessionEntry({ slotKey, entry, ownerProps, slotInjected, hookCont // Per-session remount rides this key; per-entry remount rides the outer // element's entry-identity key (the outlet's guarded() call). return ( - + - {renderOutletContent(host, slotKey, ownerProps, opts, scopeBinding)} -
+ + {spec === undefined ? null : renderOutletContent(host, slotKey, ownerProps, opts, scopeBinding, spec)} + ) } @@ -1098,14 +1106,11 @@ function renderOutletContent( ownerProps: object, opts: (RenderOpts & ChainRenderOpts) | undefined, scopeBinding: StandardSourceBinding, + spec: SlotSpec, ): ReactNode { - const spec = host.specOf(slotKey) - // Undeclared (or no-longer-declared) keys render empty: a declaring entry's - // unload returns the slot to the undeclared state while retained elements - // may still be mounted — natural empty, not an ownership failure. - if (!spec) return null + const Anchor = spec.inline === true ? 'span' : 'div' if (spec.kind === 'chain' && opts?.fallbackOnly === true) { - return renderChainResult(slotKey, null, opts) + return renderChainResult(slotKey, null, opts, Anchor) } if (spec.scope === 'session' && scopeBinding.key === undefined) { throw new SlotAssemblyError(`strict session slot '${slotKey}' rendered without a scope binding`) @@ -1130,6 +1135,7 @@ function renderOutletContent( ? ( ) : ( - + {spec.scope === 'session-maybe' ? (
+ const deadCell = () => if (spec.kind === 'single') { const entry = host.entriesOfSlot(slotKey)[0] @@ -1211,7 +1217,7 @@ function renderOutletContent( break } } - return renderChainResult(slotKey, elected, opts) + return renderChainResult(slotKey, elected, opts, Anchor) } // list: one row per id cell — the cell's shadowing winner, or the crash // face once every entry of the cell abdicated (a dry cell must not @@ -1239,7 +1245,7 @@ function renderOutletContent( <> {list.map((item, i) => item.entry !== undefined ? guarded(item.entry, `e${entryKeyOf(item.entry)}`) - :
)} + : )} ) } @@ -1249,16 +1255,17 @@ function renderChainResult( slotKey: string, elected: ReactNode, opts: (RenderOpts & ChainRenderOpts) | undefined, + Anchor: SlotAnchorTag, ): ReactNode { if (!opts?.overlay) return elected ?? <>{opts?.fallback ?? null} return ( <> -
{opts.fallback ?? null} -
+
{elected} ) diff --git a/packages/client/ui-renderer/tests/inline-slots.client.spec.tsx b/packages/client/ui-renderer/tests/inline-slots.client.spec.tsx new file mode 100644 index 0000000000..15fc5056bd --- /dev/null +++ b/packages/client/ui-renderer/tests/inline-slots.client.spec.tsx @@ -0,0 +1,123 @@ +// @vitest-environment jsdom +import { useState, type ReactNode } from 'react' +import { act, cleanup, fireEvent } from '@testing-library/react' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { PropsRenderFactories, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + 'spec.inline.single': { kind: 'single'; scope: 'root'; inline: true } + 'spec.inline.keyed': { kind: 'keyed'; scope: 'root'; inline: true } + 'spec.inline.list': { kind: 'list'; scope: 'root'; inline: true } + 'spec.inline.chain': { kind: 'chain'; scope: 'root'; inline: true; owner: { enabled: boolean } } + 'spec.inline.child': { kind: 'single'; scope: 'root'; inline: true } + 'spec.inline.block': { kind: 'single'; scope: 'root' } + } + interface SlotFactoryMap { + 'spec.inline.factory': { + scope: 'root' + children: { 'spec.inline.child': { kind: 'single'; scope: 'root'; inline: true } } + } + } +} + +afterEach(cleanup) + +async function setup() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + return runtime +} + +function Crashed(): never { + throw new Error('inline entry failed') +} + +describe('inline Slot anchors', () => { + it('keeps inline anchors and exhausted cells as spans while ordinary Slots remain divs', async () => { + const runtime = await setup() + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + await runtime.root.declare({ + 'spec.inline.single': { kind: 'single', scope: 'root', inline: true }, + 'spec.inline.keyed': { kind: 'keyed', scope: 'root', inline: true }, + 'spec.inline.list': { kind: 'list', scope: 'root', inline: true }, + 'spec.inline.block': { kind: 'single', scope: 'root' }, + }, ({ renderSlot }) => <> + {renderSlot('spec.inline.single', {})} + {renderSlot('spec.inline.keyed', {}, { entryKey: 'failed' })} + {renderSlot('spec.inline.list', {})} + {renderSlot('spec.inline.block', {}, { fallback: Ordinary fallback })} + ) + runtime.slots.register({ name: 'spec.inline.single' }, Crashed) + runtime.slots.register({ name: 'spec.inline.keyed', key: 'failed' }, Crashed) + runtime.slots.register({ name: 'spec.inline.list', id: 'failed' }, Crashed) + const view = runtime.renderRoot() + await act(async () => {}) + for (const name of ['spec.inline.single', 'spec.inline.keyed', 'spec.inline.list'] as const) { + const anchor = view.container.querySelector(`[data-slot="${name}"]`) + expect(anchor?.tagName).toBe('SPAN') + expect(anchor?.querySelector('[data-slot-error]')?.tagName).toBe('SPAN') + expect(runtime.slots.entries(name)).toHaveLength(1) + } + expect(view.container.querySelector('[data-slot="spec.inline.block"]')?.tagName).toBe('DIV') + expect(view.getByText('Ordinary fallback')).toBeTruthy() + }) + + it('uses span overlay fallbacks and span error boundaries for inline chains', async () => { + const runtime = await setup() + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + onTestFinished(() => { error.mockRestore() }) + await runtime.root.declare({ + 'spec.inline.chain': { kind: 'chain', scope: 'root', inline: true }, + }, ({ renderSlotChain }) => { + const [enabled, setEnabled] = useState(false) + return <> + + {renderSlotChain('spec.inline.chain', { enabled }, { + fallback: Fallback, overlay: true, fallbackOnly: !enabled, + })} + + }) + runtime.slots.register({ name: 'spec.inline.chain', select: ({ enabled }) => enabled ? {} : null }, Crashed) + const view = runtime.renderRoot() + const fallback = view.container.querySelector('[data-chain-overlay-fallback]')! + expect(fallback.tagName).toBe('SPAN') + expect(fallback.style.display).toBe('contents') + fireEvent.click(view.getByRole('button', { name: 'Enable' })) + expect(view.container.querySelector('[data-chain-overlay-fallback]')).toBe(fallback) + expect(fallback.style.display).toBe('none') + expect(view.container.querySelector('[data-slot-error="spec.inline.chain"]')?.tagName).toBe('SPAN') + }) + + it('retains the inline child anchor after its Factory declaration is disposed', async () => { + const runtime = await setup() + let retained: ReactNode = null + const dispose = runtime.slots.registerFactory({ + name: 'spec.inline.factory', scope: 'root', + children: { 'spec.inline.child': { kind: 'single', scope: 'root', inline: true } }, + }, ({ renderSlot }) => { + retained = renderSlot('spec.inline.child', {}, { fallback: Child fallback }) + return retained + }) + runtime.slots.register({ name: 'spec.inline.child' }, () => Child) + await runtime.root.declare({}, ({ renderFactorySlot }: PropsRuntime<'root'> & PropsRenderFactories) => { + const [hold, setHold] = useState(false) + return <> + + {hold ? retained : renderFactorySlot('spec.inline.factory', {})} + + }) + const view = runtime.renderRoot() + expect(view.getByText('Child')).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: 'Retain child' })) + const anchor = view.container.querySelector('[data-slot="spec.inline.child"]')! + expect(anchor.tagName).toBe('SPAN') + await act(async () => { dispose() }) + expect(view.container.querySelector('[data-slot="spec.inline.child"]')).toBe(anchor) + expect(anchor.textContent).toBe('') + expect(view.queryByText('Child fallback')).toBeNull() + expect(runtime.slots.entries('spec.inline.child')).toHaveLength(0) + }) +}) diff --git a/packages/client/ui-renderer/tsdown.config.ts b/packages/client/ui-renderer/tsdown.config.ts index 2aa78ec480..7aa03cebc1 100644 --- a/packages/client/ui-renderer/tsdown.config.ts +++ b/packages/client/ui-renderer/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-renderer', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-schedule/README.i18n.yaml b/packages/client/ui-schedule/README.i18n.yaml index 21244ecf66..50241a25d1 100644 --- a/packages/client/ui-schedule/README.i18n.yaml +++ b/packages/client/ui-schedule/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6bd6882dbbbefcb0 zh: 03aa15f1a65d13dc /deepseek-ai-dsh-client-ui-schedule/understand-the-implementation: - en: a03a551e0ed96c6b - zh: a85efe7db56b7df3 + en: 959145f9a08c3913 + zh: caae642a82d2acd3 /deepseek-ai-dsh-client-ui-schedule/further-exploration: en: 06e265120b05dbf5 zh: 08ab1ef979b8ea40 diff --git a/packages/client/ui-schedule/README.md b/packages/client/ui-schedule/README.md index 9f60a11b1c..2731187fae 100644 --- a/packages/client/ui-schedule/README.md +++ b/packages/client/ui-schedule/README.md @@ -67,6 +67,8 @@ A restored task tab carries no navigation parameters, because the Sidebar persis Subscriptions exist only while the framework observes a source. The final unsubscribe releases event listeners and invalidates pending responses. Components receive framework-bound `useCatalog` hooks and explicit action callbacks. The mounted Records view reads `schedule.history` with the selected task's original Session binding; catalog and list responses omit full history. Components own disposable search, filtering, selection, confirmation, and history-page state. Reminder records remain Host-owned and do not come from historical Session projections or browser-local demo data. +Task menus use the [standard menu geometry](../../../docs/ui-radius.md#nested-hover), including keyboard-highlighted rows. Created-task cards follow the [file-card family](../../../docs/ui-radius.md#radius-scale) for their radius and icon-tile material. + diff --git a/packages/client/ui-schedule/README.zh.md b/packages/client/ui-schedule/README.zh.md index 29c127bad3..cd027ea2ea 100644 --- a/packages/client/ui-schedule/README.zh.md +++ b/packages/client/ui-schedule/README.zh.md @@ -67,6 +67,8 @@ kind: "package-reference" 仅在框架观察数据源期间订阅。最后一个订阅取消时释放事件监听,并使尚未完成的响应失效。组件接收框架绑定的 `useCatalog` hook 和明确的操作回调。已挂载的任务运行记录视图使用所选任务的原会话绑定读取 `schedule.history`;目录和列表响应不包含完整历史。组件拥有可丢弃的搜索、筛选、选择、确认和历史分页状态。提醒记录由 Host 拥有,不来自历史会话投影或浏览器本地演示数据。 +任务菜单使用[标准菜单几何](../../../docs/ui-radius.zh.md#nested-hover),包含键盘高亮行。已创建任务卡片的圆角和图标底框材质遵循[文件卡片家族](../../../docs/ui-radius.zh.md#radius-scale)。 + diff --git a/packages/client/ui-schedule/package.json b/packages/client/ui-schedule/package.json index 2ec4f63955..b8a228585b 100644 --- a/packages/client/ui-schedule/package.json +++ b/packages/client/ui-schedule/package.json @@ -74,8 +74,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "clsx": "^2.1.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", diff --git a/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css b/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css index 551dee0b93..a56588c1d4 100644 --- a/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css +++ b/packages/client/ui-schedule/src/client/ScheduleCreateCard.module.css @@ -1,7 +1,4 @@ -/* schedule_create transcript card: clock, task title, frequency, open action. - The box is the delivery card's (ui-deliverables Deliverables.module.css - `.file`): the same fill/hover pair, 60px row, 8/10 padding, and 18px corner, - with one inset overlay button making the whole row open the task. */ +/* Created-task cards follow the file-card treatment in docs/ui-radius.md. */ .card { --card-fill: var(--dsw-static-neutral-50); @@ -15,7 +12,7 @@ padding: 8px 10px; overflow: hidden; border: 0.5px solid var(--dsw-alias-border-l1); - border-radius: 18px; + border-radius: var(--dsw-radius-lg); background: var(--card-fill); color: var(--dsw-alias-label-primary); transition: background-color 120ms ease; @@ -59,8 +56,6 @@ pointer-events: none; } -/* The clock glyph sits in the delivery card's icon frame (`.fileIcon`): a - 40px bordered 10px-corner square on the card's own fill. */ .leading { display: grid; flex: none; @@ -68,12 +63,16 @@ box-sizing: border-box; width: 40px; height: 40px; - border: 0.5px solid var(--dsw-alias-border-l2); + border: 0.5px solid var(--dsw-alias-border-l1); border-radius: 10px; - background: var(--card-fill); + background: color-mix(in srgb, var(--dsw-static-neutral-00) 50%, transparent); color: var(--dsw-alias-label-secondary); } +:global(body[data-ds-dark-theme]) .leading { + background: color-mix(in srgb, var(--dsw-static-neutral-00) 5%, transparent); +} + .leading svg { flex: none; } @@ -118,7 +117,7 @@ white-space: nowrap; } -/* The open control keeps the primitive's outlined capsule geometry and stays +/* The open control keeps the primitive's compact outlined geometry and stays its own target over the row-wide overlay. */ .openButton { flex: none; diff --git a/packages/client/ui-schedule/src/client/TaskMenu.module.css b/packages/client/ui-schedule/src/client/TaskMenu.module.css index 91fa09e354..5ddd158c37 100644 --- a/packages/client/ui-schedule/src/client/TaskMenu.module.css +++ b/packages/client/ui-schedule/src/client/TaskMenu.module.css @@ -10,12 +10,12 @@ .list { /* min-widths below are the design's outer card widths — include the pad. */ box-sizing: border-box; - padding: 3px; + padding: 4px; display: flex; flex-direction: column; gap: 0; border: 0; - border-radius: 16px; + border-radius: var(--dsw-radius-lg); background: var(--dsw-specific-menu); backdrop-filter: var(--dsw-menu-backdrop-filter); --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); @@ -88,7 +88,7 @@ min-height: 34px; padding: 6px 8px; border: none; - border-radius: 8px; + border-radius: var(--dsw-radius-md); background: transparent; cursor: pointer; font-size: 13px; diff --git a/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx b/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx index 9a295266ba..58a5f134a6 100644 --- a/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx +++ b/packages/client/ui-schedule/tests/schedule-create-card.client.spec.tsx @@ -284,11 +284,9 @@ describe('ScheduleCreateCard', () => { expect(frequency).toMatch(/color:\s*var\(--dsw-alias-label-tertiary\);/) expect(frequency).toMatch(/font-size:\s*10px;/) expect(frequency).toMatch(/line-height:\s*16px;/) - // The box is the delivery card's (ui-deliverables `.file`): fill/hover pair, - // 8/10 padding, 18px corner, and a 60px row (8px insets around 44px). const card = /\.card\s*\{([^}]*)\}/.exec(stylesheet)?.[1] ?? '' expect(card).toMatch(/padding:\s*8px 10px;/) - expect(card).toMatch(/border-radius:\s*18px;/) + expect(card).toMatch(/border-radius:\s*var\(--dsw-radius-lg\);/) expect(card).toMatch(/background:\s*var\(--card-fill\);/) expect(stylesheet).toMatch(/\.card:has\(\.cardOpen\):hover\s*\{[^}]*background:\s*var\(--card-hover\);/) expect(stylesheet).toMatch(/\.row\s*\{[^}]*min-height:\s*44px;/) diff --git a/packages/client/ui-schedule/tsdown.config.ts b/packages/client/ui-schedule/tsdown.config.ts index 5607f49cd6..7aa03cebc1 100644 --- a/packages/client/ui-schedule/tsdown.config.ts +++ b/packages/client/ui-schedule/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-schedule', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-secret-mask/README.i18n.yaml b/packages/client/ui-secret-mask/README.i18n.yaml new file mode 100644 index 0000000000..acb11ab860 --- /dev/null +++ b/packages/client/ui-secret-mask/README.i18n.yaml @@ -0,0 +1,40 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-secret-mask/README.md +/: + en: 1dc6c25906eed342 + zh: 6d2502e37189d576 +/deepseek-ai-dsh-client-ui-secret-mask: + en: f26ae7ca26826032 + zh: b74b0e6322c0b56c +/deepseek-ai-dsh-client-ui-secret-mask/summary: + en: 2a509a8ec34675b3 + zh: e0afbb185bde0c57 +/deepseek-ai-dsh-client-ui-secret-mask/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-client-ui-secret-mask/use-this-package: + en: b0381650c2b15970 + zh: a30982f630ea71f1 +/deepseek-ai-dsh-client-ui-secret-mask/use-this-package/what-is-masked: + en: 445a9c788955600d + zh: b36ebee0735f5c48 +/deepseek-ai-dsh-client-ui-secret-mask/understand-the-implementation: + en: 6d51c32ed0187492 + zh: 43cf79bbe45ee90b +/deepseek-ai-dsh-client-ui-secret-mask/further-exploration: + en: 7549b5b4c03132f4 + zh: 50516120cf5d0c25 +/deepseek-ai-dsh-client-ui-secret-mask/model-experience: + en: 9a362b8fa90e0d5a + zh: 65c22dcf8f352782 +/deepseek-ai-dsh-client-ui-secret-mask/model-experience/kv-cache-effect: + en: ca75c51c89c2c9b0 + zh: c2241315dc0c89c9 +/deepseek-ai-dsh-client-ui-secret-mask/known-limitations-and-deferred-work: + en: 14c6e5817a106972 + zh: 13082b68474b5a6f +/deepseek-ai-dsh-client-ui-secret-mask/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/client/ui-secret-mask/README.md b/packages/client/ui-secret-mask/README.md new file mode 100644 index 0000000000..bdd123220d --- /dev/null +++ b/packages/client/ui-secret-mask/README.md @@ -0,0 +1,99 @@ +--- +description: "Web display masking for recognized credentials in sent user text, with a per-value reveal control in interactive messages." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-secret-mask + +English | [中文](README.zh.md) + +## Summary + +Use `dsh-client-ui-secret-mask` when Web users paste API keys, tokens, or passwords into messages that others may see on a shared screen or in a screenshot. Sent user text draws each recognized credential masked: a key or token keeps its first eight characters, and each remaining character is drawn as `*`. Masking changes only what is drawn; the message text, the copy action, and the model input keep the original characters. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Mount the package beside `dsh-client-ui-conversation`. The Web app bundle mounts it by default; removing its row draws credentials as written. Every caller of the [UserText Factory](../ui-conversation/README.md#sent-user-text) masks: message bubbles, steering messages, pending echoes, queued messages, and `/goal` input bubbles. + +Each masked value is drawn in a monospace font, so revealing it does not move the surrounding text. Interactive text, which is a sent message or an admitted steering message, adds an eye control at the end of each run. The control reveals or hides that one value, and every mount starts masked. Other callers draw the masked value without a control. + + +### What is masked + +| Value | Examples | Display | +| --- | --- | --- | +| Model-service and Google API keys | `sk-…` with at least one digit, `AIza…` | First eight characters kept | +| Code-hosting and package-registry tokens | `ghp_…`, `github_pat_…`, `glpat-…`, `npm_…`, `hf_…` | First eight characters kept | +| Cloud access key IDs | `AKIA…`, `ASIA…`, `LTAI…`, `AKID…` | First eight characters kept | +| Collaboration and payment tokens | `xoxb-…`, `sk_live_…`, `rk_test_…`, `whsec_…` | First eight characters kept | +| JSON Web Tokens | `eyJ….eyJ….…` | First eight characters kept | +| Private key blocks | `-----BEGIN … PRIVATE KEY-----` through its `END` line | `BEGIN` and `END` lines and line breaks kept | +| Address passwords | `postgres://user:password@host/db` | Password masked completely, including a token used as one | + +Named assignments such as `password=…` or `API_KEY=…`, passwords written in a sentence, verification codes, and personal data have no published format and stay as written. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The plugin registers one UserText matcher, `secret`, and its keyed `conversation.user.text.node` renderer; the `/client` export is the plugin body (`apply`/`inject`) only. The matcher reads no Facts, so Facts updates never query it again. Each query returns the nearest credential at or after the requested offset and allocates nothing before it returns a node. A literal-only alternation finds where a format can begin; where a literal's suffix can begin another literal, the scan resumes at that suffix. Format checks are bounded character comparisons and sticky `[class]*` patterns, which stop at the first character outside the class and leave nothing to backtrack into. The matcher instance that `apply` creates memoizes run ends, the next digit, and the next private-key `END` line per text across queries, so all queries of one text cost linear time together; the instance keeps the last queried text until a query for another text. At an equal start, the private-key, address-password, and prefix formats win in that order, and every overlapping candidate joins the earliest under its mask. When an address's `://` precedes the requested offset, the matcher walks back over the user name only if `:`, a password, and `@` follow the offset, so a query from anywhere inside an address finds the same password. The [user-text benchmark](../../../benchmarks/user-text/user-text.bench.client.ts) bounds evaluation time for text with and without credentials, linear scaling, and the matcher's allocation ([rationale](../../../.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md)). + +The node payload carries only the masked display text. The renderer draws each run of `*` as centered marks while keeping the characters for copying and assistive technology, because a font's own asterisk sits near the cap height. It switches between that text and the node's original text, and it remembers the revealed original value instead of a flag, so a different credential at the same position starts masked. + +
+ +----- + + +## Further Exploration + +- [ui-conversation sent user text](../ui-conversation/README.md#sent-user-text) — the matcher registry, the scheduler, and the node renderer Slot. +- [User text candidate scheduling](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.md) — the forward-query and cache rules this matcher follows. +- [Credential matching performance](../../../.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.md) — the linear matcher, its per-part complexity and trade-offs, and the time and allocation gates. + +----- + + +## Model Experience + +None, as masking changes only what the browser draws; the message text and the model input keep the original characters. + +#### KV Cache effect + +None; this package neither assembles nor sends a provider request. + +## Known Limitations and Deferred Work + + + +These limits define when a credential is drawn as written; they are current package constraints. + +- **Recognition requires a published format** — a credential without one of the [recognized formats](#what-is-masked) is drawn as written. Named assignments stay plain because the same names also label ordinary values, such as token usage. +- **Only UserText callers mask** — session titles, turn previews, search excerpts, the goal bar, tool cards, assistant replies, and the unsent composer draw credentials as written. +- **An earlier reference draws its own text** — a credential inside a reference that starts before it, such as the file mention `@config/.txt`, is drawn by that reference. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/ui-secret-mask/README.zh.md b/packages/client/ui-secret-mask/README.zh.md new file mode 100644 index 0000000000..3157142215 --- /dev/null +++ b/packages/client/ui-secret-mask/README.zh.md @@ -0,0 +1,99 @@ +--- +description: "Web 端已发送用户文本中可识别凭据的显示遮挡,交互消息中每个值带显示控件。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-secret-mask + +[English](README.md) | 中文 + +## 概述 + +当 Web 用户把 API 密钥、令牌或密码粘贴进消息,而消息可能在共享屏幕或截图中被他人看到时,使用 `dsh-client-ui-secret-mask`。已发送的用户文本会遮挡每个可识别的凭据:密钥或令牌保留前八个字符,其余每个字符显示为 `*`。遮挡只改变显示内容;消息原文、复制操作和模型输入都保留原始字符。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +把本包与 `dsh-client-ui-conversation` 一起挂载。Web 应用 bundle 默认挂载本包;移除该行后凭据按原样显示。[UserText Factory](../ui-conversation/README.zh.md#sent-user-text) 的每个调用方都会遮挡:消息气泡、插话消息、发送中回显、排队消息以及 `/goal` 输入气泡。 + +每个被遮挡的值以等宽字体显示,因此展开时不会挪动周围文字。交互文本(即已发送消息或已接纳的插话消息)会在每段末尾加一个眼睛控件。该控件显示或隐藏这一个值,每次挂载都从遮挡状态开始。其他调用方只显示遮挡后的值,不带控件。 + + +### 遮挡范围 + +| 值 | 示例 | 显示 | +| --- | --- | --- | +| 模型服务与 Google API 密钥 | 至少含一个数字的 `sk-…`、`AIza…` | 保留前八个字符 | +| 代码托管与包仓库令牌 | `ghp_…`、`github_pat_…`、`glpat-…`、`npm_…`、`hf_…` | 保留前八个字符 | +| 云访问密钥 ID | `AKIA…`、`ASIA…`、`LTAI…`、`AKID…` | 保留前八个字符 | +| 协作与支付令牌 | `xoxb-…`、`sk_live_…`、`rk_test_…`、`whsec_…` | 保留前八个字符 | +| JSON Web Token | `eyJ….eyJ….…` | 保留前八个字符 | +| 私钥块 | 从 `-----BEGIN … PRIVATE KEY-----` 到对应 `END` 行 | 保留 `BEGIN`、`END` 两行及换行 | +| 地址中的密码 | `postgres://user:password@host/db` | 密码全部遮挡,用作密码的令牌也一样 | + +`password=…`、`API_KEY=…` 这类带名字的赋值、写在句子里的密码、验证码以及个人信息都没有公开格式,保持原样。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本插件注册一个 UserText 匹配器 `secret` 及其 keyed `conversation.user.text.node` renderer;`/client` 导出只有插件主体(`apply`/`inject`)。匹配器不读取 Facts,因此 Facts 更新不会再次查询它。每次查询返回请求偏移处或之后最近的凭据,返回节点之前不分配内存。一个只含字面量的交替正则找到格式可能开始的位置;字面量的后缀可能是另一个字面量的开头时,扫描从该后缀处继续。格式检查是有界的字符比较和粘性 `[字符类]*` 模式,这类模式在第一个不属于该类的字符处停止,没有可回溯的部分。`apply` 创建的匹配器实例按文本跨查询记忆字符段结尾、下一个数字和下一行私钥 `END`,因此一段文本的全部查询合计线性;实例保留最近一次查询的文本,直到查询另一段文本。同一起点上,私钥、地址密码和前缀格式依次优先;所有重叠的候选都并入最早的候选,并使用其遮挡方式。地址的 `://` 在请求偏移之前时,只有偏移后紧跟 `:`、密码和 `@` 才回看用户名,因此从地址内任何位置查询都得到同一个密码。[user-text benchmark](../../../benchmarks/user-text/user-text.bench.client.ts) 约束无凭据与含凭据文本的求值耗时、线性增长和匹配器的内存分配([理由](../../../.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md))。 + +节点 payload 只携带遮挡后的显示文本。renderer 把每段 `*` 绘制为垂直居中的标记,同时保留字符本身供复制与辅助技术读取,因为字体自带的星号靠近大写字母顶部。renderer 在该文本与节点原文之间切换,并记住已显示的原文值而不是一个开关,因此同一位置换成另一个凭据时会从遮挡状态开始。 + +
+ +----- + + +## 进一步探索 + +- [ui-conversation 已发送用户文本](../ui-conversation/README.zh.md#sent-user-text)——匹配器注册表、调度器与节点 renderer Slot。 +- [用户文本候选调度](../../../.agents/notes/implemented/architecture/2026-10-10-user-text-json-nodes.zh.md)——本匹配器遵循的向前查询与缓存规则。 +- [凭据识别的性能](../../../.agents/notes/implemented/testing/2026-10-11-user-text-credential-matching.zh.md)——线性匹配器各部分的复杂度与取舍,以及耗时与内存分配门禁。 + +----- + + +## 模型体验 + +无。遮挡只改变浏览器的显示内容;消息原文与模型输入都保留原始字符。 + +#### KV Cache 影响 + +无;本包从不组装或发送提供方请求。 + +## 已知限制与延期工作 + + + +以下限制说明凭据何时按原样显示;它们是本包当前的约束。 + +- **识别依赖公开格式**——不具备[可识别格式](#what-is-masked)的凭据按原样显示。带名字的赋值保持原样,因为同样的名字也用于 token 用量等普通值。 +- **只有 UserText 调用方会遮挡**——会话标题、轮次预览、搜索摘要、目标栏、工具卡片、助手回复以及未发送的输入框都按原样显示凭据。 +- **更早开始的引用显示自身文本**——位于更早开始的引用之内的凭据,例如文件提及 `@config/.txt`,由该引用显示。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/client/ui-secret-mask/locale/en.json b/packages/client/ui-secret-mask/locale/en.json new file mode 100644 index 0000000000..07a7beb439 --- /dev/null +++ b/packages/client/ui-secret-mask/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "ui-secret-mask", + "description": "Masks recognized keys, tokens, and passwords in sent messages." + } +} diff --git a/packages/client/ui-secret-mask/locale/zh.json b/packages/client/ui-secret-mask/locale/zh.json new file mode 100644 index 0000000000..daee3f10d8 --- /dev/null +++ b/packages/client/ui-secret-mask/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "凭据遮挡", + "description": "遮挡已发送消息中可识别的密钥、令牌与密码。" + } +} diff --git a/packages/client/ui-secret-mask/package.json b/packages/client/ui-secret-mask/package.json new file mode 100644 index 0000000000..3101e5ed7d --- /dev/null +++ b/packages/client/ui-secret-mask/package.json @@ -0,0 +1,62 @@ +{ + "name": "@deepseek-ai/dsh-client-ui-secret-mask", + "description": "Web display masking for recognized credentials in sent user text", + "version": "0.2.1-alpha.2", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/client/ui-secret-mask" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./client": { + "types": "./lib/types/client/index.d.ts", + "default": "./lib/client.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" + }, + "dsh": { + "client": { + "inject": [ + "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-conversation", + "@deepseek-ai/dsh-client-ui-renderer" + ], + "platform": "web" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "license": "MIT", + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-slots": "workspace:*", + "react": "^18.2.0" + }, + "files": [ + "locale/*.json", + "lib/index.js", + "lib/client.js", + "lib/types/**/*.d.ts" + ] +} diff --git a/packages/client/ui-secret-mask/src/client/SecretText.module.css b/packages/client/ui-secret-mask/src/client/SecretText.module.css new file mode 100644 index 0000000000..10d529c107 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/SecretText.module.css @@ -0,0 +1,62 @@ +/* A monospace box: the value and the control are flex items centered on one + axis, and the box takes the surrounding text's baseline from the value. + Each mask character keeps its original character's advance, so revealing + never reflows the line. */ +.secret { + display: inline-flex; + align-items: center; + box-sizing: border-box; + max-width: 100%; + margin: 0 2px; + font-family: var(--ds-font-family-code); + font-size: 0.875em; +} + +.value { + min-width: 0; + overflow-wrap: anywhere; +} + +/* The characters stay for copying but are not painted; an asterisk tile per + character advance replaces them, because a font's own asterisk sits near + the cap height. */ +.mask { + -webkit-text-fill-color: transparent; + background-color: currentColor; + -webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'%3E%3Cpath d='M6 5.6v8.8M2.19 7.8l7.62 4.4M2.19 12.2l7.62-4.4' stroke='%23000' stroke-width='1.5' stroke-linecap='round'/%3E%3C/svg%3E") left center / 1ch 100% repeat-x; + mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 20'%3E%3Cpath d='M6 5.6v8.8M2.19 7.8l7.62 4.4M2.19 12.2l7.62-4.4' stroke='%23000' stroke-width='1.5' stroke-linecap='round'/%3E%3C/svg%3E") left center / 1ch 100% repeat-x; +} + +/* The line-box center sits below the middle of the surrounding CJK and Latin + glyphs; both marks and the control rise together without moving layout. */ +.mask, +.toggle { + position: relative; + top: -0.125em; +} + +.toggle { + display: inline-flex; + flex: none; + align-items: center; + padding: 0; + border: none; + background: none; + color: var(--dsw-alias-label-secondary); + cursor: pointer; +} + +.toggle:hover { + color: var(--dsw-alias-label-primary); +} + +.toggle:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 1px; + border-radius: var(--dsw-radius-xs); +} + +.icon { + width: 1em; + height: 1em; +} diff --git a/packages/client/ui-secret-mask/src/client/SecretText.tsx b/packages/client/ui-secret-mask/src/client/SecretText.tsx new file mode 100644 index 0000000000..2a238d7bf7 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/SecretText.tsx @@ -0,0 +1,68 @@ +/** Masked credential presentation with a per-value reveal control in interactive text. */ +import { useState } from 'react' +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { NS } from './locales.ts' +import { MASK } from './credential-masks.ts' +import css from './SecretText.module.css' + +const EYE_CONTOUR = 'M1.5 8C2.9 5.25 5.25 3.5 8 3.5C10.75 3.5 13.1 5.25 14.5 8C13.1 10.75 10.75 12.5 8 12.5C5.25 12.5 2.9 10.75 1.5 8Z' +const EYE_PATH = `${EYE_CONTOUR}M10 8C10 9.1 9.1 10 8 10C6.9 10 6 9.1 6 8C6 6.9 6.9 6 8 6C9.1 6 10 6.9 10 8Z` +/** The struck-through glyph drops the pupil so it stays distinct at text size. */ +const EYE_OFF_PATH = `${EYE_CONTOUR}M2.5 2.5L13.5 13.5` +const MASK_RUNS = new RegExp(`(\\${MASK}+)`, 'u') + +function EyeGlyph({ path }: { readonly path: string }) { + return ( + + ) +} + +/** + * Split the masked form into kept text and mask runs. Mask runs keep their + * characters for copying and assistive technology but draw centered marks, + * because a font's own asterisk sits near the cap height. + */ +function MaskedText({ masked }: { readonly masked: string }) { + let offset = 0 + return masked.split(MASK_RUNS).map((part) => { + const key = offset + offset += part.length + if (part === '') return null + return part.startsWith(MASK) + ? {part} + : {part} + }) +} + +type SecretTextProps = UserTextNodeProps<'secret'> & PropsLocale + +/** + * Draw one credential masked; interactive text adds a control that reveals or hides this value. + * Every mount, and every different original value at the same position, starts masked. + * @param props - masked node, original spelling, interaction mode, and locale seat. + * @returns an inline masked run with an optional reveal control. + */ +export function SecretText({ node, raw, interactive, t }: SecretTextProps) { + // Holding the revealed value instead of a flag re-masks a different credential that reuses this element. + const [revealedRaw, setRevealedRaw] = useState() + const revealed = interactive && revealedRaw === raw + return ( + + {revealed ? raw : } + {interactive && ( + + )} + + ) +} diff --git a/packages/client/ui-secret-mask/src/client/credential-formats.ts b/packages/client/ui-secret-mask/src/client/credential-formats.ts new file mode 100644 index 0000000000..fc8b27c950 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/credential-formats.ts @@ -0,0 +1,100 @@ +/** + * The credential formats the matcher recognizes, as data: the literal each + * format begins with, how its candidate is validated, and the ASCII character + * classes those checks use. [format-tables.ts](./format-tables.ts) derives + * lookup tables from this list on first use. + */ + +// Character classes of one ASCII code unit, as bits. +/** `[A-Za-z0-9_-]` */ +export const KEY = 1 +/** `[A-Za-z0-9]` */ +export const ALNUM = 2 +/** `\w` */ +export const WORD = 4 +/** `[A-Za-z0-9-]` */ +export const ALNUM_DASH = 8 +/** `[A-Z0-9]` */ +export const UPPER_ALNUM = 16 +/** `[A-Z0-9 ]` */ +export const LABEL = 32 +/** `[a-z0-9+.-]` */ +export const SCHEME = 64 +/** `[a-z]` */ +export const LOWER = 128 +/** `[^\s/:@?#]` */ +export const USER = 256 +/** `[^\s/@?#]` */ +export const PASSWORD = 512 + +// Literal kinds. Same-start candidates resolve by ascending kind, so a token used as an address password is masked completely. +/** A private key block from its `-----BEGIN` line. */ +export const KEY_BLOCK = 0 +/** The password of an address that carries credentials. */ +export const ADDRESS = 1 +/** A provider key or token after its fixed prefix. */ +export const PREFIXED = 2 + +// Shapes of a prefixed format's character run after its literal. +/** The whole run, at least `min`. */ +export const RUN = 0 +/** `min` to `max`, then `\b`. */ +export const BOUNDED = 1 +/** At least `min`, with a digit among the first 256. */ +export const SK = 2 +/** Exactly `min`. */ +export const GOOGLE = 3 +/** Three runs joined by `.eyJ` and `.`. */ +export const JWT = 4 + +/** One recognized format. */ +export interface CredentialFormat { + /** ASCII literal the candidate begins with; no literal occurs inside another. */ + readonly literal: string + readonly kind: typeof KEY_BLOCK | typeof ADDRESS | typeof PREFIXED + /** Prefixed formats only: how the run after the literal is validated. */ + readonly shape: number + /** Prefixed formats only: the class bit of the run after the literal. */ + readonly run: number + readonly min: number + readonly max: number +} + +const prefixed = (literal: string, shape: number, run: number, min: number, max = 0): CredentialFormat => + ({ literal, kind: PREFIXED, shape, run, min, max }) + +/** Every prefixed format matches more than the 8 characters a mask leaves readable. */ +export const CREDENTIAL_FORMATS: readonly CredentialFormat[] = [ + { literal: '-----BEGIN ', kind: KEY_BLOCK, shape: RUN, run: 0, min: 0, max: 0 }, + { literal: '://', kind: ADDRESS, shape: RUN, run: 0, min: 0, max: 0 }, + // Model services: `sk-` keys carry a digit, which hyphenated identifiers rarely do. + prefixed('sk-', SK, KEY, 20), + prefixed('AIza', GOOGLE, KEY, 35), + // Code hosting and package registries. + prefixed('ghp_', RUN, ALNUM, 36), + prefixed('gho_', RUN, ALNUM, 36), + prefixed('ghu_', RUN, ALNUM, 36), + prefixed('ghs_', RUN, ALNUM, 36), + prefixed('ghr_', RUN, ALNUM, 36), + prefixed('github_pat_', RUN, WORD, 22), + prefixed('glpat-', RUN, KEY, 20), + prefixed('npm_', RUN, ALNUM, 36), + prefixed('hf_', RUN, ALNUM, 30), + // Cloud access key IDs. + prefixed('AKIA', BOUNDED, UPPER_ALNUM, 16, 16), + prefixed('ASIA', BOUNDED, UPPER_ALNUM, 16, 16), + prefixed('LTAI', BOUNDED, ALNUM, 12, 20), + prefixed('AKID', BOUNDED, ALNUM, 28, 36), + // Collaboration and payment services. + prefixed('xoxa-', RUN, ALNUM_DASH, 10), + prefixed('xoxb-', RUN, ALNUM_DASH, 10), + prefixed('xoxp-', RUN, ALNUM_DASH, 10), + prefixed('xoxr-', RUN, ALNUM_DASH, 10), + prefixed('xoxs-', RUN, ALNUM_DASH, 10), + prefixed('sk_live_', RUN, ALNUM, 16), + prefixed('sk_test_', RUN, ALNUM, 16), + prefixed('rk_live_', RUN, ALNUM, 16), + prefixed('rk_test_', RUN, ALNUM, 16), + prefixed('whsec_', RUN, ALNUM, 24), + prefixed('eyJ', JWT, KEY, 8, 2048), +] diff --git a/packages/client/ui-secret-mask/src/client/credential-masks.ts b/packages/client/ui-secret-mask/src/client/credential-masks.ts new file mode 100644 index 0000000000..eabccb0376 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/credential-masks.ts @@ -0,0 +1,127 @@ +/** + * Display forms of credential ranges. Every mark comes from a slice of a shared + * string, so a one-line mask is one slice and a multi-line mask one slice per line. + */ +import { ADDRESS, PREFIXED } from './credential-formats.ts' + +/** Character that replaces each hidden credential character in `masked`. */ +export const MASK = '*' +/** Leading characters of a prefixed key left readable: the provider prefix and little else. */ +const VISIBLE_PREFIX = 8 +const SHARED_MARKS = 4096 + +/** Builds masks; owns the shared mark strings and its sticky run pattern. */ +export class CredentialMasks { + private readonly marksOnly = MASK.repeat(SHARED_MARKS) + private readonly marksLf = `${this.marksOnly}\n` + private readonly marksCr = `${this.marksOnly}\r` + /** Code units that `lines` counts without inspection: neither line breaks nor surrogates. Set `lastIndex` before each test. */ + private readonly ordinary = /[^\r\n\ud800-\udfff]*/y + + /** + * The display form of `text[start, end)`, whose earliest candidate has `kind`. + * @param text - the queried text. + * @param kind - the literal kind of the range's earliest candidate. + * @param plain - the range holds only prefixed-format characters: ASCII without line breaks. + * @param start - first offset of the range. + * @param end - offset after the range. + * @returns the mask; line breaks stay in place, one mark per code point. + */ + masked(text: string, kind: number, plain: boolean, start: number, end: number): string { + if (kind === ADDRESS) return this.range(text, start, end) + if (kind === PREFIXED) { + const prefix = text.slice(start, start + VISIBLE_PREFIX) + return prefix + (plain ? this.marks(end - start - VISIBLE_PREFIX) : this.range(text, start + VISIBLE_PREFIX, end)) + } + return this.keyBlock(text, start, end) + } + + /** `count` marks: up to the shared string's length, one slice of it. */ + private marks(count: number): string { + return count <= SHARED_MARKS ? this.marksOnly.slice(0, count) : MASK.repeat(count) + } + + /** `count` marks and then the line break `code`, 10 or 13: one slice where `marks` would be one. */ + private marksThen(count: number, code: number): string { + return count <= SHARED_MARKS + ? (code === 10 ? this.marksLf : this.marksCr).slice(SHARED_MARKS - count) + : MASK.repeat(count) + (code === 10 ? '\n' : '\r') + } + + /** + * Keep the `BEGIN` line, the `END` line when present, and every line break; a block written on + * one line is masked whole. Both searches stay inside the range, so they cost what the mask costs. + */ + private keyBlock(text: string, start: number, end: number): string { + let bodyStart = start + for (let index = start; index < end; index++) { + if (text.charCodeAt(index) === 10) { + bodyStart = index + 1 + break + } + } + let bodyEnd = end + for (let index = end - '\n-----END'.length; index >= bodyStart; index--) { + if (text.charCodeAt(index) === 10 && text.startsWith('-----END', index + 1)) { + bodyEnd = index + break + } + } + // Native runs stop at a line break or the end of the text, so they stay inside a body that ends at one. + const bounded = bodyEnd === text.length || text.charCodeAt(bodyEnd) === 10 || text.charCodeAt(bodyEnd) === 13 + const body = bounded ? this.lines(text, bodyStart, bodyEnd) : this.range(text, bodyStart, bodyEnd) + return text.slice(start, bodyStart) + body + text.slice(bodyEnd, end) + } + + /** + * `text[start, end)` with every character except line breaks replaced; a surrogate pair is one + * character, as `[^\r\n]` with the `u` flag counts it. A character loop: a native run could read far past `end`. + */ + private range(text: string, start: number, end: number): string { + let masked = '' + let count = 0 + for (let index = start; index < end; index++) { + const code = text.charCodeAt(index) + if (code === 10 || code === 13) { + masked += this.marksThen(count, code) + count = 0 + continue + } + if (code >= 0xd800 && code <= 0xdbff && index + 1 < end) { + const next = text.charCodeAt(index + 1) + if (next >= 0xdc00 && next <= 0xdfff) index++ + } + count++ + } + return masked + this.marks(count) + } + + /** `range` for a body that ends at a line break or the end of the text, where native runs stop. */ + private lines(text: string, start: number, end: number): string { + const ordinary = this.ordinary + let masked = '' + let count = 0 + let index = start + while (index < end) { + ordinary.lastIndex = index + ordinary.test(text) + const stop = Math.min(ordinary.lastIndex, end) + count += stop - index + if (stop === end) break + const code = text.charCodeAt(stop) + index = stop + 1 + if (code === 10 || code === 13) { + masked += this.marksThen(count, code) + count = 0 + continue + } + // A high surrogate followed by a low one is one character. + if (code <= 0xdbff && index < end) { + const next = text.charCodeAt(index) + if (next >= 0xdc00 && next <= 0xdfff) index++ + } + count++ + } + return masked + this.marks(count) + } +} diff --git a/packages/client/ui-secret-mask/src/client/credential-scanner.ts b/packages/client/ui-secret-mask/src/client/credential-scanner.ts new file mode 100644 index 0000000000..14bf645708 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/credential-scanner.ts @@ -0,0 +1,358 @@ +/** + * Prefix-pruned, linear credential scanning that allocates nothing until it + * returns a node. A literal-only alternation finds each place a format can + * begin and resumes inside a literal that can overlap the next one. Format + * checks are bounded character comparisons and sticky `[class]*` runs, which + * end at the first character outside the class and leave nothing to backtrack + * into. Run ends, the next digit, and the next key-block `END` line are + * memoized per text across queries, so each is measured once per text. + */ +import type { UserTextNode } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { + ADDRESS, ALNUM, ALNUM_DASH, BOUNDED, GOOGLE, KEY_BLOCK, LABEL, LOWER, PREFIXED, RUN, SCHEME, SK, UPPER_ALNUM, USER, WORD, +} from './credential-formats.ts' +import { CredentialMasks } from './credential-masks.ts' +import type { FormatTables } from './format-tables.ts' + +// Memo layout: [start, end] pairs. A lookup at `offset` hits when start <= offset <= end; -1 pairs hold nothing. +const KEY_SLOTS = 0 // four pairs: a JSON Web Token measures three runs +const KEY_NEXT = 8 +const ALNUM_SLOT = 9 +const WORD_SLOT = 11 +const ALNUM_DASH_SLOT = 13 +const UPPER_ALNUM_SLOT = 15 +const USER_SLOT = 17 +const PASSWORD_SLOT = 19 +const DIGIT_FROM = 21 +const DIGIT_AT = 22 +const BLOCK_FROM = 23 +const BLOCK_END_START = 24 +const BLOCK_END = 25 +/** Start of the password that the last address check accepted. */ +const CANDIDATE_START = 26 +const MEMO_SIZE = 27 + +/** `\s` above ASCII. */ +function isWideSpace(code: number): boolean { + return code === 0xa0 || code === 0x1680 || (code >= 0x2000 && code <= 0x200a) || code === 0x2028 || code === 0x2029 + || code === 0x202f || code === 0x205f || code === 0x3000 || code === 0xfeff +} + +/** Offset after the run that sticky `pattern` matches at `start`. */ +function runEnd(pattern: RegExp, text: string, start: number): number { + pattern.lastIndex = start + pattern.test(text) + return pattern.lastIndex +} + +/** + * One matcher's scanning state: the tables, its own patterns, and a memo of the + * last queried text, which it keeps until a query for another text. Queries are + * synchronous and never re-enter, so the patterns' cursors are never shared. + */ +export class CredentialScanner { + private readonly classes: Uint16Array + private readonly literals: readonly string[] + private readonly literalLength: Uint8Array + private readonly literalKind: Uint8Array + private readonly literalShape: Uint8Array + private readonly literalMin: Int32Array + private readonly literalMax: Int32Array + private readonly literalOverlap: Uint8Array + private readonly ending: Int8Array + private readonly sharedEndings: readonly (readonly number[] | undefined)[] + /** Memo slot of each prefixed format's run class; 0 for `[A-Za-z0-9_-]`, which has four. */ + private readonly literalSlot: Uint8Array + private readonly literalPattern: readonly RegExp[] + private readonly prefixes: RegExp + // Sticky run patterns: nothing follows the starred class, so nothing backtracks, and `test` allocates nothing. + private readonly keyRun = /[A-Za-z0-9_-]*/y + private readonly userRun = /[^\s/:@?#]*/y + private readonly passwordRun = /[^\s/@?#]*/y + private readonly nonDigits = /\D*/y + private readonly masks = new CredentialMasks() + private readonly memo = new Int32Array(MEMO_SIZE).fill(-1) + private text = '' + + constructor(tables: FormatTables) { + this.classes = tables.classes + this.literals = tables.literals + this.literalLength = tables.literalLength + this.literalKind = tables.literalKind + this.literalShape = tables.literalShape + this.literalMin = tables.literalMin + this.literalMax = tables.literalMax + this.literalOverlap = tables.literalOverlap + this.ending = tables.ending + this.sharedEndings = tables.sharedEndings + this.prefixes = new RegExp(tables.prefixSource, 'g') + const patterns = new Map([ + [ALNUM, [ALNUM_SLOT, /[A-Za-z0-9]*/y]], + [WORD, [WORD_SLOT, /\w*/y]], + [ALNUM_DASH, [ALNUM_DASH_SLOT, /[A-Za-z0-9-]*/y]], + [UPPER_ALNUM, [UPPER_ALNUM_SLOT, /[A-Z0-9]*/y]], + ]) + this.literalSlot = Uint8Array.from(tables.literalRun, run => patterns.get(run)?.[0] ?? 0) + this.literalPattern = Array.from(tables.literalRun, run => patterns.get(run)?.[1] ?? this.keyRun) + } + + /** + * The nearest credential at or after `from`. Overlapping candidates of any format join the earliest + * one and take its mask, so no credential is drawn half masked. Candidates arrive in start order; + * an address password waits until the scan passes its start, and no other `://` can occur before + * then, because a user name and a password exclude `/`. A password that starts inside a range also + * ends inside it: the range holds the `:` before the password, so it is a key block, whose `END` + * line has spaces, or one that runs to the end of the text. + * @param text - the complete original text. + * @param from - the query offset. + * @returns the `secret` node, or undefined when no credential starts at or after `from`. + */ + match(text: string, from: number): UserTextNode<'secret'> | undefined { + if (text !== this.text) { + this.memo.fill(-1) + this.text = text + } + const prefixes = this.prefixes + const length = text.length + let start = -1 + let end = -1 + let kind = PREFIXED + let plain = true + let deferredEnd = this.addressBefore(from) + let deferredStart = deferredEnd < 0 ? -1 : this.slot(CANDIDATE_START) + prefixes.lastIndex = from + while (prefixes.test(text)) { + const literalEnd = prefixes.lastIndex + const literal = this.literalEndingAt(literalEnd) + const at = literalEnd - (this.literalLength[literal] as number) + prefixes.lastIndex = literalEnd - (this.literalOverlap[literal] as number) + if (deferredStart >= 0 && deferredStart <= at) { + if (start < 0) { + start = deferredStart + end = deferredEnd + kind = ADDRESS + } else if (deferredStart >= end) { + break + } + deferredStart = -1 + } + // A candidate starts at or after its literal, so none past the range reaches it; nothing extends a range to the end. + if (start >= 0 && (at >= end || end === length)) break + const literalKind = this.literalKind[literal] as number + if (literalKind === ADDRESS) { + deferredEnd = this.addressPassword(at) + deferredStart = deferredEnd < 0 ? -1 : this.slot(CANDIDATE_START) + continue + } + const candidateEnd = literalKind === KEY_BLOCK ? this.keyBlockEnd(at) : this.prefixedEnd(literal, at) + if (candidateEnd < 0) continue + if (start < 0) { + start = at + end = candidateEnd + kind = literalKind + plain = literalKind === PREFIXED + } else if (candidateEnd > end) { + end = candidateEnd + if (literalKind !== PREFIXED) plain = false + } + } + if (start < 0 && deferredStart >= 0) { + start = deferredStart + end = deferredEnd + kind = ADDRESS + } + if (start < 0) return undefined + return { id: 'secret', start, end, data: { masked: this.masks.masked(text, kind, plain, start, end) } } + } + + /** Memo entry at `index`; the layout keeps every index inside the array. */ + private slot(index: number): number { + return this.memo[index] as number + } + + /** `\w` at `index`; out of range is not a word character. */ + private isWordAt(index: number): boolean { + const code = this.text.charCodeAt(index) + return code < 128 && ((this.classes[code] as number) & WORD) !== 0 + } + + /** `[^\s/:@?#]` for one UTF-16 code unit; NaN, read out of range, is not one. */ + private isUserCode(code: number): boolean { + return code < 128 ? ((this.classes[code] as number) & USER) !== 0 : code === code && !isWideSpace(code) + } + + /** Index of the literal the prefix scan matched ending at `end`; one literal sharing the ending matches, so the last needs no check. */ + private literalEndingAt(end: number): number { + const text = this.text + const key = text.charCodeAt(end - 2) * 128 + text.charCodeAt(end - 1) + const literal = this.ending[key] as number + if (literal > 0) return literal - 1 + const shared = this.sharedEndings[key] as readonly number[] + let index = 0 + for (; index < shared.length - 1; index++) { + const candidate = shared[index] as number + if (text.startsWith(this.literals[candidate] as string, end - (this.literalLength[candidate] as number))) break + } + return shared[index] as number + } + + /** End of the `[A-Za-z0-9_-]*` run at `start`, through four memo pairs replaced in turn. */ + private keyRunEnd(start: number): number { + for (let slot = KEY_SLOTS; slot < KEY_NEXT; slot += 2) { + if (this.slot(slot) <= start && start <= this.slot(slot + 1)) return this.slot(slot + 1) + } + const end = runEnd(this.keyRun, this.text, start) + const next = (this.slot(KEY_NEXT) + 1) & 3 + this.memo[KEY_NEXT] = next + this.memo[KEY_SLOTS + 2 * next] = start + this.memo[KEY_SLOTS + 2 * next + 1] = end + return end + } + + /** End of the run `pattern` matches at `start`, through the memo pair at `slot`. */ + private memoRunEnd(pattern: RegExp, start: number, slot: number): number { + if (this.slot(slot) <= start && start <= this.slot(slot + 1)) return this.slot(slot + 1) + const end = runEnd(pattern, this.text, start) + this.memo[slot] = start + this.memo[slot + 1] = end + return end + } + + /** Offset of the first digit at or after `start`, or the text length. */ + private nextDigit(start: number): number { + if (this.slot(DIGIT_FROM) <= start && start <= this.slot(DIGIT_AT)) return this.slot(DIGIT_AT) + this.memo[DIGIT_FROM] = start + this.memo[DIGIT_AT] = runEnd(this.nonDigits, this.text, start) + return this.slot(DIGIT_AT) + } + + /** Offset after `[A-Z0-9 ]{0,40}PRIVATE KEY-----` at `start`, or -1; reads at most 52 characters. */ + private labelEnd(start: number): number { + const text = this.text + const limit = Math.min(text.length, start + 52) + let index = start + while (index < limit) { + const code = text.charCodeAt(index) + if (code > 127 || ((this.classes[code] as number) & LABEL) === 0) break + index++ + } + // "PRIVATE KEY" is label characters and the `-` after it is not, so the run ends right after it. + const tail = index - 'PRIVATE KEY'.length + return index < start + 52 && tail >= start && text.startsWith('PRIVATE KEY-----', tail) ? tail + 'PRIVATE KEY-----'.length : -1 + } + + /** + * End of the `-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----` block at `at`: after its first complete + * `END` line, or the end of the text; -1 for an invalid header. + */ + private keyBlockEnd(at: number): number { + const header = this.labelEnd(at + '-----BEGIN '.length) + if (header < 0) return -1 + if (this.slot(BLOCK_FROM) <= header && header <= this.slot(BLOCK_END_START)) return this.slot(BLOCK_END) + const text = this.text + this.memo[BLOCK_FROM] = header + this.memo[BLOCK_END_START] = text.length + this.memo[BLOCK_END] = text.length + for (let line = text.indexOf('-----END ', header); line >= 0; line = text.indexOf('-----END ', line + 1)) { + const end = this.labelEnd(line + '-----END '.length) + if (end < 0) continue + this.memo[BLOCK_END_START] = line + this.memo[BLOCK_END] = end + break + } + return this.slot(BLOCK_END) + } + + /** Whether `\b[a-z][a-z0-9+.-]{1,15}` ends at `at`; reads at most 17 characters back. */ + private schemeBefore(at: number): boolean { + const text = this.text + for (let start = at - 1; start >= 0 && start >= at - 16; start--) { + const code = text.charCodeAt(start) + const bits = code < 128 ? (this.classes[code] as number) : 0 + if ((bits & SCHEME) === 0) return false + if ((bits & LOWER) !== 0 && at - start >= 2 && !this.isWordAt(start - 1)) return true + } + return false + } + + /** + * The password in `\b[a-z][a-z0-9+.-]{1,15}://[^\s/:@?#]{0,256}:[^\s/@?#]+@` for the `://` at + * `at`; neither part crosses `?` or `#`, where the authority ends. Callers pass a `://` at or after + * the query offset, or one whose user name reaches it, so the password never starts before it. + * @returns the password end with its start in the memo, or -1. + */ + private addressPassword(at: number): number { + if (!this.schemeBefore(at)) return -1 + const text = this.text + const userStart = at + '://'.length + const userEnd = this.memoRunEnd(this.userRun, userStart, USER_SLOT) + if (userEnd - userStart > 256 || text.charCodeAt(userEnd) !== 58) return -1 + const start = userEnd + 1 + const end = this.memoRunEnd(this.passwordRun, start, PASSWORD_SLOT) + if (end === start || text.charCodeAt(end) !== 64) return -1 + this.memo[CANDIDATE_START] = start + return end + } + + /** + * The address password at or after `from` whose `://` starts before `from`, as `addressPassword` + * returns it. The walk back over the user name runs only when a `:`, a password, and `@` follow. + */ + private addressBefore(from: number): number { + const text = this.text + if (from < 3) return -1 + // `from` inside the `://`. + if (text.startsWith('://', from - 1)) return this.addressPassword(from - 1) + if (text.startsWith('://', from - 2)) return this.addressPassword(from - 2) + let index = from - 1 + const before = text.charCodeAt(index) + let passwordStart: number + if (before === 58) { + // The password starts at `from`, right after the user name's `:`. + passwordStart = from + index-- + } else if (this.isUserCode(before)) { + const userEnd = this.memoRunEnd(this.userRun, from, USER_SLOT) + if (text.charCodeAt(userEnd) !== 58) return -1 + passwordStart = userEnd + 1 + } else { + return text.startsWith('://', from - 3) ? this.addressPassword(from - 3) : -1 + } + const passwordEnd = this.memoRunEnd(this.passwordRun, passwordStart, PASSWORD_SLOT) + if (passwordEnd === passwordStart || text.charCodeAt(passwordEnd) !== 64) return -1 + // A user name is at most 256 characters, followed by `:`. + const lowest = Math.max(0, passwordStart - 258) + while (index >= lowest && this.isUserCode(text.charCodeAt(index))) index-- + return index >= 2 && text.startsWith('://', index - 2) ? this.addressPassword(index - 2) : -1 + } + + /** End of the prefixed credential whose literal starts at `at`, or -1. */ + private prefixedEnd(literal: number, at: number): number { + if (this.isWordAt(at - 1)) return -1 + const text = this.text + const start = at + (this.literalLength[literal] as number) + const shape = this.literalShape[literal] as number + const min = this.literalMin[literal] as number + if (shape === SK) { + // `(?=[A-Za-z0-9_-]{0,255}\d)[A-Za-z0-9_-]{20,}`: the memoized next digit rejects a digit-free `sk-` before any run is measured. + const digit = this.nextDigit(start) + if (digit - start > 255) return -1 + const end = this.keyRunEnd(start) + return end - start >= min && digit < end ? end : -1 + } + const slot = this.literalSlot[literal] as number + const end = slot === 0 ? this.keyRunEnd(start) : this.memoRunEnd(this.literalPattern[literal] as RegExp, start, slot) + const length = end - start + if (length < min) return -1 + if (shape === RUN) return end + if (shape === GOOGLE) return start + min + if (shape === BOUNDED) return length <= (this.literalMax[literal] as number) && !this.isWordAt(end) ? end : -1 + // `[A-Za-z0-9_-]{8,2048}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}` after `eyJ`. + if (length > (this.literalMax[literal] as number) || !text.startsWith('.eyJ', end)) return -1 + const payloadStart = end + '.eyJ'.length + const payloadEnd = this.keyRunEnd(payloadStart) + if (payloadEnd - payloadStart < min || text.charCodeAt(payloadEnd) !== 46) return -1 + const signatureEnd = this.keyRunEnd(payloadEnd + 1) + return signatureEnd - (payloadEnd + 1) >= min ? signatureEnd : -1 + } +} diff --git a/packages/client/ui-secret-mask/src/client/format-tables.ts b/packages/client/ui-secret-mask/src/client/format-tables.ts new file mode 100644 index 0000000000..07bf976e82 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/format-tables.ts @@ -0,0 +1,113 @@ +/** Lookup tables derived from the credential formats, built once on first use. */ +import { + ALNUM, ALNUM_DASH, CREDENTIAL_FORMATS, KEY, LABEL, LOWER, PASSWORD, SCHEME, UPPER_ALNUM, USER, WORD, +} from './credential-formats.ts' + +/** Tables indexed by format position in `CREDENTIAL_FORMATS`, by ASCII code unit, or by a literal's last two code units. */ +export interface FormatTables { + /** Class bits per ASCII code unit. */ + readonly classes: Uint16Array + readonly literals: readonly string[] + readonly literalLength: Uint8Array + readonly literalKind: Uint8Array + readonly literalShape: Uint8Array + readonly literalRun: Uint16Array + readonly literalMin: Int32Array + readonly literalMax: Int32Array + /** + * Length of the longest proper suffix of each literal that begins a literal. The + * scan resumes there, so a key block whose first dash ends `sk-` is still seen. + */ + readonly literalOverlap: Uint8Array + /** Literal-only alternation of every literal, grouped by shared leading characters; no quantifier. */ + readonly prefixSource: string + /** Per key `code[-2] * 128 + code[-1]`: the literal with that ending plus one, or -1 where several share it. */ + readonly ending: Int8Array + /** Literals sharing an ending, by the same key. */ + readonly sharedEndings: readonly (readonly number[] | undefined)[] +} + +let tables: FormatTables | undefined + +/** + * The tables for `CREDENTIAL_FORMATS`; the first call builds them. + * @returns the shared, read-only tables. + */ +export function formatTables(): FormatTables { + tables ??= buildTables() + return tables +} + +function buildTables(): FormatTables { + const formats = CREDENTIAL_FORMATS + const literals = formats.map(f => f.literal) + const { ending, sharedEndings } = endingTables(literals) + return { + classes: charClasses(), + literals, + literalLength: Uint8Array.from(literals, literal => literal.length), + literalKind: Uint8Array.from(formats, f => f.kind), + literalShape: Uint8Array.from(formats, f => f.shape), + literalRun: Uint16Array.from(formats, f => f.run), + literalMin: Int32Array.from(formats, f => f.min), + literalMax: Int32Array.from(formats, f => f.max), + literalOverlap: Uint8Array.from(literals, literal => overlap(literal, literals)), + prefixSource: alternation(literals), + ending, + sharedEndings, + } +} + +function charClasses(): Uint16Array { + const classes = new Uint16Array(128) + for (let code = 0; code < 128; code++) { + const upper = code >= 65 && code <= 90 + const lower = code >= 97 && code <= 122 + const digit = code >= 48 && code <= 57 + const alnum = upper || lower || digit + const authority = !((code >= 9 && code <= 13) || code === 32 || code === 47 || code === 64 || code === 63 || code === 35) + classes[code] = (alnum || code === 95 || code === 45 ? KEY : 0) | (alnum ? ALNUM : 0) | (alnum || code === 95 ? WORD : 0) + | (alnum || code === 45 ? ALNUM_DASH : 0) | (upper || digit ? UPPER_ALNUM : 0) | (upper || digit || code === 32 ? LABEL : 0) + | (lower || digit || code === 43 || code === 46 || code === 45 ? SCHEME : 0) | (lower ? LOWER : 0) + | (authority && code !== 58 ? USER : 0) | (authority ? PASSWORD : 0) + } + return classes +} + +function overlap(literal: string, literals: readonly string[]): number { + for (let size = literal.length - 1; size > 0; size--) { + const suffix = literal.slice(-size) + if (literals.some(other => other.startsWith(suffix))) return size + } + return 0 +} + +function endingTables(literals: readonly string[]): Pick { + const ending = new Int8Array(128 * 128) + const sharedEndings: number[][] = [] + literals.forEach((literal, index) => { + const key = literal.charCodeAt(literal.length - 2) * 128 + literal.charCodeAt(literal.length - 1) + const existing = ending[key] as number + if (existing === 0) { + ending[key] = index + 1 + return + } + if (existing > 0) { + sharedEndings[key] = [existing - 1] + ending[key] = -1 + } + (sharedEndings[key] as number[]).push(index) + }) + return { ending, sharedEndings } +} + +const escape = (literal: string): string => literal.replace(/[.*+?^${}()|[\]\\/]/gu, '\\$&') + +/** Literal alternatives grouped by shared leading characters; groups only factor literals and add no quantifier. */ +function alternation(literals: readonly string[]): string { + const groups = new Map() + for (const literal of literals) groups.set(literal.charAt(0), [...groups.get(literal.charAt(0)) ?? [], literal.slice(1)]) + return [...groups].map(([head, tails]) => tails.length === 1 + ? escape(head + tails.join('')) + : `${escape(head)}(?:${alternation(tails)})`).join('|') +} diff --git a/packages/client/ui-secret-mask/src/client/index.ts b/packages/client/ui-secret-mask/src/client/index.ts new file mode 100644 index 0000000000..0250d4a569 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/index.ts @@ -0,0 +1,33 @@ +/** + * Credential display masking for sent Web user text: one UserText matcher and + * its keyed `secret` node renderer. Masking changes only the drawn text; the + * message text, copy actions, and model input keep the original characters. + * + * @module @deepseek-ai/dsh-client-ui-secret-mask/client + */ +import type { Context as ClientContext } from '@deepseek-ai/cordis' +// Type-only: pulls the locale plugin's Context merge (ctx.locale). +import type {} from '@deepseek-ai/dsh-client-locale/client' +// Type-only: pulls the SlotRegistry service merge (ctx.slots). +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +// Type-only: pulls the UiConversation service merge (ctx.uiConversation). +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import { SecretText } from './SecretText.tsx' +import { createSecretRule } from './secret-rule.ts' +export type {} from './secret-rule.ts' +import { en, NS, zh } from './locales.ts' + +/** Required services: the copy, the node renderer registry, and the UserText rule registry. */ +export const inject = ['locale', 'slots', 'uiConversation'] + +/** + * Register the dictionaries, the credential matcher, and its node renderer. + * @param ctx - client root context. + */ +export function apply(ctx: ClientContext): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-secret-mask: dictionaries') + ctx.uiConversation.userText.register(createSecretRule()) + ctx.slots.inject('conversation.user.text.node', () => ctx.slots.register({ + name: 'conversation.user.text.node', key: 'secret', priority: 100, locale: NS, + }, SecretText)) +} diff --git a/packages/client/ui-secret-mask/src/client/locales.ts b/packages/client/ui-secret-mask/src/client/locales.ts new file mode 100644 index 0000000000..5a42d5a8e2 --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/locales.ts @@ -0,0 +1,28 @@ +/** `secretMask` dictionaries for the per-credential reveal control. */ + +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace owned by this plugin. */ +export const NS = 'secretMask' + +/** Simplified Chinese dictionary (the key-set source of truth). */ +export const zh = { + 'secret.reveal': '显示密钥', + 'secret.hide': '隐藏密钥', +} satisfies Record + +/** The secretMask namespace key union. */ +export type SecretMaskKey = keyof typeof zh + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Accessible names of the control that reveals one masked credential. */ + secretMask: SecretMaskKey + } +} + +/** English dictionary, checked complete against the zh key set. */ +export const en = { + 'secret.reveal': 'Show secret', + 'secret.hide': 'Hide secret', +} satisfies Record diff --git a/packages/client/ui-secret-mask/src/client/secret-rule.ts b/packages/client/ui-secret-mask/src/client/secret-rule.ts new file mode 100644 index 0000000000..ff6ead7eab --- /dev/null +++ b/packages/client/ui-secret-mask/src/client/secret-rule.ts @@ -0,0 +1,36 @@ +/** + * The `secret` UserText rule. A value is recognized by its published format + * alone: provider key and token prefixes, JSON Web Tokens, private key blocks, + * and the password of an address that carries credentials. Free-form passwords + * and `name=value` assignments have no such format and stay plain. The formats + * live in [credential-formats.ts](./credential-formats.ts); scanning lives in + * [credential-scanner.ts](./credential-scanner.ts). + */ +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { CredentialScanner } from './credential-scanner.ts' +import { formatTables } from './format-tables.ts' + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + /** One recognized credential range. */ + secret: { + /** Display form of the original range; line breaks stay in place. */ + readonly masked: string + } + } +} + +/** + * Create the credential matcher. Each instance owns a scanner whose memo holds + * the last queried text until a query for another text. + * @returns the `secret` rule; it reads no Facts, so Facts changes never invalidate its queries. + */ +export function createSecretRule(): UserTextRule<'secret'> { + const scanner = new CredentialScanner(formatTables()) + return { + id: 'secret', + // Same-start ties with other rules draw the credential masked. + order: 0, + match: (text, from) => scanner.match(text, from), + } +} diff --git a/packages/client/ui-secret-mask/src/css-modules.d.ts b/packages/client/ui-secret-mask/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-secret-mask/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-secret-mask/src/index.ts b/packages/client/ui-secret-mask/src/index.ts new file mode 100644 index 0000000000..bb2ed8f04e --- /dev/null +++ b/packages/client/ui-secret-mask/src/index.ts @@ -0,0 +1,9 @@ +/** + * Credential display masking plugin, node half. Pure UI plugin: the empty + * apply exists so the plugin appears in the host cordis.yml / Loader; the + * browser half ships via exports["./client"], discovered through the + * package.json `dsh.client` declaration. + */ + +/** Host plugin body — no host-side behavior for this display plugin. */ +export function apply(): void {} diff --git a/packages/client/ui-secret-mask/tests/browser-plugin.client.spec.ts b/packages/client/ui-secret-mask/tests/browser-plugin.client.spec.ts new file mode 100644 index 0000000000..f6bbe35e62 --- /dev/null +++ b/packages/client/ui-secret-mask/tests/browser-plugin.client.spec.ts @@ -0,0 +1,50 @@ +/** Plugin registration: the credential matcher and its keyed node renderer leave with the plugin fiber. */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished } from 'vitest' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' +import { TestSessions } from '@deepseek-ai/dsh-client-test-runtime' +import { UiConversation } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/assembly.ts' +import { SecretText } from '../src/client/SecretText.tsx' +import { NS } from '../src/client/locales.ts' +import { apply, inject } from '../src/client/index.ts' +import { apply as nodeApply } from '../src/index.ts' + +function TextSlotDeclaration(_props: PropsRenderSlots<'conversation.user.text.node'>): null { + return null +} + +describe('apply', () => { + it('declares its services and releases the matcher and renderer on disposal', async () => { + expect(inject).toEqual(['locale', 'slots', 'uiConversation']) + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + ctx.provide('locale', new LocaleRuntime(ctx)) + const sessions = new TestSessions(async (action) => { await action() }, ctx) + onTestFinished(() => sessions.disposeScopes()) + ctx.provide('sessions', sessions) + new UiConversation(ctx, sessions) + await ctx.plugin(SlotRegistry).await() + ctx.slots.register({ + name: 'root', + children: { 'conversation.user.text.node': { kind: 'keyed', scope: 'session' } }, + }, TextSlotDeclaration) + + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + expect(ctx.uiConversation.userText.entries().map(rule => rule.id)).toEqual(['secret']) + expect(ctx.slots.entries('conversation.user.text.node')).toMatchObject([ + { options: { key: 'secret' }, component: SecretText }, + ]) + expect(ctx.locale.bind(NS)('secret.reveal')).toBe('Show secret') + + await fiber.dispose() + expect(ctx.uiConversation.userText.entries()).toHaveLength(0) + expect(ctx.slots.entries('conversation.user.text.node')).toHaveLength(0) + }) + + it('the node half applies without host-side behavior', () => { + expect(() => { nodeApply() }).not.toThrow() + }) +}) diff --git a/packages/client/ui-secret-mask/tests/regex-oracle.client.ts b/packages/client/ui-secret-mask/tests/regex-oracle.client.ts new file mode 100644 index 0000000000..8a68bc6e0b --- /dev/null +++ b/packages/client/ui-secret-mask/tests/regex-oracle.client.ts @@ -0,0 +1,119 @@ +/** + * The backtracking regular-expression formats this package replaced, kept as + * an equivalence oracle for the prefix-pruned matcher. Not product code. It + * joins every overlapping match, including later matches of the same format. + */ +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '../src/client/secret-rule.ts' + +const MASK = '*' +/** Leading characters of a prefixed key left readable: the provider prefix and little else. */ +const VISIBLE_PREFIX = 8 + +const maskRun = (value: string): string => value.replace(/[^\r\n]/gu, MASK) +const maskAfterPrefix = (value: string): string => + value.slice(0, VISIBLE_PREFIX) + maskRun(value.slice(VISIBLE_PREFIX)) +/** + * Keeps the `BEGIN` line, the `END` line when present, and every line break. + * A block written on one line has no line to keep and is masked whole. + */ +const maskKeyBlock = (value: string): string => { + const bodyStart = value.indexOf('\n') + 1 + const end = value.lastIndexOf('\n-----END') + const bodyEnd = end < bodyStart ? value.length : end + return value.slice(0, bodyStart) + maskRun(value.slice(bodyStart, bodyEnd)) + value.slice(bodyEnd) +} + +interface Format { + /** Global pattern whose whole match is the credential. */ + readonly pattern: RegExp + readonly mask: (value: string) => string +} + +/** + * Credentials whose published format starts with a fixed prefix. Every pattern + * matches more than `VISIBLE_PREFIX` characters, which `maskAfterPrefix` relies on. + */ +const PREFIXED: readonly RegExp[] = [ + // Model services: `sk-` keys carry at least one digit, which hyphenated identifiers rarely do. + // The bounded lookahead keeps a long run of digit-free `sk-` repeats linear. + /\bsk-(?=[A-Za-z0-9_-]{0,255}\d)[A-Za-z0-9_-]{20,}/gu, + /\bAIza[A-Za-z0-9_-]{35}/gu, + // Code hosting and package registries. + /\bgh[pousr]_[A-Za-z0-9]{36,}/gu, + /\bgithub_pat_[A-Za-z0-9_]{22,}/gu, + /\bglpat-[A-Za-z0-9_-]{20,}/gu, + /\bnpm_[A-Za-z0-9]{36,}/gu, + /\bhf_[A-Za-z0-9]{30,}/gu, + // Cloud access key IDs. + /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/gu, + /\bLTAI[A-Za-z0-9]{12,20}\b/gu, + /\bAKID[A-Za-z0-9]{28,36}\b/gu, + // Collaboration and payment services. + /\bxox[abprs]-[A-Za-z0-9-]{10,}/gu, + /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}/gu, + /\bwhsec_[A-Za-z0-9]{24,}/gu, + // JSON Web Tokens. The header bound keeps a long run of `eyJ` repeats linear. + /\beyJ[A-Za-z0-9_-]{8,2048}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/gu, +] + +/** Same-start matches resolve in this order, so a token used as an address password is masked completely. */ +const FORMATS: readonly Format[] = [ + { + pattern: /-----BEGIN [A-Z0-9 ]{0,40}PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]{0,40}PRIVATE KEY-----|$)/gu, + mask: maskKeyBlock, + }, + // The lookbehind starts the match at the password, so a query from inside the address finds the same candidate. + // The user name may be empty, and neither part crosses `?` or `#`, where the authority ends. + { pattern: /(?<=\b[a-z][a-z0-9+.-]{1,15}:\/\/[^\s/:@?#]{0,256}:)[^\s/@?#]+(?=@)/gu, mask: maskRun }, + ...PREFIXED.map(pattern => ({ pattern, mask: maskAfterPrefix })), +] + +interface Hit { + readonly start: number + readonly end: number +} + +function find(regex: RegExp, text: string, from: number): Hit | undefined { + regex.lastIndex = from + const match = regex.exec(text) + return match === null ? undefined : { start: match.index, end: match.index + match[0].length } +} + +/** + * Return the nearest credential at or after `from`. Overlapping matches of any + * format join the earliest one and take its mask, so no credential is drawn half masked. + * Reads no Facts, so Facts changes never invalidate its queries. + */ +export const regexSecretRule: UserTextRule<'secret'> = { + id: 'secret', + order: 0, + match(text, from) { + const scans = FORMATS.map((format) => { + const regex = new RegExp(format.pattern) + return { format, regex, hit: find(regex, text, from) } + }) + let first: { readonly format: Format; readonly hit: Hit } | undefined + for (const { format, hit } of scans) { + // The strict comparison keeps the earlier format at an equal start. + if (hit !== undefined && (first === undefined || hit.start < first.hit.start)) first = { format, hit } + } + if (first === undefined) return undefined + const { start } = first.hit + let end = first.hit.end + for (let grown = true; grown;) { + grown = false + for (const scan of scans) { + while (scan.hit !== undefined && scan.hit.start < end) { + if (scan.hit.end > end) { + end = scan.hit.end + grown = true + } + // Overlapping matches of one format join as well, so a key that starts inside another is masked whole. + scan.hit = find(scan.regex, text, scan.hit.start + 1) + } + } + } + return { id: 'secret', start, end, data: { masked: first.format.mask(text.slice(start, end)) } } + }, +} diff --git a/packages/client/ui-secret-mask/tests/secret-rule-equivalence.client.spec.ts b/packages/client/ui-secret-mask/tests/secret-rule-equivalence.client.spec.ts new file mode 100644 index 0000000000..f3e51ab6ca --- /dev/null +++ b/packages/client/ui-secret-mask/tests/secret-rule-equivalence.client.spec.ts @@ -0,0 +1,102 @@ +/** + * The prefix-pruned matcher produces the same nodes as the regular-expression + * matcher it replaced, through the production evaluator, on fixed and generated inputs. + */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished } from 'vitest' +import type { UserTextRule, UserTextTransformContext } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/user-text-registry.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from '@deepseek-ai/dsh-client-ui-conversation/src/client/user-text/whitespace-rules.ts' +import { createSecretRule } from '../src/client/secret-rule.ts' +import { regexSecretRule } from './regex-oracle.client.ts' + +function evaluator(rule: UserTextRule) { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const registry = new UserTextRegistry(ctx) + for (const each of [rule, collapseWhitespaceRule, trimWhitespaceRule]) registry.register(each) + return registry.createEvaluator() +} + +const join = (...parts: string[]): string => parts.join('') +/** Fragments that begin, continue, break, or end each recognized format. */ +const FRAGMENTS = [ + join('s', 'k-'), join('s', 'k_live_'), join('r', 'k_test_'), join('AI', 'za'), join('gh', 'p_'), join('gh', 's_'), + join('github', '_pat_'), join('gl', 'pat-'), join('np', 'm_'), join('h', 'f_'), join('AK', 'IA'), join('AS', 'IA'), + join('LT', 'AI'), join('AK', 'ID'), join('xo', 'xb-'), join('wh', 'sec_'), join('ey', 'J'), '.', join('.ey', 'J'), + join('-----BEGIN', ' '), join('-----END', ' '), ' PRIVATE KEY-----', 'PRIVATE KEY-----', 'RSA ', + '://', 'https', 'postgres', ':', '@', '/', '?', '#', ' ', '\n', '\r\n', '\t', '-', '_', '+', + 'a', 'Z', '0', '7', 'abcdefgh', 'ABCDEFGH', '01234567', 'a1B2c3D4e5F6g7H8i9J0', '用', ':', '🙂', +] as const + +/** Deterministic generator so every run checks the same inputs. */ +function generator(seed: number): () => number { + let state = seed + return () => { + state = (state + 0x6d2b79f5) | 0 + let mixed = Math.imul(state ^ (state >>> 15), 1 | state) + mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed + return ((mixed ^ (mixed >>> 14)) >>> 0) / 4_294_967_296 + } +} + +function generated(count: number, seed: number, maxFragments = 60): string[] { + const random = generator(seed) + return Array.from({ length: count }, () => { + const length = 1 + Math.floor(random() * maxFragments) + return Array.from({ length }, () => { + const fragment = FRAGMENTS[Math.floor(random() * FRAGMENTS.length)]! + // Repeat short fragments so length thresholds are crossed on both sides. + return fragment.length <= 2 ? fragment.repeat(1 + Math.floor(random() * 40)) : fragment + }).join('') + }) +} + +const fill = (unit: string, characters: number): string => unit.repeat(Math.ceil(characters / unit.length)).slice(0, characters) +const FIXED = [ + '', + join('用 ', 'sk', '-', '0123456789abcdef0123456789abcdef', ' 试试'), + join('postgres://admin:', 'p4ss-W0rd', '@db.internal:5432/app'), + join('git clone https://x-access-token:', 'gh', 'p_', fill('a1B2c3', 36), '@github.com/o/r.git'), + join('redis://:p4ss@cache https://example.com:8080/a@b https://example.com:8443?e=a@b'), + join('https://', 'sk', '-', '0123456789abcdef0123456789abcdef', ':p4ss-W0rd@api.example.com/v1'), + [join('-----BEGIN', ' OPENSSH PRIVATE KEY-----'), 'b3BlbnNzaC1rZXk', join('-----END', ' OPENSSH PRIVATE KEY-----')].join('\n'), + [join('-----BEGIN', ' PRIVATE KEY-----'), 'MIIEvQIBADANBgkq', join('-----END', ' PRIVATE KEY-----')].join('\r\n'), + join('-----BEGIN', ' PRIVATE KEY-----', 'MIIE', '-----END', ' PRIVATE KEY-----'), + join('ey', 'J', fill('a1B2', 17), '.', 'ey', 'J', fill('c3D4', 30), '.', fill('e5F6', 43)), + join('xo', 'xb-1234567890-', 'sk', '-abc_', fill('a1B2', 20)), + join('AK', 'IA', 'ABCDEFGHIJ234567 ', 'AK', 'IA', 'ABCDEFGHIJ2345678 ', 'LT', 'AI', fill('a1', 20), ' ', 'AK', 'ID', fill('a1', 40)), + join('x', 's', 'k-----BEGIN', ' RSA PRIVATE KEY-----\nabc\n'), + join('gl', 'pat-----BEGIN', ' RSA PRIVATE KEY-----\nabc\n-----END', ' RSA PRIVATE KEY-----'), + join('LT', 'AIza', 'a1B2c3D4e5F6 '), + fill(join('-', 's', 'k-', 'gh', 'p_', 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJ'), 2_000), + fill(join('s', 'k-'), 2_000), + fill(join('ey', 'Jabcdefgh-'), 2_000), + fill(join('-----BEGIN', ' RSA PRIVATE KEY-----\nabc\n'), 2_000), + fill('a://u:', 2_000), + fill(`abcdefghijklmnop://${'u'.repeat(250)}:`, 2_000), + fill(join('gh', 'p_', fill('a1B2c3', 35), ' '), 2_000), +] + +const context: UserTextTransformContext = { read: () => undefined } + +describe('prefix-pruned credential matching', () => { + it.each([['fixed', FIXED], ['generated', generated(5_000, 5824)]] as const)('matches the regular-expression nodes on %s inputs', (_name, texts) => { + const pruned = evaluator(createSecretRule()) + const oracle = evaluator(regexSecretRule) + for (const text of texts) { + for (const facts of [{}, { collapseWhitespace: true, trimWhitespace: true }]) { + expect(pruned({ text, facts }), JSON.stringify(text)).toEqual(oracle({ text, facts })) + } + } + }) + + it('matches the regular-expression candidate from every query offset', () => { + const rule = createSecretRule() + for (const text of [...FIXED.filter(text => text.length <= 600), ...generated(400, 77, 25)]) { + for (let from = 0; from <= text.length; from++) { + expect(rule.match(text, from, context), `${JSON.stringify(text)} from ${String(from)}`).toEqual(regexSecretRule.match(text, from, context)) + } + } + }) +}) diff --git a/packages/client/ui-secret-mask/tests/secret-rule.client.spec.ts b/packages/client/ui-secret-mask/tests/secret-rule.client.spec.ts new file mode 100644 index 0000000000..8bc69500bb --- /dev/null +++ b/packages/client/ui-secret-mask/tests/secret-rule.client.spec.ts @@ -0,0 +1,245 @@ +/** + * Credential recognition, masking forms, and forward-query behavior through the + * production UserText evaluator. + */ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { UserTextNode, UserTextRule, UserTextTransformContext } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/user-text-registry.ts' +import { collapseWhitespaceRule, trimWhitespaceRule } from '@deepseek-ai/dsh-client-ui-conversation/src/client/user-text/whitespace-rules.ts' +import { formatTables } from '../src/client/format-tables.ts' +import { createSecretRule } from '../src/client/secret-rule.ts' + +// Samples are assembled at run time so the repository holds no literal in a credential format. +const hex = (length: number): string => '0123456789abcdef'.repeat(8).slice(0, length) +const mixed = (length: number): string => 'a1B2c3D4e5F6g7H8i9J0'.repeat(8).slice(0, length) +const stars = (length: number): string => '*'.repeat(length) +const join = (...parts: string[]): string => parts.join('') + +function setup(rules: readonly UserTextRule[] = [createSecretRule()]) { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const registry = new UserTextRegistry(ctx) + for (const rule of rules) registry.register(rule) + return registry.createEvaluator() +} + +const context: UserTextTransformContext = { read: () => undefined } +const isSecret = (node: UserTextNode): node is UserTextNode<'secret'> => node.id === 'secret' +const secrets = (text: string): UserTextNode<'secret'>[] => setup()({ text, facts: {} }).filter(isSecret) +const found = (text: string): string[] => secrets(text).map(node => text.slice(node.start, node.end)) +const masks = (text: string): string[] => secrets(text).map(node => node.data.masked) + +describe('secretRule recognition', () => { + it.each([ + ['a model-service key', join('sk', '-', hex(32))], + ['a project-scoped model-service key', join('sk', '-proj-', mixed(48))], + ['a Google API key', join('AI', 'za', mixed(35))], + ['a GitHub classic token', join('gh', 'p_', mixed(36))], + ['a GitHub fine-grained token', join('github', '_pat_', mixed(22), '_', mixed(59))], + ['a GitLab token', join('gl', 'pat-', mixed(20))], + ['an npm token', join('np', 'm_', mixed(36))], + ['a Hugging Face token', join('h', 'f_', mixed(34))], + ['an AWS access key ID', join('AK', 'IA', 'ABCDEFGHIJ234567')], + ['a temporary AWS access key ID', join('AS', 'IA', 'ABCDEFGHIJ234567')], + ['an Alibaba Cloud AccessKey ID', join('LT', 'AI', mixed(20))], + ['a Tencent Cloud SecretId', join('AK', 'ID', mixed(32))], + ['a Slack token', join('xo', 'xb-', '1234567890-', mixed(24))], + ['a Stripe secret key', join('sk', '_live_', mixed(24))], + ['a Stripe restricted key', join('rk', '_test_', mixed(24))], + ['a Stripe webhook secret', join('wh', 'sec_', mixed(32))], + ['a JSON Web Token', join('ey', 'J', mixed(17), '.', 'ey', 'J', mixed(30), '.', mixed(43))], + ])('recognizes %s inside a sentence', (_name, sample) => { + expect(found(`用 ${sample} 试试`)).toEqual([sample]) + }) + + it.each([ + ['ordinary prose', '把密码改一下,token 用量也看看,password=hunter2'], + ['a hyphenated identifier without digits', 'sk-button-primary-large-rounded'], + ['a key prefix that is too short', 'sk-12345'], + ['a key prefix inside a longer word', join('task', '-', hex(32))], + ['a commit hash', hex(40)], + ['a UUID', '123e4567-e89b-12d3-a456-426614174000'], + ])('leaves %s alone', (_name, text) => { + expect(found(text)).toEqual([]) + }) + + it('leaves addresses without a password alone', () => { + expect(found('https://example.com:8080/a@b https://user@example.com/x git@github.com:o/r.git')).toEqual([]) + expect(found('https://example.com:8443?email=alice@example.org https://example.com:8443#alice@example.org')).toEqual([]) + }) +}) + +describe('secretRule masking', () => { + it('keeps the first eight characters of a key and masks every other character', () => { + const key = join('sk', '-', hex(32)) + expect(masks(`${key}用这个`)).toEqual([key.slice(0, 8) + stars(27)]) + }) + + it('masks only the password of an address that carries credentials', () => { + const text = join('postgres://admin:', 'p4ss-W0rd', '@db.internal:5432/app') + expect(found(text)).toEqual(['p4ss-W0rd']) + expect(masks(text)).toEqual([stars(9)]) + }) + + it('masks a key used as an address user name and the password after it separately', () => { + const key = join('sk', '-', hex(32)) + const text = `https://${key}:p4ss-W0rd@api.example.com/v1` + expect(found(text)).toEqual([key, 'p4ss-W0rd']) + expect(masks(text)).toEqual([key.slice(0, 8) + stars(27), stars(9)]) + }) + + it('masks one character per code point, so an emoji or a lone surrogate in a password is one mark', () => { + expect(masks('postgres://u:p\u{1F642}\ud83dx@db')).toEqual([stars(4)]) + }) + + it('ends a key in an address user name before the password, which a later query finds', () => { + const key = join('sk', '-', hex(32)) + const token = join('gh', 'p_', mixed(36)) + const text = `https://${key}:p4ss-W0rd@api.example.com ${token}` + expect(found(text)).toEqual([key, 'p4ss-W0rd', token]) + }) + + it('masks an address password that has no user name', () => { + expect(found('redis://:p4ss-W0rd@cache:6379/0')).toEqual(['p4ss-W0rd']) + }) + + it('masks a token used as an address password completely', () => { + const token = join('gh', 'p_', mixed(36)) + const text = `git clone https://x-access-token:${token}@github.com/o/r.git` + expect(found(text)).toEqual([token]) + expect(masks(text)).toEqual([stars(token.length)]) + }) + + it('joins an overlapping later match to the earliest one and keeps its mask', () => { + const slack = join('xo', 'xb-', '1234567890-') + const key = join('sk', '-abc_', mixed(20)) + const text = `${slack}${key} 完` + expect(found(text)).toEqual([slack + key]) + expect(masks(text)).toEqual([(slack + key).slice(0, 8) + stars(slack.length + key.length - 8)]) + }) + + it('masks the body of a private key block and keeps its first and last lines', () => { + const begin = join('-----BEGIN', ' OPENSSH PRIVATE KEY-----') + const end = join('-----END', ' OPENSSH PRIVATE KEY-----') + const block = [begin, 'b3BlbnNzaC1rZXk', 'AAAAB3NzaC1yc2E=', end].join('\n') + const text = `私钥在这\n${block}\n帮我配一下` + expect(found(text)).toEqual([block]) + expect(masks(text)).toEqual([[begin, stars(15), stars(16), end].join('\n')]) + }) + + it('keeps carriage returns of a private key block with CRLF line endings', () => { + const begin = join('-----BEGIN', ' PRIVATE KEY-----') + const end = join('-----END', ' PRIVATE KEY-----') + const text = [begin, 'MIIEvQIBADANBgkq', end].join('\r\n') + expect(masks(text)).toEqual([[begin, stars(16), end].join('\r\n')]) + }) + + it('masks a private key block that is cut off before its last line', () => { + const begin = join('-----BEGIN', ' RSA PRIVATE KEY-----') + const text = `${begin}\nMIIEowIBAAKCAQEA` + expect(found(text)).toEqual([text]) + expect(masks(text)).toEqual([`${begin}\n${stars(16)}`]) + }) + + it.each([join('s', 'k-'), join('gl', 'pat-'), join('xo', 'xb-')])('finds a private key block whose first dash ends the key prefix %s', (prefix) => { + const block = [join('-----BEGIN', ' RSA PRIVATE KEY-----'), 'MIIEowIBAAKCAQEA', join('-----END', ' RSA PRIVATE KEY-----')].join('\n') + const text = `x${prefix.slice(0, -1)}${block}` + expect(found(text)).toEqual([block]) + }) + + it('masks a key longer than four thousand characters one mark per character', () => { + const key = join('sk', '-', hex(16), 'a'.repeat(5_000)) + expect(masks(`${key} 完`)).toEqual([key.slice(0, 8) + stars(key.length - 8)]) + }) + + it('joins a private key block that starts inside a key and keeps the line breaks of both', () => { + const key = join('sk', '-', hex(20)) + const block = [join('-----BEGIN', ' RSA PRIVATE KEY-----'), 'MIIE', join('-----END', ' RSA PRIVATE KEY-----')].join('\r\n') + const text = `${key}${block}` + expect(found(text)).toEqual([text]) + const tail = text.slice(8).split('\r\n').map(line => stars(line.length)).join('\r\n') + expect(masks(text)).toEqual([text.slice(0, 8) + tail]) + }) + + it('masks a private key body one mark per code point, including lone and cut surrogates', () => { + const begin = join('-----BEGIN', ' PRIVATE KEY-----') + const end = join('-----END', ' PRIVATE KEY-----') + const text = [begin, 'a\u{1F642}b\udc00c\ud83dx\ud83d', end].join('\n') + expect(masks(text)).toEqual([[begin, stars(8), end].join('\n')]) + }) + + it('masks private key body lines longer than four thousand characters, before either line break', () => { + const begin = join('-----BEGIN', ' PRIVATE KEY-----') + const end = join('-----END', ' PRIVATE KEY-----') + const text = `${begin}\n${'A'.repeat(5_000)}\r\n${'B'.repeat(5_000)}\nC\n${end}` + expect(masks(text)).toEqual([`${begin}\n${stars(5_000)}\r\n${stars(5_000)}\n${stars(1)}\n${end}`]) + }) + + it('masks an address inside a private key block as part of the block', () => { + const begin = join('-----BEGIN', ' PRIVATE KEY-----') + const end = join('-----END', ' PRIVATE KEY-----') + const key = join('sk', '-', hex(32)) + const block = [begin, 'https://u:p4ss@host', key, end].join('\n') + expect(found(`${block}\n用这个`)).toEqual([block]) + }) + + it('masks each of many one-line private key blocks whole, with text after the last', () => { + const block = join('-----BEGIN', ' PRIVATE KEY-----', 'abcd', '-----END', ' PRIVATE KEY-----') + expect(masks(`${block} ${block} 完`)).toEqual([stars(block.length), stars(block.length)]) + }) + + it('masks a private key block written on one line whole', () => { + const text = join('-----BEGIN', ' PRIVATE KEY-----', 'MIIEvQIBADANBgkq', '-----END', ' PRIVATE KEY-----') + expect(masks(text)).toEqual([stars(text.length)]) + }) +}) + +describe('secretRule scheduling', () => { + it('finds format starts through grouped literals only, so scanning cannot backtrack', () => { + const literals = formatTables().prefixSource.replace(/\\./gu, '').replaceAll('(?:', '').replaceAll(')', '') + expect(literals.split('|').length).toBeGreaterThan(20) + expect(literals).not.toMatch(/[*+?{}()[\].^$]/u) + }) + + it('reads no Facts, queries forward once per credential, and reuses the result across Facts updates', () => { + const read = vi.fn() + const rule = createSecretRule() + const match = vi.fn['match']>((text, from, context) => rule.match(text, from, { + read: (key) => { read(key); return context.read(key) }, + })) + const evaluate = setup([{ ...rule, match }]) + const first = join('gh', 'p_', mixed(36)) + const second = join('sk', '-', hex(32)) + const text = `${first} 和 ${second}` + const before = evaluate({ text, facts: {} }) + expect(before.filter(isSecret).map(node => text.slice(node.start, node.end))).toEqual([first, second]) + expect(before.map(node => [node.start, node.end])).toEqual([ + [0, first.length], [first.length, first.length + 3], [first.length + 3, text.length], + ]) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, first.length, text.length]) + expect(evaluate({ text, facts: { collapseWhitespace: true } })).toBe(before) + expect(match).toHaveBeenCalledTimes(3) + expect(read).not.toHaveBeenCalled() + }) + + it.each(['postgres://admin:p4ss@db', 'redis://:p4ss@cache'])('finds the same address password in %s from any cursor before it', (text) => { + const start = text.indexOf('p4ss') + for (let from = 0; from <= start; from++) { + // A fresh instance per cursor: no query earlier in the text warms its memo. + expect(createSecretRule().match(text, from, context), `from ${String(from)}`).toEqual({ id: 'secret', start, end: start + 4, data: { masked: stars(4) } }) + } + expect(createSecretRule().match(text, start + 1, context)).toBeUndefined() + }) + + it('keeps line breaks of a private key block when queue whitespace transforms run beside it', () => { + const begin = join('-----BEGIN', ' PRIVATE KEY-----') + const end = join('-----END', ' PRIVATE KEY-----') + const block = [begin, 'MIIEvQIBADANBgkq', end].join('\n') + const evaluate = setup([createSecretRule(), collapseWhitespaceRule, trimWhitespaceRule]) + const nodes = evaluate({ text: ` 私钥:\n${block}\n `, facts: { collapseWhitespace: true, trimWhitespace: true } }) + const display = (node: UserTextNode): string => + isSecret(node) ? node.data.masked : node.id === 'text' ? node.data.display ?? node.data.text : '' + expect(nodes.map(display).join('')).toBe(`私钥: ${[begin, stars(16), end].join('\n')}`) + }) +}) diff --git a/packages/client/ui-secret-mask/tests/secret-text.client.spec.tsx b/packages/client/ui-secret-mask/tests/secret-text.client.spec.tsx new file mode 100644 index 0000000000..c075d9de30 --- /dev/null +++ b/packages/client/ui-secret-mask/tests/secret-text.client.spec.tsx @@ -0,0 +1,59 @@ +// @vitest-environment jsdom +/** The masked credential renderer: reveal control, accessible names, and reset to masked. */ +import { cleanup, fireEvent, render } from '@testing-library/react' +import type { ComponentProps } from 'react' +import { afterEach, describe, expect, it } from 'vitest' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { SecretText } from '../src/client/SecretText.tsx' +import { en, zh } from '../src/client/locales.ts' + +afterEach(cleanup) + +type Props = ComponentProps + +// Assembled at run time so the repository holds no literal in a credential format. +const KEY = ['sk', '-', '0123456789abcdef0123456789abcdef'].join('') +const OTHER = ['sk', '-', 'fedcba9876543210fedcba9876543210'].join('') +const masked = (value: string): string => value.slice(0, 8) + '*'.repeat(value.length - 8) + +function props(raw: string, interactive: boolean, dictionary: Record = zh): Props { + // The component reads only these owner and locale seats. + return { + node: { id: 'secret', start: 0, end: raw.length, data: { masked: masked(raw) } }, + raw, interactive, t: makeTranslate(dictionary), + } as Props +} + +describe('SecretText', () => { + it('draws only the masked form without a control in non-interactive text', () => { + const view = render(
) + const run = view.container.querySelector('[data-secret]')! + expect(run.textContent).toBe(masked(KEY)) + expect(view.container.querySelector('button')).toBeNull() + }) + + it('reveals and hides the value from its own control', () => { + const view = render() + const run = view.container.querySelector('[data-secret]')! + const reveal = view.getByRole('button', { name: '显示密钥' }) + expect(run.textContent).toBe(masked(KEY)) + expect(reveal.getAttribute('aria-pressed')).toBe('false') + expect(reveal.querySelector('svg')).not.toBeNull() + + fireEvent.click(reveal) + expect(run.textContent).toBe(KEY) + const hide = view.getByRole('button', { name: '隐藏密钥' }) + expect(hide.getAttribute('aria-pressed')).toBe('true') + + fireEvent.click(hide) + expect(run.textContent).toBe(masked(KEY)) + }) + + it('starts masked again when a different credential reuses the same element', () => { + const view = render() + fireEvent.click(view.getByRole('button', { name: 'Show secret' })) + view.rerender() + expect(view.container.querySelector('[data-secret]')!.textContent).toBe(masked(OTHER)) + expect(view.getByRole('button', { name: 'Show secret' }).getAttribute('aria-pressed')).toBe('false') + }) +}) diff --git a/packages/client/ui-secret-mask/tsconfig.json b/packages/client/ui-secret-mask/tsconfig.json new file mode 100644 index 0000000000..a783ae90ea --- /dev/null +++ b/packages/client/ui-secret-mask/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-slots" + } + ] +} diff --git a/packages/client/ui-secret-mask/tsdown.config.ts b/packages/client/ui-secret-mask/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-secret-mask/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-session/locale/en.json b/packages/client/ui-session/locale/en.json new file mode 100644 index 0000000000..03c3a8e2cc --- /dev/null +++ b/packages/client/ui-session/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-session" + } +} diff --git a/packages/client/ui-session/locale/zh.json b/packages/client/ui-session/locale/zh.json new file mode 100644 index 0000000000..8dee9f572e --- /dev/null +++ b/packages/client/ui-session/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话界面连接", + "description": "将会话控制和状态连接到 React 界面组件。" + } +} diff --git a/packages/client/ui-session/package.json b/packages/client/ui-session/package.json index 8e5426b204..db6caa564f 100644 --- a/packages/client/ui-session/package.json +++ b/packages/client/ui-session/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -54,10 +55,10 @@ "@deepseek-ai/dsh-remote-mock": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-session/tsdown.config.ts b/packages/client/ui-session/tsdown.config.ts index ca879a1232..7aa03cebc1 100644 --- a/packages/client/ui-session/tsdown.config.ts +++ b/packages/client/ui-session/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-session', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-account/locale/en.json b/packages/client/ui-settings-account/locale/en.json new file mode 100644 index 0000000000..ce3988b946 --- /dev/null +++ b/packages/client/ui-settings-account/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-account" + } +} diff --git a/packages/client/ui-settings-account/locale/zh.json b/packages/client/ui-settings-account/locale/zh.json new file mode 100644 index 0000000000..505a15ac87 --- /dev/null +++ b/packages/client/ui-settings-account/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "账号设置界面", + "description": "管理 DeepSeek 登录,并打开平台账单页面。" + } +} diff --git a/packages/client/ui-settings-account/package.json b/packages/client/ui-settings-account/package.json index 3fcb8027f7..6f9784dfbe 100644 --- a/packages/client/ui-settings-account/package.json +++ b/packages/client/ui-settings-account/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -63,16 +64,15 @@ "@deepseek-ai/dsh-settings": "workspace:*", "@testing-library/react": "^16.3.3", "@types/big.js": "^6.2.2", - "@types/react": "~18.3.1", "react": "^18.2.0", "react-dom": "^18.2.0", "@deepseek-ai/dsh-client-ui-settings-models": "workspace:*", - "@types/react-dom": "~18.3.0", "@deepseek-ai/dsh-host-webserver": "workspace:*", "big.js": "^7.0.1", "@deepseek-ai/dsh-client-product-analytics": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-account/tsdown.config.ts b/packages/client/ui-settings-account/tsdown.config.ts index 08f459e8f7..45af1505d1 100644 --- a/packages/client/ui-settings-account/tsdown.config.ts +++ b/packages/client/ui-settings-account/tsdown.config.ts @@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises' import { basename } from 'node:path' import { fileURLToPath } from 'node:url' -const bundle = clientBundle('@deepseek-ai/dsh-client-ui-settings-account', ['lib/types/index.js']) +const bundle = clientBundle(import.meta.dirname, ['lib/types/index.js']) export default ((options) => bundle(options).map(config => ({ ...config, diff --git a/packages/client/ui-settings-agent-loop/locale/en.json b/packages/client/ui-settings-agent-loop/locale/en.json new file mode 100644 index 0000000000..5c9a7a32f1 --- /dev/null +++ b/packages/client/ui-settings-agent-loop/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-agent-loop" + } +} diff --git a/packages/client/ui-settings-agent-loop/locale/zh.json b/packages/client/ui-settings-agent-loop/locale/zh.json new file mode 100644 index 0000000000..c6a1dff952 --- /dev/null +++ b/packages/client/ui-settings-agent-loop/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "智能体运行设置", + "description": "配置同时执行的工具调用数量上限。" + } +} diff --git a/packages/client/ui-settings-agent-loop/package.json b/packages/client/ui-settings-agent-loop/package.json index 0361a71f09..16e111f91f 100644 --- a/packages/client/ui-settings-agent-loop/package.json +++ b/packages/client/ui-settings-agent-loop/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -54,10 +55,10 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-agent-loop/tsdown.config.ts b/packages/client/ui-settings-agent-loop/tsdown.config.ts index 7ae5a8134a..7aa03cebc1 100644 --- a/packages/client/ui-settings-agent-loop/tsdown.config.ts +++ b/packages/client/ui-settings-agent-loop/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-agent-loop', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-general/locale/en.json b/packages/client/ui-settings-general/locale/en.json new file mode 100644 index 0000000000..f6258cc9cc --- /dev/null +++ b/packages/client/ui-settings-general/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-general" + } +} diff --git a/packages/client/ui-settings-general/locale/zh.json b/packages/client/ui-settings-general/locale/zh.json new file mode 100644 index 0000000000..ed8dea60c4 --- /dev/null +++ b/packages/client/ui-settings-general/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "通用设置与欢迎提示", + "description": "提供通用设置、设置窗口文案和首次使用提示。" + } +} diff --git a/packages/client/ui-settings-general/package.json b/packages/client/ui-settings-general/package.json index 99927e5391..ba5dcebee3 100644 --- a/packages/client/ui-settings-general/package.json +++ b/packages/client/ui-settings-general/package.json @@ -26,7 +26,8 @@ "types": "./lib/types/types.d.ts" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -66,8 +67,6 @@ "@deepseek-ai/dsh-client-ui-sidebar": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-remote-mock": "workspace:*", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "clsx": "^2.0.0", "react": "^18.2.0", "@deepseek-ai/dsh-settings": "workspace:*", @@ -75,6 +74,7 @@ "@deepseek-ai/dsh-client-shortcuts": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-general/tsdown.config.ts b/packages/client/ui-settings-general/tsdown.config.ts index 45665e4054..7aa03cebc1 100644 --- a/packages/client/ui-settings-general/tsdown.config.ts +++ b/packages/client/ui-settings-general/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-general', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-models/locale/en.json b/packages/client/ui-settings-models/locale/en.json new file mode 100644 index 0000000000..100cf6fbe5 --- /dev/null +++ b/packages/client/ui-settings-models/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-models" + } +} diff --git a/packages/client/ui-settings-models/locale/zh.json b/packages/client/ui-settings-models/locale/zh.json new file mode 100644 index 0000000000..6ce8aece28 --- /dev/null +++ b/packages/client/ui-settings-models/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "模型设置界面", + "description": "管理模型服务及其接入配置,并提供相关引导。" + } +} diff --git a/packages/client/ui-settings-models/package.json b/packages/client/ui-settings-models/package.json index 69474742e2..4884bc67a0 100644 --- a/packages/client/ui-settings-models/package.json +++ b/packages/client/ui-settings-models/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -52,7 +53,6 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", @@ -64,6 +64,7 @@ "@deepseek-ai/schemastery": "workspace:~" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-models/tsdown.config.ts b/packages/client/ui-settings-models/tsdown.config.ts index 758f6681f8..7aa03cebc1 100644 --- a/packages/client/ui-settings-models/tsdown.config.ts +++ b/packages/client/ui-settings-models/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-models', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-plugin-inventory/README.i18n.yaml b/packages/client/ui-settings-plugin-inventory/README.i18n.yaml index d4b459bb3e..6aca3b6682 100644 --- a/packages/client/ui-settings-plugin-inventory/README.i18n.yaml +++ b/packages/client/ui-settings-plugin-inventory/README.i18n.yaml @@ -18,8 +18,8 @@ en: 67637808e7940157 zh: d4d0716ea4d33e4a /deepseek-ai-dsh-client-ui-settings-plugin-inventory/use-this-package/reading-a-card: - en: 141d6a73e99fee51 - zh: 2aa28b174867c967 + en: bb000df9983be741 + zh: d54ee50bafd136fb /deepseek-ai-dsh-client-ui-settings-plugin-inventory/use-this-package/the-preset-switcher: en: 84e5938329199a22 zh: 6f5cfaac56433e8b diff --git a/packages/client/ui-settings-plugin-inventory/README.md b/packages/client/ui-settings-plugin-inventory/README.md index 2107090327..bf5ad3d53e 100644 --- a/packages/client/ui-settings-plugin-inventory/README.md +++ b/packages/client/ui-settings-plugin-inventory/README.md @@ -33,7 +33,7 @@ A failed installation with pending pnpm build permissions offers **Allow these s Each collapsed card uses the plugin's localized title and description when available; a description shows at most two lines until its card is expanded. Settings shortens literal package-name or module-name fallbacks by removing the npm scope and the `cordis:`, `cordis-plugin-`, or `dsh-`/`dsh-host-`/`dsh-client-` prefix; locale titles remain unchanged. The Host supplies locale and package-field fallbacks in `meta`; the Client selects the current language. Full module specifiers remain available in details and search. Missing descriptions are omitted, and metadata diagnostics appear with the card. This compact naming applies only to Settings, not the sidebar's Plugins page. -A small enablement tag marks only the states that differ from plainly enabled: disabled, conditional, provided by presets, and failed; a plainly enabled row carries no tag. A colored root-fiber status dot marks the live phases no tag states: `pending` maps to idle, while `loading` and `unloading` map to ongoing; an `active` or `failed` fiber shows no dot. The stable entry id appears in a code chip at the card's bottom-left, in line with the title, only when it differs from the title: a composition-generated id drops its leading `include:` marker there, and an id that then repeats the title is omitted. Whenever the chip shows, its hover text and the card's accessible name carry the complete id; search and expanded details always retain it. Long entry ids truncate in the chip and remain available on hover. Expanding one card reveals its full description, the declared entry id, the full module specifier, and the state facts: a preset row names the preset it comes from, its runtime status when the composition is live, and its disable condition when it carries one; a preset-provided global row explains that agent presets provide it per session, names the presets that enable it, and offers a jump into the preset group. Preset names resolve through the shared `presetDisplayText` fold (`dsh-agent-preset-registry/display`) over [`ui-agent-preset`](../ui-agent-preset/README.md)'s dictionaries: shipped presets follow the active locale while user-authored ones keep their own metadata, so an English surface never echoes the preset declarations' Chinese names. Search filters both groups by localized title and description, module name, and entry id. +A small enablement tag marks only the states that differ from plainly enabled: disabled, conditional, provided by presets, and failed; a plainly enabled row carries no tag. A colored root-fiber status dot marks the live phases no tag states: `pending` maps to idle, while `loading` and `unloading` map to ongoing; an `active` or `failed` fiber shows no dot. The stable entry id appears in a code chip at the card's bottom-left, in line with the title, only when it differs from the title: a composition-generated id drops its leading `include:` marker there, and an id that then repeats the title is omitted. Whenever the chip shows, its hover text and the card's accessible name carry the complete id; search and expanded details always retain it. Long entry ids truncate in the chip and remain available on hover. Expanding one card reveals its full description, the declared entry id, the full module specifier, and the state facts: a preset row names the preset it comes from, its runtime status when the composition is live, and its disable condition when it carries one; a preset-provided global row explains that agent presets provide it per session, names the presets that enable it. Preset names resolve through the shared `presetDisplayText` fold (`dsh-agent-preset-registry/display`) over [`ui-agent-preset`](../ui-agent-preset/README.md)'s dictionaries: shipped presets follow the active locale while user-authored ones keep their own metadata, so an English surface never echoes the preset declarations' Chinese names. Search filters both groups by localized title and description, module name, and entry id. ### The preset switcher diff --git a/packages/client/ui-settings-plugin-inventory/README.zh.md b/packages/client/ui-settings-plugin-inventory/README.zh.md index 737ff343de..6a992313c1 100644 --- a/packages/client/ui-settings-plugin-inventory/README.zh.md +++ b/packages/client/ui-settings-plugin-inventory/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" 每张收起的卡片使用插件可用的本地化标题与描述;描述最多显示两行,展开卡片后显示全文。设置页会缩短字面的包名或模块名回退值,移除 npm scope 以及 `cordis:`、`cordis-plugin-` 或 `dsh-`/`dsh-host-`/`dsh-client-` 前缀;locale 标题保持原样。Host 在 `meta` 中提供 locale 与包字段的回退结果,Client 选择当前语言。详情与搜索仍保留完整模块标识。缺失的描述不显示,元信息诊断随卡片展示。这种短名显示仅用于设置页,不影响侧栏的插件页。 -表示启停状态的小标签只标记与普通启用不同的状态:已停用、条件启用、由预设提供与启动失败;普通启用的行不带标签。彩色根 fiber 状态圆点标记没有标签表达的存活阶段:`pending` 映射为 idle,`loading` 与 `unloading` 映射为 ongoing;`active` 或 `failed` fiber 不显示圆点。稳定的条目 id 仅在与标题不同时显示,位于卡片左下角的代码标签中,与标题左对齐:组合生成的 id 在此省略开头的 `include:` 标记,省略后与标题相同的 id 不再重复显示。显示代码标签时,其悬停提示与卡片的无障碍名称带完整 id;搜索与展开详情始终保留完整 id。长条目 id 会在代码标签内截断,悬停时仍可查看完整值。展开卡片后会显示完整描述、声明的条目 id、完整模块标识与状态事实:预设行说明它来自哪个预设、组合存活时的运行状态,以及它携带的禁用条件;被预设提供的全局行说明它由 Agent 预设按会话提供、列出启用它的预设,并提供跳转到预设组的入口。预设名经共享的 `presetDisplayText` 纯函数(`dsh-agent-preset-registry/display`)叠在 [`ui-agent-preset`](../ui-agent-preset/README.zh.md) 的字典上解析:内置预设走当前语言,用户自建预设保留自己的元数据,因此英文界面不会回显预设声明里的中文名。搜索按本地化标题与描述、模块名称及条目 id 过滤两组。 +表示启停状态的小标签只标记与普通启用不同的状态:已停用、条件启用、由预设提供与启动失败;普通启用的行不带标签。彩色根 fiber 状态圆点标记没有标签表达的存活阶段:`pending` 映射为 idle,`loading` 与 `unloading` 映射为 ongoing;`active` 或 `failed` fiber 不显示圆点。稳定的条目 id 仅在与标题不同时显示,位于卡片左下角的代码标签中,与标题左对齐:组合生成的 id 在此省略开头的 `include:` 标记,省略后与标题相同的 id 不再重复显示。显示代码标签时,其悬停提示与卡片的无障碍名称带完整 id;搜索与展开详情始终保留完整 id。长条目 id 会在代码标签内截断,悬停时仍可查看完整值。展开卡片后会显示完整描述、声明的条目 id、完整模块标识与状态事实:预设行说明它来自哪个预设、组合存活时的运行状态,以及它携带的禁用条件;被预设提供的全局行说明它由 Agent 预设按会话提供、列出启用它的预设。预设名经共享的 `presetDisplayText` 纯函数(`dsh-agent-preset-registry/display`)叠在 [`ui-agent-preset`](../ui-agent-preset/README.zh.md) 的字典上解析:内置预设走当前语言,用户自建预设保留自己的元数据,因此英文界面不会回显预设声明里的中文名。搜索按本地化标题与描述、模块名称及条目 id 过滤两组。 ### 预设切换器 diff --git a/packages/client/ui-settings-plugin-inventory/locale/en.json b/packages/client/ui-settings-plugin-inventory/locale/en.json new file mode 100644 index 0000000000..38e92db659 --- /dev/null +++ b/packages/client/ui-settings-plugin-inventory/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-plugin-inventory" + } +} diff --git a/packages/client/ui-settings-plugin-inventory/locale/zh.json b/packages/client/ui-settings-plugin-inventory/locale/zh.json new file mode 100644 index 0000000000..df4f5ab36f --- /dev/null +++ b/packages/client/ui-settings-plugin-inventory/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "内置插件列表界面", + "description": "在设置中查看全局插件和各 Agent 预设使用的插件。" + } +} diff --git a/packages/client/ui-settings-plugin-inventory/package.json b/packages/client/ui-settings-plugin-inventory/package.json index 8eb5473590..260faa8169 100644 --- a/packages/client/ui-settings-plugin-inventory/package.json +++ b/packages/client/ui-settings-plugin-inventory/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,7 +56,6 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-package-manifest": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0", @@ -65,6 +65,7 @@ "@deepseek-ai/dsh-client-store": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css index be3aa42773..5836c2b56a 100644 --- a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css +++ b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.module.css @@ -300,17 +300,6 @@ font-variant-numeric: tabular-nums; } -/* A middle dot with equal space on both sides separates the subtitle's parts. */ -.groupSub > * + *::before { - content: '·'; - padding: 0 6px; - color: var(--dsw-alias-label-tertiary); -} - -.failedCount { - color: var(--dsw-alias-state-error-primary); -} - /* The preset switcher trigger mirrors the General-settings selector pill. */ .switcher { display: inline-flex; @@ -415,13 +404,6 @@ height: 12px; } -.enabledIn { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 4px 10px; -} - .card[data-failed='true'] { border-color: color-mix(in srgb, var(--dsw-alias-state-error-primary) 45%, transparent); } diff --git a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx index 57810b993a..8138b0d397 100644 --- a/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx +++ b/packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx @@ -413,18 +413,7 @@ export function PluginInventorySettingsTab( facts={providers !== undefined ? [ [t('configuration'), t('presetProvidedDetail')], - [t('enabledIn'), ( - - {providers.map(preset => presetName(preset)).join(' · ')} - - - )], + [t('enabledIn'), providers.map(preset => presetName(preset)).join(' · ')], ] : [ [t('configuration'), t(entry.enabled ? 'enabledTag' : 'disabledTag')], @@ -527,12 +516,7 @@ export function PluginInventorySettingsTab( />
-

- {t('presetSubtitle')} - - {`${String(selectedRows.length)} ${t('countUnit')}`} - -

+

{t('presetSubtitle')}

{presetEffectiveOpen ? (
{selected.broken !== undefined ? ( @@ -577,13 +561,7 @@ export function PluginInventorySettingsTab( {t('globalTitle')}
-

- {t('globalSubtitle')} - {`${String(globalCount)} ${t('countUnit')}`} - {filteredFailed.length > 0 ? ( - {filteredFailed.length} {t('failedCountLabel')} - ) : null} -

+

{t('globalSubtitle')}

{globalEffectiveOpen && globalCount > 0 ? (
    {filteredFailed.map(entry => globalRowCard(entry))} diff --git a/packages/client/ui-settings-plugin-inventory/src/client/locales.ts b/packages/client/ui-settings-plugin-inventory/src/client/locales.ts index 3fb7662a86..d535c07a9a 100644 --- a/packages/client/ui-settings-plugin-inventory/src/client/locales.ts +++ b/packages/client/ui-settings-plugin-inventory/src/client/locales.ts @@ -15,7 +15,6 @@ export const zh = { emptySearch: '没有匹配的插件。', presetTitle: '会话插件', presetSubtitle: '由 Agent 预设按会话组成', - countUnit: '个', switcherLabel: '选择要查看的 Agent 预设', presetOptionDefault: '{name}(默认)', presetOptionBroken: '{name}(加载失败)', @@ -23,9 +22,7 @@ export const zh = { globalSubtitle: '系统与所有会话共用', presetProvidedDetail: '全局已停用,由 Agent 预设按会话提供', enabledIn: '启用于', - viewInPreset: '去预设分组查看', matchesInOtherPresets: '其他预设中还有 {count} 个匹配:', - failedCountLabel: '个失败', enabledTag: '已启用', disabledTag: '已停用', conditionalTag: '条件启用', @@ -62,7 +59,6 @@ export const en = { emptySearch: 'No matching plugins.', presetTitle: 'Session plugins', presetSubtitle: 'Composed per session by agent presets', - countUnit: 'plugins', switcherLabel: 'Choose the agent preset to inspect', presetOptionDefault: '{name} (default)', presetOptionBroken: '{name} (failed to load)', @@ -70,9 +66,7 @@ export const en = { globalSubtitle: 'Shared by the system and every session', presetProvidedDetail: 'Disabled globally; agent presets provide it per session', enabledIn: 'Enabled in', - viewInPreset: 'View in the preset group', matchesInOtherPresets: '{count} more matches in other presets: ', - failedCountLabel: 'failed', enabledTag: 'Enabled', disabledTag: 'Disabled', conditionalTag: 'Conditional', diff --git a/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx b/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx index 9a87e8d6d8..cd4e5acd14 100644 --- a/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-plugin-inventory/tests/components.client.spec.tsx @@ -193,6 +193,8 @@ describe('PluginInventorySettingsTab', () => { const { locale, pageProps } = localizedProps(list) const view = render() await screen.findByRole('searchbox', { name: en.search }) + expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) + expect(screen.getByText(en.globalSubtitle).textContent).toBe(en.globalSubtitle) fireEvent.click(globalToggle()) const global = screen.getByRole('button', { name: 'Navigation, include:global-navigation, Enabled' }) const preset = screen.getByRole('button', { name: 'Session runner, include:preset-runner, Enabled' }) @@ -209,6 +211,8 @@ describe('PluginInventorySettingsTab', () => { locale.setLocale('zh') view.rerender() + expect(screen.getByText(zh.presetSubtitle).textContent).toBe(zh.presetSubtitle) + expect(screen.getByText(zh.globalSubtitle).textContent).toBe(zh.globalSubtitle) expect(screen.getByRole('button', { name: '导航, include:global-navigation, 已启用' })).toBeTruthy() expect(screen.getByRole('button', { name: '会话执行器, include:preset-runner, 已启用' })).toBeTruthy() expect(screen.getByText('全局导航控件')).toBeTruthy() @@ -321,8 +325,7 @@ describe('PluginInventorySettingsTab', () => { ]) fireEvent.keyDown(document, { key: 'Escape' }) expect(screen.queryAllByRole('menuitem')).toHaveLength(0) - expect(screen.getByText(en.presetSubtitle)).toBeTruthy() - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('6') + expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) // The preset group starts open with its rows while the larger global plane stays folded. expect(presetToggle().getAttribute('aria-expanded')).toBe('true') @@ -338,8 +341,7 @@ describe('PluginInventorySettingsTab', () => { expect(screen.queryByRole('img', { name: en.unobserved })).toBeNull() expect(globalToggle().getAttribute('aria-expanded')).toBe('false') - expect(view.container.querySelector('[data-plugin-count]')?.getAttribute('data-plugin-count')).toBe('7') - expect(screen.getByText(`1 ${en.failedCountLabel}`)).toBeTruthy() + expect(screen.getByText(en.globalSubtitle).textContent).toBe(en.globalSubtitle) // A preset row expands into its source facts. fireEvent.click(screen.getByRole('button', { name: 'pwsh, Conditional' })) @@ -484,14 +486,14 @@ describe('PluginInventorySettingsTab', () => { } pickPreset('ptc') - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('3') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(3) fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash, Enabled' })) // An unnamed preset labels its source by id. expect(screen.getByText(en.fromPreset).nextElementSibling?.textContent).toBe('ptc') pickPreset('坏预设 (failed to load)') expect(screen.getByRole('alert').textContent).toBe('the composition file is missing') - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('0') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) }) it('folds the preset group on demand and reopens it for a search', async () => { @@ -500,10 +502,10 @@ describe('PluginInventorySettingsTab', () => { expect(toggle.getAttribute('aria-expanded')).toBe('true') expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(6) - // The header keeps its count while the rows are folded away. + // The explanatory subtitle remains visible while the rows are folded away. fireEvent.click(toggle) expect(toggle.getAttribute('aria-expanded')).toBe('false') - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('6') + expect(screen.getByText(en.presetSubtitle).textContent).toBe(en.presetSubtitle) expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) fireEvent.change(screen.getByRole('searchbox', { name: en.search }), { target: { value: 'pwsh' } }) @@ -542,28 +544,15 @@ describe('PluginInventorySettingsTab', () => { expect(screen.getByText('Localized standard · Localized ptc')).toBeTruthy() }) - it('jumps from a preset-provided row to the preset that enables it', async () => { - await renderReady() - fireEvent.click(screen.getByRole('button', { name: en.switcherLabel })) - fireEvent.click(screen.getByRole('menuitem', { name: 'ptc' })) - - fireEvent.click(globalToggle()) - fireEvent.click(screen.getByRole('button', { name: 'tool-bash, bash-host, Via presets' })) - fireEvent.click(screen.getByRole('button', { name: en.viewInPreset })) - expect(screen.getByRole('button', { name: en.switcherLabel }).textContent) - .toBe('标准模式 (default)') - }) - it('searches across scopes and points at matches in other presets', async () => { const view = await renderReady() const search = screen.getByRole('searchbox', { name: en.search }) fireEvent.change(search, { target: { value: 'tool-bash' } }) // Searching forces the collapsed global plane and drawer open. - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('1') - expect(view.container.querySelector('[data-plugin-count]')?.getAttribute('data-plugin-count')).toBe('1') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(1) + expect(view.container.querySelectorAll('[data-plugin-scope="global"] li')).toHaveLength(1) expect(screen.getByText(en.presetEnabledTag)).toBeTruthy() - expect(screen.queryByText(`1 ${en.failedCountLabel}`)).toBeNull() const hint = screen.getByText((text: string) => text.startsWith('2 more matches')) expect(hint).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: 'ptc' })) @@ -571,13 +560,13 @@ describe('PluginInventorySettingsTab', () => { // A match visible only in another preset keeps the pointer without rows. fireEvent.change(search, { target: { value: 'crashy' } }) - expect(view.container.querySelector('[data-preset-plugin-count]')?.getAttribute('data-preset-plugin-count')).toBe('0') + expect(view.container.querySelectorAll('[data-plugin-scope="preset"] li')).toHaveLength(0) expect(screen.getByText((text: string) => text.startsWith('1 more matches'))).toBeTruthy() expect(screen.queryByText(en.emptySearch)).toBeNull() // A match on a Loader entry id only reaches the global plane. fireEvent.change(search, { target: { value: '8a1b2c3d' } }) - expect(view.container.querySelector('[data-plugin-count]')?.getAttribute('data-plugin-count')).toBe('1') + expect(view.container.querySelectorAll('[data-plugin-scope="global"] li')).toHaveLength(1) expect(screen.queryByText((text: string) => text.includes('more matches'))).toBeNull() fireEvent.change(search, { target: { value: 'not-a-plugin' } }) diff --git a/packages/client/ui-settings-plugin-inventory/tsdown.config.ts b/packages/client/ui-settings-plugin-inventory/tsdown.config.ts index 205aaf47d4..7aa03cebc1 100644 --- a/packages/client/ui-settings-plugin-inventory/tsdown.config.ts +++ b/packages/client/ui-settings-plugin-inventory/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-plugin-inventory', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-plugins/locale/en.json b/packages/client/ui-settings-plugins/locale/en.json new file mode 100644 index 0000000000..bbe7eea9a3 --- /dev/null +++ b/packages/client/ui-settings-plugins/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-plugins" + } +} diff --git a/packages/client/ui-settings-plugins/locale/zh.json b/packages/client/ui-settings-plugins/locale/zh.json new file mode 100644 index 0000000000..71ab797452 --- /dev/null +++ b/packages/client/ui-settings-plugins/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "内置插件设置入口", + "description": "提供设置中的内置插件入口及其功能标签页。" + } +} diff --git a/packages/client/ui-settings-plugins/package.json b/packages/client/ui-settings-plugins/package.json index cf9c95c7eb..6a3275581a 100644 --- a/packages/client/ui-settings-plugins/package.json +++ b/packages/client/ui-settings-plugins/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -50,10 +51,10 @@ "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-plugins/tsdown.config.ts b/packages/client/ui-settings-plugins/tsdown.config.ts index f9bc4e134b..7aa03cebc1 100644 --- a/packages/client/ui-settings-plugins/tsdown.config.ts +++ b/packages/client/ui-settings-plugins/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-plugins', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-session-log/locale/en.json b/packages/client/ui-settings-session-log/locale/en.json new file mode 100644 index 0000000000..3f4017f7d2 --- /dev/null +++ b/packages/client/ui-settings-session-log/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-session-log" + } +} diff --git a/packages/client/ui-settings-session-log/locale/zh.json b/packages/client/ui-settings-session-log/locale/zh.json new file mode 100644 index 0000000000..fc41c18589 --- /dev/null +++ b/packages/client/ui-settings-session-log/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话日志上传设置", + "description": "设置是否随 DeepSeek 官方模型 API 请求上传会话日志。" + } +} diff --git a/packages/client/ui-settings-session-log/package.json b/packages/client/ui-settings-session-log/package.json index b9bd5efedd..d1f0a7a55e 100644 --- a/packages/client/ui-settings-session-log/package.json +++ b/packages/client/ui-settings-session-log/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -53,13 +54,12 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "@deepseek-ai/dsh-client-ui-layout": "workspace:*", - "react-dom": "^18.2.0", - "@types/react-dom": "~18.3.0" + "react-dom": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-session-log/tsdown.config.ts b/packages/client/ui-settings-session-log/tsdown.config.ts index 701ce5e140..7aa03cebc1 100644 --- a/packages/client/ui-settings-session-log/tsdown.config.ts +++ b/packages/client/ui-settings-session-log/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-session-log', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-shell/locale/en.json b/packages/client/ui-settings-shell/locale/en.json new file mode 100644 index 0000000000..f43265d805 --- /dev/null +++ b/packages/client/ui-settings-shell/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-shell" + } +} diff --git a/packages/client/ui-settings-shell/locale/zh.json b/packages/client/ui-settings-shell/locale/zh.json new file mode 100644 index 0000000000..aed59177c8 --- /dev/null +++ b/packages/client/ui-settings-shell/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "命令执行设置", + "description": "配置命令执行超时和输出长度上限。" + } +} diff --git a/packages/client/ui-settings-shell/package.json b/packages/client/ui-settings-shell/package.json index 0fd6020caf..2afa80d649 100644 --- a/packages/client/ui-settings-shell/package.json +++ b/packages/client/ui-settings-shell/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -54,10 +55,10 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-shell/tsdown.config.ts b/packages/client/ui-settings-shell/tsdown.config.ts index 4e48f8dff3..7aa03cebc1 100644 --- a/packages/client/ui-settings-shell/tsdown.config.ts +++ b/packages/client/ui-settings-shell/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-shell', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-subagent/locale/en.json b/packages/client/ui-settings-subagent/locale/en.json new file mode 100644 index 0000000000..08e121d1c3 --- /dev/null +++ b/packages/client/ui-settings-subagent/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-subagent" + } +} diff --git a/packages/client/ui-settings-subagent/locale/zh.json b/packages/client/ui-settings-subagent/locale/zh.json new file mode 100644 index 0000000000..1498349fa6 --- /dev/null +++ b/packages/client/ui-settings-subagent/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "子智能体设置", + "description": "配置委派深度、并发数量和可选模型。" + } +} diff --git a/packages/client/ui-settings-subagent/package.json b/packages/client/ui-settings-subagent/package.json index 0c1a5abe49..a07ea3707e 100644 --- a/packages/client/ui-settings-subagent/package.json +++ b/packages/client/ui-settings-subagent/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,10 +56,10 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-subagent/tsdown.config.ts b/packages/client/ui-settings-subagent/tsdown.config.ts index f97175aba2..7aa03cebc1 100644 --- a/packages/client/ui-settings-subagent/tsdown.config.ts +++ b/packages/client/ui-settings-subagent/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-subagent', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-web-search/locale/en.json b/packages/client/ui-settings-web-search/locale/en.json new file mode 100644 index 0000000000..5c0a85691f --- /dev/null +++ b/packages/client/ui-settings-web-search/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings-web-search" + } +} diff --git a/packages/client/ui-settings-web-search/locale/zh.json b/packages/client/ui-settings-web-search/locale/zh.json new file mode 100644 index 0000000000..e450e1004c --- /dev/null +++ b/packages/client/ui-settings-web-search/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "网页搜索设置", + "description": "配置 DeepSeek 网页搜索的密钥、服务地址和请求预算。" + } +} diff --git a/packages/client/ui-settings-web-search/package.json b/packages/client/ui-settings-web-search/package.json index db8da39f54..9604d1c6cf 100644 --- a/packages/client/ui-settings-web-search/package.json +++ b/packages/client/ui-settings-web-search/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,10 +56,10 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings-web-search/tsdown.config.ts b/packages/client/ui-settings-web-search/tsdown.config.ts index 112d2e7f96..7aa03cebc1 100644 --- a/packages/client/ui-settings-web-search/tsdown.config.ts +++ b/packages/client/ui-settings-web-search/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings-web-search', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings/locale/en.json b/packages/client/ui-settings/locale/en.json new file mode 100644 index 0000000000..71db5ec901 --- /dev/null +++ b/packages/client/ui-settings/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-settings" + } +} diff --git a/packages/client/ui-settings/locale/zh.json b/packages/client/ui-settings/locale/zh.json new file mode 100644 index 0000000000..1373f51e13 --- /dev/null +++ b/packages/client/ui-settings/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "设置界面框架", + "description": "提供设置页面的基础表单和插件扩展位置。" + } +} diff --git a/packages/client/ui-settings/package.json b/packages/client/ui-settings/package.json index 753a7e0294..d01f49a4f2 100644 --- a/packages/client/ui-settings/package.json +++ b/packages/client/ui-settings/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -48,11 +49,11 @@ "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-settings": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "@deepseek-ai/dsh-util-values": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-settings/tsdown.config.ts b/packages/client/ui-settings/tsdown.config.ts index 53ee2302d2..7aa03cebc1 100644 --- a/packages/client/ui-settings/tsdown.config.ts +++ b/packages/client/ui-settings/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-settings', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-shortcuts/locale/en.json b/packages/client/ui-shortcuts/locale/en.json new file mode 100644 index 0000000000..0602a25dff --- /dev/null +++ b/packages/client/ui-shortcuts/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-shortcuts" + } +} diff --git a/packages/client/ui-shortcuts/locale/zh.json b/packages/client/ui-shortcuts/locale/zh.json new file mode 100644 index 0000000000..ad7f1dab37 --- /dev/null +++ b/packages/client/ui-shortcuts/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "快捷键设置界面", + "description": "查看、录入和修改键盘快捷键。" + } +} diff --git a/packages/client/ui-shortcuts/package.json b/packages/client/ui-shortcuts/package.json index 516f7654a5..f50a08ccdf 100644 --- a/packages/client/ui-shortcuts/package.json +++ b/packages/client/ui-shortcuts/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,12 +56,12 @@ "@deepseek-ai/dsh-client-ui-layout": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", - "@types/react": "~18.3.1", "clsx": "^2.1.1", "react": "^18.2.0", "@deepseek-ai/dsh-client-test-runtime": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-shortcuts/tsdown.config.ts b/packages/client/ui-shortcuts/tsdown.config.ts index 5d5228cbaf..7aa03cebc1 100644 --- a/packages/client/ui-shortcuts/tsdown.config.ts +++ b/packages/client/ui-shortcuts/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-shortcuts', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-sidebar-browser/locale/en.json b/packages/client/ui-sidebar-browser/locale/en.json new file mode 100644 index 0000000000..6294ad3b9e --- /dev/null +++ b/packages/client/ui-sidebar-browser/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-browser" + } +} diff --git a/packages/client/ui-sidebar-browser/locale/zh.json b/packages/client/ui-sidebar-browser/locale/zh.json new file mode 100644 index 0000000000..111b8f6dc6 --- /dev/null +++ b/packages/client/ui-sidebar-browser/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "浏览器面板", + "description": "在右侧面板中打开和浏览网页。" + } +} diff --git a/packages/client/ui-sidebar-browser/package.json b/packages/client/ui-sidebar-browser/package.json index 5383e00f14..ecd80c90a2 100644 --- a/packages/client/ui-sidebar-browser/package.json +++ b/packages/client/ui-sidebar-browser/package.json @@ -26,7 +26,8 @@ "types": "./lib/types/types.d.ts" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -60,12 +61,11 @@ "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "react": "^18.2.0", "react-dom": "^18.2.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-sidebar-browser/tsdown.config.ts b/packages/client/ui-sidebar-browser/tsdown.config.ts index 229343b169..7aa03cebc1 100644 --- a/packages/client/ui-sidebar-browser/tsdown.config.ts +++ b/packages/client/ui-sidebar-browser/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-sidebar-browser', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml index 6a35e6a8d7..67ad419821 100644 --- a/packages/client/ui-sidebar-documentpreview/README.i18n.yaml +++ b/packages/client/ui-sidebar-documentpreview/README.i18n.yaml @@ -15,11 +15,11 @@ en: 0dd8c3a22e28aacf zh: c27c11bf4b5cceba /deepseek-ai-dsh-client-ui-sidebar-documentpreview/what-it-registers: - en: a8eaf01a3a3390ee - zh: ddea36dbcc4a0159 + en: 54a50f4a3a6e4d45 + zh: af905ed570812432 /deepseek-ai-dsh-client-ui-sidebar-documentpreview/addresses: - en: 949156aa02ec8b07 - zh: d3675754e2a37b5d + en: 57942270e23d3a8e + zh: 6617124e652b3f67 /deepseek-ai-dsh-client-ui-sidebar-documentpreview/how-it-reads: en: b056bbe0f74fe328 zh: fd9ac88f08825afc diff --git a/packages/client/ui-sidebar-documentpreview/README.md b/packages/client/ui-sidebar-documentpreview/README.md index 588a95a7e0..51e23e2208 100644 --- a/packages/client/ui-sidebar-documentpreview/README.md +++ b/packages/client/ui-sidebar-documentpreview/README.md @@ -28,7 +28,7 @@ Preview files in the right Sidebar and choose among registered renderers. Markdo ## What it registers -- **The type** — `ctx.sidebarRightTabs.register(...)` with id `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` (this implementation's identity in the tab system, and the key its body registers under), kind `text`, pattern `dsh-resource://file/**`, band `fallback`. `canOpen` accepts only Session addresses, whose paths may be relative or absolute; bare `absolute` addresses are not claimed. A type registered at the `extension` or `builtin` band for a narrower pattern (say `*.png`) takes those addresses; other supported files land here. The whole address is the content identity, so two files with one name in different directories, or one path under two sessions, are two tabs; the decoded basename is the tab title, and the keyed `sidebar.right.pane.tab.title` seat places its extension-specific `FileTypeIcon` before that title. +- **The type** — `ctx.sidebarRightTabs.register(...)` with id `@deepseek-ai/dsh-client-ui-sidebar-documentpreview` (this implementation's identity in the tab system, and the key its body registers under), kind `text`, a whole-address file-resource pattern, band `fallback`. `canOpen` accepts only Session addresses, whose paths may be relative or absolute; bare `absolute` addresses are not claimed. A type registered at the `extension` or `builtin` band for a narrower pattern (say `*.png`) takes those addresses; other supported files land here. The whole address is the content identity, so two files with one name in different directories, or one path under two sessions, are two tabs; the decoded basename is the tab title, and the keyed `sidebar.right.pane.tab.title` seat places its extension-specific `FileTypeIcon` before that title. - **The body** — the keyed `sidebar.right.pane.tab` seat under the type's id. Its fixed header shows the Host's absolute path when available, otherwise the requested path; the shared [`PathLabel`](../ui-primitives/README.md#component-catalog) subdues directories, preserves a clipped path’s trailing characters with a left-edge fade, and exposes the full value on hover. A dropdown appears when multiple supported renderers are available. Plain text is offered only for text-compatible sources; a single renderer shows no viewer control. A known binary container suffix without a registered renderer shows the file-type icon and an unsupported-preview message under the path header, without issuing a read. Two Session-scoped list child slots hand the previewed file to other plugins once its metadata reports a Host path, both with `absolutePath` as the owner prop: `sidebar.right.tab.document.actions` renders after the header's own controls in every state that shows the header, and `sidebar.right.tab.document.unpreviewable` renders in the unsupported empty state and in the empty state of a readable file the preview cannot render (`not-text`, `too-large`), where Retry would otherwise stand; a carrier or unclassified read failure keeps Retry, and a missing or non-regular path offers only its explanation. The shipped occupant of both is [`ui-open-in-app`](../ui-open-in-app/README.md). A wrap toggle appears only when the selected renderer declares `wrap: true`; its glyph describes the mode the click selects, and the per-tab preference starts on. Reload stays in this header, not the Sidebar's tab strip. Automatic refresh defaults to enabled; its separate toggle is hidden, with state, labels, styles, and toggle logic retained. The body reaches every pane edge; each renderer owns its content inset and may own an inner scrollport. This intentionally differs from the Files tab's 2px right-side scrollbar offset: previews keep the full pane width so edge-to-edge HTML and code scrollports end at the pane edge. - **Shared loading and view state**, session-scoped and bucketed by tab id. The store holds accumulated pages or complete bytes, read and observed versions, pending Resource changes, automatic-refresh state, loading/failure state, renderer choice, scroll offset, wrap, and the answered navigation revision. The ordinary inject face calls Remote readers and writes through declared store actions. Reloads and loading-mode changes retire older requests; the tab's abort signal forgets its state. @@ -39,7 +39,7 @@ Document implementations register metadata with `ctx.documentPreviews.register({ ## Addresses -A tab uses the Session address built by `fileAddressFor`, carrying a relative or absolute path. `hostFileOf(address)` takes the Session only from that address, with no external Session argument; neither current nor Tab Session is borrowed. The Host resolves file and related paths through the Session filesystem, whose backend controls read authority. Metadata for the same complete address is shared by every UI, including Global components. The [Workspace Files README](../../api/workspace-files/README.md) owns these rules; renderer selection does not change the navigation address. +A tab uses the Session address built by `fileAddressFor`, carrying a relative or absolute path. Routing preserves `.` and `..` path segments in the address and its content identity; the Host resolves them. `hostFileOf(address)` takes the Session only from that address, with no external Session argument; neither current nor Tab Session is borrowed. The Host resolves file and related paths through the Session filesystem, whose backend controls read authority. Metadata for the same complete address is shared by every UI, including Global components. The [Workspace Files README](../../api/workspace-files/README.md) owns these rules; renderer selection does not change the navigation address. After all text pages load, Markdown images use the authenticated `/api/file` route for absolute file paths and paths relative to the source document's directory. Relative images wait for the Host's absolute document path. URL escapes are decoded once; query and fragment suffixes are excluded from the filename. HTTP(S) images retain their authored URLs, and failed image loads show alt text. Local images require an HTTP(S) application base URL; image files are not added to automatic-refresh dependencies. diff --git a/packages/client/ui-sidebar-documentpreview/README.zh.md b/packages/client/ui-sidebar-documentpreview/README.zh.md index 89d90091f5..1c5be3fdc3 100644 --- a/packages/client/ui-sidebar-documentpreview/README.zh.md +++ b/packages/client/ui-sidebar-documentpreview/README.zh.md @@ -28,7 +28,7 @@ kind: "package-reference" ## 注册了什么 -- **类型** —— `ctx.sidebarRightTabs.register(...)`,id 为 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`(这个实现在 tab 系统中的身份,也是其正文注册所用的键),kind `text`,pattern `dsh-resource://file/**`,档位 `fallback`。`canOpen` 只接受 Session 地址,其中路径可为相对或绝对路径;不认领裸 `absolute` 地址。在 `extension` 或 `builtin` 档以更窄 pattern(比如 `*.png`)注册的类型接走那些地址;其他受支持文件落到这里。整个地址就是内容身份,所以不同目录下同名的两个文件、或同一路径在两个会话之下,是两个 tab;解码后的 basename 是 tab 标题,keyed slot `sidebar.right.pane.tab.title` 会在标题前放置按扩展名选择的 `FileTypeIcon`。 +- **类型** —— `ctx.sidebarRightTabs.register(...)`,id 为 `@deepseek-ai/dsh-client-ui-sidebar-documentpreview`(这个实现在 tab 系统中的身份,也是其正文注册所用的键),kind `text`,匹配完整文件资源地址的 pattern,档位 `fallback`。`canOpen` 只接受 Session 地址,其中路径可为相对或绝对路径;不认领裸 `absolute` 地址。在 `extension` 或 `builtin` 档以更窄 pattern(比如 `*.png`)注册的类型接走那些地址;其他受支持文件落到这里。整个地址就是内容身份,所以不同目录下同名的两个文件、或同一路径在两个会话之下,是两个 tab;解码后的 basename 是 tab 标题,keyed slot `sidebar.right.pane.tab.title` 会在标题前放置按扩展名选择的 `FileTypeIcon`。 - **正文** —— keyed slot `sidebar.right.pane.tab`,键为类型的 id。固定头部在可用时显示 Host 的绝对路径,否则显示请求路径;共享的 [`PathLabel`](../ui-primitives/README.zh.md#component-catalog) 弱化目录颜色,以左侧渐隐保留被裁剪路径的尾部字符,并在悬停时展示完整值。有多个受支持的渲染器时才显示下拉菜单。仅文本兼容的源文件提供纯文本选项;只有一个渲染器时不显示查看器控件。已知的二进制容器后缀没有注册渲染器时,在路径头部下方显示文件类型图标和不支持预览的说明,并且不会发起读取。两个 Session 作用域的 list 子 slot 在文件元数据报出 Host 路径后把当前文件交给其他插件,owner prop 为 `absolutePath`:`sidebar.right.tab.document.actions` 在每个显示头部的状态里渲染在头部自有控件之后;`sidebar.right.tab.document.unpreviewable` 渲染在不支持预览的空态里,以及可读但本预览无法渲染的文件(`not-text`、`too-large`)的空态里,占据原本放重试的位置;载体或未分类的读取失败仍保留重试,不存在或非普通文件的路径只给说明。两者已发布的占位者都是 [`ui-open-in-app`](../ui-open-in-app/README.zh.md)。仅当所选渲染器声明 `wrap: true` 时显示换行开关;图标表示点击后切换到的模式,该偏好按 tab 保存,初始开启。重新载入仍在此头部,不放入 Sidebar 的 tab 条。自动刷新默认开启;独立开关暂时隐藏,状态、文案、样式与切换逻辑保留。正文贴合格的每条边,各渲染器自行提供内容留白,并可拥有内部滚动区。这与 Files tab 右侧预留 2px 滚动条间距的布局有意不同:Preview 使用格的完整宽度,使贴边 HTML 与代码滚动区终止于格的边缘。 - **共享加载与视图状态**,会话作用域、按 tab id 分桶。store 持有累计页或完整字节、读取与观察版本、待处理 Resource 变化、自动刷新状态、加载/失败状态、渲染器选择、滚动位置、换行和已响应的导航 revision。普通 inject face 调用 Remote 读取,并经声明的 store action 写入。重新载入和加载模式变化会淘汰旧请求;tab 的中止信号清理其状态。 @@ -39,7 +39,7 @@ kind: "package-reference" ## 地址 -tab 使用 `fileAddressFor` 构造的 Session 地址,携带相对或绝对路径。`hostFileOf(address)` 仅从地址取得 Session,不接收外部 Session 参数,也不借用当前或 Tab Session。Host 通过 Session 文件系统解析文件及关联路径,由该后端控制读取权限。任何 UI(包括 Global 组件)都共享同一完整地址的元数据。[Workspace Files README](../../api/workspace-files/README.zh.md) 定义这些规则;渲染器选择不改变导航地址。 +tab 使用 `fileAddressFor` 构造的 Session 地址,携带相对或绝对路径。路由在地址及其内容身份中保留 `.` 与 `..` 路径段,由 Host 解析。`hostFileOf(address)` 仅从地址取得 Session,不接收外部 Session 参数,也不借用当前或 Tab Session。Host 通过 Session 文件系统解析文件及关联路径,由该后端控制读取权限。任何 UI(包括 Global 组件)都共享同一完整地址的元数据。[Workspace Files README](../../api/workspace-files/README.zh.md) 定义这些规则;渲染器选择不改变导航地址。 全部文本分页加载完成后,Markdown 图片通过已鉴权的 `/api/file` 路由读取绝对文件路径,以及相对于源文档所在目录的路径。相对图片等待 Host 返回文档绝对路径。URL 转义只解码一次;查询参数与片段后缀不计入文件名。HTTP(S) 图片保留原始 URL,加载失败的图片显示 alt 文本。本地图片要求应用基址为 HTTP(S) URL;图片文件不加入自动刷新依赖。 diff --git a/packages/client/ui-sidebar-documentpreview/locale/en.json b/packages/client/ui-sidebar-documentpreview/locale/en.json new file mode 100644 index 0000000000..7d7f557f9a --- /dev/null +++ b/packages/client/ui-sidebar-documentpreview/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-documentpreview" + } +} diff --git a/packages/client/ui-sidebar-documentpreview/locale/zh.json b/packages/client/ui-sidebar-documentpreview/locale/zh.json new file mode 100644 index 0000000000..8673bde417 --- /dev/null +++ b/packages/client/ui-sidebar-documentpreview/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文档预览面板", + "description": "在右侧面板预览文档、表格、代码、图片和网页等文件。" + } +} diff --git a/packages/client/ui-sidebar-documentpreview/package.json b/packages/client/ui-sidebar-documentpreview/package.json index d071660c88..793a88c1b1 100644 --- a/packages/client/ui-sidebar-documentpreview/package.json +++ b/packages/client/ui-sidebar-documentpreview/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -67,15 +68,12 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-office-to-pdf": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", - "@deepseek-ai/dsh-office-to-pdf": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@fortune-sheet/core": "1.0.4", "@fortune-sheet/react": "1.0.4", "@testing-library/react": "^16.3.3", "@types/papaparse": "^5.3.16", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "clsx": "^2.0.0", "dompurify": "^3.4.16", "exceljs": "4.4.0", @@ -89,6 +87,7 @@ "yaml": "^2.9.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/client.*.js", diff --git a/packages/client/ui-sidebar-documentpreview/src/client/definition.ts b/packages/client/ui-sidebar-documentpreview/src/client/definition.ts index 7f2892cffd..914616e0fb 100644 --- a/packages/client/ui-sidebar-documentpreview/src/client/definition.ts +++ b/packages/client/ui-sidebar-documentpreview/src/client/definition.ts @@ -46,7 +46,8 @@ export function textDefinition(): SidebarRightTabDefinition { return { id: TEXTPREVIEW_ID, kind: TEXTPREVIEW_KIND, - patterns: ['dsh-resource://file/**'], + // A character-class repetition includes literal dot segments that globstar excludes. + patterns: ['dsh-resource://file/[\\s\\S]+'], priority: 'fallback', canOpen: address => parseFileAddress(address)?.scope === 'session', title: basenameOf, diff --git a/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts b/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts index 63984f41ca..a842b76b24 100644 --- a/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts +++ b/packages/client/ui-sidebar-documentpreview/tests/definition.client.spec.ts @@ -9,7 +9,7 @@ */ import { describe, expect, it } from 'vitest' import { Context } from '@deepseek-ai/cordis' -import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' +import { parseFileAddress, sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' import { SidebarRightTabRegistry } from '@deepseek-ai/dsh-client-ui-sidebar-right/src/client/tab-registry.ts' import { TEXTPREVIEW_ID, TEXTPREVIEW_KIND, basenameOf, textDefinition } from '../src/client/definition.ts' @@ -32,7 +32,7 @@ describe('textDefinition', () => { const definition = textDefinition() expect(definition.id).toBe(TEXTPREVIEW_ID) expect(definition.kind).toBe(TEXTPREVIEW_KIND) - expect(definition.patterns).toEqual(['dsh-resource://file/**']) + expect(definition.patterns).toEqual(['dsh-resource://file/[\\s\\S]+']) expect(definition.priority).toBe('fallback') expect(definition.title('dsh-resource://file/session/s-1/work/README.md')).toBe('README.md') // Reads require an addressed Session, even when the file path is absolute. @@ -66,6 +66,51 @@ describe('text type in the registry', () => { } }) + it.each([ + '../AGENTS.md', + '../../AGENTS.md', + 'dir/../AGENTS.md', + 'dir/./AGENTS.md', + '/workspace/../AGENTS.md', + 'C:/workspace/../AGENTS.md', + '//host/share/workspace/../AGENTS.md', + '', + ])('claims unresolved Session paths without rewriting their identity: %s', (path) => { + const tabs = registry() + const address = sessionFileAddress('s-1', path) + expect(tabs.claim(address)).toEqual({ kind: TEXTPREVIEW_KIND, contentId: address, title: basenameOf(address) }) + expect(tabs.claim(address).contentId).toBe(address) + expect(parseFileAddress(address)).toEqual({ scope: 'session', sessionId: 's-1', path }) + }) + + it.each([ + ['./AGENTS.md', './AGENTS.md'], + ['%2e%2E/AGENTS.md', '../AGENTS.md'], + ['dir/%2E/AGENTS.md', 'dir/./AGENTS.md'], + ['%252e%252e/AGENTS.md', '%2e%2e/AGENTS.md'], + ['../a%20b%23c%3F.txt?ignored=1#section', '../a b#c?.txt'], + ])('claims an authored address while decoding its path once: %s', (encoded, path) => { + const tabs = registry() + const address = `dsh-resource://file/session/s%2F1/${encoded}` + expect(tabs.claim(address).contentId).toBe(address) + expect(parseFileAddress(address)).toEqual({ scope: 'session', sessionId: 's/1', path }) + }) + + it.each([ + 'dsh-resource://file/session', + 'dsh-resource://file/session//../a.md', + 'dsh-resource://file/session/s-1', + 'dsh-resource://file/session/%/../a.md', + 'dsh-resource://file/session/s-1/../%ZZ.md', + 'DSH-RESOURCE://file/session/s-1/../a.md', + 'dsh-resource://File/session/s-1/../a.md', + ])('keeps the Session parser veto after matching a file prefix: %s', (address) => { + const tabs = registry() + expect(tabs.candidates(address)).toEqual([]) + expect(() => tabs.claim(address)).toThrow('no registered tab type claims') + expect(() => tabs.claim(address, TEXTPREVIEW_KIND)).toThrow(`tab type "${TEXTPREVIEW_KIND}" refuses`) + }) + it.each([ 'dsh-resource://file/shared/team/notes.md', 'dsh-resource://file/absolute/home/me/notes.md', @@ -86,6 +131,38 @@ describe('text type in the registry', () => { expect(tabs.candidates('dsh-resource://file/session/s-1/w/logo.png').map(type => type.kind)).toEqual(['image', TEXTPREVIEW_KIND]) }) + it.each(['builtin', 'extension'] as const)('yields parent paths to the %s band and honors its veto', (priority) => { + const tabs = registry() + const address = sessionFileAddress('s-1', '../AGENTS.md') + const release = tabs.register({ + id: 'test/markdown', kind: 'markdown', patterns: ['*.md'], priority, title: () => 'Markdown', + }) + expect(tabs.candidates(address).map(type => type.kind)).toEqual(['markdown', TEXTPREVIEW_KIND]) + expect(tabs.claim(address)).toEqual({ kind: 'markdown', contentId: address, title: 'Markdown' }) + release() + tabs.register({ + id: 'test/markdown', kind: 'markdown', patterns: ['*.md'], priority, canOpen: () => false, title: () => 'Markdown', + }) + expect(tabs.claim(address).kind).toBe(TEXTPREVIEW_KIND) + }) + + it('ranks the file declaration by its literal length within the fallback band', () => { + const tabs = registry() + tabs.register({ + id: 'test/shorter', kind: 'shorter', patterns: ['dsh-resource://file/**/*.*'], priority: 'fallback', title: () => 'Shorter', + }) + const releaseLonger = tabs.register({ + id: 'test/longer', kind: 'longer', patterns: ['dsh-resource://file/session/**/*.md'], priority: 'fallback', title: () => 'Longer', + }) + tabs.register({ ...textDefinition(), id: 'test/tied', kind: 'tied' }) + const address = sessionFileAddress('s-1', 'AGENTS.md') + // Specificity uses the literal pattern length, not the size of its accepted address set. + expect(tabs.candidates(address).map(type => type.kind)).toEqual(['longer', TEXTPREVIEW_KIND, 'tied', 'shorter']) + expect(tabs.claim(address).kind).toBe('longer') + releaseLonger() + expect(tabs.claim(address).kind).toBe(TEXTPREVIEW_KIND) + }) + it('does not claim addresses of other schemes', () => { const tabs = registry() expect(() => tabs.claim('sidebar://guide')).toThrow('no registered tab type claims') diff --git a/packages/client/ui-sidebar-documentpreview/tsdown.config.ts b/packages/client/ui-sidebar-documentpreview/tsdown.config.ts index b664119dfd..9db8b5b107 100644 --- a/packages/client/ui-sidebar-documentpreview/tsdown.config.ts +++ b/packages/client/ui-sidebar-documentpreview/tsdown.config.ts @@ -4,7 +4,7 @@ import { dirname, join } from 'node:path' import { Rolldown, type UserConfig } from 'tsdown' import { clientBundle } from '../tsdown.client.ts' -const bundle = clientBundle('@deepseek-ai/dsh-client-ui-sidebar-documentpreview', ['lib/types/index.js'], { +const bundle = clientBundle(import.meta.dirname, ['lib/types/index.js'], { clientBanner: fileName => fileName.endsWith('client.pdf.js') ? pdfLicenseBanner() : fileName.endsWith('client.excel.js') ? excelLicenseBanner() : undefined, }) diff --git a/packages/client/ui-sidebar-files/locale/en.json b/packages/client/ui-sidebar-files/locale/en.json new file mode 100644 index 0000000000..6da0972151 --- /dev/null +++ b/packages/client/ui-sidebar-files/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-files" + } +} diff --git a/packages/client/ui-sidebar-files/locale/zh.json b/packages/client/ui-sidebar-files/locale/zh.json new file mode 100644 index 0000000000..577a5725c3 --- /dev/null +++ b/packages/client/ui-sidebar-files/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文件浏览面板", + "description": "浏览工作区目录,并在右侧面板中打开文件。" + } +} diff --git a/packages/client/ui-sidebar-files/package.json b/packages/client/ui-sidebar-files/package.json index bf9bc4d32f..4039019176 100644 --- a/packages/client/ui-sidebar-files/package.json +++ b/packages/client/ui-sidebar-files/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -62,14 +63,13 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "react": "^18.2.0", "clsx": "^2.0.0", "react-dom": "^18.2.0", "@deepseek-ai/dsh-client-shortcuts": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-sidebar-files/tsdown.config.ts b/packages/client/ui-sidebar-files/tsdown.config.ts index 15e759c557..7aa03cebc1 100644 --- a/packages/client/ui-sidebar-files/tsdown.config.ts +++ b/packages/client/ui-sidebar-files/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-sidebar-files', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-sidebar-right/locale/en.json b/packages/client/ui-sidebar-right/locale/en.json new file mode 100644 index 0000000000..4187616d33 --- /dev/null +++ b/packages/client/ui-sidebar-right/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-right" + } +} diff --git a/packages/client/ui-sidebar-right/locale/zh.json b/packages/client/ui-sidebar-right/locale/zh.json new file mode 100644 index 0000000000..22281c9e82 --- /dev/null +++ b/packages/client/ui-sidebar-right/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "右侧面板", + "description": "管理右侧面板的展开状态、内容和导航。" + } +} diff --git a/packages/client/ui-sidebar-right/package.json b/packages/client/ui-sidebar-right/package.json index a4247518af..6367d31c9f 100644 --- a/packages/client/ui-sidebar-right/package.json +++ b/packages/client/ui-sidebar-right/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -63,8 +64,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@testing-library/react": "^16.3.3", "@types/picomatch": "^4.0.3", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "react": "^18.2.0", "react-dom": "^18.2.0", "picomatch": "^4.0.7", @@ -75,6 +74,7 @@ "@deepseek-ai/dsh-brand": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-sidebar-right/tsdown.config.ts b/packages/client/ui-sidebar-right/tsdown.config.ts index 559865cdcd..7aa03cebc1 100644 --- a/packages/client/ui-sidebar-right/tsdown.config.ts +++ b/packages/client/ui-sidebar-right/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-sidebar-right', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-sidebar-terminal/locale/en.json b/packages/client/ui-sidebar-terminal/locale/en.json new file mode 100644 index 0000000000..d6ab2b3980 --- /dev/null +++ b/packages/client/ui-sidebar-terminal/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar-terminal" + } +} diff --git a/packages/client/ui-sidebar-terminal/locale/zh.json b/packages/client/ui-sidebar-terminal/locale/zh.json new file mode 100644 index 0000000000..ca36d8da54 --- /dev/null +++ b/packages/client/ui-sidebar-terminal/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "终端面板", + "description": "在右侧面板中使用交互式命令终端。" + } +} diff --git a/packages/client/ui-sidebar-terminal/package.json b/packages/client/ui-sidebar-terminal/package.json index 5a4bc2b62f..0de48c9ac3 100644 --- a/packages/client/ui-sidebar-terminal/package.json +++ b/packages/client/ui-sidebar-terminal/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -59,8 +60,6 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "react": "^18.2.0", "clsx": "^2.0.0", "react-dom": "^18.2.0", @@ -73,6 +72,7 @@ "@deepseek-ai/dsh-client-shortcuts": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/client.*.js", diff --git a/packages/client/ui-sidebar-terminal/tsdown.config.ts b/packages/client/ui-sidebar-terminal/tsdown.config.ts index 016643c5fb..7aa03cebc1 100644 --- a/packages/client/ui-sidebar-terminal/tsdown.config.ts +++ b/packages/client/ui-sidebar-terminal/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-sidebar-terminal', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-sidebar/locale/en.json b/packages/client/ui-sidebar/locale/en.json new file mode 100644 index 0000000000..dbf02a834f --- /dev/null +++ b/packages/client/ui-sidebar/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-sidebar" + } +} diff --git a/packages/client/ui-sidebar/locale/zh.json b/packages/client/ui-sidebar/locale/zh.json new file mode 100644 index 0000000000..5a3da3ba14 --- /dev/null +++ b/packages/client/ui-sidebar/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话侧栏", + "description": "展示会话列表,提供搜索、分组和状态提示。" + } +} diff --git a/packages/client/ui-sidebar/package.json b/packages/client/ui-sidebar/package.json index b93ff78675..e671c81756 100644 --- a/packages/client/ui-sidebar/package.json +++ b/packages/client/ui-sidebar/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -58,7 +59,6 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "clsx": "^2.0.0", @@ -66,6 +66,7 @@ "@deepseek-ai/dsh-client-product-analytics": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-sidebar/tsdown.config.ts b/packages/client/ui-sidebar/tsdown.config.ts index 15da8a116a..7aa03cebc1 100644 --- a/packages/client/ui-sidebar/tsdown.config.ts +++ b/packages/client/ui-sidebar/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-sidebar', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-skill/README.i18n.yaml b/packages/client/ui-skill/README.i18n.yaml index 3f5d54b740..8d82e8e675 100644 --- a/packages/client/ui-skill/README.i18n.yaml +++ b/packages/client/ui-skill/README.i18n.yaml @@ -30,8 +30,8 @@ en: 1a02a85859f851c7 zh: 03bd48b83c4a287c /deepseek-ai-dsh-client-ui-skill/understand-the-implementation/registration: - en: 1965ad3169b7fd97 - zh: efc23c44ad1d2765 + en: 4b06a66c56d19ff9 + zh: d9c8d118f73d89bb /deepseek-ai-dsh-client-ui-skill/further-exploration: en: 54198f095d0cc569 zh: 4eba4413e159967b diff --git a/packages/client/ui-skill/README.md b/packages/client/ui-skill/README.md index 08d2e1137c..4340f3f78e 100644 --- a/packages/client/ui-skill/README.md +++ b/packages/client/ui-skill/README.md @@ -59,6 +59,8 @@ Each catalog fetch requires an existing retained Client Session and waits for it The `/client` exports are the plugin body (`apply`/`inject`) only; the source object is internal to the registration effect. The tool row registers the `skill` wire name in ui-tool's keyed `tool.call.toolview` slot. +For sent text, the plugin registers a UserText matcher that returns one next original-text candidate using caller-confirmed `skillNames` and owns the `skill` entry in `conversation.user.text.node`. The renderer receives `openSkill` from its own Session-bound injection and delegates to this source’s preview operation, not to Chat owner props. Non-interactive previews remain labels. [UserText](../ui-conversation/README.md#sent-user-text) owns evaluation and node dispatch. + ----- diff --git a/packages/client/ui-skill/README.zh.md b/packages/client/ui-skill/README.zh.md index e07a59326b..d18c52f30d 100644 --- a/packages/client/ui-skill/README.zh.md +++ b/packages/client/ui-skill/README.zh.md @@ -59,6 +59,8 @@ source 不实现任何裁决钩子,也没有引用 codec:pick 落下字面 `/client` 导出接口只有插件主体(`apply`/`inject`);source 对象是注册 effect 的内部实现。工具行把 `skill` wire 名称注册进 ui-tool 的 keyed `tool.call.toolview` slot。 +对于已发送文本,插件注册使用调用方已确认 `skillNames`、返回原文中下一个候选的 UserText 匹配器,并拥有 `conversation.user.text.node` 中的 `skill` 条目。renderer 从自身绑定 Session 的 Injection 接收 `openSkill`,委托本 source 的预览操作,而非 Chat owner props。不可交互的预览仍为标签。[UserText](../ui-conversation/README.zh.md#sent-user-text) 拥有求值与节点分发。 + ----- diff --git a/packages/client/ui-skill/locale/en.json b/packages/client/ui-skill/locale/en.json new file mode 100644 index 0000000000..d61c3ff256 --- /dev/null +++ b/packages/client/ui-skill/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-skill" + } +} diff --git a/packages/client/ui-skill/locale/zh.json b/packages/client/ui-skill/locale/zh.json new file mode 100644 index 0000000000..a30c0c2fdf --- /dev/null +++ b/packages/client/ui-skill/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "技能引用与展示", + "description": "在会话中提供技能引用和技能调用展示。" + } +} diff --git a/packages/client/ui-skill/package.json b/packages/client/ui-skill/package.json index de02a05d7a..da3f022efc 100644 --- a/packages/client/ui-skill/package.json +++ b/packages/client/ui-skill/package.json @@ -23,13 +23,15 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { "inject": [ "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-locale", + "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-renderer", "@deepseek-ai/dsh-client-ui-tool", "@deepseek-ai/dsh-client-ui-input-trigger", @@ -53,6 +55,7 @@ "@deepseek-ai/dsh-client-connection": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-input-trigger": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", @@ -60,7 +63,6 @@ "@deepseek-ai/dsh-client-ui-tool": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0", @@ -69,6 +71,7 @@ "@deepseek-ai/dsh-util-workspace-path": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-skill/src/client/SkillReference.tsx b/packages/client/ui-skill/src/client/SkillReference.tsx new file mode 100644 index 0000000000..fef9d71a3e --- /dev/null +++ b/packages/client/ui-skill/src/client/SkillReference.tsx @@ -0,0 +1,28 @@ +/** Skill-reference presentation with activation owned by this keyed entry's Session injection. */ +import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { ReferenceChip } from '@deepseek-ai/dsh-client-ui-primitives' + +/** Session-bound preview action; accepting a preview is not a completion promise. */ +export interface SkillReferenceInjected { + /** + * Ask the skill source to preview a confirmed name in this entry's Session. + * @param name - skill name without its slash. + */ + readonly openSkill: (name: string) => void +} + +type SkillReferenceProps = UserTextNodeProps<'skill'> & SkillReferenceInjected + +/** + * Render a skill chip; previews omit activation even when the entry has an injected action. + * @param props - resolved node, raw token, interaction mode, and Session-bound preview action. + * @returns an inline skill label or interactive chip. + */ +export function SkillReference({ node, raw, interactive, openSkill }: SkillReferenceProps) { + return { openSkill(node.data.name) } } : {})} + /> +} diff --git a/packages/client/ui-skill/src/client/index.ts b/packages/client/ui-skill/src/client/index.ts index 2b6cd12ea2..ee67b91e4c 100644 --- a/packages/client/ui-skill/src/client/index.ts +++ b/packages/client/ui-skill/src/client/index.ts @@ -44,7 +44,11 @@ import { rankByName } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from '@deepseek-ai/dsh-client-locale/client' // Type-only: pulls the SlotRegistry service merge (ctx.slots). import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { SkillRow } from './SkillRow.tsx' +import { SkillReference, type SkillReferenceInjected } from './SkillReference.tsx' +import { skillReferenceRule } from './user-text-rules.ts' +export type {} from './user-text-rules.ts' import { en, NS, zh, type SkillKey } from './locales.ts' declare module '@deepseek-ai/dsh-api-session-controller/client' { @@ -70,7 +74,7 @@ interface CatalogFetch { } /** Required services: reference source faces plus the tool-row and locale registries. */ -export const inject = ['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight'] +export const inject = ['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight', 'uiConversation'] /** * Client plugin body: register the '/' source, dictionaries, and keyed tool row. @@ -78,6 +82,7 @@ export const inject = ['inputTriggers', 'sessions', 'slots', 'locale', 'remote', */ export function apply(ctx: ClientContext): void { ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-skill: dictionaries') + ctx.uiConversation.userText.register(skillReferenceRule) ctx.slots.inject('tool.call.toolview', () => ctx.slots.register( { name: 'tool.call.toolview', key: 'skill', locale: NS }, SkillRow, @@ -156,7 +161,7 @@ export function apply(ctx: ClientContext): void { // locale service's own fallback ladder; candidate-time reads stay plain text. const t = ctx.locale.bind(NS) - const source: InputTriggerSource = { + const source = { trigger: '/', name: 'skill', order: 2, @@ -223,7 +228,20 @@ export function apply(ctx: ClientContext): void { // line client-side before it ever becomes a prompt. return { text: `/${candidate.name} ` } }, - } + } satisfies InputTriggerSource + + ctx.slots.inject('conversation.user.text.node', () => ctx.slots.register({ + name: 'conversation.user.text.node', + key: 'skill', + priority: 100, + inject: (sessionId): SkillReferenceInjected => ({ + openSkill: (name) => { + if (sessions.scope(sessionId) === undefined) return + source.openReference({ sessionId }, { ref: `/${name}` }) + }, + }), + }, SkillReference)) + const inputTriggers = ctx.get('inputTriggers') as InputTriggerServiceContract // A preset decides which skill providers an agent reads, so a switched // session's cached catalog belongs to the composition it no longer runs. diff --git a/packages/client/ui-skill/src/client/user-text-rules.ts b/packages/client/ui-skill/src/client/user-text-rules.ts new file mode 100644 index 0000000000..96e07f1369 --- /dev/null +++ b/packages/client/ui-skill/src/client/user-text-rules.ts @@ -0,0 +1,36 @@ +/** Original-text skill candidates restricted to caller-confirmed names. */ +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' + +declare module '@deepseek-ai/dsh-client-ui-conversation/client' { + interface UserTextDataMap { + /** A skill name confirmed for this message, without the leading slash. */ + skill: { readonly name: string } + } + + interface UserTextFacts { + /** Resolved skill names; absence supplies no skill references. */ + readonly skillNames: readonly string[] + } +} + +/** Return one nearest confirmed slash token, retaining its original word boundaries. */ +export const skillReferenceRule: UserTextRule<'skill'> = { + id: 'skill', + order: 20, + match(text, from, context) { + const tokens = /(? null) const capture: PresentationCapture = { slots, @@ -80,11 +88,11 @@ async function bench(list: ListFn, addressed?: SessionId, opening: Pick { await fiber.dispose() }) await fiber.await() - return { ctx, source: captured!, remote, fiber, openResource, sessions } + return { ctx, source: captured!, remote, fiber, openResource, sessions, presentation } } const CATALOG: SkillRow[] = [ @@ -114,11 +122,12 @@ const req = (query: string, signal?: AbortSignal) => describe('apply', () => { it('declares the services it binds', () => { - expect(inject).toEqual(['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight']) + expect(inject).toEqual(['inputTriggers', 'sessions', 'slots', 'locale', 'remote', 'remote.skills', 'sidebarRight', 'uiConversation']) }) it('registers the dedicated skill row and its locale dictionaries', async () => { const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) ctx.provide('sidebarRight', { openResource: vi.fn() }) ctx.provide('inputTriggers', { registerSource: () => () => {} }) ctx.provide('sessions', { subagentAddress: () => undefined }) @@ -157,6 +166,7 @@ describe('apply', () => { it('registers the "/" skill source; disposal frees the name (HMR safety)', async () => { const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) ctx.provide('sidebarRight', { openResource: vi.fn() }) // InputTriggerService itself injects 'sessions'; the stub unblocks its fiber. ctx.provide('sessions', {}) @@ -460,6 +470,31 @@ describe('reference preview', () => { { name: 'virtual', description: 'Virtual' }, ] + it('routes sent skill previews through the reference entry’s own Session and ignores an absent scope', async () => { + const b = await bench(listOk(rows)) + const entry = b.presentation.slots.entries('conversation.user.text.node').find(row => row.options.key === 'skill') + expect(entry?.component).toBe(SkillReference) + if (entry?.inject === undefined) throw new Error('Skill reference injector was not registered') + const injectReference = entry.inject as ( + ...params: InjectParams<'conversation.user.text.node', undefined> + ) => Pick + const openReference = vi.spyOn(b.source, 'openReference') + const first = injectReference(sid('first')) + const second = injectReference(sid('second')) + first.openSkill('review') + await b.source.candidates(proj('first'), req('')) + expect(openReference).toHaveBeenLastCalledWith(proj('first'), { ref: '/review' }) + expect(b.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/first//skills/review/SKILL.md') + second.openSkill('review') + await b.source.candidates(proj('second'), req('')) + expect(openReference).toHaveBeenLastCalledWith(proj('second'), { ref: '/review' }) + expect(b.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/second//skills/review/SKILL.md') + vi.spyOn(b.sessions, 'scope').mockReturnValueOnce(undefined) + first.openSkill('review') + expect(openReference).toHaveBeenCalledTimes(2) + expect(b.openResource).toHaveBeenCalledTimes(2) + }) + it('finishes the first click after a shared warm fetch and reloads after reconnect', async () => { const gate = Promise.withResolvers() const list = vi.fn().mockReturnValueOnce(gate.promise).mockImplementation(listOk(rows)) diff --git a/packages/client/ui-skill/tests/user-text-rules.client.spec.ts b/packages/client/ui-skill/tests/user-text-rules.client.spec.ts new file mode 100644 index 0000000000..a6958ab233 --- /dev/null +++ b/packages/client/ui-skill/tests/user-text-rules.client.spec.ts @@ -0,0 +1,72 @@ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import type { UserTextRule } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { UserTextRegistry } from '@deepseek-ai/dsh-client-ui-conversation/src/client/conversation/user-text-registry.ts' +import { skillReferenceRule } from '../src/client/user-text-rules.ts' + +function setup(rule: UserTextRule = skillReferenceRule) { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const registry = new UserTextRegistry(ctx) + registry.register(rule) + return registry.createEvaluator() +} + +describe('skillReferenceRule', () => { + it('does not read names or rerun when text has no slash-token candidate', () => { + const read = vi.fn() + const match = vi.fn['match']>((text, from, context) => skillReferenceRule.match(text, from, { + read: (key) => { read(key); return context.read(key) }, + })) + const evaluate = setup({ ...skillReferenceRule, match }) + const text = 'plain text /review.md /path/to/file' + const before = evaluate({ text, facts: {} }) + expect(evaluate({ text, facts: { skillNames: ['review', 'path'] } })).toBe(before) + expect(read).not.toHaveBeenCalled() + expect(match).toHaveBeenCalledOnce() + }) + + it('reacts to missing names appearing and retains node identities when unrelated names are added', () => { + const match = vi.fn['match']>((text, from, context) => skillReferenceRule.match(text, from, context)) + const evaluate = setup({ ...skillReferenceRule, match }) + const text = 'use /review now' + expect(evaluate({ text, facts: {} }).every(node => node.id === 'text')).toBe(true) + const before = evaluate({ text, facts: { skillNames: ['review'] } }) + const after = evaluate({ text, facts: { skillNames: ['review', 'unrelated'] } }) + expect(after).toBe(before) + expect(after.find(node => node.id === 'skill')).toBe(before.find(node => node.id === 'skill')) + expect(match.mock.calls.map(([, from]) => from)).toEqual([0, 0, 11, 0, 11]) + }) + + it('recognizes only names explicitly resolved for this message', () => { + const evaluate = setup() + const text = '用 /review 再 /test-skill\n/review' + const input = Object.freeze({ text, facts: Object.freeze({ skillNames: Object.freeze(['review', 'test-skill', 'review']) }) }) + const nodes = evaluate(input) + expect(nodes.filter(node => node.id === 'skill').map(node => ({ raw: text.slice(node.start, node.end), data: node.data }))).toEqual([ + { raw: '/review', data: { name: 'review' } }, { raw: '/test-skill', data: { name: 'test-skill' } }, + { raw: '/review', data: { name: 'review' } }, + ]) + expect(JSON.parse(JSON.stringify(nodes))).toEqual(nodes) + expect(evaluate({ text, facts: {} })).toEqual([{ id: 'text', start: 0, end: text.length, data: { text } }]) + expect(evaluate({ text, facts: { skillNames: [] } }).every(node => node.id === 'text')).toBe(true) + }) + + it('requires whitespace or text boundaries and never strips attached punctuation', () => { + const evaluate = setup() + const text = '/x /x.md /x/path /path /x。 /x, (/x) prefix/x\t/x\n/x' + const nodes = evaluate({ text, facts: { skillNames: ['x'] } }) + expect(nodes.filter(node => node.id === 'skill').map(node => [node.start, node.end, text.slice(node.start, node.end)])).toEqual([ + [0, 2, '/x'], [text.indexOf('\t/x') + 1, text.indexOf('\t/x') + 3, '/x'], + [text.lastIndexOf('/x'), text.length, '/x'], + ]) + for (const input of [ + { text: '/path /x.md /x', facts: {} }, + { text: '/path /x.md /x。', facts: { skillNames: ['x'] } }, + { text: '/nfs-hg/path /root-dir/ /plan.md /plan。', facts: { skillNames: ['nfs-hg', 'root-dir', 'plan'] } }, + { text: '/plan.md /nfs-hg/path /plan。', facts: { skillNames: ['plan.md', 'nfs-hg/path', 'plan。'] } }, + ]) { + expect(evaluate(input).every(node => node.id === 'text')).toBe(true) + } + }) +}) diff --git a/packages/client/ui-skill/tsconfig.json b/packages/client/ui-skill/tsconfig.json index 18b2f4d062..276da77105 100644 --- a/packages/client/ui-skill/tsconfig.json +++ b/packages/client/ui-skill/tsconfig.json @@ -26,6 +26,9 @@ { "path": "../ui-renderer" }, + { + "path": "../ui-conversation/tsconfig.client.json" + }, { "path": "../ui-tool" }, diff --git a/packages/client/ui-skill/tsdown.config.ts b/packages/client/ui-skill/tsdown.config.ts index 4c5539a6b4..7aa03cebc1 100644 --- a/packages/client/ui-skill/tsdown.config.ts +++ b/packages/client/ui-skill/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-skill', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-slots/README.i18n.yaml b/packages/client/ui-slots/README.i18n.yaml index c19da5d570..af812bc333 100644 --- a/packages/client/ui-slots/README.i18n.yaml +++ b/packages/client/ui-slots/README.i18n.yaml @@ -18,8 +18,8 @@ en: 05691d44a0c6c48f zh: 434033d5761297f3 /deepseek-ai-dsh-client-ui-slots/use-this-package/reusable-component-factories: - en: 301de67bf2779ae6 - zh: 6e9d405ee1063d53 + en: 71cbe7aa26f3ff80 + zh: 0e35265d4d95cc36 /deepseek-ai-dsh-client-ui-slots/use-this-package/the-five-framework-props-shares: en: 45e2933a5e084956 zh: 938deedaf489f892 diff --git a/packages/client/ui-slots/README.md b/packages/client/ui-slots/README.md index 599d7c6371..fc4bfaf6ec 100644 --- a/packages/client/ui-slots/README.md +++ b/packages/client/ui-slots/README.md @@ -29,7 +29,7 @@ Compose UI through this package whenever you write a client plugin: register a c ### Reusable Component Factories -Use a Component Factory when one package defines an assembly that unrelated parents render independently. Declare its complete type in `SlotFactoryMap`, install the definition with `ctx.slots.registerFactory()`, render occurrences through the injected `renderFactorySlot()`, and select each declared local Component through the call's `slots` option. The definition reads that choice through `useFactorySlot(name, fallback)`. +A designer may choose a Component Factory for a component or assembly they consider reusable, even with one current caller; unrelated parents, separate packages, and additional injection or local slots are not prerequisites. A one-off component need not use a Factory. Declare its complete type in `SlotFactoryMap`, install the definition with `ctx.slots.registerFactory()`, render occurrences through the injected `renderFactorySlot()`, and select each declared local Component through the call's `slots` option. The definition reads that choice through `useFactorySlot(name, fallback)`. Factory `children` remain ordinary global Slots and must match `SlotMap`, while local `slots` select one Component per occurrence. An occurrence inherits its render-position scope; `renderFactorySlot()` does not accept a Session identity. Shared Store handles use ordinary scope resolution. A Store factory stays lazy until an occurrence first materializes, then creates one handle for that render position and rejects a persistent Store spec whose key would collide across occurrences. diff --git a/packages/client/ui-slots/README.zh.md b/packages/client/ui-slots/README.zh.md index 3bfa4c3aab..b08b278328 100644 --- a/packages/client/ui-slots/README.zh.md +++ b/packages/client/ui-slots/README.zh.md @@ -29,7 +29,7 @@ kind: "package-library" ### 可复用 Component Factory -当一个包定义装配、而互不相关的 parents 需要独立渲染它时,使用 Component Factory。在 `SlotFactoryMap` 中声明完整类型,通过 `ctx.slots.registerFactory()` 安装 definition,通过注入的 `renderFactorySlot()` 渲染 occurrences,并通过调用的 `slots` 选项选择每个已声明的局部 Component。definition 通过 `useFactorySlot(name, fallback)` 读取该选择。 +设计者认为组件或装配可复用时,即使当前只有一个调用方,也可以选择 Component Factory;互不相关的父级、不同的包、额外注入或局部 slot 都不是前提。一次性组件不必使用 Factory。在 `SlotFactoryMap` 中声明完整类型,通过 `ctx.slots.registerFactory()` 安装 definition,通过注入的 `renderFactorySlot()` 渲染 occurrences,并通过调用的 `slots` 选项选择每个已声明的局部 Component。definition 通过 `useFactorySlot(name, fallback)` 读取该选择。 Factory `children` 仍是普通全局 Slots 且必须与 `SlotMap` 匹配,而局部 `slots` 为每个 occurrence 选择一个 Component。occurrence 继承其渲染位置的 scope;`renderFactorySlot()` 不接受 Session identity。共享 Store handle 使用普通 scope 解析。Store factory 保持 lazy,直到 occurrence 首次物化时才为该渲染位置创建一个 handle;若持久化 Store spec 会让 persistence key 在 occurrences 之间冲突,renderer 会拒绝它。 diff --git a/packages/client/ui-slots/package.json b/packages/client/ui-slots/package.json index 96aa83737a..5155bb9d17 100644 --- a/packages/client/ui-slots/package.json +++ b/packages/client/ui-slots/package.json @@ -24,7 +24,7 @@ "license": "MIT", "devDependencies": { "@deepseek-ai/dsh-client-store": "workspace:*", - "@types/react": "~18.3.1", + "react": "^18.2.0", "@deepseek-ai/cordis": "workspace:~" }, "files": [ diff --git a/packages/client/ui-slots/src/index.ts b/packages/client/ui-slots/src/index.ts index 6e94643107..85c7d676cc 100644 --- a/packages/client/ui-slots/src/index.ts +++ b/packages/client/ui-slots/src/index.ts @@ -116,6 +116,8 @@ export interface SlotScopeTargetMap {} export interface SlotEntryDef { kind: SlotKind scope: SlotScope + /** Use span anchors and error placeholders for inline content; omitted uses div. */ + inline?: true owner?: object /** * Optional keyed-entry prop table. A keyed registration contributes one @@ -163,6 +165,8 @@ export interface SlotFactoryDef { export type SlotSpec = { kind: E['kind'] scope: E['scope'] + /** Use span anchors and error placeholders for inline content; omitted uses div. */ + inline?: true } & ('inject' extends keyof E ? E extends { inject: infer Injected extends object } ? { inject: Injected } diff --git a/packages/client/ui-slots/tsdown.config.ts b/packages/client/ui-slots/tsdown.config.ts index 09a4a4dc0e..a6264e0b21 100644 --- a/packages/client/ui-slots/tsdown.config.ts +++ b/packages/client/ui-slots/tsdown.config.ts @@ -1,6 +1,6 @@ import { staticLinked } from '../tsdown.client.ts' export default staticLinked( - '@deepseek-ai/dsh-client-ui-slots', + import.meta.dirname, ['lib/types/index.js'], ) diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 5bf8a6dee4..7cd80f156c 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -36,8 +36,8 @@ en: b817e9907392f59c zh: e42feb97d572a989 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/composer-election: - en: 1c15af4dd7c0b791 - zh: f789737ab4dd8cb2 + en: 13c33af89ba0942e + zh: 00374c7944728ae2 /deepseek-ai-dsh-client-ui-subagent/further-exploration: en: 1766e9012e307178 zh: f3ee637f5941aae5 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 30cea03817..76e0106c68 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -71,6 +71,8 @@ One-shot children always elect a read-only composer. A continuable child elects Unknown-mode catalog rows remain visible and clickable, using the child id when no label is available. Their composer is read-only until child history establishes a supported mode; a read failure is reported in the child conversation. +Lineage-menu highlights follow the [standard menu edge geometry](../../../docs/ui-radius.md#nested-hover); tree disclosure controls retain their separate left gutter. + ----- diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 0479608885..6bb19ef56c 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -71,6 +71,8 @@ one-shot child 始终选用只读编辑器。可继续 child 仅在其确切 par 模式未知的目录项仍可见、可点击,没有标签时显示子会话 id。读取子历史并确认受支持模式前,输入区保持只读;读取失败在该子会话中报告。 +会话树菜单高亮遵循[标准菜单边缘几何](../../../docs/ui-radius.zh.md#nested-hover);树形展开控件保留独立的左侧空间。 + ----- diff --git a/packages/client/ui-subagent/locale/en.json b/packages/client/ui-subagent/locale/en.json new file mode 100644 index 0000000000..143f7912c3 --- /dev/null +++ b/packages/client/ui-subagent/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-subagent" + } +} diff --git a/packages/client/ui-subagent/locale/zh.json b/packages/client/ui-subagent/locale/zh.json new file mode 100644 index 0000000000..7a018e4d03 --- /dev/null +++ b/packages/client/ui-subagent/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "子智能体会话界面", + "description": "查看和跳转子智能体会话,并支持继续对话和 @ 引用。" + } +} diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index ff0d19190b..a0d55f7c57 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -60,8 +61,6 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-subagent": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0", @@ -74,6 +73,7 @@ "@deepseek-ai/dsh-client-ui-workspace": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css index 19e1378313..4fc2a6f8f5 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css @@ -97,7 +97,7 @@ width: 336px; max-width: min(400px, calc(100vw - 32px)); max-height: min(560px, calc(100vh - 140px)); - padding: 3px; + padding: 4px; overflow: hidden; border-radius: var(--dsw-radius-lg); --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); @@ -146,7 +146,7 @@ min-height: 44px; padding: 6px 7px 6px 9px; border: 0; - border-radius: var(--dsw-radius-lg); + border-radius: var(--dsw-radius-md); background: transparent; color: var(--dsw-alias-label-primary); font-size: 12px; @@ -171,7 +171,7 @@ min-width: 0; margin: -6px -7px -6px; padding: 6px 7px; - border-radius: var(--dsw-radius-lg); + border-radius: var(--dsw-radius-md); } .rowActivitySlot { diff --git a/packages/client/ui-subagent/tsdown.config.ts b/packages/client/ui-subagent/tsdown.config.ts index 159de0398f..7aa03cebc1 100644 --- a/packages/client/ui-subagent/tsdown.config.ts +++ b/packages/client/ui-subagent/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-subagent', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-theme/locale/en.json b/packages/client/ui-theme/locale/en.json new file mode 100644 index 0000000000..d377165424 --- /dev/null +++ b/packages/client/ui-theme/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-theme" + } +} diff --git a/packages/client/ui-theme/locale/zh.json b/packages/client/ui-theme/locale/zh.json new file mode 100644 index 0000000000..82eccc9825 --- /dev/null +++ b/packages/client/ui-theme/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "界面主题", + "description": "提供浅色、深色和跟随系统的主题设置。" + } +} diff --git a/packages/client/ui-theme/package.json b/packages/client/ui-theme/package.json index b6fa339890..5c90ac94e1 100644 --- a/packages/client/ui-theme/package.json +++ b/packages/client/ui-theme/package.json @@ -24,7 +24,8 @@ }, "./src/*": "./src/*", "./package.json": "./package.json", - "./brand-font.css": "./lib/styles/brand-font.css" + "./brand-font.css": "./lib/styles/brand-font.css", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,12 +56,12 @@ "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "clsx": "^2.0.0", "@deepseek-ai/dsh-settings": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/styles", diff --git a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json index 2f962a9444..274fc5b552 100644 --- a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json +++ b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json @@ -5,6 +5,9 @@ "ui-deliverables/src/client/Deliverables.module.css": [ ".fileIcon: border-radius: 10px" ], + "ui-plan/src/client/PlanPreview.module.css": [ + ".cardIcon: border-radius: 10px" + ], "ui-schedule/src/client/ClockPicker.module.css": [ ".option: border-radius: 10px" ], @@ -23,7 +26,6 @@ ".deleteButton: border-radius: 6px" ], "ui-schedule/src/client/ScheduleCreateCard.module.css": [ - ".card: border-radius: 18px", ".leading: border-radius: 10px" ], "ui-schedule/src/client/TaskManagerPage.module.css": [ @@ -42,10 +44,6 @@ ".delivery: border-radius: 8px", ".linkedSession: border-radius: 14px" ], - "ui-schedule/src/client/TaskMenu.module.css": [ - ".list: border-radius: 16px", - ".item: border-radius: 8px" - ], "ui-settings-account/src/client/AccountNotice.module.css": [ ".card: border-radius: 16px" ], diff --git a/packages/client/ui-theme/tsdown.config.ts b/packages/client/ui-theme/tsdown.config.ts index d0be379b73..9bf50e3060 100644 --- a/packages/client/ui-theme/tsdown.config.ts +++ b/packages/client/ui-theme/tsdown.config.ts @@ -1,7 +1,7 @@ import { clientBundle } from '../tsdown.client.ts' export default clientBundle( - '@deepseek-ai/dsh-client-ui-theme', + import.meta.dirname, ['lib/types/index.js'], { lib: { diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index 04158a1ca7..01eb372ca9 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2e3c306b13d3bc25 zh: 77127f01763b3976 /deepseek-ai-dsh-client-ui-tool/use-this-package/built-in-views: - en: 4d885fc693b497f4 - zh: 2f68d9ea92f2ebd6 + en: 3643ffbb8cf80e4c + zh: b49654dc3b94b2be /deepseek-ai-dsh-client-ui-tool/understand-the-implementation: en: 00bc7b0c84edc603 zh: 1cfcf5b435248a91 @@ -30,8 +30,8 @@ en: 672e63b2f92e689b zh: ba950ecb480325a6 /deepseek-ai-dsh-client-ui-tool/understand-the-implementation/cards: - en: 679c7bb0f49d7929 - zh: 93bba9a6da95d303 + en: d3cfe0abdce4718d + zh: c2b5708e8a028226 /deepseek-ai-dsh-client-ui-tool/understand-the-implementation/declared-optional-capabilities: en: c1926deb4e5f3734 zh: c5845f465b94a459 diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index c8f88095b1..d3c98dbeeb 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -51,7 +51,7 @@ Every registered view receives the explicit `preparing`, `start`, and `result` p File-tool rows prefer a complete `file_path`; other generic rows, including search and unregistered tools, prefer a non-empty `description` before their variant-specific argument fallback. Read `args` during rendering or view construction: a preparing reader grows in place, and only previously observed answer changes trigger subsequent block publication. -This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and PTC dispatch presentations. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running atomic rows share one left-to-right highlight across their titles, separators, summaries, and suffixes, while settled rows stay static. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in PTC dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable. Background Bash calls expand to their original arguments and job acknowledgement. Their input scrolls horizontally without soft wrapping and remains selectable; only horizontal overflow adds a named keyboard focus target. Inspect is available when provided. The acknowledgement does not report the job's exit status. A native or PTC dispatch failure carrying `AUTO_REVIEW_DENIED` shows the Auto review verdict in its collapsed row and one normalized not-executed reason when expanded; a missing or whitespace-only reason uses localized fallback text. `ui-skill` demonstrates a business-owned registration for `skill`. +This package owns the generic fallback and the built-in shell/pwsh, read, read_image, write/edit, running `str_replace_editor` `create`/`str_replace`, grep/glob, web, todo, question, and PTC dispatch presentations. Structured cards derive directly from first-party raw event fields; Host `presentCall` and `presentResult` values never enter the Client. Running atomic rows share one left-to-right highlight across their titles, separators, summaries, and suffixes, while settled rows stay static. Running and settled foreground standard `bash`/`pwsh` and `terminal_send` calls use terminal cards at the root and in PTC dispatch children, subject to the same argument, result, and error checks. Persistent `bash`/`pwsh` calls use terminal cards only while running. Shell output ending in a recognized spill-policy notice uses expandable generic output in shell rows and generic output in Details; a displaced or omitted exit marker cannot establish success. Settled persistent-shell results stay generic because reset and partial-output diagnostics do not always describe one process exit status; root persistent results are expandable. Valid explicit background `bash`/`pwsh` calls use the terminal Start presentation; a successful launch acknowledgement retains the command and cwd in a static command-only card without output or execution status. Launch failures retain generic arguments and errors, while background `terminal_send` stays generic. Inspect preserves the original arguments and acknowledgement; later job output is not attached to this card ([decision](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.md)). Expanded terminal commands and background inputs wrap to the available width while preserving authored line breaks and selectable text; terminal output keeps its column-preserving layout. Only horizontal overflow adds a named keyboard focus target. Inspect is available when provided. The acknowledgement does not report the job's exit status. A native or PTC dispatch failure carrying `AUTO_REVIEW_DENIED` shows the Auto review verdict in its collapsed row and one normalized not-executed reason when expanded; a missing or whitespace-only reason uses localized fallback text. `ui-skill` demonstrates a business-owned registration for `skill`. Question rows pair answers with questions by id, using the tool result or the `userQuestions` projection for late replies. An answerable call has a button to reopen its panel. Once a late reply is in the agent Inbox, the row shows its submitted answers; “View answers” expands its read-only transcript while admission is pending. A settled call with answers opens the panel read-only. Closed calls without answers and invalid records offer no button. Cancelled and interrupted rows show their verdict without inventing answers. If no panel provider accepts the button action, it expands the row. Unsupported or ambiguous input falls back to flattened Tool text. @@ -79,7 +79,7 @@ Tool Definitions own the [lazy argument view](../../util/values/README.md). Rows ### Cards -Every card is read in place in the call tree; there is no second, full-height presentation of a selected call. Row renderers share one pure card model for each terminal, read, diff, search, and web card, and the image card's gallery renders through the tool-owned `tool.call.images` slot. These models validate raw call arguments, result content, failure state, persisted metadata, PTC dispatch `parentCallId`, and Session path facts. Unsupported or malformed inputs use flattened Tool result text. A file-path summary opens the file through the owner's `openFile`, which the chat view routes to the right Sidebar's text preview; `inspect` opens the trajectory view and is absent when that View is unavailable; cards then omit Inspect. Card-specific limits and fallback rules for the terminal, diff, read, search, and web cards remain in [the ui-primitives README](../ui-primitives/README.md); the image card's model in this package carries its own fallback rules. +Every card is read in place in the call tree; there is no second, full-height presentation of a selected call. Row renderers share one pure card model for each terminal, read, diff, search, and web card, and the image card's gallery renders through the tool-owned `tool.call.images` slot, followed by the full recorded path and each attached image's pixel size (with the original size when downscaled) and byte count. These models validate raw call arguments, result content, failure state, persisted metadata, PTC dispatch `parentCallId`, and Session path facts. Unsupported or malformed inputs use flattened Tool result text. A file-path summary opens the file through the owner's `openFile`, which the chat view routes to the right Sidebar's text preview; `inspect` opens the trajectory view and is absent when that View is unavailable; cards then omit Inspect. Card-specific limits and fallback rules for the terminal, diff, read, search, and web cards remain in [the ui-primitives README](../ui-primitives/README.md); the image card's model in this package carries its own fallback rules. Chat diff cards keep nine rows before folding, enough for a file header, one removed/added pair, and three context lines on either side. The tool row shows the primitive's exact or coarse-replacement counts; the expanded card contains the diff body without a totals footer. Hovering the tool header colors its added count green and removed count red; both retain those colors while the card is expanded. diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index 6b0d28087b..f898a9eeb1 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -51,7 +51,7 @@ owner 载荷为 `ToolCallOwnerProps`:`callId`、`toolName`、`phase` 判别字 文件工具行优先使用完整的 `file_path`;其他通用行(包括搜索和未注册的工具)优先使用非空 `description`,再回退到各自类别的参数摘要。应在渲染或构造视图时读取 `args`:准备态读器原地增长,后续仅在已观察答案变化时重新发布块。 -本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 PTC dispatch 的内置展示。结构化卡片直接从第一方原始 event 字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中的原子工具行以同一道高光从左到右扫过标题、分隔符、摘要与后缀;已完成行保持静态。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 PTC dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开。后台 Bash 调用可展开查看原始参数与后台任务回执。输入内容可横向滚动,不自动折行,并可选中;仅横向溢出时添加具名的键盘聚焦目标。提供 Inspect 时也可使用。回执不表示后台任务的退出状态。带有 `AUTO_REVIEW_DENIED` 的原生或 PTC dispatch 失败会在折叠行显示 Auto review 裁决,展开时显示一行归一化后的“未执行”原因;原因缺失或只有空白时使用本地化 fallback 文案。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。 +本包拥有 generic fallback,以及 shell/pwsh、read、read_image、write/edit、运行中的 `str_replace_editor` `create`/`str_replace`、grep/glob、web、todo、question 与 PTC dispatch 的内置展示。结构化卡片直接从第一方原始 event 字段派生;Host `presentCall` 与 `presentResult` 值不会进入 Client。运行中的原子工具行以同一道高光从左到右扫过标题、分隔符、摘要与后缀;已完成行保持静态。运行中与已完成的前台标准 `bash`/`pwsh` 和 `terminal_send` 调用,无论位于根还是 PTC dispatch 子调用中,都在通过相同的参数、结果和错误检查后使用 terminal 卡片。持久 `bash`/`pwsh` 调用仅在运行中使用 terminal 卡片。以已识别的 spill 策略提示结尾的 shell 输出,在 shell 行中使用可展开的 generic 输出,在 Details 中使用 generic 输出;位置被改变或被省略的退出标记无法证明成功。已完成的持久 shell 结果保持 generic 展示,因为 reset 与部分输出诊断不一定描述单个进程的退出状态;根调用的持久 shell 结果可展开。合法的主动后台 `bash`/`pwsh` 调用使用 terminal Start 展示;成功启动回执后,静态仅命令卡片保留 command 和 cwd,不显示输出或执行状态。启动失败保留通用参数与错误展示,后台 `terminal_send` 仍为 generic。Inspect 保留原始参数及回执,后续 job 输出不接回此卡片([决定](../../../.agents/notes/implemented/bug-fix/2026-10-10-background-shell-command-display.zh.md))。展开的终端命令与后台输入按可用宽度自动折行,保留原有换行和可选文本;终端输出保持按列对齐的排版。仅横向溢出时添加具名的键盘聚焦目标。提供 Inspect 时也可使用。回执不表示后台任务的退出状态。带有 `AUTO_REVIEW_DENIED` 的原生或 PTC dispatch 失败会在折叠行显示 Auto review 裁决,展开时显示一行归一化后的“未执行”原因;原因缺失或只有空白时使用本地化 fallback 文案。`ui-skill` 展示了业务包自行拥有的 `skill` 注册项。 问题行按 id 配对问题与答案;答案来自工具结果,迟到回答则来自 `userQuestions` 投影。可回答的调用提供按钮以重新打开面板。迟到回复进入 agent Inbox 后,问题行显示已提交的答案;等待准入期间,「查看回答」展开只读的行内记录。带有答案的已结算调用则以只读方式打开面板。没有答案的已关闭调用和无效记录不提供按钮。已取消和已中断的行显示裁决,不虚构答案。若面板提供方不接受按钮操作,点击会展开该行。不受支持或含糊的输入回退为压平的工具文本。 @@ -79,7 +79,7 @@ Tool Definition 拥有[懒计算参数视图](../../util/values/README.zh.md)。 ### 卡片 -每张卡片都直接在调用树中查看;选中调用后不会再显示第二个全高视图。行 renderer 为 terminal、read、diff、search 和 web 卡片各复用同一个纯 card model,image 卡片的图库经由工具自有 `tool.call.images` slot 渲染。这些 model 校验原始调用参数、结果内容、失败状态、持久 metadata、PTC dispatch 的 `parentCallId` 与会话路径信息。不受支持或格式错误的输入使用压平的工具结果文本。文件路径摘要经属主的 `openFile` 打开文件,chat 视图把它路由到右侧 Sidebar 的文本预览;`inspect` 打开轨迹视图;该视图不可用时不提供此回调,卡片随之隐藏 Inspect。terminal、diff、read、search 与 web 卡片的上限与 fallback 规则仍由 [ui-primitives README](../ui-primitives/README.zh.md) 负责;image 卡片的 fallback 规则由本包内的 card model 自行承载。 +每张卡片都直接在调用树中查看;选中调用后不会再显示第二个全高视图。行 renderer 为 terminal、read、diff、search 和 web 卡片各复用同一个纯 card model,image 卡片的图库经由工具自有 `tool.call.images` slot 渲染,其下显示完整的记录路径以及每张附件图片的像素尺寸(缩小时附原图尺寸)和字节数。这些 model 校验原始调用参数、结果内容、失败状态、持久 metadata、PTC dispatch 的 `parentCallId` 与会话路径信息。不受支持或格式错误的输入使用压平的工具结果文本。文件路径摘要经属主的 `openFile` 打开文件,chat 视图把它路由到右侧 Sidebar 的文本预览;`inspect` 打开轨迹视图;该视图不可用时不提供此回调,卡片随之隐藏 Inspect。terminal、diff、read、search 与 web 卡片的上限与 fallback 规则仍由 [ui-primitives README](../ui-primitives/README.zh.md) 负责;image 卡片的 fallback 规则由本包内的 card model 自行承载。 Chat diff 卡片在折叠前保留九行,足以容纳文件标题、一对删除与新增行及两侧各三行上下文。工具行显示原语提供的精确或粗粒度替换统计;展开卡片包含差异正文,不显示底部统计。悬停工具标题行时,新增数量显示绿色、删除数量显示红色;卡片展开期间保留这两种颜色。 diff --git a/packages/client/ui-tool/locale/en.json b/packages/client/ui-tool/locale/en.json new file mode 100644 index 0000000000..a071d79746 --- /dev/null +++ b/packages/client/ui-tool/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-tool" + } +} diff --git a/packages/client/ui-tool/locale/zh.json b/packages/client/ui-tool/locale/zh.json new file mode 100644 index 0000000000..2eb3bc4b7c --- /dev/null +++ b/packages/client/ui-tool/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具调用展示", + "description": "展示工具调用过程、嵌套关系和各工具的结果界面。" + } +} diff --git a/packages/client/ui-tool/package.json b/packages/client/ui-tool/package.json index e41d049302..2d0e0f2001 100644 --- a/packages/client/ui-tool/package.json +++ b/packages/client/ui-tool/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -64,7 +65,6 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", "react": "^18.2.0", "react-dom": "^18.2.0", "@deepseek-ai/dsh-api-workspace-controller": "workspace:*", @@ -80,6 +80,7 @@ "@deepseek-ai/dsh-user-questions": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css index 5be4d641be..10432d7041 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.module.css @@ -275,22 +275,23 @@ color: var(--dsw-alias-label-tertiary); } -/* The image card's in-card label: the view's replacement title, else the - shortened path — the same role ReadBlock's own label plays, so the presentation - contract's replacement-title rule is honoured here too. */ -.imageLabel { - margin-bottom: 4px; +/* The image card's full path and size lines under the gallery, in the small + code font of the expanded IN/OUT card. When the attachment slot renders + nothing, these lines are the only evidence an image was returned. pre-wrap + keeps repeated whitespace in a path. The enclosing .imageBody already carries + the row indent. */ +.imageMeta { + margin-top: 4px; + white-space: pre-wrap; overflow-wrap: anywhere; - font: var(--dsw-font-sm-13); - color: var(--dsw-alias-label-secondary); + font: var(--dsw-font-markdown-code-block-small); + color: var(--dsw-alias-label-tertiary); } -/* The image card's own result text (media type, dimensions, byte size) under the - gallery, in the same muted tone the search recovery footer uses. Always - rendered: the attachment presentation slot is optional, so when nothing - occupies it the gallery is empty and this line is the only evidence an image - was returned. The enclosing .imageBody already carries the row indent. */ -.imageMeta { +/* Text blocks other than the envelope (for example, appended by a post-execute + hook), in the muted tone the search recovery footer uses. */ +.imageExtra { + margin-top: 4px; white-space: pre-wrap; overflow-wrap: anywhere; font: var(--dsw-font-xs-13); @@ -304,6 +305,7 @@ --dsl-terminal-font: var(--dsw-font-markdown-code-block-small); --dsl-terminal-line-height: 18px; --dsl-terminal-output-max-height: 224px; + --dsl-terminal-command-whitespace: pre-wrap; border: 0.5px solid var(--dsw-alias-border-l1); } diff --git a/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx b/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx index b62d581d8b..4b4674d452 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx +++ b/packages/client/ui-tool/src/client/tool/components/ToolRow.tsx @@ -270,22 +270,33 @@ export const ToolRow = memo(function ToolRow({ ? : imageBody !== null ? ( - /* Label, gallery, then the result's OWN envelope text. The text - comes from the image card model (which reads the result's text - block), never from the row's flattened output: an image read's - content is [text envelope, image block] and flattening - JSON.stringifies the image block, printing the raw attachment - object under the picture. It is not redundant either — the - attachment slot can render nothing, and then this line is the - only evidence an image was returned. */ + /* Gallery, then the full path and each attached image's size. + These come from the image card model, never from the row's + flattened output, which JSON.stringifies the image block. They + stay visible when the attachment slot renders nothing. */
    -
    {imageBody.label}
    {renderSlot !== undefined && loadImage !== undefined && renderSlot('tool.call.images', { images: imageBody.images, loadImage, align: 'start', })} -
    {imageBody.text}
    +
    +
    {imageBody.path}
    + {imageBody.images.map(({ attachment }, index) => ( +
    + {attachment.originalDimensions === undefined + ? t('row.imageSize', { width: attachment.width, height: attachment.height, bytes: attachment.bytes }) + : t('row.imageSizeDownscaled', { + width: attachment.width, + height: attachment.height, + originalWidth: attachment.originalDimensions.width, + originalHeight: attachment.originalDimensions.height, + bytes: attachment.bytes, + })} +
    + ))} +
    + {imageBody.extraText !== null &&
    {imageBody.extraText}
    }
    ) : searchBody !== null diff --git a/packages/client/ui-tool/src/client/tool/models/image-card-model.ts b/packages/client/ui-tool/src/client/tool/models/image-card-model.ts index 085451b35b..b2d0f36073 100644 --- a/packages/client/ui-tool/src/client/tool/models/image-card-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/image-card-model.ts @@ -1,31 +1,28 @@ /** Pure image-card derivation from raw result content and metadata. @module */ import type { AttachmentId, ImageAttachmentRef, ImageMediaType } from '@deepseek-ai/dsh-attachment' -import { abbreviateHomePath, relativizeToCwd } from '@deepseek-ai/dsh-util-workspace-path' import type { ToolCallBlock } from './tool-call-model.ts' import { parsedToolCall } from './raw-tool-call.ts' /** - * The image-card material one settled call contributes: the display label plus - * the durable references the attachment slot renders as a gallery. + * The image-card material one settled call contributes: the read path plus the + * durable references the attachment slot renders as a gallery. * * The bytes are not here. `attachmentId` is opaque and provider-owned, so a UI * resolves it to a session-authorized URL at render time; this model never parses * it nor derives a path from it. */ export interface ImageCardModel { - /** Card label: the read path, shortened the way every other card's is. */ - label: string + /** The resolved path as recorded, unshortened; the row summary already shows the short form. */ + path: string /** The durable images this result returned, in result order. */ images: readonly { readonly attachment: ImageAttachmentRef }[] /** - * The model-facing envelope text, for the line under the gallery. - * - * Taken from the result's own text block rather than the row's flattened - * result text: an image read's content is `[text envelope, image block]`, and - * flattening JSON.stringifies the image block, which would print the raw - * attachment object under the picture — the symptom this card exists to remove. + * Text blocks other than the model-facing envelope (for example, text a + * post-execute hook appended), joined in order; null when there are none. + * The envelope itself is not repeated: its path and image facts are already + * `path` and `images`. */ - text: string + extraText: string | null } /** @@ -35,7 +32,7 @@ export interface ImageCardModel { * * Root calls persist it; a nested call (a read_image dispatched from inside * run_code) settles without `meta`, so the card falls back to the call's own - * `file_path` argument for the label. + * `file_path` argument for the path. * * The attachment reference deliberately does NOT come from here. The settled * `content` already carries the image block with its complete reference, so @@ -150,24 +147,17 @@ function imageReferences(content: readonly unknown[]): ImageAttachmentRef[] | nu } /** - * Read the text of every text block of a settled image result, joined in order. - * - * The envelope is one of them; a post-execute hook that appends further text - * blocks keeps them visible under the gallery instead of being dropped. The - * envelope shape is still the recognition gate: a result without it is not a - * well-formed image read and declines. - * @param content - the settled result's content blocks. - * @returns the joined text, or null when no envelope-shaped block is present. + * Join the text blocks other than the image envelope, in order. A post-execute + * hook that appends further text blocks keeps them visible under the gallery + * instead of being dropped. + * @param content - the settled result's text blocks. + * @returns the joined text, or null when there is none. */ -function imageTexts(content: readonly { type: string; text?: string }[]): string | null { - const parts: string[] = [] - let sawEnvelope = false - for (const part of content) { - if (part.type !== 'text' || typeof part.text !== 'string') continue - if (IMAGE_ENVELOPE.test(part.text)) sawEnvelope = true - parts.push(part.text) - } - return sawEnvelope && parts.length > 0 ? parts.join('\n') : null +function extraTexts(content: readonly { type: string; text?: string }[]): string | null { + const parts = content.flatMap(part => part.type === 'text' && typeof part.text === 'string' && !IMAGE_ENVELOPE.test(part.text) + ? [part.text] + : []) + return parts.length > 0 ? parts.join('\n') : null } /** @@ -197,18 +187,11 @@ function fullyRendered(content: readonly unknown[]): boolean { * returns, so a running `read_image` has none and this returns null for it. * Both root and nested calls settle as ToolResultNode. Historical nested * records without presentation metadata fall back to the call's own - * `file_path` argument for the label. + * `file_path` argument for the path. * @param block - running or settled Tool block. - * @param sessionCwd - the session workspace root; a workspace-rooted absolute - * path label displays relative to it. Absent leaves the path as authored. - * @param home - host account home; a leftover POSIX home path displays as `~`. * @returns the image-card props, or null for the generic path. */ -export function imageCardModel( - block: ToolCallBlock, - sessionCwd?: string, - home?: string, -): ImageCardModel | null { +export function imageCardModel(block: ToolCallBlock): ImageCardModel | null { // Result-side only: a running call is not a ToolResultNode and carries no // content, so it has no card here. if (!('kind' in block) || block.isError) return null @@ -217,7 +200,7 @@ export function imageCardModel( const { file_path: filePath } = call.args if (typeof filePath !== 'string' || filePath.trim() === '') return null // Historical nested records without metadata use the authored file_path - // for the label. A root call with missing or malformed meta + // for the path. A root call with missing or malformed meta // declines — malformed tool data falls back to the generic card, which shows // the flattened content rather than an author-typed path. const metaPath = imageMeta(block.meta)?.path @@ -230,11 +213,11 @@ export function imageCardModel( // truth; `meta` contributes only the path, which the content does not carry. const refs = imageReferences(block.content) if (refs === null) return null - const text = imageTexts(block.content) - if (text === null) return null + // A result without the envelope is not a well-formed image read. + if (!block.content.some(part => part.type === 'text' && typeof part.text === 'string' && IMAGE_ENVELOPE.test(part.text))) return null return { - label: abbreviateHomePath(relativizeToCwd(path, sessionCwd), home), + path, images: refs.map(ref => ({ attachment: ref })), - text, + extraText: extraTexts(block.content), } } diff --git a/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts b/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts index d6fe0fa3e0..6331f89592 100644 --- a/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/terminal-card-model.ts @@ -44,7 +44,7 @@ export interface TerminalCardModel { * The locale-neutral props {@link TerminalBlock} draws. The render site adds * `command` after resolving {@link copy} through its locale seat. */ - card: Pick + card: Pick /** * Verbatim Tool data or semantic `terminal_send` data. Product copy stays * unresolved until a render site supplies its locale seat. @@ -55,7 +55,7 @@ export interface TerminalCardModel { } interface LocalizedTerminalCardModel { - readonly card: Pick + readonly card: Pick readonly description: string | undefined } @@ -288,8 +288,9 @@ function parseExitStatus(text: string): { output: string; exitCode?: number; sig /** * Derive terminal props for supported shell and terminal-send calls, including * nested PTC dispatch calls. Standard shell results parse their final status - * marker; persistent shell results, spill previews, background calls, errors, - * and malformed input use the generic path. {@link isSettledPersistentShellCall} lets that generic + * marker. Successful background shell launches retain only their command after + * settlement; persistent shell results, spill previews, background terminal sends, + * errors, and malformed input use the generic path. {@link isSettledPersistentShellCall} lets that generic * persistent result remain expandable without inventing one process status. * @param block - running or settled Tool block. * @param sessionCwd - original workspace root used only for old results without recorded cwd. @@ -302,7 +303,7 @@ export function terminalCardModel( const parsed = parsedToolCall(block) if (parsed === null) return null const call = shellCall(parsed.name, parsed.args) ?? terminalSendCall(parsed.name, parsed.args) - if (call === null || call.background) return null + if (call === null || (call.kind === 'terminal-send' && call.background)) return null const copy: TerminalCardModel['copy'] = call.kind === 'shell' ? { kind: 'shell', command: call.command, description: call.description } @@ -322,10 +323,14 @@ export function terminalCardModel( exitCode: undefined, signal: undefined, running: true, + ...(call.kind === 'shell' && call.background ? { background: call.background } : {}), }, } } if (block.isError || (call.kind === 'shell' && call.persistent) || isSpilledShellCall(block)) return null + if (call.kind === 'shell' && call.background) { + return { copy, card: { cwd, running: false, background: call.background } } + } const output = singleResultText(block) if (output === undefined) return null const status = call.kind === 'terminal-send' ? { output } : parseExitStatus(output) diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css index e6ba3f505e..52792b8722 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.module.css @@ -16,6 +16,7 @@ --dsl-terminal-font: var(--dsw-font-markdown-code-block-small); --dsl-terminal-line-height: 18px; --dsl-terminal-output-max-height: 224px; + --dsl-terminal-command-whitespace: pre-wrap; margin: 4px 0 4px 4px; border: 0.5px solid var(--dsw-alias-border-l1); } @@ -78,6 +79,7 @@ } .commandInput { + --dsl-command-whitespace: pre-wrap; color: var(--dsw-alias-label-secondary); } diff --git a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx index f23e369d0b..52ffd1555a 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/bash-sample.tsx @@ -57,9 +57,8 @@ export const BashRow = memo(function BashRow({ toolName, block, sessionId, useSe const status = stateStatus(state, t) const { expanded, toggle: toggleExpand } = useDisclosure() const background = isBackgroundShellCall(block) - // Background launches expose their acknowledgement without assigning the - // job an exit status. Failures, persistent results, and spill previews also - // keep the generic input/output presentation. + // Failed or interrupted background launches retain raw input/output, as do + // other execution failures, persistent results, and spill previews. const genericBody = terminal === null && (model.state === 'error' || isSettledPersistentShellCall(block) || isSpilledShellCall(block) || background) && (model.bodyRaw !== null || model.output !== null) diff --git a/packages/client/ui-tool/src/client/tool/toolviews/read-image-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/read-image-row.tsx index e0095b0904..b2cd520281 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/read-image-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/read-image-row.tsx @@ -28,9 +28,9 @@ import { CONVERSATION_NS as NS } from '../../locale.ts' * slot this entry declares. */ export function ReadImageRow(props: ReadImageRowProps) { - const { block, cwd, home, renderSlot, loadImage } = props + const { block, renderSlot, loadImage } = props return readFamilyRow(props, { - image: imageCardModel(block, cwd, home), + image: imageCardModel(block), renderSlot, loadImage, }) diff --git a/packages/client/ui-tool/tests/image-card.client.spec.tsx b/packages/client/ui-tool/tests/image-card.client.spec.tsx index 8b0d642012..621e4cbcad 100644 --- a/packages/client/ui-tool/tests/image-card.client.spec.tsx +++ b/packages/client/ui-tool/tests/image-card.client.spec.tsx @@ -9,7 +9,7 @@ // The image card differs from every other card in one load-bearing way: its bytes // are a session-authorized attachment, so the row cannot draw them itself. It // renders through the tool-owned `tool.call.images` slot, and an empty slot must -// still leave the media type and dimensions visible. +// still leave the path and image size visible. import { afterEach, describe, expect, it, vi } from 'vitest' import { useDisclosure } from '@deepseek-ai/dsh-client-ui-chat/src/client/chat/use-disclosure.ts' @@ -113,11 +113,9 @@ const loadImage: MessageImageLoader = vi.fn(() => Promise.reject(new Error('not describe('imageCardModel', () => { it('derives the card from settled image metadata and its raw envelope', () => { expect(imageCardModel(settled())).toEqual({ - label: 'shots/card.png', + path: 'shots/card.png', images: [{ attachment: sampleImage }], - // The fallback line is the result's own envelope, not the row's flattened - // output (which would stringify the image block). - text: ENVELOPE, + extraText: null, }) }) @@ -128,16 +126,9 @@ describe('imageCardModel', () => { expect(attachment).not.toHaveProperty('name') }) - it('relativizes a workspace-rooted path label, and leaves others as authored', () => { - expect(imageCardModel(settled({ meta: imageMeta({ path: '/w/app/shots/card.png' }) }), '/w/app')?.label) - .toBe('shots/card.png') - expect(imageCardModel(settled({ meta: imageMeta({ path: '/srv/other.png' }) }), '/w/app')?.label) - .toBe('/srv/other.png') - }) - - it('abbreviates a leftover POSIX home path label', () => { - expect(imageCardModel(settled({ meta: imageMeta({ path: '/Users/u/card.png' }) }), '/tmp/ws', '/Users/u')?.label) - .toBe('~/card.png') + it('keeps the recorded path unshortened', () => { + expect(imageCardModel(settled({ meta: imageMeta({ path: 'G:\\breeze\\shots\\card.png' }) }))?.path) + .toBe('G:\\breeze\\shots\\card.png') }) it('accepts any non-empty attachment id, because the shape is provider-owned', () => { @@ -163,7 +154,7 @@ describe('imageCardModel', () => { { type: 'image', attachment: appended }, ], } as never)) - expect(model?.text).toBe(`${ENVELOPE}\nanalysis: the card area is empty`) + expect(model?.extraText).toBe('analysis: the card area is empty') expect(model?.images).toEqual([{ attachment: sampleImage }, { attachment: appended }]) }) @@ -205,7 +196,7 @@ describe('imageCardModel', () => { // Metadata arrives unvalidated on replay, so an obsolete or hand-edited log // must never crash the tool message. A ROOT call whose meta does not match // declines to the generic card — malformed tool data must not render a - // card labeled with the author-typed path. Only a nested call (which + // card showing the author-typed path. Only a nested call (which // persists no meta by design) falls back to its own file_path argument. for (const meta of [undefined, null, 'meta', [{ path: 'a.png' }], {}, { path: '' }, { path: 7 }]) { expect(() => imageCardModel(settled({ meta }))).not.toThrow() @@ -213,7 +204,7 @@ describe('imageCardModel', () => { } const nested = imageCardModel(settled({ parentCallId: 'parent', meta: undefined })) expect(nested).not.toBeNull() - expect(nested?.label).toBe('shots/card.png') + expect(nested?.path).toBe('shots/card.png') }) it('declines a malformed attachment reference in the content', () => { @@ -257,14 +248,14 @@ describe('imageCardModel', () => { expect(imageCardModel(settled({ isError: true }))).toBeNull() // A nested call (a read_image dispatched from inside run_code) settles as a // ToolResultNode too and renders the card; it persists no presentationMeta, - // so the label falls back to the call's file_path argument. + // so the path falls back to the call's file_path argument. const nested = imageCardModel(settled({ parentCallId: 'parent', meta: undefined })) expect(nested).not.toBeNull() - expect(nested?.label).toBe('shots/card.png') + expect(nested?.path).toBe('shots/card.png') expect(nested?.images).toHaveLength(1) // Persisted meta still wins over the argument when a nested call has one. const withMeta = imageCardModel(settled({ parentCallId: 'parent', meta: { path: 'shots/persisted.png' } })) - expect(withMeta?.label).toBe('shots/persisted.png') + expect(withMeta?.path).toBe('shots/persisted.png') }) it('declines a call head that is not read_image', () => { @@ -332,7 +323,30 @@ describe('ReadImageRow keyed toolview', () => { const text = view.container.textContent ?? '' expect(text).not.toContain('"attachmentId"') expect(text).not.toContain('"type": "image"') - expect(text).toContain('image/png image, 1496x260 px') + expect(text).not.toContain('') + expect(text).not.toContain('image/png image') + }) + + it('shows the full path once, then the image size, under the picture', () => { + const view = render() + toggleRow(view) + const lines = [...view.container.querySelectorAll('[class*="imageMeta"] > div')].map(line => line.textContent) + expect(lines).toEqual(['/w/app/shots/card.png', '1496x260px,24588 字节']) + }) + + it('names the original size of a downscaled image', () => { + const downscaled = { ...sampleImage, originalDimensions: { width: 2992, height: 520 } } + const view = render() + toggleRow(view) + expect(view.container.textContent).toContain('1496x260px(由 2992x520px 缩小),24588 字节') + }) + + it('keeps appended non-envelope text under the picture', () => { + const view = render() + toggleRow(view) + expect(view.container.textContent).toContain('analysis: empty card') }) it('keeps the result text readable when the attachment slot renders nothing', () => { @@ -343,7 +357,7 @@ describe('ReadImageRow keyed toolview', () => { toggleRow(view) expect(emptySlot).toHaveBeenCalled() expect(view.container.querySelector('[data-images]')).toBeNull() - expect(view.container.textContent).toContain('image/png image, 1496x260 px') + expect(view.container.textContent).toContain('1496x260px,24588 字节') }) it('degrades to the text body when neither the slot nor the loader is supplied', () => { diff --git a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts index b28154732d..6aed393a37 100644 --- a/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts +++ b/packages/client/ui-tool/tests/spill-policy-terminal.client.spec.ts @@ -72,8 +72,8 @@ async function executeShell(text: string, nested: boolean, name = 'bash', maxInl async execute() { return [{ type: 'text', text }] }, }))) const session = Session.create(SessionId('spill-terminal')) - // The tool pipeline reads only the owner session; no agent loop runs here. - const agent = { session } as Agent + // Nested PTC registers retained-environment cleanup on the owning context. + const agent = { ctx, session } as Agent const callId = ToolCallId('shell-call') const result = await ctx.tools.execute({ callId, diff --git a/packages/client/ui-tool/tests/terminal-card.client.spec.tsx b/packages/client/ui-tool/tests/terminal-card.client.spec.tsx index a891bad758..24117339cd 100644 --- a/packages/client/ui-tool/tests/terminal-card.client.spec.tsx +++ b/packages/client/ui-tool/tests/terminal-card.client.spec.tsx @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { useDisclosure } from '@deepseek-ai/dsh-client-ui-chat/src/client/chat/use-disclosure.ts' -import { cleanup, fireEvent, render } from '@testing-library/react' +import { act, cleanup, fireEvent, render } from '@testing-library/react' import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { StartedToolCall, ToolResultNode } from '@deepseek-ai/dsh-client-ui-chat/client' @@ -264,8 +264,35 @@ describe('terminalCardModel', () => { }))).not.toBeNull() }) - it('returns null for background, errors, malformed args, unsupported tools, and non-text results', () => { - expect(terminalCardModel(running({ argsRaw: shellArgs({ run_in_background: true }) }))).toBeNull() + it.each(['bash', 'pwsh'])('derives %s background launch commands without treating acknowledgement as output', (name) => { + const argsRaw = shellArgs({ run_in_background: true, workdir: '/requested' }) + for (const parentCallId of [undefined, 'parent']) { + const parent = parentCallId === undefined ? {} : { parentCallId } + expect(terminalCardModel(running({ name, argsRaw, ...parent }))).toEqual({ + copy: { kind: 'shell', command: 'ls -la', description: 'List files' }, + card: { cwd: '/requested', running: true, background: true, output: undefined, exitCode: undefined, signal: undefined }, + }) + for (const content of [[], [{ type: 'text' as const, text: 'started background job bash-1\n[exit code: 7]' }]]) { + const block = settled({ call: { name, argsRaw }, ...parent, meta: { cwd: '/recorded' }, content }) + const model = terminalCardModel(block)! + expect(model).toEqual({ + copy: { kind: 'shell', command: 'ls -la', description: 'List files' }, + card: { cwd: '/recorded', running: false, background: true }, + }) + expect(terminalFailed(model)).toBe(false) + expect(localizeTerminalCardModel(model, t).card).toEqual({ + command: 'ls -la', cwd: '/recorded', running: false, background: true, + }) + expect(terminalCardModel({ ...block, isError: true })).toBeNull() + expect(block.content).toBe(content) + } + } + }) + + it('returns null for background terminal sends, errors, malformed args, unsupported tools, and non-text results', () => { + expect(terminalCardModel(running({ name: 'terminal_send', argsRaw: JSON.stringify({ + sessionId: 'pty-3', text: 'make', run_in_background: true, + }) }))).toBeNull() expect(terminalCardModel(settled({ isError: true }))).toBeNull() expect(terminalCardModel(running({ argsRaw: '{' }))).toBeNull() expect(terminalCardModel(running({ name: 'read' }))).toBeNull() @@ -405,12 +432,13 @@ describe('chat row terminal body', () => { expect(view.getByText(command)).toBeTruthy() }) - it('a non-terminal call keeps the args-JSON text body', () => { + it('a background terminal_send keeps the args-JSON text body', () => { const view = render() + call: { name: 'terminal_send', argsRaw: JSON.stringify({ sessionId: 'pty-3', text: 'make', run_in_background: true }) }, + }))} toolName="terminal_send" />) toggleRow(view) - expect(view.getByText(/"command"/)).toBeTruthy() + expect(view.getByText(/"sessionId"/)).toBeTruthy() + expect(view.container.querySelector('[data-terminal]')).toBeNull() }) it('malformed empty args use the generic output body', () => { @@ -527,45 +555,112 @@ describe('BashRow terminal card', () => { expect(view.container.querySelectorAll('[class*="_ioText_"]')[1]?.textContent).toBe(output) }) - it.each([undefined, 'dispatch-parent'])('expands a background launch and its acknowledgement without reporting a job exit (parent: %s)', (parentCallId) => { - const command = 'pnpm --filter @deepseek-ai/dsh-client-ui-tool run build --watch --verbose' - const args = { command, description: 'Wait', run_in_background: true } - const argsRaw = JSON.stringify(args) + it.each([ + ['bash', undefined], ['bash', 'dispatch-parent'], ['pwsh', undefined], ['pwsh', 'dispatch-parent'], + ] as const)('keeps the %s background command open after launch without reporting job status (parent: %s)', (name, parentCallId) => { + const command = ` node worker.mjs --trace=${'background-worker-'.repeat(24)}\n\tprintf "done"\n` + const argsRaw = shellArgs({ command, description: 'Wait', workdir: '/workspace/app', run_in_background: true }) const inspect = vi.fn() const parent = parentCallId === undefined ? {} : { parentCallId } - const view = render() - const row = view.container.querySelector('[data-sample="bash"]')! + const renderRow = (block: StartedToolCall | ToolResultNode) => { + const props = { ...rowProps(block), toolName: name, inspect } + return name === 'bash' ? : + } + const view = render(renderRow(running({ name, argsRaw, ...parent }))) + const row = view.getByRole('button') expect(view.getByText('Wait')).toBeTruthy() expect(row.getAttribute('aria-expanded')).toBe('false') - - fireEvent.keyDown(row, { key: 'Enter' }) - - expect(row.getAttribute('aria-expanded')).toBe('true') - expect(view.container.querySelector('[data-command-text]')?.textContent) - .toBe(JSON.stringify(args, null, 2)) - expect(view.container.querySelector('[data-command-text]')?.hasAttribute('tabindex')).toBe(false) - expect(view.queryByText('输出')).toBeNull() - expect(view.container.querySelector('[data-terminal]')).toBeNull() + if (name === 'bash') fireEvent.keyDown(row, { key: 'Enter' }) + else fireEvent.click(row) + const terminal = view.container.querySelector('[data-terminal]') + const firstCommand = view.container.querySelector('[data-command-text]') + expect(terminal).not.toBeNull() + expect(runStateOf(view.container)).toBe('ongoing') + expect([...view.container.querySelectorAll('[data-command-text]')].map(line => line.textContent)) + .toEqual(command.slice(0, -1).split('\n')) + expect(view.getByText('app')).toBeTruthy() + expect(view.queryByText('无输出')).toBeNull() + expect(view.queryByRole('button', { name: '复制' })).toBeNull() const acknowledgement = 'started background job job-1' - view.rerender() - + const result = settled({ call: { name, argsRaw }, ...parent, meta: { cwd: '/workspace/app' }, + content: [{ type: 'text', text: acknowledgement }] }) + view.rerender(renderRow(result)) expect(row.getAttribute('aria-expanded')).toBe('true') - expect(view.container.querySelector('[data-command-text]')?.textContent) - .toBe(JSON.stringify(args, null, 2)) - expect(view.getByText(acknowledgement)).toBeTruthy() - expect(view.container.querySelector('[data-terminal], [data-state="done"]')).toBeNull() + expect(view.container.querySelector('[data-terminal]')).toBe(terminal) + expect(view.container.querySelector('[data-command-text]')).toBe(firstCommand) + expect(view.container.querySelector('[data-terminal] [data-state], [data-running]')).toBeNull() + expect(view.queryByText('运行中')).toBeNull() + expect(view.queryByText('已完成')).toBeNull() + expect(view.queryByText('无输出')).toBeNull() + expect(view.queryByText(acknowledgement)).toBeNull() + expect(view.queryByRole('button', { name: '复制' })).toBeNull() + expect(result.call?.argsRaw).toBe(argsRaw) + expect(result.content).toEqual([{ type: 'text', text: acknowledgement }]) fireEvent.click(view.getByRole('button', { name: t('row.inspect') })) expect(inspect).toHaveBeenCalledOnce() fireEvent.click(row) expect(row.getAttribute('aria-expanded')).toBe('false') + if (name === 'bash') fireEvent.keyDown(row, { key: ' ' }) + else fireEvent.click(row) + expect(row.getAttribute('aria-expanded')).toBe('true') + expect(view.container.querySelector('[data-command-text]')?.textContent).toBe(command.split('\n')[0]) expect(view.queryByText(acknowledgement)).toBeNull() }) + it.each([ + ['bash', false], ['bash', true], ['pwsh', false], ['pwsh', true], + ] as const)('keeps %s launch failures on the original generic body (interrupted: %s)', (name, interrupted) => { + const argsRaw = shellArgs({ run_in_background: true }) + const renderRow = (block: StartedToolCall | ToolResultNode) => { + const props = { ...rowProps(block), toolName: name } + return name === 'bash' ? : + } + const view = render(renderRow(running({ name, argsRaw }))) + const row = view.getByRole('button') + fireEvent.click(row) + view.rerender(renderRow(settled({ call: { name, argsRaw }, isError: true, + ...interrupted ? { error: { name: 'Interrupted', code: 'interrupted' } } : {}, + content: [{ type: 'text', text: 'Launch did not finish' }] }))) + expect(row.getAttribute('aria-expanded')).toBe('true') + expect(view.container.querySelector('[data-terminal]')).toBeNull() + expect(view.getByText(/"run_in_background": true/)).toBeTruthy() + expect(view.getAllByText('Launch did not finish').length).toBeGreaterThan(0) + expect(view.container.querySelector(`[data-state="${interrupted ? 'stopped' : 'error'}"]`)).not.toBeNull() + }) + + it.each(['BashRow', 'GenericToolCard'] as const)('%s preserves authored command lines and copies only raw output', async (renderer) => { + const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') + const writeText = vi.fn().mockResolvedValue(undefined) + const lines = [` node worker.mjs --trace=${'command-token-'.repeat(24)} `, '', '\tprintf "done"'] + const command = `${lines.join('\n')}\n` + const output = ' first\tcolumn\n\nlast \n' + const props = rowProps(settled({ + call: { name: 'bash', argsRaw: shellArgs({ command }) }, + content: [{ type: 'text', text: `${output}\n[exit code: 0]` }], + })) + vi.useFakeTimers() + try { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + const view = render(renderer === 'BashRow' ? : ) + fireEvent.click(view.container.querySelector('[data-expandable]')!) + expect([...view.container.querySelectorAll('[data-command-text]')].map(line => line.textContent)).toEqual(lines) + expect(view.getByText(' first\tcolumn', RAW)).toBeTruthy() + expect(view.getByText('last ', RAW)).toBeTruthy() + await act(async () => { fireEvent.click(view.getByRole('button', { name: '复制' })) }) + expect(writeText).toHaveBeenCalledOnce() + expect(writeText).toHaveBeenCalledWith(output) + await act(async () => { await vi.runOnlyPendingTimersAsync() }) + } finally { + cleanup() + vi.clearAllTimers() + vi.useRealTimers() + if (clipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', clipboard) + } + }) + it('keeps malformed shell arguments collapsed even when background execution is requested', () => { const view = render( null, inspectCall: vi.fn(), forkAt: vi.fn(), loadImage: vi.fn(() => Promise.reject(new Error('not used'))), diff --git a/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts b/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts index 399c588713..33cf6d52be 100644 --- a/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts +++ b/packages/client/ui-tool/tests/tool-row-styles.client.spec.ts @@ -1,9 +1,4 @@ -/** - * The one-line contract of the ToolRow summary line as CSS text. jsdom has no - * layout, so the rendering specs (chat-tool-row.spec.tsx) can pin which spans - * exist but not whether a narrow row still fits on one line; these read the - * declarations the layout depends on. - */ +/** Consumer-local command wrapping and collapsed summary declarations; jsdom has no layout. */ import { readFileSync } from 'node:fs' import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' @@ -12,15 +7,31 @@ const css = readFileSync(fileURLToPath(new URL('../src/client/tool/components/To /** Declarations only: the sheet's prose names the properties it explains. */ const declarationText = css.replace(/\/\*[\s\S]*?\*\//g, ' ') -function declarations(selector: string): string[] { +function declarations(selector: string, sheet = declarationText): string[] { // Anchored at a rule boundary: an unanchored match would silently read a // compound rule that merely contains the selector (`.root:hover .summarySuffix`) // if one ever lands above the base rule. - const rule = new RegExp(`(?:^|\\})\\s*\\${selector}\\s*\\{([^{}]*)\\}`).exec(declarationText) - if (rule === null) throw new Error(`ToolRow.module.css has no \`${selector}\` rule`) + const rule = new RegExp(`(?:^|\\})\\s*\\${selector}\\s*\\{([^{}]*)\\}`).exec(sheet) + if (rule === null) throw new Error(`Stylesheet has no \`${selector}\` rule`) return (rule[1] ?? '').split(';').map(part => part.trim()).filter(Boolean) } +describe('expanded command wrapping', () => { + it.each([ + ['../src/client/tool/toolviews/bash-sample.module.css', '.terminal', '--dsl-terminal-command-whitespace'], + ['../src/client/tool/toolviews/bash-sample.module.css', '.commandInput', '--dsl-command-whitespace'], + ['../src/client/tool/components/ToolRow.module.css', '.terminalBody', '--dsl-terminal-command-whitespace'], + ] as const)('%s opts %s into command wrapping only', (path, selector, property) => { + const sheet = readFileSync(fileURLToPath(new URL(path, import.meta.url)), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, ' ') + expect(declarations(selector, sheet)).toContain(`${property}: pre-wrap`) + expect(sheet).not.toContain('--dsl-terminal-line-whitespace') + expect(declarations('.summary', sheet)).toEqual(expect.arrayContaining([ + 'white-space: nowrap', 'overflow: hidden', 'text-overflow: ellipsis', + ])) + }) +}) + describe('ToolRow.module.css summary line', () => { it.each([ ['ToolRow', '../src/client/tool/components/ToolRow.module.css'], diff --git a/packages/client/ui-tool/tsdown.config.ts b/packages/client/ui-tool/tsdown.config.ts index cd27a6e92b..7aa03cebc1 100644 --- a/packages/client/ui-tool/tsdown.config.ts +++ b/packages/client/ui-tool/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-tool', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-trajectory/README.i18n.yaml b/packages/client/ui-trajectory/README.i18n.yaml index 153776c82e..6db4c334a3 100644 --- a/packages/client/ui-trajectory/README.i18n.yaml +++ b/packages/client/ui-trajectory/README.i18n.yaml @@ -18,8 +18,8 @@ en: 4bd17d05b8385675 zh: 5174e27f754f2a03 /deepseek-ai-dsh-client-ui-trajectory/use-this-package/inspecting-records: - en: e4ba2d9cab2fb258 - zh: 7db041270420b2ba + en: 130d568589ae108e + zh: 2a52a19499e9c0a7 /deepseek-ai-dsh-client-ui-trajectory/use-this-package/the-timing-overview: en: 0f4ee2189324ac06 zh: 12e76fed22c09bc1 diff --git a/packages/client/ui-trajectory/README.md b/packages/client/ui-trajectory/README.md index eaf559d464..6a9fa9698d 100644 --- a/packages/client/ui-trajectory/README.md +++ b/packages/client/ui-trajectory/README.md @@ -31,7 +31,7 @@ Open the Trajectory tab in the conversation's view ring to inspect agent activit Calls are identified by their recorded tool name. For `run_code`, the row shows the program description and the inspector opens numbered, highlighted source. The Code tab provides wrapping, a `{}` toggle for the original JSON arguments, and exact source copying, including trailing newlines. Copying the original arguments retains their recorded JSON whitespace. Each newly opened code view takes the last wrapping choice; changing it leaves other open views as they are. Output preserves the recorded text, using a tree for complete JSON objects or arrays. Highlighting uses only an unambiguous TypeScript or Python hint in the recorded tool schema; missing or conflicting hints leave plain source. -Selection, timeline navigation, folding, and search cover the React-visible window. Request numbers and cumulative usage cover the complete resident snapshot. Selecting a record opens a local inspector for token usage, duration, Input, Output, Timing, and durable images. Image URLs use the Conversation-owned per-session cache, so Chat and Trajectory share one authorized read per attachment. A user record shows both nonzero image and ordinary-file counts beside its text, including attachment-only records. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. +Selection, timeline navigation, folding, and search cover the React-visible window. Request numbers and cumulative usage cover the complete resident snapshot. Selecting a record opens a local inspector for token usage, duration, Input, Output, Timing, and durable images. Image URLs use the Conversation-owned per-session cache, so Chat and Trajectory share one authorized read per attachment. The Trajectory view declares `conversation.trajectory.images`; ledger children call this Slot through the framework `renderSlot` seat, passing image references, display options, and the authorized loader explicitly. Its official `MessageImages` entry calls the shared `conversation.images.content` Factory. A user record shows both nonzero image and ordinary-file counts beside its text, including attachment-only records. A standalone compaction request appears chronologically in its own `Between turns` section, while a numbered compaction remains inside its owning turn. Summary and Preview share one ordered attachment list after the message text, preserving repeated references. Each row shows a contained image thumbnail or file-type icon, the recorded filename (a localized numbered label for unnamed images), and recorded size, type, and image dimensions where available. Zero-byte files retain their size, and truncated filenames expose the full name in a tooltip. Images open the existing lightbox. Raw keeps content-block order and unrendered text, with images and files in initially collapsed disclosures containing their complete recorded fields. diff --git a/packages/client/ui-trajectory/README.zh.md b/packages/client/ui-trajectory/README.zh.md index 2cfc3d7ca3..c37632a926 100644 --- a/packages/client/ui-trajectory/README.zh.md +++ b/packages/client/ui-trajectory/README.zh.md @@ -31,7 +31,7 @@ Trajectory 标签页让你以按轮次组织的事件记录表和交互式时间 调用按已记录的工具名识别。对于 `run_code`,记录行展示程序说明,检查器显示带行号和语法高亮的源码。“代码”页提供换行、查看原始 JSON 参数的 `{}` 切换按钮,以及保留末尾换行的源码原样复制。复制原始参数时保留记录中 JSON 的空白。每个新打开的代码视图采用上次选择的换行状态;切换时,其他已打开视图保持原状。输出保留记录中的文本,完整 JSON 对象或数组使用树形展示。高亮只采用已记录工具 Schema 中明确且无冲突的 TypeScript 或 Python 提示;提示缺失或冲突时显示纯文本源码。 -选择、时间线导航、折叠与搜索只覆盖 React 可见窗口。请求编号与累计用量覆盖完整的驻留快照。选择记录会打开局部检查器,查看 token 用量、耗时、输入、输出、计时与持久保留的图片。图片 URL 使用 Conversation 拥有的逐会话缓存,因此 Chat 与 Trajectory 对每个附件共享一次已授权读取。用户记录会在文本旁同时显示非零的图片与普通文件数量,仅含附件的记录也显示这些数量。独立运行的压缩请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。 +选择、时间线导航、折叠与搜索只覆盖 React 可见窗口。请求编号与累计用量覆盖完整的驻留快照。选择记录会打开局部检查器,查看 token 用量、耗时、输入、输出、计时与持久保留的图片。图片 URL 使用 Conversation 拥有的逐会话缓存,因此 Chat 与 Trajectory 对每个附件共享一次已授权读取。Trajectory 视图声明 `conversation.trajectory.images`;账本子组件通过框架 `renderSlot` 席位调用该 Slot,显式传入图片引用、显示参数及授权 loader。官方 `MessageImages` 条目调用共享的 `conversation.images.content` Factory。用户记录会在文本旁同时显示非零的图片与普通文件数量,仅含附件的记录也显示这些数量。独立运行的压缩请求会按时间顺序显示在自己的 `Between turns` 区段中,而带编号的压缩仍位于其所属轮次内。 概述与预览共用正文之后的有序附件列表,保留重复引用。每行展示完整缩放的图片缩略图或文件类型图标、已记录的文件名(未命名图片使用本地化的编号名称),以及可用的已记录大小、类型和图片尺寸。零字节文件保留大小显示,截断的文件名通过提示显示完整名称。图片打开现有灯箱。原始内容保留内容块顺序和未渲染文本,图片与文件使用默认折叠的展开项,包含完整的已记录字段。 diff --git a/packages/client/ui-trajectory/locale/en.json b/packages/client/ui-trajectory/locale/en.json new file mode 100644 index 0000000000..f1f5eb2fb6 --- /dev/null +++ b/packages/client/ui-trajectory/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-trajectory" + } +} diff --git a/packages/client/ui-trajectory/locale/zh.json b/packages/client/ui-trajectory/locale/zh.json new file mode 100644 index 0000000000..3591dbed97 --- /dev/null +++ b/packages/client/ui-trajectory/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "运行轨迹", + "description": "按轮次查看消息、工具调用、耗时和 Token 等运行记录。" + } +} diff --git a/packages/client/ui-trajectory/package.json b/packages/client/ui-trajectory/package.json index d847bebe73..d41c148836 100644 --- a/packages/client/ui-trajectory/package.json +++ b/packages/client/ui-trajectory/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,8 +56,6 @@ "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-compaction": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0", @@ -72,6 +71,7 @@ "diff": "^9.0.0" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx index 33c8ee1b91..4cf15a0847 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryTable.tsx @@ -23,9 +23,10 @@ import { writeClipboard, } from '@deepseek-ai/dsh-client-ui-primitives' import type { JsonTreeLabels, JsonTreeProps, MarkdownLabels } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { structuredPatch } from 'diff' import type { - AssistantRequestConfig, ConversationPromptSnapshot, RenderMessageImages, + AssistantRequestConfig, ConversationPromptSnapshot, MessageImageLoader, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { AssistantMetricDetail, TrajectoryCellKind, TrajectoryCellProps, TrajectorySourceBlock, @@ -392,7 +393,9 @@ export interface TrajectoryTableProps { /** Trajectory locale seat. */ t: TrajectoryTranslate /** Slot-backed durable image renderer shared with the Chat gallery. */ - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + /** Session-bound loader for durable message image attachments. */ + loadImage: MessageImageLoader /** Session-global request numbers for the request groups visible in this context. */ requestNumbers?: readonly TrajectoryRequestNumber[] /** Grouped records in display order. */ @@ -1238,12 +1241,14 @@ function recordAttachments( function RecordAttachments({ blocks, preview, - renderImages, + renderSlot, + loadImage, t, }: { blocks: readonly TrajectorySourceBlock[] | undefined preview: boolean - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader t: TrajectoryTranslate }) { const attachments = recordAttachments(blocks, t) @@ -1256,10 +1261,11 @@ function RecordAttachments({ {attachments.map(({ block, index, name, metadata }) => (
  • {block.attachment !== undefined - ? renderImages({ + ? renderSlot('conversation.trajectory.images', { images: [{ attachment: block.attachment, label: name }], align: 'start', thumbnail: true, + loadImage, }) : }
    @@ -1474,14 +1480,16 @@ function ToolOutputBlocks({ error, errorDetail, preview, - renderImages, + renderSlot, + loadImage, }: { blocks: readonly TrajectorySourceBlock[] error: boolean /** Failure name and code preserved beside image-only error content. */ errorDetail?: string | undefined preview: boolean - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader }) { return (
    - {renderImages({ images: [{ attachment: block.attachment }], align: 'start' })} + {renderSlot('conversation.trajectory.images', { images: [{ attachment: block.attachment }], align: 'start', loadImage })}
    ) : block.content !== '' @@ -1514,7 +1522,8 @@ function MarkdownRecordContent({ thinkingExpanded, onThinkingExpandedChange, onOpenCall, - renderImages, + renderSlot, + loadImage, t, }: { record: TableRecord @@ -1523,7 +1532,8 @@ function MarkdownRecordContent({ thinkingExpanded: boolean onThinkingExpandedChange: (expanded: boolean) => void onOpenCall: (callId: string) => void - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader t: TrajectoryTranslate }) { if (record.cell.sourceBlocks?.length && record.cell.sourceBlocks.every(block => @@ -1593,7 +1603,8 @@ function MarkdownRecordContent({
    @@ -1623,7 +1634,8 @@ function MarkdownRecordContent({ t={t} /> )} - +
) } @@ -1692,14 +1704,16 @@ function RecordPayload({ record, direction, preview = false, - renderImages, + renderSlot, + loadImage, stringWrapping, t, }: { record: TableRecord direction: 'input' | 'output' preview?: boolean - renderImages: RenderMessageImages + renderSlot: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] + loadImage: MessageImageLoader stringWrapping: JsonTreeProps['stringWrapping'] t: TrajectoryTranslate }) { @@ -1740,7 +1754,8 @@ function RecordPayload({ error={error} errorDetail={error ? value : undefined} preview={preview} - renderImages={renderImages} + renderSlot={renderSlot} + loadImage={loadImage} /> ) } @@ -2070,7 +2085,8 @@ function OverviewSection({ export function TrajectoryTable({ t, stringWrapping, - renderImages, + renderSlot, + loadImage, requestNumbers: sessionRequestNumbers, turns, streamingCells = [], @@ -3294,7 +3310,8 @@ export function TrajectoryTable({ > { activateTab('rendered') }}> {selected.cell.inputDetail && ( { activateTab('input') }}> - + )} {selected.cell.outputDetail && ( { activateTab('output') }}> - + )} { activateTab('schema') }}> @@ -3470,7 +3488,8 @@ export function TrajectoryTable({ {!promptSelected && selected !== undefined && activeTab === 'rendered' && ( + ? : )} {!promptSelected && selected !== undefined && activeTab === 'output' && ( selectedProgram === undefined - ? + ? : )} {!promptSelected && selected !== undefined && activeTab === 'schema' && ( diff --git a/packages/client/ui-trajectory/src/client/TrajectoryView.tsx b/packages/client/ui-trajectory/src/client/TrajectoryView.tsx index 0a4b50c9d4..e36386e819 100644 --- a/packages/client/ui-trajectory/src/client/TrajectoryView.tsx +++ b/packages/client/ui-trajectory/src/client/TrajectoryView.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { - AssistantBlock, AssistantMessageNode, ConvViewProps, MessageImageLoader, RenderMessageImages, + AssistantBlock, AssistantMessageNode, ConvViewProps, MessageImageLoader, ToolCallBlock, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { InjectFace, PropsLocale, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' @@ -133,14 +133,10 @@ export function TrajectoryView({ useSession, useTrajectory, useDuration, loadOlder, loadImage, setActualDuration, viewRequest, completeViewRequest, renderSlot, t, jsonStringWrapping, }: ConvViewProps - & PropsRenderSlots<'conversation.trajectory.images'> + & Pick, 'renderSlot'> & InjectFace & PropsLocale<'trajectory'>) { const [collapsedTurns, setCollapsedTurns] = useState>(EMPTY_TURN_IDS) - const renderImages = useCallback( - owner => renderSlot('conversation.trajectory.images', { ...owner, loadImage }), - [loadImage, renderSlot], - ) const [collapsedAssistants, setCollapsedAssistants] = useState>(EMPTY_RECORD_IDS) const [timelineSelection, setTimelineSelection] = useState(null) @@ -554,7 +550,8 @@ export function TrajectoryView({ ...jsonStringWrapping, label: t('record.wrapLines'), }} - renderImages={renderImages} + renderSlot={renderSlot} + loadImage={loadImage} requestNumbers={requestNumbers} turns={timelineTurns} streamingCells={streamingCells} diff --git a/packages/client/ui-trajectory/src/client/index.ts b/packages/client/ui-trajectory/src/client/index.ts index 935a43ff2c..0b438d1aae 100644 --- a/packages/client/ui-trajectory/src/client/index.ts +++ b/packages/client/ui-trajectory/src/client/index.ts @@ -82,9 +82,7 @@ export function apply(ctx: Context): void { order: 10, locale: NS, label: () => t('view.trajectory'), - children: { - 'conversation.trajectory.images': { kind: 'single', scope: 'session' }, - }, + children: { 'conversation.trajectory.images': { kind: 'single', scope: 'session' } }, inject: (sessionId: SessionId): TrajectoryViewInjected => { const session = ctx.sessions.binding(sessionId)?.session if (session === undefined) { diff --git a/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx b/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx index fab29e0637..ab9bd12d41 100644 --- a/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/code-inspector.client.spec.tsx @@ -26,7 +26,7 @@ function Harness({ cell = CELL, getDefault = () => false, setDefault = () => {} }) { return null} t={t} + renderSlot={() => null} loadImage={async () => 'blob:unused'} t={t} stringWrapping={{ label: 'Wrap lines', getDefault, setDefault }} collapsedTurns={new Set()} onToggleTurn={() => {}} collapsedAssistants={new Set()} onToggleAssistant={() => {}} diff --git a/packages/client/ui-trajectory/tests/table.client.spec.tsx b/packages/client/ui-trajectory/tests/table.client.spec.tsx index 1401a5a67c..188b96bb5f 100644 --- a/packages/client/ui-trajectory/tests/table.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/table.client.spec.tsx @@ -1,17 +1,23 @@ // @vitest-environment jsdom /** Trajectory ledger selection, details, status, and fold behavior. */ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { AttachmentId } from '@deepseek-ai/dsh-attachment' -import type { ComponentProps } from 'react' -import type { RenderMessageImages } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { useState, type ComponentProps, type ReactNode } from 'react' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import type { MessageImageLoader, MessageImagesOwnerProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { TrajectoryTable as LocalizedTrajectoryTable } from '../src/client/TrajectoryTable.tsx' import { deriveTrajectoryLayout, type TrajectoryTurnModel } from '../src/client/layout.ts' import { trajectoryRecordId } from '../src/client/trajectory-record.ts' import { t, tZh } from './locale.client.ts' -const renderImagesStub: RenderMessageImages = ({ images }) => ( +const loadImage: MessageImageLoader = async () => 'blob:trajectory' +const renderNoImages: PropsRenderSlots<'conversation.trajectory.images'>['renderSlot'] = () => null + +const RecordImages = ({ images }: MessageImagesOwnerProps) => (
{images.map((image, index) => ( (
) +async function imageSlotFixture() { + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + await runtime.sessions.add({ id: 'trajectory-images' }) + const session = runtime.sessions.retainFor(runtime.ctx, SessionId('trajectory-images')) + type Seats = PropsRenderSlots<'conversation.trajectory.images'> + const captured: { seats?: Seats; setContent?: (content: ReactNode) => void } = {} + await runtime.root.declare({ 'conversation.trajectory.images': { kind: 'single', scope: 'session' } }, function TestRoot(props) { + const [content, setContent] = useState(null) + captured.seats = props + captured.setContent = setContent + const { SessionProvider } = props + return {content} + }) + runtime.slots.register({ name: 'conversation.trajectory.images' }, RecordImages) + const view = runtime.renderRoot() + const { seats, setContent } = captured + if (seats === undefined || setContent === undefined) throw new Error('trajectory image fixture root did not render') + return { + renderSlot: seats.renderSlot, + render: (content: ReactNode) => { + act(() => { setContent(content) }) + return view + }, + } +} + +type TableProps = ComponentProps + function TrajectoryTable( - props: Omit, 't' | 'renderImages'> - & { renderImages?: RenderMessageImages }, + props: Omit + & Partial>, ) { const inferred: Array[number] & { firstIndex: number }> = [] for (const turn of props.turns) { @@ -58,7 +93,7 @@ function TrajectoryTable( .map(({ firstIndex: _firstIndex, ...request }, index) => ({ ...request, number: index + 1 })) return ( { render( ()} onToggleTurn={() => {}} @@ -963,7 +998,7 @@ describe('TrajectoryTable', () => { }] const table = (status: 'running' | 'complete' | 'error') => ( { it.each([['English', t, 'Attachments', 'Image 1', 'Summary', 'Preview', 'Raw'], ['Chinese', tZh, '附件', '图片 1', '概述', '预览', '原始内容']] as const)( 'keeps mixed attachments ordered and raw fields complete in %s', - (_locale, translate, listLabel, imageLabel, summaryTab, previewTab, rawTab) => { + async (_locale, translate, listLabel, imageLabel, summaryTab, previewTab, rawTab) => { const attachment = { attachmentId: AttachmentId(`sha256:${'a'.repeat(64)}`), mediaType: 'image/png' as const, @@ -1132,8 +1167,10 @@ describe('TrajectoryTable', () => { partial: null, runningCalls: [], }, translate) - const renderImages = vi.fn(renderImagesStub) - const view = render() + const { render, renderSlot: slotRenderer } = await imageSlotFixture() + const renderSlot = vi.fn((name: 'conversation.trajectory.images', owner: object) => slotRenderer(name, owner as MessageImagesOwnerProps)) + const view = render() fireEvent.click(view.container.querySelector('[data-trajectory-row-key]')!) for (const tab of [summaryTab, previewTab]) { fireEvent.click(screen.getByRole('tab', { name: tab })) @@ -1142,7 +1179,9 @@ describe('TrajectoryTable', () => { expect(names).toEqual([imageLabel, file.name, imageLabel.replace('1', '2')]) expect(within(list).getByText('TXT · 0B')).toBeTruthy() expect(within(list).getAllByText('image/png · 68B · 40 × 800')).toHaveLength(2) - expect(renderImages).toHaveBeenCalledWith({ images: [{ attachment, label: imageLabel }], align: 'start', thumbnail: true }) + expect(renderSlot).toHaveBeenCalledWith('conversation.trajectory.images', { + images: [{ attachment, label: imageLabel }], align: 'start', thumbnail: true, loadImage, + }) } fireEvent.click(screen.getByRole('tab', { name: rawTab })) expect(screen.queryByTestId('record-images')).toBeNull() @@ -1158,15 +1197,16 @@ describe('TrajectoryTable', () => { }, ) - it('renders a tool-result image through the shared gallery in the Result tab', () => { + it('renders a tool-result image through the shared gallery in the Result tab', async () => { + const { render, renderSlot } = await imageSlotFixture() const attachment = { - attachmentId: `sha256:${'b'.repeat(64)}`, + attachmentId: AttachmentId(`sha256:${'b'.repeat(64)}`), mediaType: 'image/png', bytes: 68, width: 320, height: 640, name: 'capture.png', - } as unknown as NonNullable< + } satisfies NonNullable< NonNullable[number]['attachment'] > const turns: readonly TrajectoryTurnModel[] = [{ @@ -1184,7 +1224,7 @@ describe('TrajectoryTable', () => { }], }] - render() + render() fireEvent.click(screen.getByRole('row', { name: /TOOL/ })) fireEvent.click(screen.getByRole('tab', { name: 'Result' })) @@ -1194,15 +1234,16 @@ describe('TrajectoryTable', () => { .toBe(String(attachment.attachmentId)) }) - it('keeps the failure name beside an image-only error result', () => { + it('keeps the failure name beside an image-only error result', async () => { + const { render, renderSlot } = await imageSlotFixture() const attachment = { - attachmentId: `sha256:${'c'.repeat(64)}`, + attachmentId: AttachmentId(`sha256:${'c'.repeat(64)}`), mediaType: 'image/png', bytes: 68, width: 320, height: 320, name: 'failed.png', - } as unknown as NonNullable< + } satisfies NonNullable< NonNullable[number]['attachment'] > const turns: readonly TrajectoryTurnModel[] = [{ @@ -1221,7 +1262,7 @@ describe('TrajectoryTable', () => { }], }] - render() + render() fireEvent.click(screen.getByRole('row', { name: /TOOL/ })) fireEvent.click(screen.getByRole('tab', { name: 'Result' })) diff --git a/packages/client/ui-trajectory/tests/views.client.spec.tsx b/packages/client/ui-trajectory/tests/views.client.spec.tsx index e9557677df..2f5dd4a45e 100644 --- a/packages/client/ui-trajectory/tests/views.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.client.spec.tsx @@ -7,7 +7,7 @@ * event ledger with its timing overview, and fiber disposal removes the tab. * Timeline projection and inclusive focus edge cases ride along. */ -import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' +import type { GlobalStandardProps, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react' import { createElement, type ComponentProps, type FC, type ReactNode } from 'react' @@ -245,7 +245,6 @@ function standaloneProps( completeViewRequest: () => {}, // Image seats the outlet would bake: standalone renders omit the gallery. renderSlot: () => null, - SessionProvider: ({ children }) => <>{children}, loadImage: () => Promise.reject(new Error('standalone views load no images')), // The locale seat the outlet would inject for the declared namespace. t: tZh, @@ -387,13 +386,16 @@ function mount(fixture: Awaited>) { const trajectory = injected as TrajectoryViewInjected return { loadOlder: trajectory.loadOlder, + loadImage: trajectory.loadImage, setActualDuration: trajectory.setActualDuration, useDuration: bindSnapshotSelector(trajectory.hooks.duration), t: tZh, } })() : injected - const viewProps: ConvViewProps = { ...owner, ...standardProps } + const viewProps: ConvViewProps & Pick, 'renderSlot'> = { + ...owner, ...standardProps, renderSlot: () => null, + } return ( null, inspectCall: vi.fn(), forkAt: vi.fn(), loadImage: vi.fn(() => Promise.reject(new Error('not used'))), diff --git a/packages/client/ui-user-questions/tsdown.config.ts b/packages/client/ui-user-questions/tsdown.config.ts index a60da00031..7aa03cebc1 100644 --- a/packages/client/ui-user-questions/tsdown.config.ts +++ b/packages/client/ui-user-questions/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-user-questions', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-workflow-run/locale/en.json b/packages/client/ui-workflow-run/locale/en.json new file mode 100644 index 0000000000..ed487bf62e --- /dev/null +++ b/packages/client/ui-workflow-run/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-workflow-run" + } +} diff --git a/packages/client/ui-workflow-run/locale/zh.json b/packages/client/ui-workflow-run/locale/zh.json new file mode 100644 index 0000000000..319be876a6 --- /dev/null +++ b/packages/client/ui-workflow-run/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作流运行展示", + "description": "在会话中展示工作流运行记录及其成员详情。" + } +} diff --git a/packages/client/ui-workflow-run/package.json b/packages/client/ui-workflow-run/package.json index a3c5a392ef..a1f452e556 100644 --- a/packages/client/ui-workflow-run/package.json +++ b/packages/client/ui-workflow-run/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -44,6 +45,7 @@ "watch": "tsdown --watch" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" @@ -67,7 +69,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-tool-workflow": "workspace:*", "@deepseek-ai/dsh-workflow": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0" } diff --git a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx index 18d5ff95b8..3fa00ccc54 100644 --- a/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx +++ b/packages/client/ui-workflow-run/tests/workflow-run.client.spec.tsx @@ -363,12 +363,10 @@ function panelProps(data: WorkflowRunChatData, sessions = listState(), openSessi useTurnData: () => undefined, useDisclosure: () => { throw new Error('unused') }, useGroupAction: () => { throw new Error('unused') }, - openSkill: vi.fn(), openFile: () => {}, inspectCall: () => {}, forkAt: () => {}, loadImage: () => Promise.reject(new Error('not used')), - renderMessageImages: () => null, fileMentions: () => undefined, openSession, t: makeTranslate(zh), diff --git a/packages/client/ui-workflow-run/tsdown.config.ts b/packages/client/ui-workflow-run/tsdown.config.ts index 87d4cd34c1..7aa03cebc1 100644 --- a/packages/client/ui-workflow-run/tsdown.config.ts +++ b/packages/client/ui-workflow-run/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-workflow-run', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index cf3f7896bd..ed87dba3eb 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -27,14 +27,14 @@ en: 9eab3bfbaf98c987 zh: 54e7e141dae5c9e8 /deepseek-ai-dsh-client-ui-workspace/use-this-package/managing-sessions: - en: cafc87e8e0ac4058 - zh: 4c35bc5bfa24ba6c + en: e96b714aeb6dcd03 + zh: 75b63aa2cafbb57a /deepseek-ai-dsh-client-ui-workspace/use-this-package/pending-interactions: en: 9fb88260380bf093 zh: 3bace2b96ecd4a82 /deepseek-ai-dsh-client-ui-workspace/use-this-package/active-schedule-markers: - en: 04956ad6ba31cc86 - zh: 0e5fb72cfa932d25 + en: 68423607516bb58e + zh: 550e5c55cc6a25db /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation: en: 721d5a49fe231191 zh: 3ef1dd720219e00e @@ -42,8 +42,8 @@ en: 868904dbfb5713f8 zh: 225906bfef7398bf /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions: - en: a3b80d0e844d2929 - zh: 85fe5dfb2968b491 + en: 24d196702ca9a5a0 + zh: 351b4896a0217ac1 /deepseek-ai-dsh-client-ui-workspace/understand-the-implementation/session-row-actions/packaged-client-plugin: en: 36934671b80b11ae zh: 8e0aea6162e35e77 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index e1dbed75c4..116cebbbd7 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -51,13 +51,15 @@ Collapsed search is one header action beside the view and add actions: activatin ### Managing sessions -The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action reads ordinary cold history normally. When the Host reports that source migration is required, an app-wide Toast offers to open that Session; the action only navigates and does not retry fork. A successful fork uses the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, and Archive are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it. +The final built-in item in a Session row's "..." menu is Copy Session ID. It closes the menu and copies the complete ID directly, without opening a dialog. Clipboard success or failure appears in the global toast; a failed copy can be retried from the menu. Copying does not retain the Session, load its history, or call the Host. + +The Session row's Rename action opens a dialog prefilled with the row's display title; confirming an unchanged title is deliberately allowed — it pins the current automatic title against regeneration. Double-clicking a title also opens Rename; for an unarchived Session, the preceding clicks open its conversation. Rename uses a temporary `workspaceOperation` reference and awaits its initial history opening. The row's Fork action reads ordinary cold history normally. When the Host reports that source migration is required, an app-wide Toast offers to open that Session; the action only navigates and does not retry fork. A successful fork uses the source's last completed turn and increments the inherited persisted title through Session Controller without retaining the child, opening its history, or changing selection. Workspace Delete opens a confirmation that states the retention boundary; success removes the group while its Sessions remain under Ungrouped. Pin, Rename, Fork, Archive, and Copy Session ID are themselves entries of the `sidebar.workspaces.session.menu.item` list (pin and archive also of `sidebar.workspaces.session.row.action`), so a client plugin's action takes whatever position its `order` gives it. Archive commits without a confirmation dialog for a quiet Session and retains the Session's account position. A Session with running work is the one case that asks first: the Host refuses the plain archive and names that work, and the sidebar opens a stop-and-archive dialog listing it by family — the turn in progress, running subagents, background jobs, scheduled reminders, each with its labels — with the restore path stated; confirming asks the Host to stop the work the way the stop button does and archives once the archive set is durable, while the stops settle in the background, and cancelling leaves the Session running and visible. View options control visibility through one explicit three-way choice: Hide archived (the default) hides archived Sessions, All conversations (show archived) includes them, and Archived only hides ordinary Sessions and drops Workspaces without an archived Session; in tree grouping, children of a dropped Workspace nest under the nearest shown ancestor. Visible archived rows are grayed and carry an accessible explanation that they cannot be opened until restored; Rename, Fork, and Unarchive remain available. A successful archive shows a notice with an undo action and — while archived rows are hidden — a "filter archived sessions" action that switches the filter to All conversations (show archived); a stop-and-archive shows the same notice under its own wording, and undo restores the Session without resuming the stopped work. Unarchive removes the archive mark without restoring a pin or changing the saved position. An empty list shows a centered glyph-over-text placeholder; the Archived-only view names its own emptiness (No archived sessions yet) and adds a View other sessions text action that switches the filter back to Hide archived. Session update times use the tertiary label color, including on archived rows. A Session title wider than its row is clipped with an ellipsis at rest. Hovering the row scrolls the title to its far edge — the incremented title of a fork, for example — and reveals it without the ellipsis; leaving the row returns the title to its start. -The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. Rename requires a nonblank main Conversation with no modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. +The keyboard reference exposes New Session, Search sessions, Add workspace, Rename session, Fork session, and Archive session. Desktop defaults use the platform's primary modifier, with Mod+K for search; Windows and macOS Web use the [shortcut service’s platform defaults](../shortcuts/README.md); Linux Web leaves these commands unbound until configured. Button tooltips and Session row menus display the effective bindings. Clicking a menu item targets that row; pressing its shortcut targets the main Session. Desktop and Windows/macOS Web rename use Mod+Alt+G, leaving Mod+Shift+R to browser reload. Rename requires a nonblank main Conversation with no modal obscuring it; a retained Session behind another main panel is unavailable. Other Windows and macOS Desktop bindings also execute from terminal input and modal dialogs; other environments follow the command's region and modal restrictions. Search and rename requests belong to this package; input drafts remain in the browser. The directory picker rejects another open while selection or Workspace adoption is pending. Fork captures the retained main-view Session, for which navigation has requested history opening, and keeps automatic migration. It uses the row action's Host operation to select its last completed turn, without loading older Client history. Missing or blank Sessions are unavailable; the Host rejects a source with no completed turn. A rejected shortcut fork preserves the current selection, displays a localized notification, and can be retried; unexpected failures also retain diagnostic logging. Its notification shares the frame-wide Workspace notice channel: only the latest notice remains visible, and removing the browsing region does not dismiss it. ### Pending interactions @@ -69,11 +71,11 @@ Grouped and flat Session rows show a clock mark when the Session has active sche ----- -`ctx.uiWorkspace.openSession(target)` synchronously replaces the owned `mainView` reference and returns the main area to Conversation without waiting for `reference.ready`, so history loading renders inside the selected Session view. The target may be a known Session id or a durable direct-parent subagent address; an explicit address does not require a preloaded parent catalog. `openWorkspace(id, beforeOpen?)` opens a Workspace blank only if no later navigation has superseded the request; an explicit New Session creates a fresh Session. `forkSession(id)` creates the child without navigating or superseding a pending navigation. The optional synchronous preparation callback runs after the target is retained and only for a current Workspace request, so superseded requests do not move composer drafts. Navigation or owner disposal suppresses the late UI commit, not the underlying Session creation. Startup restoration retains its main reference without changing the selected panel or cancelling a later navigation. Archiving the main Session releases its reference and clears the main selection. Selection failure leaves a global panel visible. Session rows read `usePanelInfo` to suppress their selected appearance while a global panel is active; search and directory-picker focus alone do not leave that panel. +`ctx.uiWorkspace.openSession(target)` synchronously replaces the owned `mainView` reference and returns the main area to Conversation without waiting for `reference.ready`, so history loading renders inside the selected Session view. The target may be a known Session id or a durable direct-parent subagent address; an explicit address does not require a preloaded parent catalog. `openWorkspace(id, beforeOpen?, options?)` opens a Workspace blank only if no later navigation has superseded the request; an explicit New Session creates a fresh Session. `forkSession(id)` creates the child without navigating or superseding a pending navigation. The optional synchronous preparation callback runs after the target is retained and only for a current Workspace request, so superseded requests do not move composer drafts. Navigation or owner disposal suppresses the late UI commit, not the underlying Session creation. Startup restoration retains its main reference without changing the selected panel or cancelling a later navigation. Archiving the main Session releases its reference and clears the main selection. Selection failure leaves a global panel visible. Session rows read `usePanelInfo` to suppress their selected appearance while a global panel is active; search and directory-picker focus alone do not leave that panel. -Navigation and startup restoration obtain the selected Session's projections from its `follow`; neither issues a separate projection refresh for that Session or its parent. +Navigation and startup restoration obtain the selected Session's projections from its `follow`; neither issues a separate projection refresh for that Session or its parent, except that restoring a saved blank first reloads that Session's projections, because listed values are cached hints that can lag its log after an unclean Host exit. -Workspace reopening and explicit draft preparation try to acquire the first eligible blank in catalog order; startup restoration tries the saved blank. If that writer is held, navigation creates a new Session without trying other blanks. Other acquisition failures abort the request: an explicit New Session or hero Workspace pick shows the failure as a transient notice quoting the Host's code and message (for example a preset that fails to mount) or, for a failure that is not a Host refusal, that failure's own message; a request a later navigation or owner disposal superseded raises no notice, and startup restoration reports only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. +Workspace reopening and explicit draft preparation name the first eligible blank in catalog order when they ask the Host for a Session; startup restoration names the saved blank. The Host reuses the named blank under the requested preset, or under its default when the request names none, and creates another Session when the blank has started, left the Workspace, or is held by another writer; navigation opens the returned Session without trying other blanks. `startSession` with draft options, `openWorkspace`, and `connectWorkspace` accept `{ agentPreset }` for a flow that knows its preset before it starts, such as the creator entry; a connection joins the latest in-flight connection to its Workspace only when both request the same preset, so the latest request always reaches the Host. Startup restoration passes the preset the saved blank's log recorded, so the draft keeps that preset; when the Host reports the preset as missing (`agent-preset/not-found`) or failing to activate (`agent-preset/invalid`), restoration asks again without a preset and the draft continues under the Host default. Other failures abort the request: an explicit New Session or hero Workspace pick shows the failure as a transient notice quoting the Host's code and message (for example a preset that fails to mount) or, for a failure that is not a Host refusal, that failure's own message; a request a later navigation or owner disposal superseded raises no notice, and startup restoration reports only to the console. Released blanks retain their slash-command state when reused. Later navigation cancels a pending startup selection. Once both Workspace and Session startup baselines are ready, an empty installation calls `workspaces.initializeDefault` and creates or reuses its blank Session. The composer becomes editable when that Session is selected; no message is submitted automatically. Later navigation or owner disposal prevents startup from selecting its result. Ineligible first use leaves the folder picker available without an error. Default Workspace creation failure shows a transient notice directing the user to Choose workspace, and is not retried until the next startup. Session creation failures use the ordinary restoration error handling. The registered Workspace remains available if Session creation or later submission fails. @@ -97,10 +99,12 @@ Each registration declares a **directory-flow child hole** (`single` kind: `conv ### Session row actions -The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), and `archive` (menu 400, button 100) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action. +The Session row's "..." menu and its hover buttons are two `list` slots declared by the WorkspaceBrowser entry: `sidebar.workspaces.session.menu.item` and `sidebar.workspaces.session.row.action`. Every menu row and every hover button is an entry, this package's own actions included: `apply` registers `pin` (menu 100, button 200), `rename` (200), `fork` (300), `archive` (menu 400, button 100), and `session-id` (450) the way a client plugin registers its actions, so a plugin action lands wherever its `order` says, and reusing a shipped id at another `priority` shadows that action. An entry receives only the row identity (`sessionId`, `displayTitle`) and owns everything else. It reads the Host state it cares about through its own injected hooks (the pin and archive sets, as Sets derived once per Workspace snapshot), decides its own visibility (pin renders nothing on an archived row, because the Host keeps the two sets exclusive), carries its whole behavior in its registration's `inject` face (a pin also fronts the Session in its saved orders; an archive raises the notice), and raises its own surfaces: the rename dialog, the stop-and-archive dialog, and the row-action notice are this package's `shell.overlay` entries, fed by the requests the actions inject. A menu entry renders one `role="menuitem"` button (this package's rows use `MenuItemButton` from ui-primitives, which adds the host styling and `separatorBefore` for a group start; the hairline comes and goes with the row) and dismisses the menu through the slot-level `useMenuOpenState` hook, the menu's own open state bound from the row's render occurrence; a hover button entry renders one icon button, and the strip keeps its clicks from opening the row. The browser passes no action callbacks to its rows; its remaining verbs are the search results' restore button and the title double-click, which raises the same rename request. +The existing notice overlay dispatches `workspace.toast` by notice kind. Keyed registrations inject localized display mappings and their own actions; only archive notices subscribe to the viewing filter. They render the package-local `workspace.toast.content` Factory, which reuses the Toast primitive once for all presentations. The existing notice state, display sequence, latest-notice replacement, and dismissal remain shared; locale or filter changes do not restart the same notice's timer. + #### Packaged client plugin Declare `ui-workspace`, `ui-slots`, `ui-renderer`, `client-locale`, and `ui-primitives` as browser/type development dependencies according to the Client dependency policy. The type-only `ui-workspace/client` import loads this package's `SlotMap` declaration; without it, an independently compiled plugin does not know the slot keys. Keep the Component at module scope and own visible copy in the contributing package's locale namespace. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index a1e1a0fd5a..7be85089f9 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -51,13 +51,15 @@ kind: "package-reference" ### 管理会话 -Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 正常读取普通冷历史。Host 报告源会话需要迁移时,应用级 Toast 提供打开该会话的操作;该操作仅导航,不重试 fork。成功的 fork 在源会话最后一个已完成轮次处创建分支,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。 +Session 行“...”菜单的最后一个内置项为“复制 Session ID”。点击后关闭菜单并直接复制完整 ID,不打开对话框。复制成功或失败通过全局提示反馈;失败时可从菜单重试。复制不会 retain 会话、加载历史或调用 Host。 + +Session 行内的 Rename 操作打开一个以该行显示标题预填的对话框;确认未修改的标题是有意允许的——这正是把当前自动标题钉住、不再被重新生成覆盖的手势。双击标题也会打开 Rename;对于未归档 Session,先发生的点击会打开其对话。Rename 使用临时 `workspaceOperation` reference,并等待首次历史打开。行内 Fork 正常读取普通冷历史。Host 报告源会话需要迁移时,应用级 Toast 提供打开该会话的操作;该操作仅导航,不重试 fork。成功的 fork 在源会话最后一个已完成轮次处创建分支,通过 Session Controller 递增继承的持久化标题,不 retain 子会话、不打开其历史,也不改变选择。Workspace 行内的 Delete 操作会打开确认框,说明保留边界;成功后该分组被移除,其 Session 则留在 Ungrouped 下。Pin、Rename、Fork、Archive 和复制 Session ID 本身就是 `sidebar.workspaces.session.menu.item` 列表的条目(pin 与 archive 同时也是 `sidebar.workspaces.session.row.action` 的条目),因此客户端插件的 action 由其 `order` 决定落在哪个位置。 对静止的 Session,Archive 不经确认对话框直接提交,并保留 Session 的记账位置。仍有工作在跑的 Session 是唯一会先询问的情形:Host 拒绝普通归档并列出这些工作,侧栏随即打开"停止并归档"对话框,按族列出——进行中的回合、运行中的子代理、后台任务、定时提醒,各带名称——并写明恢复路径;确认后请 Host 按停止按钮同样的方式停止这些工作,归档集合持久化后即完成归档,停止在后台收敛;取消则让 Session 继续运行并保持可见。视图选项以一组显式三选一控制显隐:隐藏已归档(默认项)隐藏已归档 Session,全部对话(显示已归档)将其纳入列表,仅显示已归档则隐藏普通 Session,并丢弃没有归档 Session 的 Workspace;树形分组下,被丢弃 Workspace 的子级挂到最近一个仍显示的祖先下。可见的归档行置灰,并提供无障碍说明,告知取消归档后才能打开;Rename、Fork 与取消归档仍然可用。归档成功后的提示提供"撤销"动作,并在归档行仍被隐藏时附带"筛选已归档会话"动作,后者直接把筛选切到全部对话(显示已归档);停止并归档显示同样的提示但措辞不同,撤销只恢复 Session,不会让被停止的工作继续。取消归档移除归档标记,但不恢复置顶,也不改变保存的位置。列表为空时显示居中的"图标在上、文字在下"占位;仅显示已归档视图用自己的文案(暂无已归档会话),并附"查看其他会话"文字按钮,点击把筛选切回隐藏已归档。 会话更新时间使用 tertiary 文本色,包括已归档行。标题宽于所在行时,静止状态以省略号裁切。把指针停在行上,标题会滚动到远端——例如 fork 递增后的标题——并在揭示时不显示省略号;指针离开后标题回到开头。 -快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。重命名要求主区域正在显示非空会话,且没有模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。 +快捷键速查提供新建会话、搜索会话、添加工作区、重命名会话、分叉会话和归档会话。桌面默认使用平台的主修饰键,搜索为 Mod+K;Windows 和 macOS Web 使用[快捷键服务的平台默认值](../shortcuts/README.zh.md);Linux Web 在用户配置前不绑定这些命令。按钮提示和会话行菜单显示当前有效绑定。点击菜单项操作该行,按快捷键操作主会话。Desktop 和 Windows/macOS Web 的重命名均使用 Mod+Alt+G,将 Mod+Shift+R 留给浏览器刷新。重命名要求主区域正在显示非空会话,且没有模态对话框遮挡;切换到其他主面板后,后台保留的会话不可作为重命名目标。其他 Windows 和 macOS Desktop 绑定也可从终端输入区域和模态对话框中执行;其他环境遵循命令的区域和模态限制。搜索和重命名的打开请求归本包管理,输入草稿保留在浏览器中。目录选择或工作区接纳尚未结束时,目录选择器拒绝重复打开。分叉捕获主视图已持有并发起历史打开的会话,保留自动迁移;它使用与行菜单相同的 Host 操作选择最近已完成轮次,不读取更早的 Client 历史。没有会话或会话为空时不可用;没有已完成轮次的源会话由 Host 拒绝。快捷键分叉被拒绝时保留当前选择、显示本地化提示,并允许重试;非预期失败还会保留诊断日志。该提示共用应用级 Workspace 通知通道:只显示最新提示,移除浏览区域不会关闭它。 ### 待处理交互 @@ -69,11 +71,11 @@ Session 行渲染运行时的实时 `pendingInteraction` 分类:审批显示** ----- -`ctx.uiWorkspace.openSession(target)` 会同步替换其拥有的 `mainView` reference,并让主区域返回 Conversation,而不等待 `reference.ready`,因此历史加载会显示在已经选中的 Session 视图内。目标可以是已知 Session id,也可以是持久的直接父子 subagent 地址;显式地址不要求预先加载 parent catalog。`openWorkspace(id, beforeOpen?)` 仅在请求未被后续导航替代时打开工作区空白 Session;显式新会话操作会创建新的 Session。`forkSession(id)` 创建子会话,不导航,也不替代尚未完成的导航。可选的同步准备回调在目标被 retain 后执行,并且仅对仍有效的 Workspace 请求执行,因此过期请求不会搬移 composer 草稿。后续导航或 owner 释放会阻止晚到的 UI 提交,但不取消底层 Session 创建。启动恢复会 retain 主 reference,不改变已选面板,也不取消后续导航。归档主 Session 会释放其 reference 并清除主选择。选择失败时保留当前全局面板。Session 行读取 `usePanelInfo`,在全局面板活跃时不显示 Session 选中样式;仅把焦点移到搜索框或目录选择器不会离开该面板。 +`ctx.uiWorkspace.openSession(target)` 会同步替换其拥有的 `mainView` reference,并让主区域返回 Conversation,而不等待 `reference.ready`,因此历史加载会显示在已经选中的 Session 视图内。目标可以是已知 Session id,也可以是持久的直接父子 subagent 地址;显式地址不要求预先加载 parent catalog。`openWorkspace(id, beforeOpen?, options?)` 仅在请求未被后续导航替代时打开工作区空白 Session;显式新会话操作会创建新的 Session。`forkSession(id)` 创建子会话,不导航,也不替代尚未完成的导航。可选的同步准备回调在目标被 retain 后执行,并且仅对仍有效的 Workspace 请求执行,因此过期请求不会搬移 composer 草稿。后续导航或 owner 释放会阻止晚到的 UI 提交,但不取消底层 Session 创建。启动恢复会 retain 主 reference,不改变已选面板,也不取消后续导航。归档主 Session 会释放其 reference 并清除主选择。选择失败时保留当前全局面板。Session 行读取 `usePanelInfo`,在全局面板活跃时不显示 Session 选中样式;仅把焦点移到搜索框或目录选择器不会离开该面板。 -导航和启动恢复通过所选 Session 的 `follow` 获取投影,不会另行刷新该 Session 或其父会话的投影。 +导航和启动恢复通过所选 Session 的 `follow` 获取投影,不会另行刷新该 Session 或其父会话的投影;例外是恢复已保存的空白会话时先重新加载该 Session 的投影,因为列表中的值是缓存提示,Host 非正常退出后可能落后于其日志。 -重新打开工作区和显式准备草稿尝试获取列表中第一个符合条件的空白会话;启动恢复尝试已保存的空白会话。若该写锁被占用,导航直接新建 Session,不再尝试其他空白会话。其他获取错误会中止请求:显式新建会话或在 hero 中选择工作区时,失败以短暂提示展示,引用 Host 的错误码和消息(例如 preset 挂载失败),非 Host 拒绝的失败则显示其自身消息;已被后续导航或 owner 销毁取代的请求不弹提示,启动恢复仍只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 +重新打开工作区和显式准备草稿向 Host 请求 Session 时指明列表中第一个符合条件的空白会话;启动恢复指明已保存的空白会话。Host 以请求的 preset 复用该空白会话,请求未指明 preset 时使用其默认 preset;若该空白会话已开始、已离开该工作区或写锁被其他写者占用,Host 改为新建 Session;导航打开 Host 返回的 Session,不再尝试其他空白会话。带草稿选项的 `startSession`、`openWorkspace` 和 `connectWorkspace` 接受 `{ agentPreset }`,供开始前已确定 preset 的流程使用,例如创造模式入口;一次连接仅在与该工作区最近一次进行中的连接请求相同 preset 时与之合并,因此最新的请求总会到达 Host。启动恢复传入已保存空白会话日志记录的 preset,使草稿保留该 preset;当 Host 报告该 preset 不存在(`agent-preset/not-found`)或无法激活(`agent-preset/invalid`)时,启动恢复改为不带 preset 再请求一次,草稿在 Host 默认 preset 下继续。其他错误会中止请求:显式新建会话或在 hero 中选择工作区时,失败以短暂提示展示,引用 Host 的错误码和消息(例如 preset 挂载失败),非 Host 拒绝的失败则显示其自身消息;已被后续导航或 owner 销毁取代的请求不弹提示,启动恢复仍只报告到控制台。已释放的空白会话被复用时保留 slash 命令状态。后续导航会取消尚未完成的启动选择。 Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `workspaces.initializeDefault`,创建或复用其空白 Session。选中该 Session 后输入框才可编辑,不会自动提交消息。后续导航或所属上下文销毁会阻止启动流程选中其结果。不符合首次使用条件时仍可选择文件夹,不显示错误。默认工作区创建失败时显示短暂提示,引导用户通过“选择工作区”选择文件夹,直到下次启动才重试。Session 创建失败沿用普通的恢复错误处理。登记成功的工作区在 Session 创建或后续提交失败时仍然保留。 @@ -97,10 +99,12 @@ Workspace 和 Session 的启动基线均就绪后,空安装环境调用 `works ### Session 行 action -Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。 +Session 行的 "..." 菜单和行尾悬停按钮是 WorkspaceBrowser 注册项声明的两个 `list` slot:`sidebar.workspaces.session.menu.item` 与 `sidebar.workspaces.session.row.action`。每一个菜单行、每一个悬停按钮都是条目,本包自己的 action 也不例外:`apply` 以客户端插件注册自己 action 的同一方式注册 `pin`(菜单 100、按钮 200)、`rename`(200)、`fork`(300)、`archive`(菜单 400、按钮 100)和 `session-id`(450),因此插件 action 落在其 `order` 所指的位置,以另一个 `priority` 复用内置 id 则遮蔽该 action。 条目只接收行身份(`sessionId`、`displayTitle`),其余一切自己负责:用自己注入的 hook 读自己关心的 Host 状态(置顶与归档集合,以每次 Workspace 快照只派生一次的 Set 形式),自己决定是否显示(Host 规定归档与置顶互斥,所以 pin 在归档行上不渲染),整套行为放在注册项自己的 `inject` face 里(置顶成功后顺带把会话推到保存顺序最前,归档成功后发提示),浮层也自己带——重命名对话框、停止并归档对话框和行 action 的提示是本包注册在 `shell.overlay` 的条目,由 action 注入的请求驱动。菜单条目渲染一个 `role="menuitem"` 的按钮(本包自己的行用 ui-primitives 的 `MenuItemButton`,它带宿主样式,开启新分组的行加 `separatorBefore`,分隔线随行一起出现和消失),并通过 slot 级 `useMenuOpenState` hook(菜单自身的打开状态,从该行的渲染出现处绑定)关闭菜单;悬停按钮条目渲染一个图标按钮,按钮条会拦住点击、不让它打开该行。browser 不再向行传任何 action 回调,它剩下的动作只有搜索结果里的恢复按钮和标题双击,后者发出的是同一个重命名请求。 +现有通知浮层按通知 kind 分派 `workspace.toast`。各 keyed 注册注入本地化展示映射与自己的操作,只有归档通知订阅查看筛选状态。它们渲染包内的 `workspace.toast.content` Factory,所有展示共用一处 Toast primitive。现有通知状态、显示序号、最新提示替换及关闭逻辑仍共享;语言或筛选变化不会重新启动同一条提示的计时。 + #### 打包客户端插件 按照 Client 依赖规则,将 `ui-workspace`、`ui-slots`、`ui-renderer`、`client-locale` 与 `ui-primitives` 声明为浏览器/类型开发依赖。纯类型的 `ui-workspace/client` import 会加载本包的 `SlotMap` 声明;缺少该 import 时,独立编译的插件不会知道这些 slot key。Component 保持模块级稳定身份;用户可见文案由贡献包自己的 locale namespace 持有。 diff --git a/packages/client/ui-workspace/locale/en.json b/packages/client/ui-workspace/locale/en.json new file mode 100644 index 0000000000..077d51787e --- /dev/null +++ b/packages/client/ui-workspace/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "ui-workspace" + } +} diff --git a/packages/client/ui-workspace/locale/zh.json b/packages/client/ui-workspace/locale/zh.json new file mode 100644 index 0000000000..d61486204e --- /dev/null +++ b/packages/client/ui-workspace/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区选择界面", + "description": "在侧栏和新会话页面中选择工作区。" + } +} diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index e5ef226767..c2d44e8939 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -55,6 +56,7 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-api-workspace-controller": "workspace:*", "@deepseek-ai/dsh-client-connection": "workspace:*", @@ -75,13 +77,13 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", - "@types/react": "~18.3.1", "clsx": "^2.0.0", "react": "^18.2.0", "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index 568368dc63..d00b3658d8 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -26,8 +26,8 @@ * row of a Session's "..." menu is an entry of * `sidebar.workspaces.session.menu.item`, and every hover button at the row's * end is an entry of `sidebar.workspaces.session.row.action`. The shipped - * actions — pin, rename, fork, archive — are ordinary entries this package - * registers from `apply`, each carrying its own behavior in its own inject + * actions — pin, rename, fork, archive, copy ID — are ordinary entries + * registered from `apply`, each carrying its own behavior in its own inject * face and reading its own Host state through hooks that face injects, so a * client plugin's action lands beside them by `order` and needs nothing from * the browser beyond the row identity. @@ -53,6 +53,7 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { ShortcutCatalogEntry } from '@deepseek-ai/dsh-client-shortcuts/client' import type { WorkspaceShortcutState } from '../shortcuts.ts' import type { StartSessionOptions } from '../navigation.ts' +import type {} from './toast.ts' import type { createWorkspaceViewStore } from '../stores.ts' /** @@ -136,8 +137,8 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { /** * The rows of one Session's "..." menu, in ascending `order`. ui-workspace * registers the shipped rows here — `pin` (100), `rename` (200), `fork` - * (300), `archive` (400) — so a plugin row is placed by its own `order` - * among them. Use a package-namespaced `id`; reusing a shipped id at + * (300), `archive` (400), and `session-id` (450) — so a plugin row is placed + * by its own `order` among them. Use a package-namespaced `id`; reusing a shipped id at * another `priority` shadows that row. Each entry renders one * `role="menuitem"` `
) } diff --git a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx index b082a36f29..fae564a45b 100644 --- a/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx +++ b/packages/client/ui-workspace/src/client/session-actions/RowActionToast.tsx @@ -1,92 +1,14 @@ -/** - * The `shell.overlay` entry for Workspace and Session notices. - * One notice is visible at a time; a parent rerender does not extend its hold. - */ -import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' -import { assertNever } from '@deepseek-ai/dsh-util-values' -import type { RowToastProps, RowToastState } from '../contract/slots.ts' +/** The existing overlay dispatches the latest Workspace notice to its keyed presentation. */ +import type { RowToastProps } from '../contract/slots.ts' +import type {} from '../contract/toast.ts' /** - * Hold for the notices that take longer to read than a one-line warning: the - * archive and fork recovery actions, and a refused Session creation quoting the Host's reason. + * Dispatch the current notice without interpreting its business payload. + * @param props - Current notice, dismissal, and the declared keyed renderer. + * @returns The selected notice presentation, or nothing. */ -const LONG_TOAST_HOLD_MS = 6000 - -/** - * Render an operation notice, retaining recovery actions for six seconds. - * @param props - notice and viewing sources, dismissal and recovery callbacks, and localized copy. - * @returns the notice on display, or null. - */ -export function RowActionToast({ useToast, useStore, dismissToast, undoArchive, showArchived, openForkSource, t }: RowToastProps) { - const toast = useToast(current => current) - const archivedRowsVisible = useStore(state => (state.archivedFilter ?? 'default') !== 'default') - if (toast === null) return null - if (toast.kind === 'forkRequiresOpen') { - return ( - } - holdMs={LONG_TOAST_HOLD_MS} - actions={[{ - label: t('toast.openForkSource'), - onClick: () => { dismissToast(); openForkSource(toast.sessionId) }, - }]} - onDone={dismissToast} - /> - ) - } - if (toast.kind === 'archived' || toast.kind === 'stoppedAndArchived') { - const { sessionId } = toast - return ( - { dismissToast(); undoArchive(sessionId) } }, - ...archivedRowsVisible ? [] : [ - { prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), onClick: () => { dismissToast(); showArchived() } }, - ], - ]} - onDone={dismissToast} - /> - ) - } - if (toast.kind === 'createFailed') { - return ( - } - holdMs={LONG_TOAST_HOLD_MS} - onDone={dismissToast} - /> - ) - } - return ( - } - onDone={dismissToast} - /> - ) -} - -/** The copy of one plain warning, keyed by the notice kind the union closes over. */ -function plainNoticeText( - toast: Exclude, - t: RowToastProps['t'], -): string { - switch (toast.kind) { - case 'pinFailed': return t('toast.pinFailed') - case 'unpinFailed': return t('toast.unpinFailed') - case 'defaultWorkspaceFailed': return t('defaultWorkspace.failed') - case 'archivedNotOpenable': return t('toast.archivedNotOpenable') - /* v8 ignore next 2 -- closed-union backstop; only reached if a notice kind is forged */ - default: - return assertNever(toast) - } +export function RowActionToast({ useToast, dismissToast, renderSlot }: RowToastProps) { + const notice = useToast(current => current) + if (notice === null) return null + return renderSlot('workspace.toast', { ...notice, dismissToast }, { entryKey: notice.kind }) } diff --git a/packages/client/ui-workspace/src/client/session-actions/SessionId.tsx b/packages/client/ui-workspace/src/client/session-actions/SessionId.tsx new file mode 100644 index 0000000000..da292e67b3 --- /dev/null +++ b/packages/client/ui-workspace/src/client/session-actions/SessionId.tsx @@ -0,0 +1,20 @@ +/** Copy the row's Session ID without opening its history. */ +import { IconCopyOutlineRegular, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' +import type { SessionIdInjected, SessionMenuItemProps } from '../contract/slots.ts' + +/** + * Copy the complete ID after dismissing the row menu. + * @param props - Row identity, menu dismissal, clipboard action, and locale. + * @returns The final built-in menu item. + */ +export function SessionIdMenuItem({ sessionId, useMenuOpenState, copySessionId, t }: SessionMenuItemProps) { + const [, setMenuOpen] = useMenuOpenState() + return ( + } onSelect={() => { + setMenuOpen(false) + void copySessionId(sessionId) + }}> + {t('menu.sessionId')} + + ) +} diff --git a/packages/client/ui-workspace/src/client/shortcuts.ts b/packages/client/ui-workspace/src/client/shortcuts.ts index 52296c1434..ed9852b81a 100644 --- a/packages/client/ui-workspace/src/client/shortcuts.ts +++ b/packages/client/ui-workspace/src/client/shortcuts.ts @@ -13,7 +13,6 @@ export interface WorkspaceShortcutState { readonly addRequested: boolean readonly directoryBusy: boolean readonly renameTarget: { readonly sessionId: SessionId; readonly currentTitle: string } | null - readonly forkError: { readonly reason: 'unavailable' | 'failed'; readonly seq: number } | null } interface WorkspaceShortcutControls { @@ -24,8 +23,6 @@ interface WorkspaceShortcutControls { directoryBusy: (busy: boolean) => void rename: (sessionId: SessionId, currentTitle: string) => void closeRename: () => void - forkFailed: (reason: 'unavailable' | 'failed') => void - dismissForkError: () => void } /** @@ -34,9 +31,8 @@ interface WorkspaceShortcutControls { */ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { const state = createSnapshotStore({ - searchRequest: 0, addRequested: false, directoryBusy: false, renameTarget: null, forkError: null, + searchRequest: 0, addRequested: false, directoryBusy: false, renameTarget: null, }) - let forkErrorSeq = 0 return { state, search: () => { state.set({ ...state.getSnapshot(), searchRequest: state.getSnapshot().searchRequest + 1 }) }, @@ -47,11 +43,6 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { state.set({ ...state.getSnapshot(), renameTarget: { sessionId, currentTitle } }) }, closeRename: () => { state.set({ ...state.getSnapshot(), renameTarget: null }) }, - forkFailed: (reason) => { - forkErrorSeq += 1 - state.set({ ...state.getSnapshot(), forkError: { reason, seq: forkErrorSeq } }) - }, - dismissForkError: () => { state.set({ ...state.getSnapshot(), forkError: null }) }, } } @@ -62,12 +53,14 @@ export function createWorkspaceShortcutControls(): WorkspaceShortcutControls { * @param navigation - session creation and forking from the pointer controls' navigation service. * @param controls - browser-owned opening requests. * @param archiveSession - shared archive action, including running-work confirmation and notices. + * @param reportForkFailure - publish a classified failure through the frame-wide notice channel. */ export function installWorkspaceShortcuts( ctx: Context, navigation: Pick, controls: ReturnType, archiveSession: (sessionId: SessionId) => void, + reportForkFailure: (reason: 'unavailable' | 'failed') => void, ): void { const t = ctx.locale.bind('workspace') const current = () => Object.values(ctx.sessions.list.getSnapshot().byId) @@ -110,7 +103,7 @@ export function installWorkspaceShortcuts( // Client plugin bundles do not share error-class identity. const unavailable = error instanceof Error && error.name === 'SessionForkError' && (error as SessionForkError).rpcError.code === 'session/fork-unavailable' - controls.forkFailed(unavailable ? 'unavailable' : 'failed') + reportForkFailure(unavailable ? 'unavailable' : 'failed') if (!unavailable) console.warn('session fork rejected:', error) }) } } diff --git a/packages/client/ui-workspace/src/client/toast/Toast.tsx b/packages/client/ui-workspace/src/client/toast/Toast.tsx new file mode 100644 index 0000000000..fea6c6d109 --- /dev/null +++ b/packages/client/ui-workspace/src/client/toast/Toast.tsx @@ -0,0 +1,44 @@ +/** One presentation Factory and the adapters for keyed Workspace notices. */ +import { IconWarningOutlineRegular, Toast } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { ArchiveToastEntryProps, ToastEntryProps, WorkspaceToastProps } from '../contract/toast.ts' + +/** + * Render one notice using the shared Factory. + * @param props - Keyed payload, injected display mapping, locale, and Factory renderer. + * @returns The shared Toast occurrence. + */ +export function ToastEntry

>(props: ToastEntryProps

) { + const { dismissToast, display, t, renderFactorySlot, seq } = props + return renderFactorySlot('workspace.toast.content', { ...display(props, t, dismissToast), seq, onDone: dismissToast }) +} + +/** + * Keep the archive filter action reactive without subscribing unrelated notices. + * @param props - Archive notice, display mapping, and the existing viewing store. + * @returns The shared Toast occurrence with its current actions. + */ +export function ArchiveToastEntry(props: ArchiveToastEntryProps) { + const { dismissToast, display, filterAction, useStore, t, renderFactorySlot, seq } = props + const archivedVisible = useStore(state => (state.archivedFilter ?? 'default') !== 'default') + const fields = display(props, t, dismissToast) + return renderFactorySlot('workspace.toast.content', { + ...fields, + actions: [...fields.actions ?? [], ...archivedVisible ? [] : [filterAction(t, dismissToast)]], + seq, + onDone: dismissToast, + }) +} + +/** + * Present plain display data with the shared primitive's timing and portal. + * @param props - Localized display fields, display identity, and dismissal. + * @returns One Toast, remounted only for a new display identity. + */ +export function WorkspaceToast({ seq, text, tone, holdMs, actions, onDone }: WorkspaceToastProps) { + return } : {}} + {...holdMs === undefined ? {} : { holdMs }} + {...actions === undefined ? {} : { actions }} /> +} diff --git a/packages/client/ui-workspace/src/client/toast/register.ts b/packages/client/ui-workspace/src/client/toast/register.ts new file mode 100644 index 0000000000..efadbf89c2 --- /dev/null +++ b/packages/client/ui-workspace/src/client/toast/register.ts @@ -0,0 +1,104 @@ +/** Business-owned mappings into the keyed Workspace Toast slot. */ +import type { Context } from '@deepseek-ai/cordis' +import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { RowToastActions, WorkspaceViewStoreHandle } from '../contract/slots.ts' +import type { ArchiveToastInjected, ToastDisplayInjected } from '../contract/toast.ts' +import { ArchiveToastEntry, ToastEntry, WorkspaceToast } from './Toast.tsx' + +/** Register notice presentations with their business-owned display fields and actions. + * @param ctx - Workspace plugin context. + * @param viewStore - Viewing store, read only by archive notices. + * @param actions - Archive and source-opening callbacks. + */ +export function registerToasts( + ctx: Context, + viewStore: WorkspaceViewStoreHandle, + actions: Pick, +): void { + const archiveFilterAction: ArchiveToastInjected['filterAction'] = (t, dismiss) => ({ + prefix: t('toast.archivedOr'), label: t('toast.archivedFilter'), + onClick: () => { dismiss(); actions.showArchived() }, + }) + ctx.slots.registerFactory({ name: 'workspace.toast.content', scope: 'root' }, WorkspaceToast) + ctx.slots.inject('workspace.toast', function* () { + yield ctx.slots.register({ + name: 'workspace.toast', key: 'sessionIdCopied', locale: 'workspace', + inject: (): ToastDisplayInjected<'sessionIdCopied'> => ({ + display: (_notice, t) => ({ text: t('toast.sessionIdCopied'), tone: 'success' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'sessionIdCopyFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'sessionIdCopyFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.sessionIdCopyFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'pinFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'pinFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.pinFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'unpinFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'unpinFailed'> => ({ + display: (_notice, t) => ({ text: t('toast.unpinFailed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'archivedNotOpenable', locale: 'workspace', + inject: (): ToastDisplayInjected<'archivedNotOpenable'> => ({ + display: (_notice, t) => ({ text: t('toast.archivedNotOpenable'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'defaultWorkspaceFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'defaultWorkspaceFailed'> => ({ + display: (_notice, t) => ({ text: t('defaultWorkspace.failed'), tone: 'warning' }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'shortcutForkFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'shortcutForkFailed'> => ({ + display: (notice, t) => ({ + text: t(notice.reason === 'unavailable' ? 'shortcut.noCompletedTurn' : 'shortcut.forkFailed'), tone: 'plain', + }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'createFailed', locale: 'workspace', + inject: (): ToastDisplayInjected<'createFailed'> => ({ + display: (notice, t) => ({ text: t('toast.createFailed', { message: notice.message }), tone: 'warning', holdMs: 6000 }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'forkRequiresOpen', locale: 'workspace', + inject: (): ToastDisplayInjected<'forkRequiresOpen'> => ({ + display: (notice, t, dismiss) => ({ + text: t('toast.forkRequiresOpen'), tone: 'warning', holdMs: 6000, + actions: [{ label: t('toast.openForkSource'), onClick: () => { dismiss(); actions.openForkSource(notice.sessionId) } }], + }), + }), + }, ToastEntry>) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'archived', locale: 'workspace', store: viewStore, + inject: (): ArchiveToastInjected => ({ + display: (notice, t, dismiss) => ({ + text: t('toast.archived'), tone: 'success', holdMs: 6000, + actions: [{ label: t('toast.archivedUndo'), onClick: () => { dismiss(); actions.undoArchive(notice.sessionId) } }], + }), + filterAction: archiveFilterAction, + }), + }, ArchiveToastEntry) + yield ctx.slots.register({ + name: 'workspace.toast', key: 'stoppedAndArchived', locale: 'workspace', store: viewStore, + inject: (): ArchiveToastInjected => ({ + display: (notice, t, dismiss) => ({ + text: t('toast.stoppedAndArchived'), tone: 'success', holdMs: 6000, + actions: [{ label: t('toast.archivedUndo'), onClick: () => { dismiss(); actions.undoArchive(notice.sessionId) } }], + }), + filterAction: archiveFilterAction, + }), + }, ArchiveToastEntry) + }) +} diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index 0e1024f119..af8b5622ba 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -8,7 +8,8 @@ import { SessionForkError } from '@deepseek-ai/dsh-api-session-controller/client import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { PropsRenderSlots, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots' +import type { ShortcutCommand } from '@deepseek-ai/dsh-client-shortcuts/client' import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { apply, inject } from '@deepseek-ai/dsh-client-ui-workspace/client' @@ -16,7 +17,7 @@ import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from '@deepsee import { type ArchiveSessionInjected, type ForkSessionInjected, menuOpenStateFactory, type PinSessionInjected, type RenameSessionInjected, type RowToastInjected, type SessionArchiveConfirmInjected, type SessionRenameDialogInjected, - type WorkspaceViewStoreHandle, + type SessionIdInjected, type WorkspaceViewStoreHandle, } from '../src/client/contract/slots.ts' import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx' import { ArchiveSessionMenuItem, ArchiveSessionRowButton, SessionArchiveConfirmDialog } from '../src/client/session-actions/ArchiveSession.tsx' @@ -24,6 +25,8 @@ import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.t import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx' import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx' import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx' +import type { ArchiveToastInjected, ToastDisplayInjected } from '../src/client/contract/toast.ts' +import { SessionIdMenuItem } from '../src/client/session-actions/SessionId.tsx' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' import { FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' @@ -53,7 +56,14 @@ const workspaceState = ( async function bench() { const ctx = new Context() - ctx.provide('shortcuts', { register: () => () => {}, catalog: createSnapshotStore([]) }) + const commands = new Map() + ctx.provide('shortcuts', { + register: (command: ShortcutCommand) => { + commands.set(command.id, command) + return () => { commands.delete(command.id) } + }, + catalog: createSnapshotStore([]), + }) ctx.provide('uiConversation', {}) await ctx.plugin(SlotRegistry).await() const create = vi.fn(async (input: { name: string } | { path: string }) => ({ @@ -148,7 +158,7 @@ async function bench() { locale.setLocale('zh') ctx.provide('locale', locale) return { - ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, + ctx, slots: ctx.get('slots') as SlotRegistry, locale, create, rename, commands, retain, using, selectPanel, search, renameSession, binding, fork, pickDirectory, pinSession, unpinSession, workspacesSubscribe, initializeDefault, history, scope, sessionOf, setWorkspaces: (snapshot: WorkspaceSnapshot): void => { workspaceSnapshot = snapshot }, @@ -170,6 +180,11 @@ function declare(slots: SlotRegistry, ...names: HoleName[]): () => void { return slots.register({ name: 'root', children } as never, () => null) } +/** Own the sidebar declaration independently of the frame-wide overlay in lifecycle tests. */ +function SidebarDeclarationOwner({ renderSlot }: PropsRenderSlots<'sidebar.workspaces'>) { + return renderSlot('sidebar.workspaces', { wide: true, expandSidebar: () => {} }) +} + /** The one entry registered under `id` in a list. */ function entry(slots: SlotRegistry, key: RowListName, id: string): StoredEntry { const found = slots.entries(key).find(candidate => candidate.options.id === id) @@ -234,7 +249,7 @@ describe('ui-workspace apply', () => { await Promise.resolve() expect(after.slots.entries('conversation.hero.workspace')[0]!.component).toBe(WorkspacePicker) // The row actions follow the browser's own declaration, whenever it lands. - expect(after.slots.entries(MENU_ITEM)).toHaveLength(4) + expect(after.slots.entries(MENU_ITEM)).toHaveLength(5) expect(after.slots.entries(ROW_ACTION)).toHaveLength(2) expect(after.slots.entries('shell.overlay')).toHaveLength(3) }) @@ -257,6 +272,7 @@ describe('ui-workspace apply', () => { ['rename', 200, RenameSessionMenuItem, 'workspace'], ['fork', 300, ForkSessionMenuItem, 'workspace'], ['archive', 400, ArchiveSessionMenuItem, 'workspace'], + ['session-id', 450, SessionIdMenuItem, 'workspace'], ]) expect(rows(ROW_ACTION)).toEqual([ ['archive', 100, ArchiveSessionRowButton, 'workspace'], @@ -265,17 +281,22 @@ describe('ui-workspace apply', () => { expect(rows('shell.overlay')).toEqual([ ['workspace.session-rename', undefined, SessionRenameDialog, 'workspace'], ['workspace.session-archive', undefined, SessionArchiveConfirmDialog, 'workspace'], - ['workspace.row-toast', undefined, RowActionToast, 'workspace'], + ['workspace.row-toast', undefined, RowActionToast, undefined], ]) - // The browser and the row toast declare the same viewing-store handle, - // which hands out one instance: the browser's injected callbacks write - // view state through it and the toast reads the archived filter from it. - // The row actions and the other overlay surfaces declare none. + // Only archive notice entries share the browser's viewing store. const browser = b.slots.entries('sidebar.workspaces')[0]! expect(browser.store).toBeDefined() expect(viewInstance(b.slots)).toBe(viewInstance(b.slots)) const rowToastEntry = entry(b.slots, 'shell.overlay', 'workspace.row-toast') - expect(rowToastEntry.store).toBe(browser.store) + expect(rowToastEntry.store).toBeUndefined() + expect(b.slots.entries('workspace.toast').map(row => row.options.key)).toEqual([ + 'sessionIdCopied', 'sessionIdCopyFailed', 'pinFailed', 'unpinFailed', 'archivedNotOpenable', + 'defaultWorkspaceFailed', 'shortcutForkFailed', 'createFailed', 'forkRequiresOpen', 'archived', 'stoppedAndArchived', + ]) + for (const registration of b.slots.entries('workspace.toast')) { + expect(registration.locale).toBe('workspace') + expect(registration.store).toBe(['archived', 'stoppedAndArchived'].includes(String(registration.options.key)) ? browser.store : undefined) + } for (const registration of [...b.slots.entries(MENU_ITEM), ...b.slots.entries(ROW_ACTION), ...b.slots.entries('shell.overlay')]) { if (registration === rowToastEntry) continue expect(registration.store).toBeUndefined() @@ -287,6 +308,77 @@ describe('ui-workspace apply', () => { } }) + it.each([true, false])('copies an ID directly without loading its Session (clipboard accepted: %s)', async (accepted) => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + declare(b.slots, 'sidebar.workspaces', 'shell.overlay') + await b.ctx.plugin({ inject: [...inject], apply }).await() + const action = faceOf(entry(b.slots, MENU_ITEM, 'session-id')) as SessionIdInjected + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const writeText = vi.fn(async () => { + if (!accepted) throw new Error('clipboard denied') + }) + vi.stubGlobal('navigator', { clipboard: { writeText } }) + onTestFinished(() => { vi.unstubAllGlobals() }) + await action.copySessionId(sid('cold-session')) + expect(writeText).toHaveBeenCalledExactlyOnceWith('cold-session') + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: accepted ? 'sessionIdCopied' : 'sessionIdCopyFailed' }) + expect(b.retain).not.toHaveBeenCalled() + expect(b.using).not.toHaveBeenCalled() + expect(b.binding).not.toHaveBeenCalled() + }) + + it('publishes shortcut fork failures through the same latest-notice source as row actions', async () => { + const b = await bench() + onTestFinished(() => b.ctx.fiber.dispose()) + declare(b.slots, 'shell.overlay') + const removeBrowser = b.slots.register({ + name: 'shell.overlay', id: 'test-sidebar-owner', + children: { 'sidebar.workspaces': { kind: 'single', scope: 'root' } }, + }, SidebarDeclarationOwner) + await b.ctx.plugin({ inject: [...inject], apply }).await() + b.setSessions(sessionState([{ ...summary('source', 1), retainedBy: { mainView: 1 } }])) + const browser = faceOf(b.slots.entries('sidebar.workspaces')[0]!) as WorkspaceBrowserInjected + const toast = faceOf(entry(b.slots, 'shell.overlay', 'workspace.row-toast')) as RowToastInjected + const warning = vi.spyOn(console, 'warn').mockImplementation(() => {}) + onTestFinished(() => { warning.mockRestore() }) + const invoke = () => { + const resolution = b.commands.get('session.fork')!.resolve({ region: 'page', modal: null, target: null }) + if (resolution.status !== 'handled') throw new Error('the source must be available') + resolution.run() + } + + browser.notifyArchivedNotOpenable() + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'archivedNotOpenable' }) + b.fork.mockRejectedValueOnce(new SessionForkError( + new RemoteError('session/fork-unavailable', 'no completed turn', { sessionId: sid('source') }), sid('source'), + )) + invoke() + await vi.waitFor(() => { + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'shortcutForkFailed', reason: 'unavailable' }) + }) + expect(b.fork).toHaveBeenCalledExactlyOnceWith({ sessionId: sid('source'), increaseTitle: true }) + expect(warning).not.toHaveBeenCalled() + const unavailable = toast.hooks.toast.getSnapshot() + b.fork.mockRejectedValueOnce(new Error('connection closed')) + invoke() + await vi.waitFor(() => { + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'shortcutForkFailed', reason: 'failed' }) + }) + expect(toast.hooks.toast.getSnapshot()).not.toBe(unavailable) + expect(warning).toHaveBeenCalledExactlyOnceWith('session fork rejected:', expect.any(Error)) + const failure = toast.hooks.toast.getSnapshot() + removeBrowser() + expect(b.slots.entries('sidebar.workspaces')).toEqual([]) + expect(entry(b.slots, 'shell.overlay', 'workspace.row-toast').component).toBe(RowActionToast) + expect(toast.hooks.toast.getSnapshot()).toBe(failure) + browser.notifyArchivedNotOpenable() + expect(toast.hooks.toast.getSnapshot()).toMatchObject({ kind: 'archivedNotOpenable' }) + toast.dismissToast() + expect(toast.hooks.toast.getSnapshot()).toBeNull() + expect(browser).not.toHaveProperty('dismissForkError') + }) + it('derives the pinned and archived Sets from the Workspace snapshot, rebuilt only when it changes', async () => { const b = await bench() b.setWorkspaces(workspaceState([workspace('alpha', ['one', 'two'])], [sid('two')], [sid('one')])) @@ -472,17 +564,19 @@ describe('ui-workspace apply', () => { unsubscribe() expect(view.getSnapshot().archivedFilter).toBe('default') - toast.showArchived() + const archived = b.slots.entries('workspace.toast').find(row => row.options.key === 'archived')! + const archiveDisplay = faceOf(archived) as ArchiveToastInjected + archiveDisplay.filterAction(b.locale.bind('workspace'), toast.dismissToast).onClick() expect(view.getSnapshot().archivedFilter).toBe('show') - toast.undoArchive(sid('one')) + archiveDisplay.display({ kind: 'archived', sessionId: sid('one'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() expect(unarchiveSession).toHaveBeenCalledWith('one') // A rejected undo is a console diagnostic. const rejection = new Error('unarchive exploded') unarchiveSession.mockRejectedValueOnce(rejection) const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) try { - toast.undoArchive(sid('two')) + archiveDisplay.display({ kind: 'archived', sessionId: sid('two'), seq: 2 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('session unarchive rejected:', rejection) }) } finally { warn.mockRestore() @@ -594,7 +688,8 @@ describe('ui-workspace apply', () => { expect(b.retain).not.toHaveBeenCalled() expect(b.selectPanel).not.toHaveBeenCalled() toast.dismissToast() - toast.openForkSource(sid('source')) + ;(faceOf(b.slots.entries('workspace.toast').find(row => row.options.key === 'forkRequiresOpen')!) as ToastDisplayInjected<'forkRequiresOpen'>) + .display({ kind: 'forkRequiresOpen', sessionId: sid('source'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() expect(b.retain).toHaveBeenCalledExactlyOnceWith('source', { source: 'mainView' }) expect(b.selectPanel).toHaveBeenCalledExactlyOnceWith(null) expect(b.fork).toHaveBeenCalledOnce() @@ -621,7 +716,8 @@ describe('ui-workspace apply', () => { if (timing === 'after the notice') b.setWorkspaces(workspaceState([], [sid('source')])) toast.dismissToast() - toast.openForkSource(sid('source')) + ;(faceOf(b.slots.entries('workspace.toast').find(row => row.options.key === 'forkRequiresOpen')!) as ToastDisplayInjected<'forkRequiresOpen'>) + .display({ kind: 'forkRequiresOpen', sessionId: sid('source'), seq: 1 }, b.locale.bind('workspace'), toast.dismissToast).actions![0]!.onClick() expect(toast.hooks.toast.getSnapshot()).toEqual({ kind: 'archivedNotOpenable', seq: 2 }) expect(b.retain).not.toHaveBeenCalled() @@ -764,7 +860,7 @@ describe('ui-workspace apply', () => { declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace', 'conversation.empty.workspace', 'shell.overlay') const fiber = b.ctx.plugin({ inject: [...inject], apply }) await fiber.await() - expect(b.slots.entries(MENU_ITEM)).toHaveLength(4) + expect(b.slots.entries(MENU_ITEM)).toHaveLength(5) expect(b.slots.entries(ROW_ACTION)).toHaveLength(2) expect(b.slots.entries('shell.overlay')).toHaveLength(3) await fiber.dispose() @@ -776,5 +872,7 @@ describe('ui-workspace apply', () => { expect(b.slots.entries(MENU_ITEM)).toHaveLength(0) expect(b.slots.entries(ROW_ACTION)).toHaveLength(0) expect(b.slots.entries('shell.overlay')).toHaveLength(0) + expect(b.slots.entries('workspace.toast')).toHaveLength(0) + expect(b.slots.snapshot('factory:workspace.toast.content')).toEqual([]) }) }) diff --git a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx index 0187272d53..274f595533 100644 --- a/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx +++ b/packages/client/ui-workspace/tests/rename-assembly.client.spec.tsx @@ -14,7 +14,7 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' * (session.spec.ts#rename), the entries' own arms with * session-actions.client.spec, the row's list rendering with rows.client.spec. */ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, waitFor, within } from '@testing-library/react' import type { ISession } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId } from '@deepseek-ai/dsh-api-workspace-controller/client' @@ -111,7 +111,7 @@ describe('session rename through the assembled browser', () => { }, ) } - // `order` places plugin rows after the shipped rows (100/200/300/400) + // `order` places plugin rows after the shipped rows (100/200/300/400/450) // even when the later registration has the lower shadowing priority // assigned to dynamic browser packages; the first plugin row opens the // plugin group with a hairline. @@ -123,7 +123,7 @@ describe('session rename through the assembled browser', () => { const trigger = within(row as HTMLElement).getByLabelText('会话“Persisted title”的操作') fireEvent.click(trigger) expect(view.getAllByRole('menuitem').map(item => item.textContent)).toEqual([ - '置顶会话', '重命名', '分叉会话', '归档会话', 'Export action', 'Last action', + '置顶会话', '重命名', '分叉会话', '归档会话', '复制 Session ID', 'Export action', 'Last action', ]) expect(view.getAllByRole('separator')).toHaveLength(1) const last = view.getByRole('menuitem', { name: 'Last action' }) @@ -140,6 +140,18 @@ describe('session rename through the assembled browser', () => { expect(view.queryByRole('menu')).toBeNull() await act(async () => { await Promise.resolve() }) expect(document.activeElement).toBe(trigger) + const writeText = vi.fn(async () => {}) + const clipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }) + onTestFinished(() => { + if (clipboard === undefined) Reflect.deleteProperty(navigator, 'clipboard') + else Object.defineProperty(navigator, 'clipboard', clipboard) + }) + fireEvent.click(trigger) + fireEvent.click(view.getByRole('menuitem', { name: '复制 Session ID' })) + expect(view.queryByRole('menu')).toBeNull() + expect(writeText).toHaveBeenCalledExactlyOnceWith(SID) + await view.findByText('Session ID 已复制') await runtime.dispose() }) diff --git a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx index 44e01f8671..35e40222e2 100644 --- a/packages/client/ui-workspace/tests/session-actions.client.spec.tsx +++ b/packages/client/ui-workspace/tests/session-actions.client.spec.tsx @@ -1,22 +1,25 @@ // @vitest-environment jsdom /** * The shipped Session row actions rendered directly with hand-built props: - * the pin, rename, fork, and archive menu rows, the archive and pin hover - * buttons, and the two `shell.overlay` surfaces they raise (rename dialog, - * row notice). Every action reads its own injected hooks and calls its own - * injected callbacks; what those callbacks do is apply.client.spec's + * the menu rows, hover buttons, dialogs, and global notices. Every action + * reads its own injected hooks and calls its own injected callbacks; + * what those callbacks do is apply.client.spec's * subject. The browser and the slot machinery stay out; the assembled * chain lives in rename-assembly.client.spec. */ -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' import type { WorkspaceId, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' -import type { GlobalStandardProps, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' -import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { GlobalStandardProps, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import { bindSnapshotSelector, makeTranslate, SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { registerToasts } from '../src/client/toast/register.ts' +import { ArchiveToastEntry } from '../src/client/toast/Toast.tsx' +import type { ArchiveToastEntryProps } from '../src/client/contract/toast.ts' import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' import type { @@ -30,6 +33,7 @@ import { ForkSessionMenuItem } from '../src/client/session-actions/ForkSession.t import { PinSessionMenuItem, PinSessionRowButton } from '../src/client/session-actions/PinSession.tsx' import { RenameSessionMenuItem, SessionRenameDialog } from '../src/client/session-actions/RenameSession.tsx' import { RowActionToast } from '../src/client/session-actions/RowActionToast.tsx' +import { SessionIdMenuItem } from '../src/client/session-actions/SessionId.tsx' import { createWorkspaceViewStore } from '../src/client/stores.ts' import { en, zh } from '../src/client/locales.ts' import { ShortcutRegistry } from '../../shortcuts/src/client/registry.ts' @@ -109,6 +113,19 @@ function callOrder(fn: { mock: { invocationCallOrder: readonly number[] } }, nth return fn.mock.invocationCallOrder[nth] ?? Number.POSITIVE_INFINITY } +describe('Session ID action', () => { + it.each([t, tEn])('dismisses the menu before copying the complete row ID', (translate) => { + const { state, setMenuOpen } = openMenu() + const sessionId = sid('session-c4421b66-252e-44c0-80ed-6e320abeba25') + const copySessionId = vi.fn(async () => {}) + render() + fireEvent.click(screen.getByRole('menuitem', { name: translate('menu.sessionId') })) + expect(setMenuOpen).toHaveBeenCalledWith(false) + expect(copySessionId).toHaveBeenCalledExactlyOnceWith(sessionId) + expect(callOrder(setMenuOpen)).toBeLessThan(callOrder(copySessionId)) + }) +}) + describe('pin action', () => { /** The pin share over fixed membership: the bound Set hooks and the two callbacks the entries call. */ const pinShare = (pinned: readonly string[] = [], archived: readonly string[] = []) => ({ @@ -488,9 +505,28 @@ declare module '@deepseek-ai/dsh-workspace/types' { } } +function ToastFrame({ renderSlot }: PropsRenderSlots<'shell.overlay'>) { + return renderSlot('shell.overlay', {}) +} + describe('RowActionToast', () => { + it('adds the archive filter action when the display mapping supplies no actions', () => { + const instance = createWorkspaceViewStore().create() + const dismissToast = vi.fn() + const showArchived = vi.fn() + const filter = { label: 'Show archived', onClick: showArchived } + const renderFactorySlot = vi.fn(() => null) + render( ({ text: 'Archived', tone: 'success' })} filterAction={() => filter} />) + expect(renderFactorySlot).toHaveBeenCalledWith('workspace.toast.content', { + text: 'Archived', tone: 'success', actions: [filter], seq: 1, onDone: dismissToast, + }) + }) + /** The notice surface over a test-owned notice source; dismissal clears the notice the way apply does. */ - function toastSurface( + async function toastSurface( viewState: { archivedFilter?: 'default' | 'show' | 'only' } = { archivedFilter: 'default' }, translate = t, ) { @@ -506,28 +542,59 @@ describe('RowActionToast', () => { const undoArchive = vi.fn() const showArchived = vi.fn() const openForkSource = vi.fn() - render( - , - ) + const runtime = await SlotTestRuntime.create() + onTestFinished(() => runtime.dispose()) + const locale = new LocaleRuntime(runtime.ctx) + locale.setLocale(translate === tEn ? 'en' : 'zh') + locale.register('workspace', { en, zh }) + runtime.ctx.provide('locale', locale) + runtime.slots.installLocale(locale) + await runtime.root.declare({ 'shell.overlay': { kind: 'list', scope: 'root' } }, ToastFrame) + registerToasts(runtime.ctx, { + ...createWorkspaceViewStore(), + create: () => ({ + ...instance, store: view, + getSnapshot: () => view.getSnapshot(), + subscribe: listener => view.subscribe(listener), + }), + }, { + undoArchive, showArchived, openForkSource, + }) + runtime.slots.register({ + name: 'shell.overlay', id: 'workspace.row-toast', + children: { 'workspace.toast': { kind: 'keyed', scope: 'root' } }, + inject: () => ({ hooks: { toast }, dismissToast }), + }, RowActionToast) + runtime.renderRoot() let seq = 0 const notify = (notice: RowToast): void => { act(() => { toast.set({ ...notice, seq: ++seq }) }) } - return { dismissToast, undoArchive, showArchived, openForkSource, notify } + return { dismissToast, undoArchive, showArchived, openForkSource, notify, locale, view } } - it('renders nothing without a notice', () => { - toastSurface() + it('updates locale and archive actions without restarting the same notice', async () => { + const { notify, locale, view, dismissToast } = await toastSurface() + vi.useFakeTimers() + try { + notify({ kind: 'archived', sessionId: sid('one') }) + const alert = screen.getByRole('alert') + act(() => { vi.advanceTimersByTime(3000) }) + act(() => { locale.setLocale('en'); view.set({ ...view.getSnapshot(), archivedFilter: 'show' }) }) + expect(screen.getByRole('alert')).toBe(alert) + expect(alert.textContent).toContain('Session archived') + expect(screen.queryByRole('button', { name: 'filter archived sessions' })).toBeNull() + act(() => { vi.advanceTimersByTime(3999) }) + expect(dismissToast).not.toHaveBeenCalled() + act(() => { vi.advanceTimersByTime(1) }) + expect(dismissToast).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + } + }) + + it('renders nothing without a notice', async () => { + await toastSurface() expect(screen.queryByRole('alert')).toBeNull() expect(document.body.textContent).toBe('') }) @@ -535,8 +602,8 @@ describe('RowActionToast', () => { it.each([ ['zh', t, '请先打开原会话完成迁移,再创建分支', '打开原会话'], ['en', tEn, 'Open the original session to complete migration before creating a branch.', 'Open original session'], - ] as const)('keeps the %s fork notice after menu unmount and opens only on its action', (_locale, translate, message, action) => { - const { dismissToast, openForkSource, notify } = toastSurface(undefined, translate) + ] as const)('keeps the %s fork notice after menu unmount and opens only on its action', async (_locale, translate, message, action) => { + const { dismissToast, openForkSource, notify } = await toastSurface(undefined, translate) const { state, setMenuOpen } = openMenu() const forkSession = vi.fn((sessionId: SessionId) => { notify({ kind: 'forkRequiresOpen', sessionId }) }) const menu = render() @@ -558,16 +625,73 @@ describe('RowActionToast', () => { expect(screen.queryByRole('alert')).toBeNull() }) - it('the stopped-and-archived notice offers the same undo and filter actions under its own wording', () => { - const { undoArchive, notify } = toastSurface() + it.each([t, tEn])('reports clipboard success and failure through the global toast', async (translate) => { + const { notify } = await toastSurface(undefined, translate) + notify({ kind: 'sessionIdCopied' }) + expect(screen.getByRole('alert').textContent).toBe(translate('toast.sessionIdCopied')) + notify({ kind: 'sessionIdCopyFailed' }) + expect(screen.getByRole('alert').textContent).toBe(translate('toast.sessionIdCopyFailed')) + }) + + it.each([t, tEn])('replaces other notices with plain shortcut fork failures and only keeps the latest', async (translate) => { + const { dismissToast, notify } = await toastSurface(undefined, translate) + vi.useFakeTimers() + try { + notify({ kind: 'archived', sessionId: sid('one') }) + act(() => { vi.advanceTimersByTime(1000) }) + notify({ kind: 'shortcutForkFailed', reason: 'unavailable' }) + const first = screen.getByRole('alert') + expect(first.textContent).toBe(translate('shortcut.noCompletedTurn')) + expect(first.querySelector('svg')).toBeNull() + expect(first.querySelector('button')).toBeNull() + act(() => { vi.advanceTimersByTime(3000) }) + expect(screen.getByRole('alert')).toBe(first) + notify({ kind: 'shortcutForkFailed', reason: 'failed' }) + const retry = screen.getByRole('alert') + expect(retry).not.toBe(first) + expect(retry.textContent).toBe(translate('shortcut.forkFailed')) + expect(retry.querySelector('svg')).toBeNull() + act(() => { vi.advanceTimersByTime(3999) }) + expect(screen.getAllByRole('alert')).toEqual([retry]) + expect(dismissToast).not.toHaveBeenCalled() + act(() => { vi.advanceTimersByTime(1) }) + expect(dismissToast).toHaveBeenCalledOnce() + expect(screen.queryByRole('alert')).toBeNull() + + notify({ kind: 'shortcutForkFailed', reason: 'failed' }) + act(() => { vi.advanceTimersByTime(1000) }) + notify({ kind: 'sessionIdCopied' }) + const latest = screen.getByRole('alert') + expect(latest.textContent).toBe(translate('toast.sessionIdCopied')) + act(() => { vi.advanceTimersByTime(3000) }) + expect(screen.getAllByRole('alert')).toEqual([latest]) + expect(dismissToast).toHaveBeenCalledOnce() + act(() => { vi.advanceTimersByTime(1000) }) + expect(screen.queryByRole('alert')).toBeNull() + } finally { + vi.useRealTimers() + } + }) + + it('the stopped-and-archived notice offers the same undo and filter actions under its own wording', async () => { + const { dismissToast, undoArchive, showArchived, notify } = await toastSurface() notify({ kind: 'stoppedAndArchived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('已停止并归档,可撤销或筛选已归档会话') fireEvent.click(screen.getByRole('button', { name: '撤销' })) expect(undoArchive).toHaveBeenCalledWith(sid('one')) + expect(callOrder(dismissToast)).toBeLessThan(callOrder(undoArchive)) + + notify({ kind: 'stoppedAndArchived', sessionId: sid('two') }) + fireEvent.click(screen.getByRole('button', { name: '筛选已归档会话' })) + expect(dismissToast).toHaveBeenCalledTimes(2) + expect(showArchived).toHaveBeenCalledOnce() + expect(callOrder(dismissToast, 1)).toBeLessThan(callOrder(showArchived)) + expect(undoArchive).toHaveBeenCalledOnce() + expect(screen.queryByRole('alert')).toBeNull() }) - it('the archived notice takes itself down, then undoes the archive or shows the archived rows', () => { - const { dismissToast, undoArchive, showArchived, notify } = toastSurface() + it('the archived notice takes itself down, then undoes the archive or shows the archived rows', async () => { + const { dismissToast, undoArchive, showArchived, notify } = await toastSurface() notify({ kind: 'archived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销或筛选已归档会话') fireEvent.click(screen.getByRole('button', { name: '撤销' })) @@ -586,14 +710,14 @@ describe('RowActionToast', () => { expect(screen.queryByRole('alert')).toBeNull() }) - it('treats a view without a persisted filter as the hidden default and keeps the filter action', () => { - const { notify } = toastSurface({}) + it('treats a view without a persisted filter as the hidden default and keeps the filter action', async () => { + const { notify } = await toastSurface({}) notify({ kind: 'archived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销或筛选已归档会话') }) - it.each(['show', 'only'] as const)('omits the filter action while the %s filter already shows archived rows', (archivedFilter) => { - const { notify } = toastSurface({ archivedFilter }) + it.each(['show', 'only'] as const)('omits the filter action while the %s filter already shows archived rows', async (archivedFilter) => { + const { notify } = await toastSurface({ archivedFilter }) notify({ kind: 'archived', sessionId: sid('one') }) expect(screen.getByRole('alert').textContent).toBe('会话已归档,可撤销') expect(screen.queryByRole('button', { name: '筛选已归档会话' })).toBeNull() @@ -605,10 +729,10 @@ describe('RowActionToast', () => { ['unpinFailed', '取消置顶失败,请稍后重试'], ['archivedNotOpenable', '已归档对话暂时无法查看,请取消归档后查看'], ['defaultWorkspaceFailed', '无法创建默认工作区,请通过“选择工作区”选择文件夹'], - ] as const)('shows the %s warning and takes it down when its hold ends', (kind, text) => { + ] as const)('shows the %s warning and takes it down when its hold ends', async (kind, text) => { + const { dismissToast, notify } = await toastSurface() vi.useFakeTimers() try { - const { dismissToast, notify } = toastSurface() notify({ kind }) const alert = screen.getByRole('alert') expect(alert.textContent).toBe(text) @@ -621,10 +745,10 @@ describe('RowActionToast', () => { } }) - it('shows a refused creation with the Host reason and holds it as long as the archived notice', () => { + it('shows a refused creation with the Host reason and holds it as long as the archived notice', async () => { + const { dismissToast, notify } = await toastSurface() vi.useFakeTimers() try { - const { dismissToast, notify } = toastSurface() notify({ kind: 'createFailed', message: 'agent-preset/invalid: agent-presets: preset "broken" failed to mount' }) const alert = screen.getByRole('alert') expect(alert.textContent).toBe('新建会话失败:agent-preset/invalid: agent-presets: preset "broken" failed to mount') @@ -639,10 +763,10 @@ describe('RowActionToast', () => { } }) - it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', () => { + it('the archived notice holds longer than a plain notice, and a repeat restarts its hold', async () => { + const { dismissToast, notify } = await toastSurface() vi.useFakeTimers() try { - const { dismissToast, notify } = toastSurface() notify({ kind: 'archived', sessionId: sid('one') }) act(() => { vi.advanceTimersByTime(4000) }) expect(screen.getByRole('alert')).toBeTruthy() diff --git a/packages/client/ui-workspace/tests/shortcuts.client.spec.ts b/packages/client/ui-workspace/tests/shortcuts.client.spec.ts index 6a11c44b56..50caf09818 100644 --- a/packages/client/ui-workspace/tests/shortcuts.client.spec.ts +++ b/packages/client/ui-workspace/tests/shortcuts.client.spec.ts @@ -54,14 +54,16 @@ async function bench(runtime: 'web' | 'desktop' = 'desktop', platform: ShortcutP startSession: vi.fn(), forkSession: vi.fn(async () => 'fork-child' as SessionId), archiveSession: vi.fn(async (_sessionId: SessionId) => {}), } const controls = createWorkspaceShortcutControls() + const reportForkFailure = vi.fn() const fiber = ctx.plugin((scoped) => { - installWorkspaceShortcuts(scoped, navigation, controls, (id) => { void navigation.archiveSession(id) }) + installWorkspaceShortcuts(scoped, navigation, controls, + (id) => { void navigation.archiveSession(id) }, reportForkFailure) }) await fiber.await() const select = (id: string) => { list.set({ ...list.getSnapshot(), byId: { [sid('a')]: row('a', id === 'a'), [sid('b')]: row('b', id === 'b'), } }) } - return { ctx, fiber, registry, commands, navigation, controls, list, directory, select, history, loadOlder, panelInfo } + return { ctx, fiber, registry, commands, navigation, controls, reportForkFailure, list, directory, select, history, loadOlder, panelInfo } } afterEach(() => { vi.restoreAllMocks() }) @@ -188,12 +190,11 @@ describe('workspace shortcut ownership', () => { )) const invoke = () => b.registry.dispatch(key('KeyF', { alt: true }), context, vi.fn()) expect(invoke().status).toBe('handled') - await vi.waitFor(() => { expect(b.controls.state.getSnapshot().forkError).toMatchObject({ reason: 'unavailable' }) }) + await vi.waitFor(() => { expect(b.reportForkFailure).toHaveBeenCalledExactlyOnceWith('unavailable') }) expect(warning).not.toHaveBeenCalled() - b.controls.dismissForkError() b.navigation.forkSession.mockRejectedValueOnce(new Error('connection closed')) expect(invoke().status).toBe('handled') - await vi.waitFor(() => { expect(b.controls.state.getSnapshot().forkError).toMatchObject({ reason: 'failed' }) }) + await vi.waitFor(() => { expect(b.reportForkFailure).toHaveBeenNthCalledWith(2, 'failed') }) expect(warning).toHaveBeenCalledOnce() b.list.set({ ...b.list.getSnapshot(), byId: { [sid('a')]: { ...row('a', true), running: true } } }) expect(invoke().status).toBe('handled') diff --git a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx index f88dd51e96..40b9a97a6d 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.client.spec.tsx @@ -11,13 +11,12 @@ import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/c import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { MainPanelId } from '@deepseek-ai/dsh-client-ui-layout/client' import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' -import { en as commonEn } from '@deepseek-ai/dsh-client-locale/src/locales/en.ts' import type { DirectoryFlowOwnerProps, WorkspaceBrowserProps } from '../src/client/contract/slots.ts' import { createWorkspaceShortcutControls } from '../src/client/shortcuts.ts' import { createWorkspaceViewStore, FLAT_SESSION_ORDER_KEY } from '../src/client/stores.ts' import { UNGROUPED_KEY } from '../src/client/tree.ts' import { WorkspaceBrowser } from '../src/client/rows/WorkspaceBrowser.tsx' -import { en, zh } from '../src/client/locales.ts' +import { zh } from '../src/client/locales.ts' // Every fixture carries the resource hook the resources plugin merges into GlobalStandardProps. const useResource = (() => ({ status: 'none' as const, value: undefined, failure: undefined, reload: () => {} })) as GlobalStandardProps['useResource'] @@ -114,7 +113,6 @@ function mount(overrides: Partial = {}) { closeAddWorkspace: controls.closeAdd, setDirectoryBusy: controls.directoryBusy, requestSessionRename: controls.rename, - dismissForkError: controls.dismissForkError, wide: true, expandSidebar: vi.fn(), useSessions: hook(sessionState([])), @@ -151,19 +149,6 @@ function rerender(b: ReturnType, overrides: Partial { - it.each([{ messages: en, common: commonEn }, { messages: zh, common: commonZh }])('shows localized fork failures and dismisses them', ({ messages, common }) => { - const b = mount({ t: makeTranslate(messages, common) }) - act(() => { b.controls.forkFailed('unavailable') }) - const first = screen.getByRole('alert') - expect(first.textContent).toBe(messages['shortcut.noCompletedTurn']) - act(() => { b.controls.dismissForkError(); b.controls.forkFailed('unavailable') }) - expect(screen.getByRole('alert')).not.toBe(first) - act(() => { b.controls.forkFailed('failed') }) - expect(screen.getByRole('alert').textContent).toBe(messages['shortcut.forkFailed']) - act(() => { b.controls.dismissForkError() }) - expect(screen.queryByRole('alert')).toBeNull() - }) - it.each(['workspace', 'flat', 'ungrouped'] as const)('keeps %s recency independent of arrival order and saved manual positions', (mode) => { localStorage.clear() const preferences = createWorkspaceViewStore().create() diff --git a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts index 4ea440e149..1662c1cd5f 100644 --- a/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts +++ b/packages/client/ui-workspace/tests/workspaces-service.client.spec.ts @@ -1055,7 +1055,9 @@ describe('UiWorkspaceService', () => { workspaces: workspaceState([workspace('a', [sid('other'), sid('saved')])]), configureSessions: (sessions) => { sessions.create.mockReturnValue(acquired.promise) }, }) - expect(b.sessions.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: wid('a'), sessionId: sid('saved') }) + await vi.waitFor(() => { + expect(b.sessions.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: wid('a'), sessionId: sid('saved') }) + }) expect(b.sessions.retain).not.toHaveBeenCalled() acquired.resolve(sid('saved')) await vi.waitFor(() => { @@ -1063,7 +1065,7 @@ describe('UiWorkspaceService', () => { }) }) - it.each(['saved', 'workspace'])('creates after the selected %s blank is held without trying another blank', async (source) => { + it.each(['saved', 'workspace'])('opens the Session the Host returns for the selected %s blank', async (source) => { if (source === 'saved') persistSelection({ sessionId: sid('held') }) const b = bench({ sessions: sessionState([ @@ -1071,11 +1073,7 @@ describe('UiWorkspaceService', () => { summary('free', { blank: true, cwd: '/w/a' }), ], source === 'saved' ? 'ready' : 'pending'), workspaces: workspaceState([workspace('a', [sid('held'), sid('free')])]), - configureSessions: (sessions) => { - sessions.create.mockRejectedValueOnce(new SessionCreateError( - new RemoteError('session/writer-held', 'held', { sessionId: sid('held') }), sid('held'), - )) - }, + configureSessions: (sessions) => { sessions.create.mockResolvedValueOnce(sid('created-a')) }, }) if (source === 'saved') { await vi.waitFor(() => { @@ -1084,10 +1082,170 @@ describe('UiWorkspaceService', () => { } else { await expect(b.uiWorkspace.connectWorkspace(wid('a'))).resolves.toBe(sid('created-a')) } + expect(b.sessions.create.mock.calls).toEqual([[{ workspaceId: wid('a'), sessionId: sid('held') }]]) + }) + + it('reloads the projections of a blank the Host declined so a stale blank row is corrected', async () => { + const b = bench({ + sessions: sessionState([summary('stale', { blank: true, cwd: '/w/a' })], 'pending'), + workspaces: workspaceState([workspace('a', [sid('stale')])]), + configureSessions: (sessions) => { sessions.create.mockResolvedValueOnce(sid('fresh')) }, + }) + + await expect(b.uiWorkspace.connectWorkspace(wid('a'))).resolves.toBe(sid('fresh')) + + expect(b.sessions.refreshProjections).toHaveBeenCalledExactlyOnceWith(sid('stale')) + }) + + it('leaves the projections of a reused blank to its own follow', async () => { + const b = bench({ + sessions: sessionState([summary('blank', { blank: true, cwd: '/w/a' })], 'pending'), + workspaces: workspaceState([workspace('a', [sid('blank')])]), + }) + + await expect(b.uiWorkspace.connectWorkspace(wid('a'))).resolves.toBe(sid('blank')) + + expect(b.sessions.refreshProjections).not.toHaveBeenCalled() + }) + + it('reports a failed projection reload of a declined blank without failing the connection', async () => { + const failure = new Error('projection reader crashed') + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const b = bench({ + sessions: sessionState([summary('stale', { blank: true, cwd: '/w/a' })], 'pending'), + workspaces: workspaceState([workspace('a', [sid('stale')])]), + configureSessions: (sessions) => { + sessions.create.mockResolvedValueOnce(sid('fresh')) + sessions.refreshProjections.mockRejectedValueOnce(failure) + }, + }) + + await expect(b.uiWorkspace.connectWorkspace(wid('a'))).resolves.toBe(sid('fresh')) + + await vi.waitFor(() => { + expect(warn).toHaveBeenCalledExactlyOnceWith('declined blank Session projection reload failed:', failure) + }) + }) + + it('restores a saved blank under the preset it recorded', async () => { + persistSelection({ sessionId: sid('saved') }) + const b = bench({ + sessions: sessionState([summary('saved', { blank: true, cwd: '/w/a', projectionValues: { agentPreset: 'ptc' } })]), + workspaces: workspaceState([workspace('a', [sid('saved')])]), + }) + await vi.waitFor(() => { + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + }) + expect(b.sessions.create.mock.calls).toEqual([[{ workspaceId: wid('a'), sessionId: sid('saved'), agentPreset: 'ptc' }]]) + }) + + it('restores a saved blank under the preset its log recorded when the listed value lags', async () => { + persistSelection({ sessionId: sid('saved') }) + const b = bench({ + sessions: sessionState([summary('saved', { blank: true, cwd: '/w/a', projectionValues: { agentPreset: 'standard' } })]), + workspaces: workspaceState([workspace('a', [sid('saved')])]), + configureSessions: (sessions) => { + sessions.refreshProjections.mockImplementation(async (id) => { + sessions.list.update(state => ({ + ...state, + byId: { ...state.byId, [id]: { ...state.byId[id]!, projectionValues: { agentPreset: 'ptc' } } }, + })) + }) + }, + }) + await vi.waitFor(() => { + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + }) + expect(b.sessions.refreshProjections).toHaveBeenCalledExactlyOnceWith(sid('saved')) + expect(b.sessions.create.mock.calls).toEqual([[{ workspaceId: wid('a'), sessionId: sid('saved'), agentPreset: 'ptc' }]]) + }) + + it.each(['agent-preset/not-found', 'agent-preset/invalid'] as const)( + 'restores a saved blank under the default when its recorded preset fails with %s', + async (code) => { + persistSelection({ sessionId: sid('saved') }) + const b = bench({ + sessions: sessionState([summary('saved', { blank: true, cwd: '/w/a', projectionValues: { agentPreset: 'liangshen' } })]), + workspaces: workspaceState([workspace('a', [sid('saved')])]), + configureSessions: (sessions) => { + const refusal = code === 'agent-preset/not-found' + ? new RemoteError(code, 'unknown preset', { agentPreset: 'liangshen', available: ['standard'] }) + : new RemoteError(code, 'activation failed', { agentPreset: 'liangshen', reason: 'activation failed' }) + sessions.create.mockRejectedValueOnce(new SessionCreateError(refusal, sid('saved'))) + }, + }) + await vi.waitFor(() => { + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('saved'), { source: 'mainView' }) + }) + expect(b.sessions.create.mock.calls).toEqual([ + [{ workspaceId: wid('a'), sessionId: sid('saved'), agentPreset: 'liangshen' }], + [{ workspaceId: wid('a'), sessionId: sid('saved') }], + ]) + expect(b.notify).not.toHaveBeenCalled() + }, + ) + + it('does not retry a saved blank restoration refused for another reason', async () => { + persistSelection({ sessionId: sid('saved') }) + const refused = new SessionCreateError(new RemoteError('gateway/internal', 'read failed', {}), sid('saved')) + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + const b = bench({ + sessions: sessionState([summary('saved', { blank: true, cwd: '/w/a', projectionValues: { agentPreset: 'ptc' } })]), + workspaces: workspaceState([workspace('a', [sid('saved')])]), + configureSessions: (sessions) => { sessions.create.mockRejectedValueOnce(refused) }, + }) + await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith('initial Session restoration failed:', refused) }) + expect(b.sessions.create).toHaveBeenCalledOnce() + expect(b.sessions.retain).not.toHaveBeenCalled() + }) + + it('requests the New Session preset from the Host with the reusable blank', async () => { + const b = bench({ + sessions: sessionState([summary('blank', { blank: true, cwd: '/w/a' })], 'pending'), + workspaces: workspaceState([workspace('a', [sid('blank')])]), + }) + b.uiWorkspace.startSession(wid('a'), { agentPreset: 'ptc' }) + await vi.waitFor(() => { + expect(b.sessions.retain).toHaveBeenCalledExactlyOnceWith(sid('blank'), { source: 'mainView' }) + }) + expect(b.sessions.create).toHaveBeenCalledExactlyOnceWith({ workspaceId: wid('a'), sessionId: sid('blank'), agentPreset: 'ptc' }) + }) + + it('coalesces only Workspace connections that request the same preset', async () => { + const acquired = Promise.withResolvers() + const b = bench({ + sessions: sessionState([summary('blank', { blank: true, cwd: '/w/a' })], 'pending'), + workspaces: workspaceState([workspace('a', [sid('blank')])]), + configureSessions: (sessions) => { sessions.create.mockReturnValue(acquired.promise) }, + }) + const plain = b.uiWorkspace.connectWorkspace(wid('a')) + const creator = b.uiWorkspace.connectWorkspace(wid('a'), { agentPreset: 'ptc' }) + const again = b.uiWorkspace.connectWorkspace(wid('a'), { agentPreset: 'ptc' }) expect(b.sessions.create.mock.calls).toEqual([ - [{ workspaceId: wid('a'), sessionId: sid('held') }], - [{ workspaceId: wid('a') }], + [{ workspaceId: wid('a'), sessionId: sid('blank') }], + [{ workspaceId: wid('a'), sessionId: sid('blank'), agentPreset: 'ptc' }], ]) + acquired.resolve(sid('blank')) + await expect(Promise.all([plain, creator, again])).resolves.toEqual([sid('blank'), sid('blank'), sid('blank')]) + }) + + it('does not join an earlier Workspace connection that a different preset request superseded', async () => { + const earliest = Promise.withResolvers() + const b = bench({ + sessions: sessionState([summary('blank', { blank: true, cwd: '/w/a' })], 'pending'), + workspaces: workspaceState([workspace('a', [sid('blank')])]), + configureSessions: (sessions) => { sessions.create.mockReturnValueOnce(earliest.promise) }, + }) + const plain = b.uiWorkspace.connectWorkspace(wid('a')) + const creator = b.uiWorkspace.connectWorkspace(wid('a'), { agentPreset: 'ptc' }) + const latest = b.uiWorkspace.connectWorkspace(wid('a')) + expect(b.sessions.create.mock.calls).toEqual([ + [{ workspaceId: wid('a'), sessionId: sid('blank') }], + [{ workspaceId: wid('a'), sessionId: sid('blank'), agentPreset: 'ptc' }], + [{ workspaceId: wid('a'), sessionId: sid('blank') }], + ]) + earliest.resolve(sid('blank')) + await expect(Promise.all([plain, creator, latest])).resolves.toEqual([sid('blank'), sid('blank'), sid('blank')]) }) it.each(['workspace', 'panel'])('does not let saved blank restoration replace a later %s navigation', async (target) => { diff --git a/packages/client/ui-workspace/tsconfig.json b/packages/client/ui-workspace/tsconfig.json index ab3b3c6025..0bf315d56f 100644 --- a/packages/client/ui-workspace/tsconfig.json +++ b/packages/client/ui-workspace/tsconfig.json @@ -11,6 +11,9 @@ { "path": "../../api/session-controller/tsconfig.client.json" }, + { + "path": "../../preset/agent-preset-registry" + }, { "path": "../../api/workspace-controller/tsconfig.client.json" }, diff --git a/packages/client/ui-workspace/tsdown.config.ts b/packages/client/ui-workspace/tsdown.config.ts index c4bb255e57..7aa03cebc1 100644 --- a/packages/client/ui-workspace/tsdown.config.ts +++ b/packages/client/ui-workspace/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-client-ui-workspace', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/web/README.i18n.yaml b/packages/client/web/README.i18n.yaml index bc5ef996f5..7037ec70a4 100644 --- a/packages/client/web/README.i18n.yaml +++ b/packages/client/web/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-web/use-this-package: - en: 0c8b98946feedb0f - zh: ae10ae7b9ecbf89c + en: 8778e166024b9628 + zh: 777d6923db199337 /deepseek-ai-dsh-client-web/use-this-package/what-boot-looks-like: en: f3b01aa878764e5c zh: f02eab65d441bfe0 diff --git a/packages/client/web/README.md b/packages/client/web/README.md index 5278ad3ccb..42b6c63efc 100644 --- a/packages/client/web/README.md +++ b/packages/client/web/README.md @@ -31,6 +31,8 @@ Static application pages install `__DSH_BOOT_READY__` before the entry runs. The The shell base styles apply automatic CJK/Latin spacing to ordinary content in supporting browsers. Semantic code and terminal, diff, read, and search output containers retain literal source spacing and column alignment; browsers without `text-autospace` support ignore both declarations. +Web and Desktop mathematical rendering requires WOFF2 support. The [Web build](../../../apps/web/katex-fonts.ts) retains every KaTeX font face in WOFF2 and omits WOFF/TTF fallbacks; a face without WOFF2 rejects the build. Font glyphs, weights, styles, and layout rules are preserved. + ### What boot looks like Boot runs in two stages: the module stage adopts the parser-loaded bootstrap batch, builds the module system from the Host-provided boot graph, and prefetches the `immediately` tier through the shared application-batch URL, which executes once. The plugin stage then activates every graph entry and waits for all of them before handing the marked boot DOM to the UI renderer, which hydrates it and switches to the complete UI. diff --git a/packages/client/web/README.zh.md b/packages/client/web/README.zh.md index ccaef3e558..31ff77c606 100644 --- a/packages/client/web/README.zh.md +++ b/packages/client/web/README.zh.md @@ -31,6 +31,8 @@ kind: "package-library" 外壳基础样式会在支持的浏览器中为普通内容自动添加中西文间距。语义化代码以及终端、diff、读取和搜索输出容器会保留源码中的原始间距和列对齐;不支持 `text-autospace` 的浏览器会忽略这两项声明。 +Web 和 Desktop 的数学公式渲染要求支持 WOFF2。[Web 构建](../../../apps/web/katex-fonts.ts)以 WOFF2 保留全部 KaTeX 字体样式,并排除 WOFF/TTF 后备格式;任一字体样式缺少 WOFF2 都会使构建失败。字体的字形、字重、样式和布局规则保持不变。 + ### 启动过程是怎样的 启动分两个阶段:模块阶段接纳 parser 已加载的 bootstrap 批次,从 Host 提供的启动图构建模块系统,并通过只执行一次的共享 application 批次 URL 预取 `immediately` 层级。插件阶段随后激活每个图 entry 并等待全部就绪,之后才把带标记的启动 DOM 交给 UI 渲染器,由它 hydrate 并切换到完整 UI。 diff --git a/packages/client/web/package.json b/packages/client/web/package.json index e3733a87e5..01e929ffe7 100644 --- a/packages/client/web/package.json +++ b/packages/client/web/package.json @@ -34,8 +34,6 @@ "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0", diff --git a/packages/client/web/tsdown.config.ts b/packages/client/web/tsdown.config.ts index 0e55d8d080..862901c133 100644 --- a/packages/client/web/tsdown.config.ts +++ b/packages/client/web/tsdown.config.ts @@ -1,6 +1,6 @@ import { staticLinked } from '../tsdown.client.ts' export default staticLinked( - '@deepseek-ai/dsh-client-web', + import.meta.dirname, ['lib/types/index.js', 'lib/types/apply-injections.js'], ) diff --git a/packages/compaction/command-compact/locale/en.json b/packages/compaction/command-compact/locale/en.json new file mode 100644 index 0000000000..6a900164f6 --- /dev/null +++ b/packages/compaction/command-compact/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "command-compact" + } +} diff --git a/packages/compaction/command-compact/locale/zh.json b/packages/compaction/command-compact/locale/zh.json new file mode 100644 index 0000000000..a2145890a2 --- /dev/null +++ b/packages/compaction/command-compact/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "上下文压缩命令", + "description": "让用户通过命令主动压缩当前会话上下文。" + } +} diff --git a/packages/compaction/command-compact/package.json b/packages/compaction/command-compact/package.json index 9dbee619ef..3f83a85414 100644 --- a/packages/compaction/command-compact/package.json +++ b/packages/compaction/command-compact/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/compaction/compaction-basic/locale/en.json b/packages/compaction/compaction-basic/locale/en.json new file mode 100644 index 0000000000..78fd31f32f --- /dev/null +++ b/packages/compaction/compaction-basic/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "compaction-basic" + } +} diff --git a/packages/compaction/compaction-basic/locale/zh.json b/packages/compaction/compaction-basic/locale/zh.json new file mode 100644 index 0000000000..352616d5fe --- /dev/null +++ b/packages/compaction/compaction-basic/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "上下文压缩", + "description": "在上下文达到阈值时,使用模型总结历史内容。" + } +} diff --git a/packages/compaction/compaction-basic/package.json b/packages/compaction/compaction-basic/package.json index ae066a2059..67f90972ba 100644 --- a/packages/compaction/compaction-basic/package.json +++ b/packages/compaction/compaction-basic/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/compaction/compaction-image-offload/locale/en.json b/packages/compaction/compaction-image-offload/locale/en.json new file mode 100644 index 0000000000..8cfed647b9 --- /dev/null +++ b/packages/compaction/compaction-image-offload/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "compaction-image-offload" + } +} diff --git a/packages/compaction/compaction-image-offload/locale/zh.json b/packages/compaction/compaction-image-offload/locale/zh.json new file mode 100644 index 0000000000..87047960d2 --- /dev/null +++ b/packages/compaction/compaction-image-offload/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "历史图片卸载", + "description": "将超出模型图片预算的历史图片替换为附件引用,再重试请求。" + } +} diff --git a/packages/compaction/compaction-image-offload/package.json b/packages/compaction/compaction-image-offload/package.json index 5f205b61f5..c0e0435ad6 100644 --- a/packages/compaction/compaction-image-offload/package.json +++ b/packages/compaction/compaction-image-offload/package.json @@ -22,9 +22,11 @@ "./projection": { "types": "./lib/types/projection.d.ts", "default": "./lib/types/projection.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/compaction/compaction-tool-result-pruner/locale/en.json b/packages/compaction/compaction-tool-result-pruner/locale/en.json new file mode 100644 index 0000000000..ad406873b1 --- /dev/null +++ b/packages/compaction/compaction-tool-result-pruner/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "compaction-tool-result-pruner" + } +} diff --git a/packages/compaction/compaction-tool-result-pruner/locale/zh.json b/packages/compaction/compaction-tool-result-pruner/locale/zh.json new file mode 100644 index 0000000000..bfe5aa3a57 --- /dev/null +++ b/packages/compaction/compaction-tool-result-pruner/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具结果精简", + "description": "在上下文压力较大时,精简过长的工具输出并保留首尾内容。" + } +} diff --git a/packages/compaction/compaction-tool-result-pruner/package.json b/packages/compaction/compaction-tool-result-pruner/package.json index d5947bd324..4ba34defc8 100644 --- a/packages/compaction/compaction-tool-result-pruner/package.json +++ b/packages/compaction/compaction-tool-result-pruner/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/context/README.i18n.yaml b/packages/context/README.i18n.yaml index 0aa51cfac3..89e1b24992 100644 --- a/packages/context/README.i18n.yaml +++ b/packages/context/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /context-request-context-plugins/packages: - en: e2fccdf2ec112e9c - zh: 3f6ff79970796bcc + en: 662b691a371ae95f + zh: c03a505eba42eaa2 /context-request-context-plugins/related-documentation: en: 1d8d028a1ca69991 zh: 32f261bb380e0812 diff --git a/packages/context/README.md b/packages/context/README.md index 3ddd0c5105..a5c2326b94 100644 --- a/packages/context/README.md +++ b/packages/context/README.md @@ -30,6 +30,7 @@ The context group provides plugins that add model-visible context to each reques | [`file-reference-local/`](file-reference-local/README.md) | Local-workspace completion provider for `@file` mentions | — | | [`time-context/`](time-context/README.md) | Current time, browser zone, and elapsed time per step | — | | [`tmux-context/`](tmux-context/README.md) | The agent's tmux session, window, and pane location | — | +| [`harness-dev-context/`](harness-dev-context/README.md) | The harness checkout and Web GUI URL as runtime context, keeping the system prompt stable across processes | — | ----- diff --git a/packages/context/README.zh.md b/packages/context/README.zh.md index 98b4133036..c8550a77ac 100644 --- a/packages/context/README.zh.md +++ b/packages/context/README.zh.md @@ -30,6 +30,7 @@ context 组提供不定义任何工具、为每次请求添加模型可见上下 | [`file-reference-local/`](file-reference-local/README.zh.md) | `@file` 提及的本地工作区补全提供方 | — | | [`time-context/`](time-context/README.zh.md) | 每个步骤的当前时间、浏览器时区与经过时长 | — | | [`tmux-context/`](tmux-context/README.zh.md) | agent 所在的 tmux 会话、窗口与窗格位置 | — | +| [`harness-dev-context/`](harness-dev-context/README.zh.md) | 以运行时上下文给出 harness checkout 与 Web GUI URL,使系统提示词跨进程保持稳定 | — | ----- diff --git a/packages/context/agent-instructions/locale/en.json b/packages/context/agent-instructions/locale/en.json new file mode 100644 index 0000000000..816d9020ab --- /dev/null +++ b/packages/context/agent-instructions/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-instructions" + } +} diff --git a/packages/context/agent-instructions/locale/zh.json b/packages/context/agent-instructions/locale/zh.json new file mode 100644 index 0000000000..0bb7fd9f4c --- /dev/null +++ b/packages/context/agent-instructions/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区指令加载", + "description": "读取 AGENTS.md、CLAUDE.md 等文件,为 AI 提供工作区规则。" + } +} diff --git a/packages/context/agent-instructions/package.json b/packages/context/agent-instructions/package.json index 1f090de17d..cd365762ac 100644 --- a/packages/context/agent-instructions/package.json +++ b/packages/context/agent-instructions/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/context/file-reference-local/locale/en.json b/packages/context/file-reference-local/locale/en.json new file mode 100644 index 0000000000..bdb13b8300 --- /dev/null +++ b/packages/context/file-reference-local/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "file-reference-local" + } +} diff --git a/packages/context/file-reference-local/locale/zh.json b/packages/context/file-reference-local/locale/zh.json new file mode 100644 index 0000000000..3762795210 --- /dev/null +++ b/packages/context/file-reference-local/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "本地文件引用", + "description": "提供本地文件的搜索和引用能力。" + } +} diff --git a/packages/context/file-reference-local/package.json b/packages/context/file-reference-local/package.json index b59ef051f3..25ff5de92c 100644 --- a/packages/context/file-reference-local/package.json +++ b/packages/context/file-reference-local/package.json @@ -23,9 +23,11 @@ "default": "./lib/types/search.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/context/harness-dev-context/README.i18n.yaml b/packages/context/harness-dev-context/README.i18n.yaml new file mode 100644 index 0000000000..adc0b95c0e --- /dev/null +++ b/packages/context/harness-dev-context/README.i18n.yaml @@ -0,0 +1,67 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/context/harness-dev-context/README.md +/: + en: 8fed567b18e9dfa2 + zh: 2ab54db218cc0197 +/deepseek-ai-dsh-harness-dev-context: + en: b47701c093269adb + zh: e147a06ec0d6047f +/deepseek-ai-dsh-harness-dev-context/summary: + en: daf618174270461e + zh: 4c5b56fe4380c91f +/deepseek-ai-dsh-harness-dev-context/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-harness-dev-context/use-this-package: + en: d3192709a416f7fb + zh: 479253a5ae1adcb2 +/deepseek-ai-dsh-harness-dev-context/use-this-package/what-the-model-gets: + en: d9f5b11af33b3eb8 + zh: fc96b972503a0b99 +/deepseek-ai-dsh-harness-dev-context/use-this-package/sessions-from-earlier-releases: + en: d810950db5118265 + zh: d20e3965fa78e0f8 +/deepseek-ai-dsh-harness-dev-context/understand-the-implementation: + en: 2d21fa2aad5a729d + zh: cfbfada0eb647435 +/deepseek-ai-dsh-harness-dev-context/understand-the-implementation/design-concept: + en: 401a852a3444aff4 + zh: 5288a593f61c168b +/deepseek-ai-dsh-harness-dev-context/understand-the-implementation/source-map: + en: 4696b6c3a1f91f96 + zh: 3a56d257ec768a5e +/deepseek-ai-dsh-harness-dev-context/understand-the-implementation/main-flow: + en: f3844a1825b2e329 + zh: bdcafbcadbc6d316 +/deepseek-ai-dsh-harness-dev-context/further-exploration: + en: f291741c499581ac + zh: 8ee0baef51e69ef0 +/deepseek-ai-dsh-harness-dev-context/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-harness-dev-context/model-experience/harness-checkout-and-web-gui: + en: ddbe5927f55a6275 + zh: 1687795c41c16a8c +/deepseek-ai-dsh-harness-dev-context/model-experience/harness-checkout-and-web-gui/what-the-model-sees: + en: f3236c45cf5bc3a6 + zh: 1a3499b2e21f4761 +/deepseek-ai-dsh-harness-dev-context/model-experience/harness-checkout-and-web-gui/what-the-model-sees/system-prompt-paragraphs: + en: c6c9fa4caf6f2f30 + zh: f501149c17c0ea60 +/deepseek-ai-dsh-harness-dev-context/model-experience/harness-checkout-and-web-gui/what-the-model-sees/runtime-context-lines: + en: 37680cbe3eaabef5 + zh: 8c1b432ddf7d20b5 +/deepseek-ai-dsh-harness-dev-context/model-experience/harness-checkout-and-web-gui/token-effect: + en: 2c629df08d801b36 + zh: 437d43a9c5fdc68a +/deepseek-ai-dsh-harness-dev-context/model-experience/harness-checkout-and-web-gui/kv-cache-effect: + en: e8f89a14bd36dae0 + zh: bd4ec43e07e234c9 +/deepseek-ai-dsh-harness-dev-context/known-limitations-and-deferred-work: + en: 558945e2f537db5b + zh: f584fcde6275c2da +/deepseek-ai-dsh-harness-dev-context/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/context/harness-dev-context/README.md b/packages/context/harness-dev-context/README.md new file mode 100644 index 0000000000..04d3925181 --- /dev/null +++ b/packages/context/harness-dev-context/README.md @@ -0,0 +1,132 @@ +--- +description: "Model context for users and maintainers of the Web GUI that names the DeepSeek Harness checkout and GUI URL without letting either change the system prompt." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-harness-dev-context + +English | [中文](README.zh.md) + +## Summary + +`dsh-harness-dev-context` tells an agent running behind the DeepSeek Harness Web GUI where the harness implementation checkout lives, how the GUI relates to "this page", and which URL serves it. The system prompt carries only value-free guidance; the current checkout path and GUI URL arrive as runtime context, so starting the process from another checkout, port, or installation never rewrites a Session's logged system prompt. Sessions whose prompt still embeds those values from earlier releases keep that text verbatim. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +The shipped Web bundle mounts this plugin as its `harness-dev-context` row. Disable that row in a profile patch when the agent should not learn the harness checkout or GUI URL. The plugin takes no configuration and activates only where every injected service exists: `systemPrompt`, `sessionProjections`, and the `webApp` service of the Web runtime, so `--help` and non-Web compositions never mount it. + +### What the model gets + +Two system-prompt sections explain that the checkout differs from the working directory and that "this page" means this GUI, together with the GUI update contract. Two runtime-context lines state the current values: the installation root four directories above this package, and the Web GUI's advertised URL from `webApp.getAdvertisedUrl()`, the same value as `DSH_WEB_URL` and the startup URL. Runtime context follows the shared snapshot rules: an unchanged value adds nothing, and a changed one appends a snapshot before the step's input instead of rewriting earlier messages. + +### Sessions from earlier releases + +Earlier releases embedded both values in the system prompt. When a Session's latest nonempty system prompt still contains those exact paragraphs, the sections repeat them verbatim, old values included, so upgrading and later port or checkout changes leave that Session's prompt byte-identical; the runtime-context lines still give the current values. Text that only resembles an earlier paragraph receives the current guidance. + +----- + + +## Understand the implementation + +

+Implementation internals — click to expand + +This section explains the design of the plugin; the observable behavior is covered in [Use this package](#use-this-package). + +### Design concept + +A host-only session projection, `harnessDevLegacyPrompt`, folds every committed nonempty `system/message` into the earlier-format paragraphs it contains, matched by their fixed text around the value on one line. The section text providers read that state through `AssembleContext.agent`; assemblies without an agent use the current guidance. The projection is restored with every other unit when a Session resumes, so no historical event is read synchronously. + +### Source map + +| File | Role | +|---|---| +| [`src/index.ts`](src/index.ts) | Plugin entry: sections, runtime contexts, earlier-format projection | + +### Main flow + +Activation registers the projection unit, both sections, and both contexts. At each assembly the sections choose the admitted earlier paragraph or the current guidance; at each request admission the contexts read the advertised URL. Disposing the plugin fiber removes every registration. + +
+ +----- + + +## Further Exploration + +Read these pages when the package-level contract is not enough. They move from the decision record to the services this plugin reads. + +- [Process-specific values as runtime context](../../../.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.md) — why the values left the system prompt and how earlier Sessions stay stable. +- [Session projections subsystem](../../../docs/subsystems/session-projection.md) — the projection contract the earlier-format state uses. +- [Web app bundle](../../bundle/web-app/README.md) — the `webApp` service and the row that mounts this plugin. +- [Context group map](../README.md) — sibling request-context packages. + +----- + + +## Model Experience + +### Harness checkout and Web GUI + +#### What the model sees + +Two system-prompt paragraphs at first-party orders 10000 and 10100, after reusable instructions, and two runtime-context lines at context orders 200 and 210. A Session admitted under an earlier release sees its own earlier paragraphs instead of the two below. + +##### System-prompt paragraphs + +```markdown +The runtime context names the DeepSeek Harness implementation checkout. The checkout location and current working directory are separate values and may differ; never infer the working directory from the checkout path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself. + +You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. The browser provides no implicit DOM, route, or screenshot context. The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. Starting another server does not update this GUI. The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL. +``` + +##### Runtime-context lines + +```markdown +Current DeepSeek Harness implementation checkout: "". + +Current DeepSeek Harness Web GUI URL: "". +``` + +#### Token effect + +Two prompt paragraphs per Session and two lines in each runtime-context snapshot. A changed checkout or URL adds one snapshot. + +#### KV Cache effect + +The system prompt is identical across checkouts, ports, and installations, so a process started elsewhere leaves the cached prefix intact; a changed value appends one runtime-context snapshot after it. + +## Known Limitations and Deferred Work + + + +These limits describe what the stability guarantee covers. They are current package constraints. + +- **Two paragraphs only** — other system-prompt text that changes between releases still rewrites the first system message on routes without in-history prompt updates. +- **Earlier values stay** — an earlier-format Session keeps its old checkout path and URL in the system prompt for its whole lifetime; only the later runtime-context lines are current. +- **Mixed releases** — a release without this package rewrites the first system message of a Session started with it, so every checkout that serves a shared `DSH_HOME` needs this package before they alternate. +- **Optional values** — the two runtime-context lines are optional, so a custom persona that sets `includeRuntimeContext: false` without `complete: true` keeps the sections that point at values its requests never carry. The shipped `minimal` persona sets both. +- **Sessions without the sections** — a Session created while `surfaceContext: false` hid both paragraphs has neither in its log, so the first resumed request adds the new sections and rewrites the first system message on routes without in-history prompt updates. +- **One earlier wording** — the projection recognizes the paragraphs as the release immediately before this package rendered them; a Session holding an older wording gets the current guidance. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/context/harness-dev-context/README.zh.md b/packages/context/harness-dev-context/README.zh.md new file mode 100644 index 0000000000..e108c6f161 --- /dev/null +++ b/packages/context/harness-dev-context/README.zh.md @@ -0,0 +1,132 @@ +--- +description: "面向 Web GUI 用户与维护者的模型上下文:给出 DeepSeek Harness checkout 与 GUI URL,且两者都不会改变系统提示词。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-harness-dev-context + +[English](README.md) | 中文 + +## 概述 + +`dsh-harness-dev-context` 告诉运行在 DeepSeek Harness Web GUI 背后的 agent:harness 实现 checkout 在哪里、GUI 与「this page」是什么关系,以及哪个 URL 提供该 GUI。系统提示词只包含不含值的说明;当前 checkout 路径与 GUI URL 以运行时上下文送达,因此从别的 checkout、端口或安装位置启动进程,绝不会改写会话已记录的系统提示词。提示词仍嵌有早期版本这些值的会话会原样保留那段文本。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +随附的 Web bundle 以 `harness-dev-context` 行挂载此插件。不希望 agent 得知 harness checkout 或 GUI URL 时,在 profile patch 中禁用该行。插件不接受配置,只在每个注入服务都存在时激活:`systemPrompt`、`sessionProjections`,以及 Web 运行时的 `webApp` 服务,因此 `--help` 与非 Web 组合永远不会挂载它。 + +### 模型得到什么 + +两个系统提示词段落说明 checkout 与工作目录不同、「this page」指此 GUI,并给出 GUI 的更新约定。两行运行时上下文给出当前值:本包上方四层目录处的安装根,以及 `webApp.getAdvertisedUrl()` 给出的 Web GUI 公告 URL,与 `DSH_WEB_URL` 和启动 URL 相同。运行时上下文遵循共享的快照规则:值不变不追加内容,值变化时在本步输入之前追加一份快照,而不是改写更早的消息。 + +### 早期版本的会话 + +早期版本把两个值都嵌在系统提示词里。会话最新的非空系统提示词仍含那两段原文时,两个段落会原样重复它们(包括旧值),因此升级以及之后更换端口或 checkout 都不会改变该会话提示词的任何字节;运行时上下文行仍给出当前值。只是看起来像早期段落的文本会得到当前说明。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +本节解释插件的设计;可观察行为见[使用本包](#use-this-package)。 + +### 设计思路 + +仅限宿主的会话投影 `harnessDevLegacyPrompt` 把每个已提交的非空 `system/message` 折叠为其中包含的早期格式段落,按值两侧的固定文本在同一行内匹配。段落文本提供函数通过 `AssembleContext.agent` 读取该状态;没有 agent 的组装使用当前说明。会话恢复时该投影与其他单元一起恢复,因此不同步读取任何历史事件。 + +### 源码地图 + +| 文件 | 职责 | +|---|---| +| [`src/index.ts`](src/index.ts) | 插件入口:段落、运行时上下文、早期格式投影 | + +### 主流程 + +激活时注册投影单元、两个段落与两个上下文。每次组装时,段落在已提交的早期段落与当前说明之间选择;每次请求准入时,上下文读取公告 URL。销毁插件 fiber 会移除全部注册。 + +
+ +----- + + +## 进一步探索 + +包级约定不够用时阅读这些页面。它们从决策记录走到本插件读取的服务。 + +- [进程相关值改走运行时上下文](../../../.agents/notes/implemented/bug-fix/2026-10-11-process-specific-prompt-values-in-runtime-context.zh.md)——这些值为什么离开系统提示词,以及早期会话如何保持稳定。 +- [会话投影子系统](../../../docs/subsystems/session-projection.zh.md)——早期格式状态使用的投影约定。 +- [Web app bundle](../../bundle/web-app/README.zh.md)——`webApp` 服务与挂载本插件的行。 +- [Context 组地图](../README.zh.md)——同组的请求上下文包。 + +----- + + +## 模型体验 + +### Harness checkout 与 Web GUI + +#### 模型看到什么 + +两个系统提示词段落,位于可复用指令之后的第一方顺序 10000 与 10100;两行运行时上下文,位于上下文顺序 200 与 210。在早期版本下提交过提示词的会话看到的是自己的早期段落,而不是下面两段。 + +##### 系统提示词段落 + +```markdown +The runtime context names the DeepSeek Harness implementation checkout. The checkout location and current working directory are separate values and may differ; never infer the working directory from the checkout path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself. + +You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. The browser provides no implicit DOM, route, or screenshot context. The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while `pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. Starting another server does not update this GUI. The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL. +``` + +##### 运行时上下文行 + +```markdown +Current DeepSeek Harness implementation checkout: "". + +Current DeepSeek Harness Web GUI URL: "". +``` + +#### Token 影响 + +每个会话两段提示词,每份运行时上下文快照两行。checkout 或 URL 变化时追加一份快照。 + +#### KV Cache 影响 + +系统提示词在不同 checkout、端口与安装位置下完全相同,因此在别处启动的进程不会破坏已缓存的前缀;值变化时在其后追加一份运行时上下文快照。 + +## 已知限制与延期工作 + + + +这些限制说明稳定性保证覆盖哪些内容。它们是当前包约束。 + +- **只覆盖两段**——版本之间变化的其他系统提示词文本,在不支持 in-history 提示词更新的路由上仍会改写第一条 system 消息。 +- **早期值保留**——早期格式会话在整个生命周期内都在系统提示词里保留旧 checkout 路径与 URL;只有之后的运行时上下文行是当前值。 +- **混用版本**——不含本包的版本会改写以本包启动的会话的第一条 system 消息,因此共用同一 `DSH_HOME` 的每个 checkout 都需要先包含本包,才能交替运行。 +- **可选值**——两行运行时上下文是可选的,因此设置 `includeRuntimeContext: false` 但未设置 `complete: true` 的自定义 persona 会保留指向其请求从不携带之值的段落。随附的 `minimal` persona 两者都设置。 +- **没有段落的会话**——在 `surfaceContext: false` 隐藏两段时创建的会话,日志中两段都没有,因此恢复后的第一个请求会加入新段落,并在不支持 in-history 提示词更新的路由上改写第一条 system 消息。 +- **只认一版早期措辞**——投影按本包之前紧邻的版本渲染的段落识别;保存更早措辞的会话会得到当前说明。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +无。 + +
diff --git a/packages/context/harness-dev-context/package.json b/packages/context/harness-dev-context/package.json new file mode 100644 index 0000000000..6a54e0f994 --- /dev/null +++ b/packages/context/harness-dev-context/package.json @@ -0,0 +1,49 @@ +{ + "name": "@deepseek-ai/dsh-harness-dev-context", + "description": "Model context naming the DeepSeek Harness checkout and Web GUI URL without letting either change the system prompt", + "version": "0.2.1-alpha.2", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/context/harness-dev-context" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts" + ], + "license": "MIT", + "dependencies": { + "zod": "4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-web-app": "workspace:*" + } +} diff --git a/packages/context/harness-dev-context/src/index.ts b/packages/context/harness-dev-context/src/index.ts new file mode 100644 index 0000000000..becb4a6005 --- /dev/null +++ b/packages/context/harness-dev-context/src/index.ts @@ -0,0 +1,165 @@ +/** + * @deepseek-ai/dsh-harness-dev-context — model context for an agent that can + * inspect and extend the DeepSeek Harness serving its Web GUI. It registers + * path- and URL-free prompt sections and states the current implementation + * checkout and Web GUI URL as runtime context, so a process started from + * another checkout, port, or installation leaves the system prompt unchanged. + * A Session whose admitted prompt holds the paragraphs that embedded those + * values keeps them verbatim, so resuming it never rewrites its logged prompt. + * @module @deepseek-ai/dsh-harness-dev-context + */ + +import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import { z as zod } from 'zod' +import type {} from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-web-app' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-session-projection' +import type { AssembleContext } from '@deepseek-ai/dsh-system-prompt' + +/** Stable Cordis plugin name. */ +export const name = 'harness-dev-context' + +/** Prompt registries, the projection registry, and the Web GUI whose URL the model learns. */ +export const inject = ['systemPrompt', 'sessionProjections', 'webApp'] + +/** This installation's root, four directories above this package's source or built entry. */ +const SOURCE_ROOT = fileURLToPath(new URL('../../../..', import.meta.url)) + +/** Prompt-section and runtime-context name for the implementation checkout. */ +const HARNESS_SOURCE = 'harness:source' + +/** Prompt-section and runtime-context name for the Web GUI orientation and its URL. */ +const WEB_SURFACE = 'app:web-surface' + +const HARNESS_SOURCE_GUIDANCE = 'The checkout location and current working directory are separate values and may differ; ' + + 'never infer the working directory from the checkout path. Use pwd to determine the current working directory. ' + + 'Use this checkout only to inspect or extend DSH itself.' + +const HARNESS_SOURCE_PROMPT = `The runtime context names the DeepSeek Harness implementation checkout. ${HARNESS_SOURCE_GUIDANCE}` + +const WEB_SURFACE_GUIDANCE = 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. ' + + 'The browser provides no implicit DOM, route, or screenshot context. ' + + 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while ' + + '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. ' + + 'Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. ' + + 'Starting another server does not update this GUI. ' + + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. ' + + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.' + +const WEB_SURFACE_PROMPT = `You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. ${WEB_SURFACE_GUIDANCE}` + +/** + * Fixed text around the value in each paragraph that embedded it, frozen as + * those releases rendered it: never edit these together with the current + * guidance, or Sessions holding the earlier paragraphs stop matching and + * rewrite their logged prompt. + */ +const LEGACY_SOURCE = { + prefix: 'The DeepSeek Harness implementation checkout is at ', + suffix: '. The checkout location and current working directory are separate values and may differ; ' + + 'never infer the working directory from this path. Use pwd to determine the current working directory. ' + + 'Use this checkout only to inspect or extend DSH itself.', +} +// The frozen copy repeats today's guidance on purpose; the two may diverge. +/* jscpd:ignore-start */ +const LEGACY_WEB_SURFACE = { + prefix: 'You are interacting with the user through the DeepSeek Harness Web GUI at ', + suffix: '. When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. ' + + 'The browser provides no implicit DOM, route, or screenshot context. ' + + 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while ' + + '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. ' + + 'Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. ' + + 'Starting another server does not update this GUI. ' + + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. ' + + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.', +} +/* jscpd:ignore-end */ + +/** Host-only projection key of the value-bearing paragraphs a Session admitted. */ +const LEGACY_PROMPT = 'harnessDevLegacyPrompt' + +const legacyPromptSchema = zod.object({ source: zod.string().nullable(), web: zod.string().nullable() }) + +/** Value-bearing paragraphs of the latest nonempty system prompt a Session committed; `null` where it has none. */ +type LegacyPrompt = zod.infer + +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionStateMap { + /** Value-bearing harness-source and Web-surface paragraphs of the latest nonempty admitted system prompt. */ + harnessDevLegacyPrompt: LegacyPrompt + } +} + +/** The complete single-line paragraph between `prefix` and `suffix`, or `null` when the prompt has none. */ +function legacyParagraph(prompt: string, { prefix, suffix }: { prefix: string; suffix: string }): string | null { + const start = prompt.indexOf(prefix) + if (start < 0) return null + const end = prompt.indexOf(suffix, start + prefix.length) + if (end < 0) return null + const paragraph = prompt.slice(start, end + suffix.length) + return paragraph.includes('\n') ? null : paragraph +} + +/** + * Fold one committed event into the admitted paragraphs. Like the loop's own + * prompt-version reading, only a single nonempty text block is a prompt + * version; an emptied or other version keeps the previous state, because a + * series consolidation can log only the emptied later version. + */ +function foldLegacyPrompt(state: LegacyPrompt, event: SessionEvent): LegacyPrompt { + if (event.type !== 'system/message') return state + const { content } = event.data.message + const [block] = content + if (content.length !== 1 || block?.type !== 'text' || block.text === '') return state + const source = legacyParagraph(block.text, LEGACY_SOURCE) + const web = legacyParagraph(block.text, LEGACY_WEB_SURFACE) + return source === state.source && web === state.web ? state : { source, web } +} + +const ADMITS_NOTHING: LegacyPrompt = { source: null, web: null } + +/** + * Register the two sections, their runtime-context values, and the + * projection that keeps a Session's admitted paragraphs. + * @param ctx - plugin context with every {@link inject} service. + */ +export function apply(ctx: Context): void { + ctx.sessionProjections.register({ + key: LEGACY_PROMPT, + stateVersion: 1, + stateSchema: legacyPromptSchema, + init: () => ADMITS_NOTHING, + apply: foldLegacyPrompt, + }) + const admitted = (context: AssembleContext): LegacyPrompt => { + const session = context.agent?.session + // This plugin registers the unit above, so its state exists for every Session. + return session === undefined ? ADMITS_NOTHING : ctx.sessionProjections.stateOf(session, LEGACY_PROMPT) as LegacyPrompt + } + ctx.systemPrompt.section({ + name: HARNESS_SOURCE, + order: ctx.systemPrompt.getSectionOrder('HARNESS_SOURCE'), + interpolate: false, + text: context => admitted(context).source ?? HARNESS_SOURCE_PROMPT, + }) + ctx.systemPrompt.context({ + name: HARNESS_SOURCE, + order: ctx.systemPrompt.getContextOrder('HARNESS_SOURCE'), + interpolate: false, + text: `Current DeepSeek Harness implementation checkout: ${JSON.stringify(SOURCE_ROOT)}.`, + }) + ctx.systemPrompt.section({ + name: WEB_SURFACE, + order: ctx.systemPrompt.getSectionOrder('WEB_SURFACE'), + interpolate: false, + text: context => admitted(context).web ?? WEB_SURFACE_PROMPT, + }) + ctx.systemPrompt.context({ + name: WEB_SURFACE, + order: ctx.systemPrompt.getContextOrder('WEB_SURFACE'), + interpolate: false, + text: () => `Current DeepSeek Harness Web GUI URL: ${JSON.stringify(ctx.webApp.getAdvertisedUrl())}.`, + }) +} diff --git a/packages/context/harness-dev-context/tests/harness-dev-context.spec.ts b/packages/context/harness-dev-context/tests/harness-dev-context.spec.ts new file mode 100644 index 0000000000..0538895c52 --- /dev/null +++ b/packages/context/harness-dev-context/tests/harness-dev-context.spec.ts @@ -0,0 +1,230 @@ +/** Prompt stability of the harness checkout and Web GUI URL across processes, checkouts, and ports. */ + +import { describe, expect, it, onTestFinished } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' +import { + createUserMessage, LlmAdapter, + type GenerateOptions, type LlmResolvedModelInfo, type StreamChunk, type SystemPromptUpdate, +} from '@deepseek-ai/dsh-llm' +import { SessionId, type Session } from '@deepseek-ai/dsh-session' +import { renderContextSnapshot, renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import * as HarnessDevContext from '../src/index.ts' + +const SOURCE_PROMPT = 'The runtime context names the DeepSeek Harness implementation checkout. The checkout location and current working directory are separate values and may differ; never infer the working directory from the checkout path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself.' +const WEB_GUIDANCE = 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. ' + + 'The browser provides no implicit DOM, route, or screenshot context. ' + + 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while ' + + '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. ' + + 'Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. ' + + 'Starting another server does not update this GUI. ' + + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. ' + + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.' +const WEB_PROMPT = `You are interacting with the user through the DeepSeek Harness Web GUI whose URL the runtime context names. ${WEB_GUIDANCE}` + +/** The value-bearing paragraphs earlier releases rendered. */ +const LEGACY_SOURCE = 'The DeepSeek Harness implementation checkout is at /old/checkout/. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself.' +// Frozen as earlier releases rendered it, independent of the current guidance. +const LEGACY_WEB = 'You are interacting with the user through the DeepSeek Harness Web GUI at http://127.0.0.1:3100. ' + + 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. ' + + 'The browser provides no implicit DOM, route, or screenshot context. ' + + 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while ' + + '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. ' + + 'Every other change — the apps/web shell and plain packages — requires rebuilding the affected Web artifacts and verifying this existing URL after a page refresh. ' + + 'Starting another server does not update this GUI. ' + + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. ' + + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.' + +/** Records every request and answers each with one short text reply. */ +class RecordingAdapter extends LlmAdapter { + readonly requests: GenerateOptions[] = [] + + constructor(private readonly systemPromptUpdate: SystemPromptUpdate | undefined) { + super() + } + + override resolveModel(provider: string, model: string): Promise { + return Promise.resolve({ + provider, id: model, name: model, + ...this.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: this.systemPromptUpdate }, + }) + } + + async * stream(options: GenerateOptions): AsyncIterable { + this.requests.push(options) + yield { type: 'block-start', index: 0, blockType: 'text' } + yield { type: 'text-delta', index: 0, text: 'ok' } + yield { type: 'block-end', index: 0, block: { type: 'text', text: 'ok' } } + yield { type: 'usage', usage: { inputTokens: 1, outputTokens: 1 } } + yield { type: 'finish', reason: { kind: 'stop' } } + } +} + +const ROUTE = { provider: 'route', model: 'model' } + +/** The Web GUI service with a port the test can move, as restarted processes see it. */ +function provideWebServices(ctx: Context): { port: number } { + const listener = { port: 4567 } + ctx.provide('webApp', { + getAdvertisedUrl: () => `http://127.0.0.1:${String(listener.port)}`, + } satisfies Context['webApp']) + return listener +} + +/** A production AgentLoop with this plugin mounted. */ +async function promptLoop(systemPromptUpdate: SystemPromptUpdate | undefined) { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const listener = provideWebServices(ctx) + await mountAgentLoopTestDependencies(ctx) + const adapter = new RecordingAdapter(systemPromptUpdate) + ctx.llm.registerAdapter([ROUTE.provider], adapter) + await ctx.plugin(HarnessDevContext) + const harness = await mountAgentLoopTestHarness(ctx) + /** Resume the Session's complete log under a new Agent, as a restarted process does. */ + const resume = async (session: Session, id: string): Promise => (await ctx.agents.create({ + sessionId: SessionId(id), agentOptions: ROUTE, seed: [...session.snapshotEvents()], + })).agent + /** One turn under an earlier release: the given paragraphs and no value contexts. */ + const earlierSession = async (source = LEGACY_SOURCE, web = LEGACY_WEB): Promise => { + const earlierRelease = ctx.on('system-prompt/assemble', async (_assembly, _context, next) => { + const assembly = await next() + return { + ...assembly, + sections: assembly.sections.map(section => section.name === 'harness:source' ? { ...section, text: source } + : section.name === 'app:web-surface' ? { ...section, text: web } : section), + contexts: assembly.contexts.filter(entry => entry.name !== 'harness:source' && entry.name !== 'app:web-surface'), + } + }) + const agent = await harness.create(SessionId('earlier'), ROUTE) + await send(agent, 'before the upgrade') + earlierRelease() + return agent + } + return { ctx, listener, adapter, harness, resume, earlierSession } +} + +async function send(agent: Agent, text: string): Promise { + agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } })) + await agent.whenIdle() +} + +/** Every committed system prompt version in event order; a cleared version is `''`. */ +function systemPrompts(session: Session): string[] { + return session.snapshotEvents().flatMap(event => event.type === 'system/message' + ? [event.data.message.content.map(block => block.type === 'text' ? block.text : '').join('')] + : []) +} + +function latestRuntimeContext(session: Session): string | undefined { + const event = session.snapshotEvents().findLast(entry => entry.type === 'user/message' + && entry.data.source.kind === 'runtime-context') + const block = event?.type === 'user/message' ? event.data.content[0] : undefined + return block?.type === 'text' ? block.text : undefined +} + +function requestSystemPrompts(request: GenerateOptions | undefined): string[] { + return (request?.messages ?? []).filter(message => message.role === 'system') + .flatMap(message => message.content.map(block => block.type === 'text' ? block.text : '')) +} + +describe('harness-dev-context', () => { + it('registers value-free sections and reports the checkout and Web GUI URL as runtime context', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + provideWebServices(ctx) + await mountAgentLoopTestDependencies(ctx) + const fiber = ctx.plugin(HarnessDevContext) + await fiber + const assembly = await ctx.systemPrompt.assemble() + expect(assembly.sections.filter(entry => entry.name === 'harness:source' || entry.name === 'app:web-surface') + .map(entry => entry.text)).toEqual([SOURCE_PROMPT, WEB_PROMPT]) + expect(renderPrompt(assembly)).not.toContain('127.0.0.1') + expect(renderContextSnapshot(assembly).split('\n\n').slice(1)).toEqual([ + expect.stringMatching(/^Current DeepSeek Harness implementation checkout: ".+"\.$/u), + 'Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:4567".', + ]) + + await fiber.dispose() + const disposed = await ctx.systemPrompt.assemble() + expect(disposed.sections.some(entry => entry.name === 'harness:source' || entry.name === 'app:web-surface')).toBe(false) + expect(disposed.contexts).toEqual([]) + }) + + it.each([ + { route: 'replace-only', systemPromptUpdate: undefined }, + { route: 'in-history', systemPromptUpdate: 'in-history' as const }, + ])('resumes an earlier-format Session on other ports without rewriting its system prompt ($route)', async ({ systemPromptUpdate }) => { + const h = await promptLoop(systemPromptUpdate) + const original = await h.earlierSession() + const logged = systemPrompts(original.session) + expect(logged).toHaveLength(1) + expect(logged[0]).toContain(LEGACY_SOURCE) + expect(logged[0]).toContain(LEGACY_WEB) + + let session = original.session + for (const port of [4568, 4569]) { + h.listener.port = port + const resumed = await h.resume(session, `earlier-on-${String(port)}`) + await send(resumed, `after the upgrade on ${String(port)}`) + expect(systemPrompts(resumed.session)).toEqual(logged) + expect(requestSystemPrompts(h.adapter.requests.at(-1))).toEqual(logged) + expect(latestRuntimeContext(resumed.session)) + .toContain(`Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:${String(port)}".`) + expect(latestRuntimeContext(resumed.session)).toContain('Current DeepSeek Harness implementation checkout: "') + session = resumed.session + } + }) + + it('keeps earlier paragraphs after a series consolidation empties a later prompt version', async () => { + const h = await promptLoop('in-history') + const resumed = await h.resume((await h.earlierSession()).session, 'earlier-consolidated') + const [earlier] = systemPrompts(resumed.session) + const update = h.ctx.systemPrompt.section({ name: 'test:update', order: 0, text: 'Updated instruction.' }) + await send(resumed, 'append the update') + expect(systemPrompts(resumed.session)).toHaveLength(2) + update() + h.ctx.on('agent/pre-step', async (_payload, next) => { + const decision = await next() + return decision.kind === 'enter' ? { ...decision, startsRequestSeries: true } : decision + }) + // The head already matches, so consolidation logs only the emptied later version. + await send(resumed, 'start a new series') + expect(systemPrompts(resumed.session)).toEqual([earlier, expect.stringContaining('Updated instruction.'), '']) + await send(resumed, 'continue the series') + expect(systemPrompts(resumed.session)).toHaveLength(3) + expect(requestSystemPrompts(h.adapter.requests.at(-1))).toEqual([earlier]) + }) + + it.each([ + { variant: 'a paragraph without the fixed ending', source: 'The DeepSeek Harness implementation checkout is at /old/checkout/.' }, + { variant: 'a paragraph broken across lines', source: LEGACY_SOURCE.replace('/old/checkout/', '/old/\ncheckout/') }, + ])('replaces text that only resembles an earlier paragraph: $variant', async ({ source }) => { + const h = await promptLoop(undefined) + const original = await h.earlierSession(source, WEB_PROMPT) + const resumed = await h.resume(original.session, 'resembling') + await send(resumed, 'after the upgrade') + const current = systemPrompts(resumed.session).at(-1) + expect(current).toContain(SOURCE_PROMPT) + expect(current).not.toContain('/old/') + }) + + it('keeps a new Session system prompt free of process values across ports', async () => { + const h = await promptLoop(undefined) + const agent = await h.harness.create(SessionId('fresh'), ROUTE) + await send(agent, 'first') + const logged = systemPrompts(agent.session) + expect(logged).toHaveLength(1) + expect(logged[0]).toContain(SOURCE_PROMPT) + expect(logged[0]).toContain(WEB_PROMPT) + expect(logged[0]).not.toContain('127.0.0.1') + expect(latestRuntimeContext(agent.session)).toContain('Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:4567".') + + h.listener.port = 4568 + const resumed = await h.resume(agent.session, 'fresh-on-4568') + await send(resumed, 'second') + expect(systemPrompts(resumed.session)).toEqual(logged) + expect(latestRuntimeContext(resumed.session)).toContain('Current DeepSeek Harness Web GUI URL: "http://127.0.0.1:4568".') + }) +}) diff --git a/packages/context/harness-dev-context/tsconfig.json b/packages/context/harness-dev-context/tsconfig.json new file mode 100644 index 0000000000..e81811d974 --- /dev/null +++ b/packages/context/harness-dev-context/tsconfig.json @@ -0,0 +1,33 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../core/session" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../session/session-projection" + }, + { + "path": "../../bundle/web-app" + } + ] +} diff --git a/packages/context/session-reference/locale/en.json b/packages/context/session-reference/locale/en.json new file mode 100644 index 0000000000..5ce3c4233b --- /dev/null +++ b/packages/context/session-reference/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session-reference" + } +} diff --git a/packages/context/session-reference/locale/zh.json b/packages/context/session-reference/locale/zh.json new file mode 100644 index 0000000000..57f311219c --- /dev/null +++ b/packages/context/session-reference/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "跨会话引用", + "description": "为 AI 提供其他会话的只读内容快照。" + } +} diff --git a/packages/context/session-reference/package.json b/packages/context/session-reference/package.json index cc60df45da..3daff8f14d 100644 --- a/packages/context/session-reference/package.json +++ b/packages/context/session-reference/package.json @@ -31,9 +31,11 @@ "default": "./lib/typert.remote-client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", diff --git a/packages/core/agent-default-model/locale/en.json b/packages/core/agent-default-model/locale/en.json new file mode 100644 index 0000000000..f186bd3011 --- /dev/null +++ b/packages/core/agent-default-model/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-default-model" + } +} diff --git a/packages/core/agent-default-model/locale/zh.json b/packages/core/agent-default-model/locale/zh.json new file mode 100644 index 0000000000..6b68fb5e2c --- /dev/null +++ b/packages/core/agent-default-model/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "默认模型", + "description": "为新建智能体提供默认模型选择。" + } +} diff --git a/packages/core/agent-default-model/package.json b/packages/core/agent-default-model/package.json index 3adf19597d..a179669090 100644 --- a/packages/core/agent-default-model/package.json +++ b/packages/core/agent-default-model/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/core/agent-loop/locale/en.json b/packages/core/agent-loop/locale/en.json new file mode 100644 index 0000000000..d0db02ecc5 --- /dev/null +++ b/packages/core/agent-loop/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-loop" + } +} diff --git a/packages/core/agent-loop/locale/zh.json b/packages/core/agent-loop/locale/zh.json new file mode 100644 index 0000000000..b21c2b149c --- /dev/null +++ b/packages/core/agent-loop/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "智能体运行循环", + "description": "协调模型请求、工具调用和后续步骤,推进智能体任务。" + } +} diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json index 36f124ca94..47f0791833 100644 --- a/packages/core/agent-loop/package.json +++ b/packages/core/agent-loop/package.json @@ -18,9 +18,11 @@ "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/core/agent-tool-presentation/locale/en.json b/packages/core/agent-tool-presentation/locale/en.json new file mode 100644 index 0000000000..f8dd1865fc --- /dev/null +++ b/packages/core/agent-tool-presentation/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent-tool-presentation" + } +} diff --git a/packages/core/agent-tool-presentation/locale/zh.json b/packages/core/agent-tool-presentation/locale/zh.json new file mode 100644 index 0000000000..804d500211 --- /dev/null +++ b/packages/core/agent-tool-presentation/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具调用方式", + "description": "选择智能体通过原生工具或 PTC 代码来调用工具。" + } +} diff --git a/packages/core/agent-tool-presentation/package.json b/packages/core/agent-tool-presentation/package.json index 9837b88713..466465b75a 100644 --- a/packages/core/agent-tool-presentation/package.json +++ b/packages/core/agent-tool-presentation/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/core/agent/locale/en.json b/packages/core/agent/locale/en.json new file mode 100644 index 0000000000..62656fe619 --- /dev/null +++ b/packages/core/agent/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "agent" + } +} diff --git a/packages/core/agent/locale/zh.json b/packages/core/agent/locale/zh.json new file mode 100644 index 0000000000..0ec511ecc3 --- /dev/null +++ b/packages/core/agent/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "智能体管理", + "description": "管理智能体实例及其运行上下文和事件。" + } +} diff --git a/packages/core/agent/package.json b/packages/core/agent/package.json index ded699a4b7..deb3a08154 100644 --- a/packages/core/agent/package.json +++ b/packages/core/agent/package.json @@ -23,9 +23,11 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/core/session/locale/en.json b/packages/core/session/locale/en.json new file mode 100644 index 0000000000..c7519b7bc7 --- /dev/null +++ b/packages/core/session/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "session" + } +} diff --git a/packages/core/session/locale/zh.json b/packages/core/session/locale/zh.json new file mode 100644 index 0000000000..acf2adf883 --- /dev/null +++ b/packages/core/session/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "会话记录", + "description": "记录会话中的消息、工具调用和运行事件。" + } +} diff --git a/packages/core/session/package.json b/packages/core/session/package.json index b8085f30a6..3f062803cc 100644 --- a/packages/core/session/package.json +++ b/packages/core/session/package.json @@ -31,9 +31,11 @@ "./surface": { "types": "./lib/types/surface.d.ts", "default": "./lib/types/surface.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/core/system-prompt/locale/en.json b/packages/core/system-prompt/locale/en.json new file mode 100644 index 0000000000..1bf4f235c8 --- /dev/null +++ b/packages/core/system-prompt/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "system-prompt" + } +} diff --git a/packages/core/system-prompt/locale/zh.json b/packages/core/system-prompt/locale/zh.json new file mode 100644 index 0000000000..2b29254c25 --- /dev/null +++ b/packages/core/system-prompt/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "系统提示词组装", + "description": "汇总各插件提供的系统提示词内容。" + } +} diff --git a/packages/core/system-prompt/package.json b/packages/core/system-prompt/package.json index 57adb8cc95..0e3ec253ea 100644 --- a/packages/core/system-prompt/package.json +++ b/packages/core/system-prompt/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/core/system-prompt/src/index.ts b/packages/core/system-prompt/src/index.ts index 2f027dfaf9..d3b719f818 100644 --- a/packages/core/system-prompt/src/index.ts +++ b/packages/core/system-prompt/src/index.ts @@ -172,6 +172,9 @@ const CONTEXT_ORDERS = { SANDBOX_POLICY: 110, APPROVAL_POLICY: 115, SUBAGENT_DELEGATION: 120, + // Process-specific paths and endpoints stay out of the cached system prompt. + HARNESS_SOURCE: 200, + WEB_SURFACE: 210, } as const /** Name of a centrally allocated runtime-context position. */ diff --git a/packages/core/system-prompt/tests/system-prompt.spec.ts b/packages/core/system-prompt/tests/system-prompt.spec.ts index 86512fa81c..a8bef706d1 100644 --- a/packages/core/system-prompt/tests/system-prompt.spec.ts +++ b/packages/core/system-prompt/tests/system-prompt.spec.ts @@ -26,6 +26,7 @@ const SECTION_ORDER_NAMES = [ const CONTEXT_ORDER_NAMES = [ 'WORKING_DIRECTORY', 'SANDBOX_POLICY', 'APPROVAL_POLICY', 'SUBAGENT_DELEGATION', + 'HARNESS_SOURCE', 'WEB_SURFACE', ] as const satisfies readonly PromptContextOrderName[] function contributed(assembly: PromptAssembly): PromptAssembly['sections'] { return assembly.sections.filter(section => !BUILT_IN.includes(section.name)) diff --git a/packages/core/tools/README.i18n.yaml b/packages/core/tools/README.i18n.yaml index 739e42cb05..2817538d44 100644 --- a/packages/core/tools/README.i18n.yaml +++ b/packages/core/tools/README.i18n.yaml @@ -21,8 +21,8 @@ en: 9d2e6caa39c53d62 zh: 096a777f828c7565 /deepseek-ai-dsh-tools/use-this-package/configure-the-presentation-mode: - en: 19a752864651fc41 - zh: 48e20c3cdc867428 + en: 4e27c45ae889369e + zh: 7a0cd7a9dc7fe139 /deepseek-ai-dsh-tools/use-this-package/restrict-tools-per-agent: en: c6f98b2283cc2e47 zh: c2cdce5d13473f15 @@ -45,8 +45,8 @@ en: dc44a88997777988 zh: 56454aeace1c8b77 /deepseek-ai-dsh-tools/understand-the-implementation/ptc-mode: - en: 0dc05f09633632cb - zh: 35324cf1fdd11912 + en: 387700aa396f7ca2 + zh: d440b283027e4fbd /deepseek-ai-dsh-tools/understand-the-implementation/extension-points: en: c2a14d6f22bc9428 zh: 89c1414fca465931 @@ -96,8 +96,8 @@ en: 2fbf2175168e8244 zh: ad59a120b54a0996 /deepseek-ai-dsh-tools/known-limitations-and-deferred-work: - en: 1fa3e7e53c700b69 - zh: 62ebbc3a254a1709 + en: 4a412f89b8a71b5a + zh: 803d995b036d5dbf /deepseek-ai-dsh-tools/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/core/tools/README.md b/packages/core/tools/README.md index bbf221031b..db88aad341 100644 --- a/packages/core/tools/README.md +++ b/packages/core/tools/README.md @@ -65,7 +65,7 @@ The unified schema DSL supports `string`, `number`, `integer`, `boolean`, `null` ### Configure the presentation mode -The `mode` config decides what the model sees: `native` (every visible schema) or `ptc` (only `run_code` plus a generated SDK). +The `mode` config decides what the model sees: `native` (every visible schema) or `ptc` (only `run_code` plus a generated SDK). The runtime supplies evaluation syntax, output syntax and state-retention guidance through `executionInstructions`; this package owns tool-call rules, SDK declarations and image-result attachment. ```yaml - name: '@deepseek-ai/dsh-tools' @@ -133,7 +133,7 @@ New sub-calls use `:ptc:` ids. Consumers treat these ids as opaque an Successful image-bearing subcall results become deferred user-message context with `source.kind` set to `ptc-mode`. Other additional contexts retain their producing tool's attribution. -`run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. +`run_code` accepts `timeoutMs` when the mounted runtime supports an override; its schema reports the configured default and maximum, and the runtime's usage instructions. The Node default is 120,000 ms with a 600,000 ms cap, including nested tool and approval waits. A wider `sandbox_permissions` mode requires a non-empty `justification` and approval before the program starts. The schema asks the model to write that reason in the current user's language. The grant applies to that complete execution; standing Session policy and nested tools retain their own authority. Programs are never replayed automatically: inspect earlier effects before explicitly retrying a denied program. Retained PTC environments follow the standing file policy. PTC observes committed Session mode changes and immediately cancels affected calls in both Node modes. Later PTC calls wait for their nested-tool cleanup before resolving the latest policy. The runtime owns process invalidation and cleanup; permission setters remain synchronous. One-time escalations omit the state owner and complete in a temporary environment; standing variables remain available to ordinary calls. ### Extension points @@ -235,7 +235,7 @@ These limits define when the registry needs special care. They are current packa - **`timeoutMs` on a definition is declarative only** — the registry never enforces deadlines; enforcement requires the `@deepseek-ai/dsh-tool-call-timeout-policy` wrapper. - **PTC mode's SDK language follows the one loaded runtime, and a presentation is per agent rather than per tool** — `mode: ptc` rejects prompt assembly unless `ctx.ptcRuntime.language` has a registered SDK renderer; within one agent no tool can be native-only while another is ptc-only. - **PTC mode intermediate values are execution-local and unbounded by bytes** — they cannot be reconstructed from session replay and may exhaust process or worker memory; only the outer `run_code` output has the worker's configurable hard cap. -- **`run_code` state is fresh per run** — a persistent REPL-style kernel is rejected for the MVP, because cross-call state would be invisible to the log. +- **State depends on the runtime**: the default backend starts fresh; a REPL backend retains memory per live Agent. Agent disposal awaits release. Restart and execution failures can clear memory; model-visible guidance explains how to recreate missing variables. Programs and results remain in the Session log, without serializing live objects. `defineTool()`, registry schema projection, and system-prompt assembly preserve `deferLoading: true`. The marker requests deferred definition loading and does not imply a `tool-addition` record; the [LLM package](../../../packages/llm/llm/README.md#known-limitations-and-deferred-work) documents provider enforcement limits. diff --git a/packages/core/tools/README.zh.md b/packages/core/tools/README.zh.md index a3e9989874..b8fe64c4f0 100644 --- a/packages/core/tools/README.zh.md +++ b/packages/core/tools/README.zh.md @@ -65,7 +65,7 @@ ctx.tools.register(defineTool({ ### 配置呈现模式 -`mode` 配置决定模型看到什么:`native`(每个可见 schema)或 `ptc`(只有 `run_code` 加一份生成 SDK)。 +`mode` 配置决定模型看到什么:`native`(每个可见 schema)或 `ptc`(只有 `run_code` 加一份生成 SDK)。运行时通过 `executionInstructions` 提供求值语法、输出方式和状态保留指引;本包负责工具调用规则、SDK 声明和图片结果附加。 ```yaml - name: '@deepseek-ai/dsh-tools' @@ -133,7 +133,7 @@ ctx.tools.register(defineTool({ 成功且包含图片的子调用结果会成为延后的 user-message 上下文,其 `source.kind` 为 `ptc-mode`。其他 additional context 保留其生产工具的归属。 -当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限以及运行时使用说明。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。schema 提示模型使用当前用户的语言撰写理由。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 +当已挂载运行时支持覆盖时,`run_code` 接受 `timeoutMs`;其 schema 报告配置的默认值和上限以及运行时使用说明。Node 默认值为 120,000 ms,上限为 600,000 ms,包含嵌套工具和审批等待。更宽的 `sandbox_permissions` 模式要求非空 `justification`,并在程序启动前获得审批。schema 提示模型使用当前用户的语言撰写理由。授权仅用于该次完整执行;常驻 Session 策略与嵌套工具保留各自权限。程序不会自动重放:显式重试被拒程序前,应检查先前已发生的效果。 保留状态的 PTC 环境遵循会话文件策略。PTC 观察已提交的 Session 模式变化,并立即取消两种 Node 模式下受影响的调用。后续 PTC 调用等待这些调用的嵌套工具清理后,再解析最新策略。运行时负责进程失效和清理,权限设置保持同步。单次提权省略状态所有者,在临时环境中执行;普通调用仍可访问原环境的变量。 ### 扩展点 @@ -235,7 +235,7 @@ Program-only SDK bindings: - **定义中的 `timeoutMs` 仅作声明之用**:注册表绝不会强制执行截止时间;要强制执行,必须使用 `@deepseek-ai/dsh-tool-call-timeout-policy` 包装层。 - **PTC mode 的 SDK 语言由当前加载的运行时决定,且呈现方式按 agent 而非按工具**:`mode: ptc` 会拒绝组装提示词,除非 `ctx.ptcRuntime.language` 有已注册的 SDK 渲染器;同一个 agent 内不能让一个工具仅使用 Native,而另一个仅使用 PTC。 - **PTC mode 中间值只存在于执行局部,且没有字节上限**:它们无法从会话回放重建,并可能耗尽进程或 worker 内存;只有外层 `run_code` 输出受 worker 可配置的硬上限约束。 -- **每次运行都会获得全新的 `run_code` 状态**:MVP 不采用持久 REPL 风格内核,因为跨调用状态不会出现在日志中。 +- **状态由运行时决定**:默认后端每次重新开始;REPL 后端按存活 Agent 保留内存。Agent 销毁时等待环境释放。重启与执行失败可能清除内存;模型说明会指导重新创建缺失变量。程序与结果仍写入 Session 日志,不序列化运行中的对象。 `defineTool()`、注册表模式投影和系统提示组装会保留 `deferLoading: true`。该标记请求延迟加载工具定义,并不意味着存在 `tool-addition` 记录;提供方执行语义的限制见 [LLM 包](../../../packages/llm/llm/README.zh.md#known-limitations-and-deferred-work)。 diff --git a/packages/core/tools/locale/en.json b/packages/core/tools/locale/en.json new file mode 100644 index 0000000000..c9a7634507 --- /dev/null +++ b/packages/core/tools/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "tools" + } +} diff --git a/packages/core/tools/locale/zh.json b/packages/core/tools/locale/zh.json new file mode 100644 index 0000000000..eb3227360e --- /dev/null +++ b/packages/core/tools/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工具注册与执行", + "description": "管理可用工具及其调用执行流程。" + } +} diff --git a/packages/core/tools/package.json b/packages/core/tools/package.json index 3cc8922032..caa9985b76 100644 --- a/packages/core/tools/package.json +++ b/packages/core/tools/package.json @@ -27,9 +27,11 @@ "default": "./lib/types/presentation.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/core/tools/src/index.ts b/packages/core/tools/src/index.ts index e506d99da0..0970c7e2b0 100644 --- a/packages/core/tools/src/index.ts +++ b/packages/core/tools/src/index.ts @@ -842,12 +842,14 @@ export class ToolRuntime extends Service { * Reserved presentation transport, kept outside the filterable registration * layers. Built on first need rather than at construction: which agents run * a PTC mode is no longer known when the service is constructed, and the - * transport is stateless beyond its closures over `this`. + * transport owns its PTC call tracking and state-owner registrations. */ private ptcTransport: ToolDefinition | undefined + private readonly ptcContext: Context constructor(ctx: Context, config: Config = {}) { super(ctx, 'tools') + this.ptcContext = ctx // The schema already defaulted an omitted mode; the ?? narrows the // optional-input type for direct (non-Loader) construction in tests. this.defaultMode = config.mode ?? 'native' @@ -965,7 +967,7 @@ export class ToolRuntime extends Service { peekRuntime: () => this.ctx.get('ptcRuntime'), maxParallel: this.maxParallelSubCalls, shapeDispatchLog: dispatch => this.shapeDispatchLog(dispatch), - }) + }, this.ptcContext) return this.ptcTransport } diff --git a/packages/core/tools/src/ptc-calls.ts b/packages/core/tools/src/ptc-calls.ts new file mode 100644 index 0000000000..16de96380c --- /dev/null +++ b/packages/core/tools/src/ptc-calls.ts @@ -0,0 +1,64 @@ +/** Cancellation and settlement of complete PTC calls, including nested tools. */ +import type { Context } from '@deepseek-ai/cordis' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' + +interface Call { + mode: SandboxMode + controller: AbortController + done: Promise +} + +/** Keeps calls under a changed policy from overlapping their canceled predecessors. */ +export class PtcCalls { + private readonly calls = new Map>() + private disposed = false + + /** + * Observe policy changes for the owning tool registry. + * @param ctx - Registry lifecycle and Session events. + */ + constructor(ctx: Context) { + ctx.on('session/event', (session, event) => { + if (event.type !== 'sandbox/mode') return + for (const call of this.calls.get(session.id) ?? []) { + if (call.mode !== event.data.mode) call.controller.abort(new Error('sandbox mode changed')) + } + }, { global: true }) + ctx.effect(() => async () => { + this.disposed = true + const calls = [...this.calls.values()].flatMap(calls => [...calls]) + for (const call of calls) call.controller.abort(new Error('PTC tool registry disposed')) + await Promise.all(calls.map(call => call.done)) + }, 'PTC calls') + } + + /** + * Await canceled predecessors before resolving authority and admitting a call. + * @param sessionId - Calling Session. + * @param signal - Caller cancellation. + * @param mode - Current standing mode, read after preceding cleanup. + * @param run - Complete call, including nested-tool cleanup. + * @returns The call result. + */ + async run(sessionId: SessionId, signal: AbortSignal, mode: () => SandboxMode, run: (signal: AbortSignal) => Promise): Promise { + for (;;) { + const pending = [...this.calls.get(sessionId) ?? []].filter(call => call.controller.signal.aborted) + if (pending.length === 0) break + await Promise.all(pending.map(call => call.done)) + } + signal.throwIfAborted() + if (this.disposed) throw new Error('PTC tool registry disposed') + const controller = new AbortController() + const done = Promise.withResolvers() + const call = { mode: mode(), controller, done: done.promise } + let calls = this.calls.get(sessionId) + if (calls === undefined) this.calls.set(sessionId, calls = new Set()) + calls.add(call) + try { return await run(AbortSignal.any([signal, controller.signal])) } finally { + calls.delete(call) + if (calls.size === 0) this.calls.delete(sessionId) + done.resolve(undefined) + } + } +} diff --git a/packages/core/tools/src/ptc.ts b/packages/core/tools/src/ptc.ts index 9d3bea545b..d2ec751c10 100644 --- a/packages/core/tools/src/ptc.ts +++ b/packages/core/tools/src/ptc.ts @@ -6,6 +6,7 @@ * @module @deepseek-ai/dsh-tools/src/ptc */ +import { symbols, type Context } from '@deepseek-ai/cordis' import { brandString } from '@deepseek-ai/dsh-brand' import { createUserMessage, HarnessError } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { @@ -22,6 +23,7 @@ import type { SandboxExecutionPolicy } from '@deepseek-ai/dsh-sandbox' import type { ApprovalService } from '@deepseek-ai/dsh-user-approval' import { deepFreeze, snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-util-values' import { defineTool, parameterSchemaSpecToJsonSchema } from './schema.ts' +import { PtcCalls } from './ptc-calls.ts' import { TOOL_RUNTIME_SCHEDULER } from './index.ts' import type { PtcDispatchLog, ToolDefinition, ToolExecutionResult, ToolRuntime, ToolRunContext } from './index.ts' import type {} from './types.ts' @@ -44,38 +46,19 @@ interface RunCodeFlavor { readonly codeDescription: string } -/** - * The TypeScript flavor: the fallback for a schema read with no runtime - * mounted ({@link resolveFlavor} owns which readers reach that). A real - * assembly always resolves a runtime first, so the model never sees this - * fallback outside its own language. - */ -const TYPESCRIPT_FLAVOR: RunCodeFlavor = { - description: - 'Execute a TypeScript program against the available tools. Takes two required ' - + 'arguments: `description`, a short summary of what the program does, and `code`, ' - + 'the BODY of an async function (erasable syntax only; top-level `await` and ' - + '`return` work). Call tools as `await tools.name(args)` per the declarations in the system ' - + 'prompt. Only what you print or return is program output — curate it. Image-bearing ' - + 'subtool results are attached after the run.', - codeDescription: 'The program: the body of an async TypeScript function.', +/** Keep tool-call rules here; the runtime owns evaluation syntax and state retention. */ +function runCodeFlavor(language: string): RunCodeFlavor { + return { + description: `Execute a ${language} program against the available tools. Takes two required arguments: ` + + '`description`, a short summary of what the program does, and `code`, the program to execute. ' + + 'Call tools as `await tools.name(args)` per the declarations in the system prompt. ' + + 'Curate the program output. Image-bearing subtool results are attached after the run.', + codeDescription: `The ${language} program to execute, following this tool's execution instructions.`, + } } -/** - * The Python flavor: the body of an async function, top-level `await` and - * `return`, answer via `print` and/or the returned value, matching - * {@link ./py-types.ts}'s SDK instructions. - */ -const PYTHON_FLAVOR: RunCodeFlavor = { - description: - 'Execute a Python program against the available tools. Takes two required ' - + 'arguments: `description`, a short summary of what the program does, and `code`, ' - + 'the BODY of an async function (top-level `await` and `return` work). Call tools as ' - + '`await tools.name(args)` per the declarations in the system prompt. Use ' - + '`print(...)` and/or `return ` for program output — curate it. Image-bearing ' - + 'subtool results are attached after the run.', - codeDescription: 'The program: the body of an async Python function.', -} +const TYPESCRIPT_FLAVOR = runCodeFlavor('TypeScript') +const PYTHON_FLAVOR = runCodeFlavor('Python') /** * The languages PTC mode ships a presentation for. Both per-language tables — @@ -331,10 +314,13 @@ export interface RunCodeBridgeOptions { * @param registry - the owning registry (sub-calls go through its `execute`, * bindings cover its registered tools). * @param options - the registry-private capabilities described above. + * @param ctx - Owning registry context, independent of the calling Agent. * @returns the registry-ready definition. */ -export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeOptions): ToolDefinition { +export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeOptions, ctx: Context): ToolDefinition { const { requireRuntime, peekRuntime, maxParallel, shapeDispatchLog } = options + const stateOwners = new WeakMap>() + const calls = new PtcCalls(ctx) const definition = defineTool({ name: RUN_CODE_NAME, // The description and `code` parameter description are placeholders here: @@ -384,355 +370,376 @@ export function createRunCodeTool(registry: ToolRuntime, options: RunCodeBridgeO throw new Error('invalid description: expected a non-empty string') } const runtime = requireRuntime() - validateEscalationArgs(args.sandbox_permissions, args.justification) - if (args.timeoutMs !== undefined && runtime.timeout === undefined) { - throw new Error('timeoutMs is not available for this PTC runtime') - } - if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) { - throw new Error('invalid timeoutMs: expected a positive finite number') - } - const standingPolicy = runtime.sandboxMode === undefined ? undefined : options.resolveSandboxPolicy(exec) - let policy = standingPolicy - if (args.sandbox_permissions !== undefined && args.justification !== undefined) { - if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this PTC runtime') - const approvedMode = await approveEscalation({ - requestedMode: args.sandbox_permissions, - justification: args.justification, - effectiveMode: standingPolicy.mode, - subject: 'program', - }, { - approver: options.peekApprover(), agent: exec.agent, callId: exec.callId, - toolName: RUN_CODE_NAME, signal: exec.signal, - }) - policy = { ...standingPolicy, mode: approvedMode } - } - const cwd = await options.resolveWorkingDirectory(exec) - exec.signal.throwIfAborted() - - // The run-scoped abort: follows the outer signal in, and fires when the - // run settles for ANY reason, so an in-flight sub-dispatch is aborted - // (its executor kills on this signal) instead of orphaned, and - // queued-unstarted dispatches are abandoned. - const runController = new AbortController() - const onOuterAbort = (): void => { runController.abort(exec.signal.reason) } - exec.signal.addEventListener('abort', onOuterAbort, { once: true }) - - let dispatches = 0 - // The per-run scheduler uses the registry's staged interface and follows - // the same concurrency rules as the native loop. It also follows the - // native loop's SEQUENCING: every ordered stage (the dispatch-start - // append, prepare = pre-execute/guards, finalize/finish = post-execute, - // context deferral, the settle append) runs inside ONE driver lane, so - // ordered policy stages never overlap each other and only the - // around-dispatch/body stage runs concurrently. Starts are strictly - // submission-ordered; results commit in submission order through the - // head-of-line cursor. Consecutive parallel-classified calls overlap up - // to maxParallel; an exclusive call waits for the pool to drain, runs - // alone, and holds its barrier until its COMMIT (post-execute included) - // completes, exactly like a native exclusive group. Classification is - // re-read via executionMode() immediately before each start (a registry - // mutation while queued can flip a call exclusive), matching the native - // scheduler's lazy reclassification. - interface PendingDispatch { - /** Ordered stage: append the start event, await prepare (pre-execute/guards), launch the body into `flight`. */ - start(): Promise - classify(): 'parallel' | 'exclusive' - abandon(): void - /** Ordered stage: post-execute + context deferral + settle event, in submission order. */ - commit(): Promise - /** The launched around-dispatch/body stage; resolved until start() replaces it. */ - flight: Promise - /** True once the dispatch stage parked its outcome; the commit cursor waits on it. */ - settled: boolean - /** The classification this entry started under; an exclusive holds its barrier through commit(). */ - mode?: 'parallel' | 'exclusive' - } - const pendingQueue: PendingDispatch[] = [] - const inFlight = new Set>() - /** Tracked settle-event side work (log-content listener + append), drained at run settlement. */ - const logWork = new Set>() - const commitQueue: PendingDispatch[] = [] - let exclusiveActive = false - let driving = false - let driverRun: Promise = Promise.resolve() - let wake: (() => void) | undefined - const wakeup = (): void => { - const release = wake - wake = undefined - release?.() - } - /** - * The single ordered lane. Each pass commits the head-of-line settled - * dispatch (ordered post-execute), then starts the next queued entry if - * its slot is free (ordered pre-execute), and otherwise sleeps until a - * body settles or a new submission arrives. One run reaching the - * empty-queues/empty-pool state is quiescence. - */ - const drive = (): Promise => { - if (driving) return driverRun - driving = true - driverRun = (async () => { - try { - for (;;) { - // Create the wakeup promise before inspecting state so a settle or submission arriving - // between the checks and the await below cannot be lost. - const signal = new Promise((resolve) => { wake = resolve }) - const commitHead = commitQueue[0] - if (commitHead !== undefined && commitHead.settled) { - commitQueue.shift() - await commitHead.commit() - // The barrier covers post-execute: later starts wait for the - // exclusive call's full pipeline, as under the native loop. - if (commitHead.mode === 'exclusive') exclusiveActive = false - continue - } - const head = pendingQueue[0] - if (head !== undefined) { - if (runController.signal.aborted) { - pendingQueue.shift() - head.abandon() - continue - } - // Reclassify at start time (fail-closed on registry changes). - const mode = head.classify() - const capacity = !exclusiveActive - && (mode === 'exclusive' ? inFlight.size === 0 : inFlight.size < maxParallel) - if (capacity) { - if (mode === 'exclusive') exclusiveActive = true - head.mode = mode - pendingQueue.shift() - // Joined before start() so the commit cursor sees submission - // order; nothing commits it until `settled` flips. - commitQueue.push(head) - await head.start() - const flight: Promise = head.flight.finally(() => { - inFlight.delete(flight) - wakeup() - }) - inFlight.add(flight) - continue - } - } - if (pendingQueue.length === 0 && commitQueue.length === 0 && inFlight.size === 0) return - await signal - } - } finally { - driving = false - wake = undefined - } - })() - return driverRun - } - /** Every dispatch settled AND committed; nothing can start (the run is aborted at call time). */ - const drainDispatches = async (): Promise => { - // The abort already fired: the driver abandons queued-unstarted - // entries, awaits the live pool, and drains the ordered commit lane — - // including a commit already in progress when the program returned. - await drive() - // Every settle event is appended inside the open run_code turn - // (tasks self-remove on settlement). - while (logWork.size > 0) await Promise.allSettled([...logWork]) - } - - // Read through a call, not a bare property: the abort state genuinely - // changes across awaits, and a direct `.aborted` re-check after one - // would be narrowed away by control flow analysis. - const runOver = (): boolean => runController.signal.aborted - - const binding = (schema: ToolSchema): PtcBindingFunction => async (rawArgs: unknown): Promise => { - const { name } = schema - if (runOver()) { - throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`) + const run = async (callSignal: AbortSignal): Promise => { + validateEscalationArgs(args.sandbox_permissions, args.justification) + if (args.timeoutMs !== undefined && runtime.timeout === undefined) { + throw new Error('timeoutMs is not available for this PTC runtime') } - const normalized = jsonNormalizeArgs(rawArgs) - const n = ++dispatches - const subCallId = brandString(`${String(exec.callId)}:ptc:${n}`) - const input = { - callId: subCallId, - rootCallId: exec.rootCallId, - name, - schema, - arguments: normalized.dispatched, - ...exec.agent ? { agent: exec.agent } : {}, - parent: exec.token, - signal: runController.signal, + if (args.timeoutMs !== undefined && (!Number.isFinite(args.timeoutMs) || args.timeoutMs <= 0)) { + throw new Error('invalid timeoutMs: expected a positive finite number') } - type DispatchOutcome = { isError: true; message: string } | { isError: false; value: JsonValue } - const scheduler = registry[TOOL_RUNTIME_SCHEDULER] - const outcome = await new Promise((resolve, reject) => { - // Set by the dispatch stage (or start() for a pre-settled result): what commit() finalizes in submission order. - let parked: - | { kind: 'post-result' | 'final-result'; exec: ToolRunContext; result: ToolExecutionResult } - | undefined - const settle = (result: ToolExecutionResult): void => { - // The program gets its value NOW: the log-content listener (for - // example, a spill backend) must never delay the binding or occupy - // a dispatch slot. The event append is tracked side work; the run's - // settlement drains logWork so every settle event is still appended - // inside the open turn (shapeDispatchLog is contained, so this - // chain cannot reject). - resolve(result.isError - ? { isError: true, message: result.error.message } - : { isError: false, value: result.value }) - const agent = exec.agent - if (agent === undefined) return - const task: Promise = (async () => { - // The listener may replace the durable copy with a preview and - // locator; the program's value and model-visible result are - // untouched. - const logged = await shapeDispatchLog({ - exec, agent, subCallId, name, isError: result.isError, - // The registry deep-froze this projection at result - // finalization; append snapshots the final copy again, so - // the log stays detached. - content: result.content, - }) - agent.session.append('tool/ptc-dispatch', { - rootCallId: exec.rootCallId, - parentCallId: exec.callId, - subCallId, - name, - // The SIBLING parse of the dispatched value: byte-identical JSON, - // but a separate object — a tool mutating its args cannot desync - // this record from what it actually received. - arguments: normalized.logged, - isError: result.isError, - ...result.error?.info === undefined ? {} : { error: result.error.info }, - content: logged, - ...result.meta === undefined ? {} : { meta: result.meta }, - }) - })().finally(() => { logWork.delete(task) }) - logWork.add(task) - } - pendingQueue.push({ - flight: Promise.resolve(), - settled: false, - // Re-read per driver pass against the same agent view the SDK - // declared; fail-closed exclusive when undeclared/invalid. - classify: () => registry.executionMode(input).kind, - abandon: () => { - reject(new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`)) - }, - async start(): Promise { - exec.agent?.session.append('tool/ptc-dispatch-start', { - rootCallId: exec.rootCallId, - parentCallId: exec.callId, - subCallId, - name, - arguments: normalized.logged, - }) - // Ordered prepare runs INSIDE the driver lane: the next entry's - // pre-execute waits for this resolution, as under the native - // scheduler. Only the launched body below overlaps. - const prepared = await scheduler.prepare(input) - if (prepared.kind === 'dispatch') { - this.flight = scheduler.dispatch(prepared.exec).then((dispatchOutcome) => { - parked = { kind: dispatchOutcome.kind, exec: prepared.exec, result: dispatchOutcome.result } - this.settled = true - }) - return - } - parked = { kind: prepared.kind, exec: prepared.exec, result: prepared.result } - this.settled = true - }, - async commit(): Promise { - /* v8 ignore next -- commit() runs only after `settled` flipped, which set parked. */ - if (parked === undefined) return - const result = parked.kind === 'post-result' - ? await scheduler.finalize(parked.exec, parked.result) - : scheduler.finish(parked.exec, parked.result) - if (!result.isError && result.content.some(block => block.type === 'image')) { - exec.deferContext(createUserMessage({ - content: result.content, - source: { kind: 'ptc-mode' }, - })) - } - for (const context of result.additionalContexts ?? []) { - exec.deferContext(context) - } - // The composite forwards `additionalContexts` above and - // `concludesTurn` here from the nested result. Only a successful - // nested result can carry the terminal marker - // (ToolExecutionFailure types it never), so a policy-converted - // failure cannot stop the turn through a recovering program. - if (result.concludesTurn) exec.concludeTurn() - settle(result) - // Backpressure on pending event-append tasks: each task retains - // a full result while a slow backend stores it, so the pool cap - // bounds their count. Beyond the cap, the - // ordered lane waits, so later sub-calls cannot start and - // pending I/O/memory cannot grow without bound. - while (logWork.size > maxParallel) await Promise.race(logWork) - }, + const standingPolicy = runtime.sandboxMode === undefined ? undefined : options.resolveSandboxPolicy(exec) + let policy = standingPolicy + if (args.sandbox_permissions !== undefined && args.justification !== undefined) { + if (standingPolicy === undefined) throw new Error('sandbox_permissions is not available for this PTC runtime') + const approvedMode = await approveEscalation({ + requestedMode: args.sandbox_permissions, + justification: args.justification, + effectiveMode: standingPolicy.mode, + subject: 'program', + }, { + approver: options.peekApprover(), agent: exec.agent, callId: exec.callId, + toolName: RUN_CODE_NAME, signal: callSignal, }) - wakeup() - void drive() - }) - // A budget expiry or outer cancel that occurs while this call was in - // flight already aborted the dispatch; stop the program now rather - // than hand it a result from a run that is over. - if (runOver()) { - throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`) + policy = { ...standingPolicy, mode: approvedMode } } - // The worker turns a binding rejection into ToolCallError and adds - // only the binding name. Native content and internal error metadata - // stay outside the program-facing failure contract. - if (outcome.isError) throw new Error(outcome.message) - return outcome.value - } + const cwd = await options.resolveWorkingDirectory({ ...exec, signal: callSignal }) + callSignal.throwIfAborted() - // Null-prototype + defineProperty, mirroring the worker-side namespace - // build: a registered tool named `__proto__` must become an ordinary - // own key (a plain-object assignment would hit the prototype setter, - // silently dropping the binding), and the runtime host resolves - // binding names as own properties only. - const functions: Record = Object.create(null) as Record - // Enumerate the CALLING AGENT's visible set (scoped tools join, - // restricted globals vanish) — the same view the SDK section declared, - // so a program can bind exactly what its prompt promised; sub-dispatch - // re-resolves per call through the same view (exec.agent threads down). - for (const schema of registry.schemas(exec.agent)) { - if (schema.name === RUN_CODE_NAME) continue - Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(deepFreeze(schema)) }) - } + // The run-scoped abort: follows the outer signal in, and fires when the + // run settles for ANY reason, so an in-flight sub-dispatch is aborted + // (its executor kills on this signal) instead of orphaned, and + // queued-unstarted dispatches are abandoned. + const runController = new AbortController() + const onOuterAbort = (): void => { runController.abort(callSignal.reason) } + callSignal.addEventListener('abort', onOuterAbort, { once: true }) - try { - let result: PtcRunResult - try { - result = await runtime.run(runtime.resolve({ - program: args.code, - bindings: [{ - global: 'tools', - functions, - errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, - }], + let dispatches = 0 + // The per-run scheduler uses the registry's staged interface and follows + // the same concurrency rules as the native loop. It also follows the + // native loop's SEQUENCING: every ordered stage (the dispatch-start + // append, prepare = pre-execute/guards, finalize/finish = post-execute, + // context deferral, the settle append) runs inside ONE driver lane, so + // ordered policy stages never overlap each other and only the + // around-dispatch/body stage runs concurrently. Starts are strictly + // submission-ordered; results commit in submission order through the + // head-of-line cursor. Consecutive parallel-classified calls overlap up + // to maxParallel; an exclusive call waits for the pool to drain, runs + // alone, and holds its barrier until its COMMIT (post-execute included) + // completes, exactly like a native exclusive group. Classification is + // re-read via executionMode() immediately before each start (a registry + // mutation while queued can flip a call exclusive), matching the native + // scheduler's lazy reclassification. + interface PendingDispatch { + /** Ordered stage: append the start event, await prepare (pre-execute/guards), launch the body into `flight`. */ + start(): Promise + classify(): 'parallel' | 'exclusive' + abandon(): void + /** Ordered stage: post-execute + context deferral + settle event, in submission order. */ + commit(): Promise + /** The launched around-dispatch/body stage; resolved until start() replaces it. */ + flight: Promise + /** True once the dispatch stage parked its outcome; the commit cursor waits on it. */ + settled: boolean + /** The classification this entry started under; an exclusive holds its barrier through commit(). */ + mode?: 'parallel' | 'exclusive' + } + const pendingQueue: PendingDispatch[] = [] + const inFlight = new Set>() + /** Tracked settle-event side work (log-content listener + append), drained at run settlement. */ + const logWork = new Set>() + const commitQueue: PendingDispatch[] = [] + let exclusiveActive = false + let driving = false + let driverRun: Promise = Promise.resolve() + let wake: (() => void) | undefined + const wakeup = (): void => { + const release = wake + wake = undefined + release?.() + } + /** + * The single ordered lane. Each pass commits the head-of-line settled + * dispatch (ordered post-execute), then starts the next queued entry if + * its slot is free (ordered pre-execute), and otherwise sleeps until a + * body settles or a new submission arrives. One run reaching the + * empty-queues/empty-pool state is quiescence. + */ + const drive = (): Promise => { + if (driving) return driverRun + driving = true + driverRun = (async () => { + try { + for (;;) { + // Create the wakeup promise before inspecting state so a settle or submission arriving + // between the checks and the await below cannot be lost. + const signal = new Promise((resolve) => { wake = resolve }) + const commitHead = commitQueue[0] + if (commitHead !== undefined && commitHead.settled) { + commitQueue.shift() + await commitHead.commit() + // The barrier covers post-execute: later starts wait for the + // exclusive call's full pipeline, as under the native loop. + if (commitHead.mode === 'exclusive') exclusiveActive = false + continue + } + const head = pendingQueue[0] + if (head !== undefined) { + if (runController.signal.aborted) { + pendingQueue.shift() + head.abandon() + continue + } + // Reclassify at start time (fail-closed on registry changes). + const mode = head.classify() + const capacity = !exclusiveActive + && (mode === 'exclusive' ? inFlight.size === 0 : inFlight.size < maxParallel) + if (capacity) { + if (mode === 'exclusive') exclusiveActive = true + head.mode = mode + pendingQueue.shift() + // Joined before start() so the commit cursor sees submission + // order; nothing commits it until `settled` flips. + commitQueue.push(head) + await head.start() + const flight: Promise = head.flight.finally(() => { + inFlight.delete(flight) + wakeup() + }) + inFlight.add(flight) + continue + } + } + if (pendingQueue.length === 0 && commitQueue.length === 0 && inFlight.size === 0) return + await signal + } + } finally { + driving = false + wake = undefined + } + })() + return driverRun + } + /** Every dispatch settled AND committed; nothing can start (the run is aborted at call time). */ + const drainDispatches = async (): Promise => { + // The abort already fired: the driver abandons queued-unstarted + // entries, awaits the live pool, and drains the ordered commit lane — + // including a commit already in progress when the program returned. + await drive() + // Every settle event is appended inside the open run_code turn + // (tasks self-remove on settlement). + while (logWork.size > 0) await Promise.allSettled([...logWork]) + } + + // Read through a call, not a bare property: the abort state genuinely + // changes across awaits, and a direct `.aborted` re-check after one + // would be narrowed away by control flow analysis. + const runOver = (): boolean => runController.signal.aborted + + const binding = (schema: ToolSchema): PtcBindingFunction => async (rawArgs: unknown): Promise => { + const { name } = schema + if (runOver()) { + throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} not dispatched`) + } + const normalized = jsonNormalizeArgs(rawArgs) + const n = ++dispatches + const subCallId = brandString(`${String(exec.callId)}:ptc:${n}`) + const input = { + callId: subCallId, + rootCallId: exec.rootCallId, + name, + schema, + arguments: normalized.dispatched, + ...exec.agent ? { agent: exec.agent } : {}, + parent: exec.token, signal: runController.signal, - ...cwd !== undefined ? { cwd } : {}, - ...policy !== undefined ? { sandboxPolicy: policy } : {}, - ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {}, - })) - } finally { - // Abort sub-dispatches and drain every in-flight dispatch before - // closing the turn (queued-unstarted ones are abandoned unlogged). - // Binding failures remain observable through their individual promises. - runController.abort('run_code settled') - await drainDispatches() + } + type DispatchOutcome = { isError: true; message: string } | { isError: false; value: JsonValue } + const scheduler = registry[TOOL_RUNTIME_SCHEDULER] + const outcome = await new Promise((resolve, reject) => { + // Set by the dispatch stage (or start() for a pre-settled result): what commit() finalizes in submission order. + let parked: + | { kind: 'post-result' | 'final-result'; exec: ToolRunContext; result: ToolExecutionResult } + | undefined + const settle = (result: ToolExecutionResult): void => { + // The program gets its value NOW: the log-content listener (for + // example, a spill backend) must never delay the binding or occupy + // a dispatch slot. The event append is tracked side work; the run's + // settlement drains logWork so every settle event is still appended + // inside the open turn (shapeDispatchLog is contained, so this + // chain cannot reject). + resolve(result.isError + ? { isError: true, message: result.error.message } + : { isError: false, value: result.value }) + const agent = exec.agent + if (agent === undefined) return + const task: Promise = (async () => { + // The listener may replace the durable copy with a preview and + // locator; the program's value and model-visible result are + // untouched. + const logged = await shapeDispatchLog({ + exec, agent, subCallId, name, isError: result.isError, + // The registry deep-froze this projection at result + // finalization; append snapshots the final copy again, so + // the log stays detached. + content: result.content, + }) + agent.session.append('tool/ptc-dispatch', { + rootCallId: exec.rootCallId, + parentCallId: exec.callId, + subCallId, + name, + // The SIBLING parse of the dispatched value: byte-identical JSON, + // but a separate object — a tool mutating its args cannot desync + // this record from what it actually received. + arguments: normalized.logged, + isError: result.isError, + ...result.error?.info === undefined ? {} : { error: result.error.info }, + content: logged, + ...result.meta === undefined ? {} : { meta: result.meta }, + }) + })().finally(() => { logWork.delete(task) }) + logWork.add(task) + } + pendingQueue.push({ + flight: Promise.resolve(), + settled: false, + // Re-read per driver pass against the same agent view the SDK + // declared; fail-closed exclusive when undeclared/invalid. + classify: () => registry.executionMode(input).kind, + abandon: () => { + reject(new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} tool call abandoned`)) + }, + async start(): Promise { + exec.agent?.session.append('tool/ptc-dispatch-start', { + rootCallId: exec.rootCallId, + parentCallId: exec.callId, + subCallId, + name, + arguments: normalized.logged, + }) + // Ordered prepare runs INSIDE the driver lane: the next entry's + // pre-execute waits for this resolution, as under the native + // scheduler. Only the launched body below overlaps. + const prepared = await scheduler.prepare(input) + if (prepared.kind === 'dispatch') { + this.flight = scheduler.dispatch(prepared.exec).then((dispatchOutcome) => { + parked = { kind: dispatchOutcome.kind, exec: prepared.exec, result: dispatchOutcome.result } + this.settled = true + }) + return + } + parked = { kind: prepared.kind, exec: prepared.exec, result: prepared.result } + this.settled = true + }, + async commit(): Promise { + /* v8 ignore next -- commit() runs only after `settled` flipped, which set parked. */ + if (parked === undefined) return + const result = parked.kind === 'post-result' + ? await scheduler.finalize(parked.exec, parked.result) + : scheduler.finish(parked.exec, parked.result) + if (!result.isError && result.content.some(block => block.type === 'image')) { + exec.deferContext(createUserMessage({ + content: result.content, + source: { kind: 'ptc-mode' }, + })) + } + for (const context of result.additionalContexts ?? []) { + exec.deferContext(context) + } + // The composite forwards `additionalContexts` above and + // `concludesTurn` here from the nested result. Only a successful + // nested result can carry the terminal marker + // (ToolExecutionFailure types it never), so a policy-converted + // failure cannot stop the turn through a recovering program. + if (result.concludesTurn) exec.concludeTurn() + settle(result) + // Backpressure on pending event-append tasks: each task retains + // a full result while a slow backend stores it, so the pool cap + // bounds their count. Beyond the cap, the + // ordered lane waits, so later sub-calls cannot start and + // pending I/O/memory cannot grow without bound. + while (logWork.size > maxParallel) await Promise.race(logWork) + }, + }) + wakeup() + void drive() + }) + // A budget expiry or outer cancel that occurs while this call was in + // flight already aborted the dispatch; stop the program now rather + // than hand it a result from a run that is over. + if (runOver()) { + throw new Error(`run_code run is over (${String(runController.signal.reason)}); ${name} result discarded`) + } + // The worker turns a binding rejection into ToolCallError and adds + // only the binding name. Native content and internal error metadata + // stay outside the program-facing failure contract. + if (outcome.isError) throw new Error(outcome.message) + return outcome.value } - if (result.error) { - const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : '' - const sandboxText = result.sandbox === undefined ? '' - : `\nFile sandbox: ${result.sandbox.mode}${result.sandbox.enforcement === undefined ? '' : `; enforcement: ${result.sandbox.enforcement}`}${result.sandbox.denied ? '; operation denied' : ''}.` - throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime) : ''}`) + // Null-prototype + defineProperty, mirroring the worker-side namespace + // build: a registered tool named `__proto__` must become an ordinary + // own key (a plain-object assignment would hit the prototype setter, + // silently dropping the binding), and the runtime host resolves + // binding names as own properties only. + const functions: Record = Object.create(null) as Record + // Enumerate the CALLING AGENT's visible set (scoped tools join, + // restricted globals vanish) — the same view the SDK section declared, + // so a program can bind exactly what its prompt promised; sub-dispatch + // re-resolves per call through the same view (exec.agent threads down). + for (const schema of registry.schemas(exec.agent)) { + if (schema.name === RUN_CODE_NAME) continue + Object.defineProperty(functions, schema.name, { enumerable: true, value: binding(deepFreeze(schema)) }) } - return { - logs: result.logs, - ...result.sandbox === undefined ? {} : { sandbox: result.sandbox }, - ...result.value !== undefined ? { result: result.value } : {}, + + try { + let result: PtcRunResult + try { + if (exec.agent !== undefined) { + const agent = exec.agent + let runtimes = stateOwners.get(agent) + if (runtimes === undefined) stateOwners.set(agent, runtimes = new WeakSet()) + // Cordis can wrap service returns repeatedly; cleanup belongs to the original provider. + let provider = runtime + for (;;) { + const original = (provider as PtcRuntime & { [symbols.original]?: PtcRuntime })[symbols.original] + if (original === undefined) break + provider = original + } + if (!runtimes.has(provider)) { + agent.ctx.effect(() => () => runtime.release(agent), 'PTC retained environment') + runtimes.add(provider) + } + } + result = await runtime.run(runtime.resolve({ + program: args.code, + ...exec.agent === undefined || policy?.mode !== standingPolicy?.mode ? {} : { stateOwner: exec.agent }, + bindings: [{ + global: 'tools', + functions, + errorClass: { name: 'ToolCallError', memberNameProperty: 'toolName' }, + }], + signal: runController.signal, + ...cwd !== undefined ? { cwd } : {}, + ...policy !== undefined ? { sandboxPolicy: policy } : {}, + ...args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {}, + })) + } finally { + // Abort sub-dispatches and drain every in-flight dispatch before + // closing the turn (queued-unstarted ones are abandoned unlogged). + // Binding failures remain observable through their individual promises. + runController.abort('run_code settled') + await drainDispatches() + } + + if (result.error) { + const logsText = result.logs.length > 0 ? `\nCaptured output:\n${result.logs.join('\n')}` : '' + const sandboxText = result.sandbox === undefined ? '' + : `\nFile sandbox: ${result.sandbox.mode}${result.sandbox.enforcement === undefined ? '' : `; enforcement: ${result.sandbox.enforcement}`}${result.sandbox.denied ? '; operation denied' : ''}.` + throw new CodeRunFailedError(`code run failed (${result.error.kind}): ${result.error.message}${logsText}${sandboxText}${result.sandbox?.denied ? escalationGuidance(runtime) : ''}`) + } + return { + logs: result.logs, + ...result.sandbox === undefined ? {} : { sandbox: result.sandbox }, + ...result.value !== undefined ? { result: result.value } : {}, + } + } finally { + callSignal.removeEventListener('abort', onOuterAbort) } - } finally { - exec.signal.removeEventListener('abort', onOuterAbort) } + return runtime.sandboxMode === undefined || exec.agent === undefined ? run(exec.signal) + : calls.run(exec.agent.session.id, exec.signal, () => options.resolveSandboxPolicy(exec).mode, run) }, // The model-authored description is the call's always-visible UI label // (the bash `description` precedent); the program itself rides rawInput. diff --git a/packages/core/tools/src/py-types.ts b/packages/core/tools/src/py-types.ts index 531ff13113..1f0f6e1067 100644 --- a/packages/core/tools/src/py-types.ts +++ b/packages/core/tools/src/py-types.ts @@ -732,12 +732,12 @@ export function jsonSchemaToPy(schema: unknown): string { /** The fixed model-facing usage contract rendered above the declarations. */ const SDK_INSTRUCTIONS = `## Writing code for run_code -\`run_code\` takes two required arguments: \`description\`, a short summary of what the program does, and \`code\` — the body of an async Python function (top-level \`await\` and \`return\` both work). At run time exactly two of the names declared below are bound: \`tools\` and \`ToolCallError\`. Everything else is a STATIC STUB describing argument and return types — in particular the \`TypedDict\` classes do NOT exist at run time, so build arguments as plain \`dict\`/\`list\` JSON values: \`await tools.name({"field": 1})\`, never \`FooArgs(field=1)\`, which raises \`NameError\`. Inside the program: +\`run_code\` takes two required arguments: \`description\`, a short summary of what the program does, and \`code\`, the program to execute. At run time exactly two of the names declared below are bound: \`tools\` and \`ToolCallError\`. Everything else is a STATIC STUB describing argument and return types — in particular the \`TypedDict\` classes do NOT exist at run time, so build arguments as plain \`dict\`/\`list\` JSON values: \`await tools.name({"field": 1})\`, never \`FooArgs(field=1)\`, which raises \`NameError\`. Inside the program: - Call tools as \`await tools.name(args)\` — subscript access for exotic, reserved, or underscore-leading names: \`await tools["my-tool"](args)\`. Every call resolves to the tool's typed canonical JSON value (each method's return type below). Tool arguments must be lossless JSON. - A FAILED tool call raises \`ToolCallError\`, whose \`toolName\` identifies the failed tool and whose message is human-readable — wrap in \`try/except\` to handle and continue. - Independent read-only calls MAY overlap under \`asyncio.gather\` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with \`await\`. -- Emit the run's answer with \`print(...)\` and/or a top-level \`return \`; the returned value must be lossless JSON. Only what you print and return is program output. A successful tool result containing an image is attached after the run so you can inspect it on the next step; every other intermediate result stays out of the conversation, so extract just what you need. +- Only values emitted as program output enter the conversation. A successful tool result containing an image is attached after the run so you can inspect it on the next step; every other intermediate result stays out of the conversation, so extract just what you need. The available tools:` diff --git a/packages/core/tools/src/ts-types.ts b/packages/core/tools/src/ts-types.ts index 1c4c71c38a..91abe9945d 100644 --- a/packages/core/tools/src/ts-types.ts +++ b/packages/core/tools/src/ts-types.ts @@ -249,14 +249,14 @@ export function jsonSchemaToTs(schema: unknown, indent = 0): string { /** The fixed model-facing usage contract rendered above the declarations (see the PTC mode Agent Note's "What the model sees"). */ const SDK_INSTRUCTIONS = `## Writing code for run_code -\`run_code\` takes two required arguments: \`description\`, a short summary of what the program does, and \`code\` — the body of an async TypeScript function (erasable syntax only — no \`enum\` or namespaces; type annotations are advisory, the code runs type-stripped). The declarations below are SDK bindings for this program. A declaration does not make its name a directly callable tool; only names supplied as separate tool schemas may be called directly.` +\`run_code\` takes two required arguments: \`description\`, a short summary of what the program does, and \`code\`, the program to execute. The declarations below are SDK bindings for this program. A declaration does not make its name a directly callable tool; only names supplied as separate tool schemas may be called directly.` const SDK_PROGRAM_INSTRUCTIONS = `Inside the program: - Call tools as \`await tools.name(args)\` — quoted access for exotic names: \`tools["my-tool"](args)\`. Every call resolves to the tool's typed canonical JSON value. Tool arguments must be lossless JSON. - A FAILED tool call rejects with \`ToolCallError\`, whose \`toolName\` identifies the failed tool and whose \`message\` is human-readable — \`try/catch\` it to handle and continue. - Independent read-only calls MAY overlap under \`Promise.all\` (safe calls run concurrently; mutating calls run alone, in submission order). Sequence dependent work with \`await\`. -- Emit results with \`return\` and/or \`console.log(...)\`. Only what you print or return is program output. A successful tool result containing an image is attached after the run so you can inspect it on the next step; every other intermediate result stays out of the conversation, so extract just what you need. +- Only values emitted as program output enter the conversation. A successful tool result containing an image is attached after the run so you can inspect it on the next step; every other intermediate result stays out of the conversation, so extract just what you need. Program-only SDK bindings:` @@ -279,7 +279,7 @@ function renderBashExample(schemas: ToolSdkSchema[]): string { const needsDescription = required.includes('description') if (needsDescription && !acceptsExampleString(parameters.properties?.description, 'Show current directory')) return '' const description = needsDescription ? "description: 'Show current directory', " : '' - return ` When no separate \`bash\` schema is supplied, invoke a declared \`bash\` binding inside \`run_code\`:\n\n\`run_code({ description: "Show current directory", code: "return await tools.bash({ ${description}command: 'pwd' })" })\`` + return ` When no separate \`bash\` schema is supplied, invoke a declared \`bash\` binding inside \`run_code\`:\n\n\`run_code({ description: "Show current directory", code: "console.log(await tools.bash({ ${description}command: 'pwd' }))" })\`` } /** diff --git a/packages/core/tools/tests/ptc-calls.spec.ts b/packages/core/tools/tests/ptc-calls.spec.ts new file mode 100644 index 0000000000..bf5dce527a --- /dev/null +++ b/packages/core/tools/tests/ptc-calls.spec.ts @@ -0,0 +1,89 @@ +import { Context } from '@deepseek-ai/cordis' +import Sessions, { SessionId } from '@deepseek-ai/dsh-session' +import SandboxPolicy, { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' +import SessionProjections from '@deepseek-ai/dsh-session-projection' +import { expect, it, onTestFinished, vi } from 'vitest' +import { PtcCalls } from '../src/ptc-calls.ts' + +async function setup() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(Sessions) + await ctx.plugin(SessionProjections) + await ctx.plugin(SandboxPolicy, { mode: 'workspace-write' }) + const session = ctx.sessions.create(SessionId('ptc-calls')) + const calls = new PtcCalls(ctx) + const mode = () => ctx.sandboxPolicy.resolve({ session }).mode + const signal = new AbortController().signal + return { ctx, session, calls, mode, signal } +} + +it('commits policy immediately, cancels existing calls, and waits for their complete cleanup before reading the latest mode', async () => { + const { ctx, session, calls, mode, signal } = await setup() + const cleanup = Promise.withResolvers() + let oldSignal: AbortSignal | undefined + const first = calls.run(session.id, signal, mode, async (current) => { oldSignal = current; await cleanup.promise }) + const next = vi.fn(async () => mode()) + try { + session.append('turn/start', { turn: 1 }) + setSandboxMode(ctx.sessions.create(SessionId('another')), 'read-only') + setSandboxMode(session, 'workspace-write') + expect(oldSignal?.aborted).toBe(false) + setSandboxMode(session, 'read-only') + expect(mode()).toBe('read-only') + expect(oldSignal?.aborted).toBe(true) + const second = calls.run(session.id, signal, mode, next) + expect(next).not.toHaveBeenCalled() + setSandboxMode(session, 'danger-full-access') + cleanup.resolve(undefined) + await first + expect(await second).toBe('danger-full-access') + } finally { cleanup.resolve(undefined); await first } +}) + +it('releases failed calls and allows same-policy calls to overlap', async () => { + const { session, calls, mode, signal } = await setup() + const cleanup = Promise.withResolvers() + const first = calls.run(session.id, signal, mode, () => cleanup.promise) + try { + await expect(calls.run(session.id, signal, mode, async () => { throw new Error('failed call') })).rejects.toThrow('failed call') + expect(await calls.run(session.id, signal, mode, async () => 'next')).toBe('next') + } finally { cleanup.resolve(undefined); await first } +}) + +it('honors cancellation while waiting for a canceled predecessor', async () => { + const { session, calls, mode, signal } = await setup() + const cleanup = Promise.withResolvers() + const first = calls.run(session.id, signal, mode, () => cleanup.promise) + setSandboxMode(session, 'read-only') + const controller = new AbortController() + const next = vi.fn(async () => 'unexpected') + const second = calls.run(session.id, controller.signal, mode, next) + const rejected = expect(second).rejects.toThrow('caller canceled') + controller.abort(new Error('caller canceled')) + cleanup.resolve(undefined) + await first + await rejected + expect(next).not.toHaveBeenCalled() +}) + +it('unloads the registry only after calls stop and refuses late admission', async () => { + const { ctx, session, calls, mode, signal } = await setup() + const cleanup = Promise.withResolvers() + const stopped = Promise.withResolvers() + const first = calls.run(session.id, signal, mode, async (current) => { + current.addEventListener('abort', () => { stopped.resolve(undefined) }, { once: true }) + await cleanup.promise + }) + const disposed = ctx.fiber.dispose() + try { + await stopped.promise + const next = calls.run(session.id, signal, mode, async () => 'unexpected') + const rejected = expect(next).rejects.toThrow('PTC tool registry disposed') + cleanup.resolve(undefined) + await first + await rejected + await disposed + await expect(calls.run(session.id, signal, mode, async () => 'unexpected')).rejects.toThrow('PTC tool registry disposed') + } finally { cleanup.resolve(undefined); await first; await disposed } +}) diff --git a/packages/core/tools/tests/ptc.spec.ts b/packages/core/tools/tests/ptc.spec.ts index aa18a99f0f..5d2f888674 100644 --- a/packages/core/tools/tests/ptc.spec.ts +++ b/packages/core/tools/tests/ptc.spec.ts @@ -1,4 +1,5 @@ -import { describe, expect, it, vi } from 'vitest' +import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' +import { describe, expect, it, onTestFinished, vi } from 'vitest' import { provideWorkingDirectoryFixture } from '@deepseek-ai/dsh-agent-loop-testkit' import { Context } from '@deepseek-ai/cordis' import { createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm' @@ -12,7 +13,7 @@ import type { PtcRunRequest, PtcRunResult } from '@deepseek-ai/dsh-ptc-runtime' import ToolRuntime, { CodeRunFailedError, RUN_CODE_NAME, TOOL_ABORTED_BEFORE_DISPATCH, defineContentToolFixture, defineTool } from '@deepseek-ai/dsh-tools' import type { Config, JsonSchemaNode, PostToolDecision, ToolExecutionResult } from '@deepseek-ai/dsh-tools' import type { Agent } from '@deepseek-ai/dsh-agent' -import { Session, SessionId } from '@deepseek-ai/dsh-session' +import SessionStore, { Session, SessionId } from '@deepseek-ai/dsh-session' import ApprovalService, { type ApprovalOutcome, type ApprovalRequest } from '@deepseek-ai/dsh-user-approval' import type { SessionEventMap } from '@deepseek-ai/dsh-session' import type { JsonValue } from '@deepseek-ai/dsh-util-values' @@ -78,7 +79,7 @@ async function setup(options: SetupOptions = {}) { /** Mint an agent scope configured like production that can register scoped tool policy. */ async function mintAgentScope(ctx: Context, name = 'scoped'): Promise<{ scope: Scope; agent: Agent }> { - const agent = { id: SessionId(name), session: { header: {}, append: () => {} } } as unknown as Agent + const agent = { ctx, id: SessionId(name), session: Session.create(SessionId(name)) } as Agent let scope!: Scope await ctx.plugin(Object.assign((inner: Context) => { scope = createScope(inner, agent) }, { inject: ['tools', 'systemPrompt'] })) @@ -107,12 +108,15 @@ function registerEcho(ctx: Context, name = 'echo'): unknown[] { /** A structural fake of the owning agent: captures session appends. */ function fakeAgent(): { agent: Agent; events: { type: string; data: unknown }[] } { const events: { type: string; data: unknown }[] = [] + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) const agent = { + ctx, session: { header: { cwd: '/workspace' }, append: (type: string, data: unknown) => { events.push({ type, data }) }, }, - } as unknown as Agent + } as Agent return { agent, events } } @@ -145,7 +149,7 @@ it('logs detached frozen nested metadata without changing the binding value or l })) ctx.on('tools/ptc-dispatch-log', async () => [{ type: 'text', text: 'redacted durable preview' }]) const session = Session.create(SessionId('ptc-location')) - const agent = { session } as Agent + const agent = { ctx, session } as Agent runtime.behavior = async (request) => { const value = await request.bindings[0]!.functions.location!({}) expect(value).toBe('original contents') @@ -453,7 +457,7 @@ describe('mode-aware wire contribution', () => { const sdk = assembly.sections.find(section => section.name === 'tools:sdk') expect(sdk?.text).toContain('class Tools(Protocol):') expect(sdk?.text).toContain('async def echo(self, args:') - expect(sdk?.text).toContain('top-level `await`') + expect(sdk?.text).toContain('and `code`, the program to execute') expect(assembly.tools.map(tool => tool.name)).toEqual([RUN_CODE_NAME]) expect(assembly.tools[0]?.description).toContain('Execute a Python program') }) @@ -489,13 +493,13 @@ describe('mode-aware wire contribution', () => { const assembly = await systemPrompt.assemble() const runCodeSchema = assembly.tools.find(tool => tool.name === RUN_CODE_NAME) expect(runCodeSchema?.description).toContain('Execute a TypeScript program') - expect(runCodeSchema?.description).toContain('BODY of an') + expect(runCodeSchema?.description).toContain('`code`, the program to execute') // Both required arguments are named here, not only in the parameter // schema: prose that describes the call as "pass the program" is what // leads a model to emit `{code}` alone and fail INVALID_ARGS. expect(runCodeSchema?.description).toContain('`description`') const codeParam = (runCodeSchema?.parameters as { properties: { code: { description: string } } }).properties.code - expect(codeParam.description).toBe('The program: the body of an async TypeScript function.') + expect(codeParam.description).toBe("The TypeScript program to execute, following this tool's execution instructions.") }) it('emits a Python-flavored run_code schema under a python runtime (matches the SDK language)', async () => { @@ -504,11 +508,11 @@ describe('mode-aware wire contribution', () => { const assembly = await systemPrompt.assemble() const runCodeSchema = assembly.tools.find(tool => tool.name === RUN_CODE_NAME) expect(runCodeSchema?.description).toContain('Execute a Python program') - expect(runCodeSchema?.description).toContain('`return `') + expect(runCodeSchema?.description).toContain('`code`') expect(runCodeSchema?.description).toContain('`description`') expect(runCodeSchema?.description).not.toContain('TypeScript') const codeParam = (runCodeSchema?.parameters as { properties: { code: { description: string } } }).properties.code - expect(codeParam.description).toBe('The program: the body of an async Python function.') + expect(codeParam.description).toBe("The Python program to execute, following this tool's execution instructions.") }) it('resolves the run_code schema flavor lazily and fails loud on a language absent from the flavor table', async () => { @@ -539,7 +543,7 @@ describe('mode-aware wire contribution', () => { const definition = ctx.tools.get(RUN_CODE_NAME) expect(definition?.description).toContain('Execute a TypeScript program') const params = definition?.parameters as { properties: { code: { description: string } } } - expect(params.properties.code.description).toBe('The program: the body of an async TypeScript function.') + expect(params.properties.code.description).toBe("The TypeScript program to execute, following this tool's execution instructions.") }) it("rejects the assembly when toolOrder names a native tool that mode 'ptc' no longer contributes", async () => { @@ -1788,7 +1792,7 @@ describe('the run_code dispatch bridge', () => { }, })) const session = Session.create(SessionId('deep-code-arguments')) - const agent = { session } as Agent + const agent = { ctx, session } as Agent runtime.behavior = async (request) => { let nested: JsonValue = 'leaf' for (let index = 0; index < depth; index++) nested = [nested] @@ -2258,6 +2262,7 @@ describe('PTC standing file policy and sandbox outcomes', () => { describe('per-program execution controls', () => { async function controlledSetup(approval = true) { const state = await setup() + await state.ctx.plugin(SessionStore) await state.ctx.plugin(SessionProjections) await state.ctx.plugin(SandboxPolicy, { mode: 'read-only', workspaceRoot: process.cwd() }) if (approval) await state.ctx.plugin(ApprovalService, { policy: 'ask' }) @@ -2266,9 +2271,9 @@ describe('per-program execution controls', () => { executionInstructions: { get: () => 'Programs start with an empty environment.' }, timeout: { get: () => ({ defaultMs: 120_000, maxMs: 600_000 }) }, }) - const session = Session.create(SessionId('program-controls')) + const session = state.ctx.sessions.create(SessionId('program-controls')) session.append('turn/start', { turn: 1 }) - const agent = { session } as unknown as Agent + const agent = { ctx: state.ctx, session } as Agent const execute = (args: Record, signal = testToolSignal) => state.tools.execute({ callId: ToolCallId('program-controls'), name: RUN_CODE_NAME, arguments: { code: 'program', description: 'Test execution controls', ...args }, agent, signal, @@ -2276,6 +2281,26 @@ describe('per-program execution controls', () => { return { ...state, agent, session, execute } } + it('executes an agentless confined program without a Session execution scope', async () => { + const { ctx, runtime } = await controlledSetup() + try { + expect((await runCode(ctx, 'program')).isError).toBe(false) + expect(runtime.lastRequest?.stateOwner).toBeUndefined() + expect(runtime.lastRequest?.sandboxPolicy?.sessionId).toBeUndefined() + } finally { await ctx.fiber.dispose() } + }) + + it('rejects Agent-owned confined execution when its policy service is absent', async () => { + const { ctx, runtime } = await setup() + const mode = vi.spyOn(runtime, 'sandboxMode', 'get').mockReturnValue('read-only') + const { agent } = fakeAgent() + try { + const result = await runCode(ctx, 'program', { agent }) + expect(result.isError).toBe(true) + expect(JSON.stringify(result.content)).toContain('confined PTC runtime requires sandboxPolicy') + } finally { mode.mockRestore(); await ctx.fiber.dispose() } + }) + it('advertises configured timeout values and one-execution scope only when supported', async () => { const { ctx, tools } = await controlledSetup() try { @@ -2358,6 +2383,18 @@ describe('per-program execution controls', () => { } finally { await ctx.fiber.dispose() } }) + it('reuses the standing owner when sandbox_permissions repeats the current mode', async () => { + const { ctx, runtime, session, agent, execute } = await controlledSetup() + const ask = vi.fn(() => Promise.resolve('allowed-once')) + ctx.on('approval/request', ask) + try { + setSandboxMode(session, 'workspace-write') + expect((await execute({ sandbox_permissions: 'workspace-write', justification: 'Use current file permissions' })).isError).toBe(false) + expect(runtime.lastRequest?.stateOwner).toBe(agent) + expect(ask).not.toHaveBeenCalled() + } finally { await ctx.fiber.dispose() } + }) + it('fails closed when no approval service is mounted', async () => { const { ctx, runtime, execute } = await controlledSetup(false) try { @@ -2367,8 +2404,8 @@ describe('per-program execution controls', () => { } finally { await ctx.fiber.dispose() } }) - it('cancels an outstanding approval without launching the program', async () => { - const { ctx, runtime, execute } = await controlledSetup() + it.each(['caller', 'policy'] as const)('cancels an outstanding approval after %s cancellation without launching the program', async (source) => { + const { ctx, runtime, session, execute } = await controlledSetup() const asked = Promise.withResolvers() const answer = Promise.withResolvers() const controller = new AbortController() @@ -2376,7 +2413,8 @@ describe('per-program execution controls', () => { const result = execute({ sandbox_permissions: 'workspace-write', justification: 'Write generated source' }, controller.signal) try { await asked.promise - controller.abort('cancel outer approval') + if (source === 'caller') controller.abort('cancel outer approval') + else setSandboxMode(session, 'workspace-write') expect((await result).isError).toBe(true) expect(runtime.lastRequest).toBeUndefined() } finally { answer.resolve('cancelled'); await result; await ctx.fiber.dispose() } @@ -2434,7 +2472,41 @@ describe('per-program execution controls', () => { expect(completed.isError).toBe(false) expect(requests.map(req => req.toolName)).toEqual([RUN_CODE_NAME, 'echo']) expect(runtime.lastRequest?.timeoutMs).toBe(1234) + expect(runtime.lastRequest?.stateOwner).toBeUndefined() expect(ctx.sandboxPolicy.resolve({ session: agent.session }).mode).toBe('read-only') } finally { answer.resolve('cancelled'); await result; await ctx.fiber.dispose() } }) }) + +describe('PTC state ownership', () => { + it.each(['function-body', 'repl'] as const)('uses one Agent owner and releases %s provider state on disposal', async (programFormat) => { + const { ctx, runtime } = await setup() + const agentContext = new Context() + const { agent } = fakeAgent() + Object.defineProperty(agent, 'ctx', { value: agentContext }) + const format = vi.spyOn(runtime, 'programFormat', 'get').mockReturnValue(programFormat) + const release = vi.spyOn(runtime, 'release') + try { + expect(ctx.tools.schemas().find(tool => tool.name === 'run_code')?.description).not.toContain('persistent-in-memory') + expect((await runCode(ctx, 'let value = 1', { agent })).isError).toBe(false) + expect((await runCode(ctx, 'value', { agent })).isError).toBe(false) + expect(runtime.lastRequest?.stateOwner).toBe(agent) + await agentContext.fiber.dispose() + expect(release).toHaveBeenCalledExactlyOnceWith(agent) + expect((await runCode(ctx, '1')).isError).toBe(false) + expect(runtime.lastRequest?.stateOwner).toBeUndefined() + } finally { format.mockRestore(); release.mockRestore(); await agentContext.fiber.dispose(); await ctx.fiber.dispose() } + }) + + it('keeps provider evaluation instructions independent of language and program format', async () => { + const { ctx, runtime } = await setup({ runtime: { language: 'python' } }) + const format = vi.spyOn(runtime, 'programFormat', 'get').mockReturnValue('repl') + const instructions = vi.spyOn(runtime, 'executionInstructions', 'get').mockReturnValue('Each call evaluates Python expressions in a fresh environment.') + try { + const description = ctx.tools.schemas().find(tool => tool.name === 'run_code')?.description + expect(description).toContain('Each call evaluates Python expressions in a fresh environment.') + expect(description).not.toContain('persistent-in-memory') + expect(description).not.toContain('TypeScript') + } finally { format.mockRestore(); instructions.mockRestore(); await ctx.fiber.dispose() } + }) +}) diff --git a/packages/core/tools/tests/py-types.spec.ts b/packages/core/tools/tests/py-types.spec.ts index 48dbfdd815..f940c45e42 100644 --- a/packages/core/tools/tests/py-types.spec.ts +++ b/packages/core/tools/tests/py-types.spec.ts @@ -151,7 +151,7 @@ describe('renderToolsSdkPy', () => { expect(text).toContain('# tools["my-mcp.tool"](args: dict[str, Any]) -> str') expect(text).toContain('# tools["class"](args: dict[str, Any]) -> str') // Fixed instruction lines the model relies on. - expect(text).toContain('top-level `await`') + expect(text).toContain('and `code`, the program to execute') // The binding boundary: `tools`/`ToolCallError` are bound, the TypedDicts // are not. Both halves are pinned — dropping either one turns a correct // contract into a wrong one (a model that reads only "STATIC STUB" would diff --git a/packages/core/tools/tests/ts-types.spec.ts b/packages/core/tools/tests/ts-types.spec.ts index 78a1f48203..a0f4c81ff0 100644 --- a/packages/core/tools/tests/ts-types.spec.ts +++ b/packages/core/tools/tests/ts-types.spec.ts @@ -146,7 +146,7 @@ describe('renderToolsSdk', () => { expect(text).toContain('[K in ToolName]: (args: ToolArgsMap[K]) => Promise;') expect(text).toContain('/** Run a shell command. */') // The fixed instruction lines the model relies on. - expect(text).toContain('erasable syntax only') + expect(text).toContain('and `code`, the program to execute') expect(text).toContain('rejects with `ToolCallError`') expect(text).toContain('MAY overlap under `Promise.all`') expect(text).toContain('lossless JSON') @@ -163,7 +163,7 @@ describe('renderToolsSdk', () => { const text = renderToolsSdk([bash]) expect(text).toContain('A declaration does not make its name a directly callable tool') expect(text).toContain('only names supplied as separate tool schemas may be called directly') - expect(text).toContain('`run_code({ description: "Show current directory", code: "return await tools.bash({ description: \'Show current directory\', command: \'pwd\' })" })`') + expect(text).toContain('`run_code({ description: "Show current directory", code: "console.log(await tools.bash({ description: \'Show current directory\', command: \'pwd\' }))" })`') expect(text).toContain('Program-only SDK bindings:') expect(text).not.toContain('The available tools:') }) @@ -214,6 +214,14 @@ describe('renderToolsSdk', () => { expect(renderToolsSdk([constrained])).toContain('tools.bash({ command: \'pwd\' })') }) + it('uses an output example accepted by both Node execution modes', () => { + const text = renderToolsSdk([bash]) + expect(text).toContain('console.log(await tools.bash(') + expect(text).not.toContain('return await tools.bash') + expect(text).not.toContain('body of an async TypeScript function') + expect(text).not.toContain('TypeScript REPL statements') + }) + it('is deterministic: same tool set, byte-identical text regardless of input order', () => { expect(renderToolsSdk([bash, exotic])).toBe(renderToolsSdk([exotic, bash])) // Equal names sort stably (the comparator's equal arm). diff --git a/packages/credentials/authorization/locale/en.json b/packages/credentials/authorization/locale/en.json new file mode 100644 index 0000000000..8994ac6ecc --- /dev/null +++ b/packages/credentials/authorization/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "authorization" + } +} diff --git a/packages/credentials/authorization/locale/zh.json b/packages/credentials/authorization/locale/zh.json new file mode 100644 index 0000000000..bdf3420d15 --- /dev/null +++ b/packages/credentials/authorization/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "授权流程服务", + "description": "组织需要用户参与的登录和凭据授权流程。" + } +} diff --git a/packages/credentials/authorization/package.json b/packages/credentials/authorization/package.json index 63def783d8..f0c692c7aa 100644 --- a/packages/credentials/authorization/package.json +++ b/packages/credentials/authorization/package.json @@ -23,9 +23,11 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/credentials/credentials-local/locale/en.json b/packages/credentials/credentials-local/locale/en.json new file mode 100644 index 0000000000..04f0645da2 --- /dev/null +++ b/packages/credentials/credentials-local/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "credentials-local" + } +} diff --git a/packages/credentials/credentials-local/locale/zh.json b/packages/credentials/credentials-local/locale/zh.json new file mode 100644 index 0000000000..1c3eb9d615 --- /dev/null +++ b/packages/credentials/credentials-local/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "本地凭据存储", + "description": "保存 API 密钥等凭据,并按优先级读取环境变量和本地凭据文件。" + } +} diff --git a/packages/credentials/credentials-local/package.json b/packages/credentials/credentials-local/package.json index 7eafba6772..501e8515ce 100644 --- a/packages/credentials/credentials-local/package.json +++ b/packages/credentials/credentials-local/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/credentials/deepseek-account-platform/locale/en.json b/packages/credentials/deepseek-account-platform/locale/en.json new file mode 100644 index 0000000000..542b6b880f --- /dev/null +++ b/packages/credentials/deepseek-account-platform/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "deepseek-account-platform" + } +} diff --git a/packages/credentials/deepseek-account-platform/locale/zh.json b/packages/credentials/deepseek-account-platform/locale/zh.json new file mode 100644 index 0000000000..86bbe95c12 --- /dev/null +++ b/packages/credentials/deepseek-account-platform/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "DeepSeek 账号登录", + "description": "通过浏览器完成 DeepSeek 账号登录授权。" + } +} diff --git a/packages/credentials/deepseek-account-platform/package.json b/packages/credentials/deepseek-account-platform/package.json index c07bd45e51..fbd24caa37 100644 --- a/packages/credentials/deepseek-account-platform/package.json +++ b/packages/credentials/deepseek-account-platform/package.json @@ -23,9 +23,11 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/credentials/deepseek-account-platform/tests/account.spec.ts b/packages/credentials/deepseek-account-platform/tests/account.spec.ts index 938a6f30c0..8bb802aec1 100644 --- a/packages/credentials/deepseek-account-platform/tests/account.spec.ts +++ b/packages/credentials/deepseek-account-platform/tests/account.spec.ts @@ -624,9 +624,11 @@ it('closes the failed Web authorization tab without redirecting and keeps the sh it('completes login through a local TCP forward using the browser port rather than the Host port', async () => { const f = await fixture() + const hostPort = f.ctx.webServer.port + if (hostPort === undefined) throw new Error('account test: the Host listener has not bound a port') const sockets = new Set() const forward = createTcpServer((socket) => { - const upstream = connect(f.ctx.webServer.port, '127.0.0.1') + const upstream = connect(hostPort, '127.0.0.1') for (const connection of [socket, upstream]) { sockets.add(connection) connection.on('close', () => { sockets.delete(connection) }) diff --git a/packages/deliverables/tool-present/locale/en.json b/packages/deliverables/tool-present/locale/en.json new file mode 100644 index 0000000000..6efec8a8e1 --- /dev/null +++ b/packages/deliverables/tool-present/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "tool-present" + } +} diff --git a/packages/deliverables/tool-present/locale/zh.json b/packages/deliverables/tool-present/locale/zh.json new file mode 100644 index 0000000000..c884f69fdd --- /dev/null +++ b/packages/deliverables/tool-present/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "文件交付工具", + "description": "让 AI 将工作区文件明确标记为本轮交付内容。" + } +} diff --git a/packages/deliverables/tool-present/package.json b/packages/deliverables/tool-present/package.json index f0c0e74b0f..6876a3ac26 100644 --- a/packages/deliverables/tool-present/package.json +++ b/packages/deliverables/tool-present/package.json @@ -23,10 +23,12 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "license": "MIT", "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/deliverables/workspace-changes/locale/en.json b/packages/deliverables/workspace-changes/locale/en.json new file mode 100644 index 0000000000..909d083bde --- /dev/null +++ b/packages/deliverables/workspace-changes/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "workspace-changes" + } +} diff --git a/packages/deliverables/workspace-changes/locale/zh.json b/packages/deliverables/workspace-changes/locale/zh.json new file mode 100644 index 0000000000..da51fea706 --- /dev/null +++ b/packages/deliverables/workspace-changes/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "工作区变更记录", + "description": "记录每轮任务的文件变化,供逐文件比较。" + } +} diff --git a/packages/deliverables/workspace-changes/package.json b/packages/deliverables/workspace-changes/package.json index c82567db87..fef51365a2 100644 --- a/packages/deliverables/workspace-changes/package.json +++ b/packages/deliverables/workspace-changes/package.json @@ -23,10 +23,12 @@ "default": "./lib/types/types.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "license": "MIT", "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts" diff --git a/packages/document/office-to-pdf/locale/en.json b/packages/document/office-to-pdf/locale/en.json new file mode 100644 index 0000000000..574f708afe --- /dev/null +++ b/packages/document/office-to-pdf/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "office-to-pdf" + } +} diff --git a/packages/document/office-to-pdf/locale/zh.json b/packages/document/office-to-pdf/locale/zh.json new file mode 100644 index 0000000000..6a6243be60 --- /dev/null +++ b/packages/document/office-to-pdf/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Office 转 PDF", + "description": "将 Word、Excel 和 PowerPoint 等文档转换为 PDF,供预览使用。" + } +} diff --git a/packages/document/office-to-pdf/package.json b/packages/document/office-to-pdf/package.json index 087d544293..eaf703ac3a 100644 --- a/packages/document/office-to-pdf/package.json +++ b/packages/document/office-to-pdf/package.json @@ -32,9 +32,11 @@ "./typert": { "types": "./lib/typert.host.d.ts", "default": "./lib/typert.host.js" - } + }, + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", diff --git a/packages/experimental/client-ui-agent-team/package.json b/packages/experimental/client-ui-agent-team/package.json index 73a171a53d..93d4ed4c76 100644 --- a/packages/experimental/client-ui-agent-team/package.json +++ b/packages/experimental/client-ui-agent-team/package.json @@ -70,8 +70,6 @@ "@deepseek-ai/dsh-experimental-agent-team": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", - "@types/react-dom": "~18.3.0", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0" diff --git a/packages/experimental/client-ui-agent-team/tsdown.config.ts b/packages/experimental/client-ui-agent-team/tsdown.config.ts index f76b2c66fe..71d5bd77f8 100644 --- a/packages/experimental/client-ui-agent-team/tsdown.config.ts +++ b/packages/experimental/client-ui-agent-team/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../../client/tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-experimental-client-ui-agent-team', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/experimental/client-ui-claude-code-mods/package.json b/packages/experimental/client-ui-claude-code-mods/package.json index 64416f9042..6cab2cf49f 100644 --- a/packages/experimental/client-ui-claude-code-mods/package.json +++ b/packages/experimental/client-ui-claude-code-mods/package.json @@ -76,7 +76,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react": "~18.3.1", "react": "^18.2.0", "react-dom": "^18.2.0" } diff --git a/packages/experimental/client-ui-claude-code-mods/tsdown.config.ts b/packages/experimental/client-ui-claude-code-mods/tsdown.config.ts index 9bc22b4332..71d5bd77f8 100644 --- a/packages/experimental/client-ui-claude-code-mods/tsdown.config.ts +++ b/packages/experimental/client-ui-claude-code-mods/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../../client/tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-experimental-client-ui-claude-code-mods', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/experimental/client-ui-cot-translation/package.json b/packages/experimental/client-ui-cot-translation/package.json index 9dcc42cc82..22125d92bd 100644 --- a/packages/experimental/client-ui-cot-translation/package.json +++ b/packages/experimental/client-ui-cot-translation/package.json @@ -82,7 +82,6 @@ "@deepseek-ai/dsh-client-ui-settings": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", - "@types/react": "~18.3.1", "react": "^18.2.0", "react-dom": "^18.2.0", "@testing-library/react": "^16.3.3", diff --git a/packages/experimental/client-ui-cot-translation/tsdown.config.ts b/packages/experimental/client-ui-cot-translation/tsdown.config.ts index 4ccd63c3ed..e0c1efd7dc 100644 --- a/packages/experimental/client-ui-cot-translation/tsdown.config.ts +++ b/packages/experimental/client-ui-cot-translation/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../../client/tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-experimental-client-ui-cot-translation', ['lib/types/index.js'], { hostPhase: true }) +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/experimental/client-ui-voice-input/package.json b/packages/experimental/client-ui-voice-input/package.json index 2c8aec199d..ff330d345a 100644 --- a/packages/experimental/client-ui-voice-input/package.json +++ b/packages/experimental/client-ui-voice-input/package.json @@ -67,7 +67,6 @@ "@deepseek-ai/dsh-experimental-api-speech-to-text": "workspace:*", "@deepseek-ai/dsh-experimental-speech-to-text": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", - "@types/react": "~18.3.1", "react": "^18.2.0", "react-dom": "^18.2.0", "@testing-library/react": "^16.3.3", diff --git a/packages/experimental/client-ui-voice-input/tsdown.config.ts b/packages/experimental/client-ui-voice-input/tsdown.config.ts index 04383e44a9..71d5bd77f8 100644 --- a/packages/experimental/client-ui-voice-input/tsdown.config.ts +++ b/packages/experimental/client-ui-voice-input/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../../client/tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-experimental-client-ui-voice-input', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/experimental/inspector/package.json b/packages/experimental/inspector/package.json index 4177a94c8a..69a656dbc6 100644 --- a/packages/experimental/inspector/package.json +++ b/packages/experimental/inspector/package.json @@ -67,7 +67,6 @@ "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@testing-library/react": "^16.3.3", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/dsh-client-ui-layout": "workspace:*", "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", diff --git a/packages/experimental/inspector/tsdown.config.ts b/packages/experimental/inspector/tsdown.config.ts index 95b3266d38..6048fcc14c 100644 --- a/packages/experimental/inspector/tsdown.config.ts +++ b/packages/experimental/inspector/tsdown.config.ts @@ -21,7 +21,7 @@ const worker: UserConfig = { /** Build the Host plugin and Worker during the Host pass, and the dynamic Client plugin during the Client pass. */ export default clientBundle( - '@deepseek-ai/dsh-experimental-inspector', + import.meta.dirname, ['lib/types/index.js'], { hostPhase: true, diff --git a/packages/experimental/ptc-runtime-python/README.i18n.yaml b/packages/experimental/ptc-runtime-python/README.i18n.yaml index 8891300eb9..b2a4ea1f60 100644 --- a/packages/experimental/ptc-runtime-python/README.i18n.yaml +++ b/packages/experimental/ptc-runtime-python/README.i18n.yaml @@ -48,8 +48,8 @@ en: ab4a08f301de599d zh: e698b35ccf3ce665 /deepseek-ai-dsh-experimental-ptc-runtime-python/model-experience: - en: 42064c81cda8f059 - zh: fa68d1acac16e263 + en: 79863a171221fa59 + zh: 961125d015b1e800 /deepseek-ai-dsh-experimental-ptc-runtime-python/model-experience/kv-cache-effect: en: 40294c1c31b74824 zh: d805c6bd7270505e diff --git a/packages/experimental/ptc-runtime-python/README.md b/packages/experimental/ptc-runtime-python/README.md index 179f5a6886..9ca77841c6 100644 --- a/packages/experimental/ptc-runtime-python/README.md +++ b/packages/experimental/ptc-runtime-python/README.md @@ -36,7 +36,7 @@ The runtime advertises file confinement so `run_code` exposes `sandbox_permissio The runtime supplies these execution instructions: ```text -Each call runs in a fresh Python process. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution's sandbox policy. +The program is the body of an async Python function. Top-level await and return are supported. Emit output with print(...) or return a lossless JSON value. Only printed values and the returned value become program output. Each call runs in a fresh Python process; variables and imported modules do not persist across calls. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution's sandbox policy. ``` ### What you get @@ -112,7 +112,7 @@ Read these when the runtime contract is not enough. They move from the seam defi ## Model Experience -Indirectly, through PTC mode in `dsh-tools` when an explicit composition mounts this provider; it renders the program's completion value or failure into a retained `run_code` result, and no shipped profile mounts this experimental package. +Indirectly, through PTC mode in `dsh-tools` when explicitly composed: the consumer appends this provider's async-function, output and fresh-process instructions to `run_code` and renders its completion value or failure as the tool result. #### KV Cache effect diff --git a/packages/experimental/ptc-runtime-python/README.zh.md b/packages/experimental/ptc-runtime-python/README.zh.md index 74b7d4a35d..c987c9b48d 100644 --- a/packages/experimental/ptc-runtime-python/README.zh.md +++ b/packages/experimental/ptc-runtime-python/README.zh.md @@ -36,7 +36,7 @@ kind: "package-reference" 运行时提供以下执行指引: ```text -Each call runs in a fresh Python process. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution's sandbox policy. +The program is the body of an async Python function. Top-level await and return are supported. Emit output with print(...) or return a lossless JSON value. Only printed values and the returned value become program output. Each call runs in a fresh Python process; variables and imported modules do not persist across calls. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution's sandbox policy. ``` ### 你得到什么 @@ -112,7 +112,7 @@ Each call runs in a fresh Python process. Relative paths use the supplied workin ## 模型体验 -间接地,通过 `dsh-tools` 中的 PTC mode;当显式组合挂载本提供方时,它会把程序的完成值或失败渲染成保留的 `run_code` 结果,且已发布 profile 均不挂载这个实验包。 +间接地,通过显式组合中的 `dsh-tools` PTC mode:消费者将本提供方的异步函数、输出和新进程执行指引附加到 `run_code`,并将程序的完成值或失败渲染为工具结果。 #### KV Cache 效应 diff --git a/packages/experimental/ptc-runtime-python/src/index.ts b/packages/experimental/ptc-runtime-python/src/index.ts index 2785958fe0..1e12cd1e5f 100644 --- a/packages/experimental/ptc-runtime-python/src/index.ts +++ b/packages/experimental/ptc-runtime-python/src/index.ts @@ -759,7 +759,7 @@ export class PythonPtcRuntime extends PtcRuntime { override get sandboxMode(): SandboxMode { return this.ctx.sandboxPolicy.defaultMode } override get executionInstructions(): string { - return 'Each call runs in a fresh Python process. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution\'s sandbox policy.' + return 'The program is the body of an async Python function. Top-level await and return are supported. Emit output with print(...) or return a lossless JSON value. Only printed values and the returned value become program output. Each call runs in a fresh Python process; variables and imported modules do not persist across calls. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution\'s sandbox policy.' } private readonly config: ResolvedConfig diff --git a/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts index 139172bbb6..29a547ae7a 100644 --- a/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts +++ b/packages/experimental/ptc-runtime-python/tests/runtime.spec.ts @@ -73,7 +73,7 @@ describe('PythonPtcRuntime — seam descriptors and misuse', () => { const { runtime } = await setup() expect(runtime.language).toBe('python') expect(runtime.isolation).toBe('process') - expect(runtime.executionInstructions).toBe('Each call runs in a fresh Python process. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution\'s sandbox policy.') + expect(runtime.executionInstructions).toBe('The program is the body of an async Python function. Top-level await and return are supported. Emit output with print(...) or return a lossless JSON value. Only printed values and the returned value become program output. Each call runs in a fresh Python process; variables and imported modules do not persist across calls. Relative paths use the supplied working directory; only TMPDIR is set in the environment. Direct filesystem access follows this execution\'s sandbox policy.') }) it('resolves its configured deadline and cwd while refusing unsupported execution choices', async () => { diff --git a/packages/experimental/session-inspector/package.json b/packages/experimental/session-inspector/package.json index e9fc0837bc..17c325b5b7 100644 --- a/packages/experimental/session-inspector/package.json +++ b/packages/experimental/session-inspector/package.json @@ -55,7 +55,6 @@ "devDependencies": { "@deepseek-ai/dsh-client-test-runtime": "workspace:*", "@testing-library/react": "^16.3.3", - "@types/react-dom": "~18.3.0", "react-dom": "^18.2.0", "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", @@ -66,7 +65,6 @@ "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", "@tanstack/react-virtual": "^3.14.10", - "@types/react": "~18.3.1", "react": "^18.2.0", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-client-locale": "workspace:*", diff --git a/packages/experimental/session-inspector/tsdown.config.ts b/packages/experimental/session-inspector/tsdown.config.ts index 121f194f40..71d5bd77f8 100644 --- a/packages/experimental/session-inspector/tsdown.config.ts +++ b/packages/experimental/session-inspector/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../../client/tsdown.client.ts' -export default clientBundle('@deepseek-ai/dsh-experimental-session-inspector', ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/experimental/tool-ralph/locale/en.json b/packages/experimental/tool-ralph/locale/en.json new file mode 100644 index 0000000000..fb6feb52e6 --- /dev/null +++ b/packages/experimental/tool-ralph/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "tool-ralph" + } +} diff --git a/packages/experimental/tool-ralph/locale/zh.json b/packages/experimental/tool-ralph/locale/zh.json new file mode 100644 index 0000000000..5e9601ee1f --- /dev/null +++ b/packages/experimental/tool-ralph/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Ralph 迭代工具", + "description": "围绕同一目标逐轮运行新的子智能体,并传递上一轮的简要报告。" + } +} diff --git a/packages/experimental/tool-ralph/package.json b/packages/experimental/tool-ralph/package.json index fca05d68cc..c7d94eb28a 100644 --- a/packages/experimental/tool-ralph/package.json +++ b/packages/experimental/tool-ralph/package.json @@ -19,9 +19,11 @@ "default": "./lib/index.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.d.ts" ], diff --git a/packages/experimental/webhook/tests/session.spec.ts b/packages/experimental/webhook/tests/session.spec.ts index 8dec0361d5..2585023fec 100644 --- a/packages/experimental/webhook/tests/session.spec.ts +++ b/packages/experimental/webhook/tests/session.spec.ts @@ -14,7 +14,7 @@ interface HarnessOptions { failAt?: 'permission-resolve' | 'preset-resolve' | 'standing' | 'workspace' | 'agent' | 'attach' | 'permission-set' | 'title' | 'followup' failDetach?: boolean failDispose?: boolean - abortAt?: 'workspace' | 'agent' + abortAt?: 'workspace' | 'agent' | 'attach' | 'permission-continuation' } interface SessionHarness { @@ -66,6 +66,7 @@ function harness(options: HarnessOptions = {}): SessionHarness { path: '/workspace', async attachSession() { calls.push('attach') + if (options.abortAt === 'attach') controller.abort(new Error('abort after attach')) if (options.failAt === 'attach') throw new Error('attach failed') }, async detachSession() { @@ -83,6 +84,10 @@ function harness(options: HarnessOptions = {}): SessionHarness { }, set(_session: unknown, name: string) { calls.push(`permission-set:${name}`) + if (options.abortAt === 'permission-continuation') queueMicrotask(() => { + calls.push('abort') + controller.abort(new Error('abort after permission setup')) + }) if (options.failAt === 'permission-set') throw new Error('permission set failed') }, }, @@ -312,10 +317,21 @@ describe('webhook Session creation', () => { expect((test.ctx.logger.warn as ReturnType)).toHaveBeenCalledTimes(2) }) - it.each(['workspace', 'agent'] as const)('honors cancellation after %s settlement', async (abortAt) => { + it.each(['workspace', 'agent', 'attach'] as const)('honors cancellation after %s settlement', async (abortAt) => { const test = harness({ abortAt }) await expect(create(test)).rejects.toThrow(/abort after/) expect(test.calls).not.toContain('followup') - if (abortAt === 'agent') expect(test.calls).toContain('dispose') + if (abortAt !== 'workspace') expect(test.calls).toContain('dispose') + if (abortAt === 'attach') expect(test.calls).toContain('detach') }) + + it('admits the prompt synchronously after permission setup before a queued cancellation', async () => { + const test = harness({ abortAt: 'permission-continuation' }) + await create(test) + expect(test.calls.indexOf('followup')).toBeGreaterThan(test.calls.indexOf('permission-set:read-only')) + expect(test.calls.indexOf('abort')).toBeGreaterThan(test.calls.indexOf('followup')) + expect(test.calls).not.toContain('detach') + expect(test.calls).not.toContain('dispose') + }) + }) diff --git a/packages/experimental/webworker-packer/tests/preview.spec.ts b/packages/experimental/webworker-packer/tests/preview.spec.ts index f3b5937ab9..0e0c7f7e12 100644 --- a/packages/experimental/webworker-packer/tests/preview.spec.ts +++ b/packages/experimental/webworker-packer/tests/preview.spec.ts @@ -42,7 +42,7 @@ function restore(bytes: Uint8Array | undefined) { } describe('Node preparation of Preview Session data', () => { - it('packs strictly migrated current successors beside every unchanged example file', () => { + it('packs current Sessions and migrated children beside every unchanged example file', () => { const fixture = previewFixtures(repoRoot)[0]! const original = packVfsOverlay(fixture.trees) const projected = packPreviewFixture(fixture.trees) @@ -50,15 +50,13 @@ describe('Node preparation of Preview Session data', () => { expect(currentFiles).toHaveLength(3) for (const [path, bytes] of Object.entries(original.files)) expect(projected.files[path], path).toEqual(bytes) for (const path of currentFiles) { - const sourcePath = path.replace(/\/session\.v\d+\.jsonl$/u, '/session.v3.jsonl') - const historical = restore(original.files[sourcePath]) const current = restore(projected.files[path]) - const appended = path.includes('/preview-showcase/') ? [ - { version: 0, childId: 'preview-architecture-review', childCreatedAt: 1787472100000, mode: 'one-shot', label: 'Review preview architecture' }, - { version: 0, childId: 'preview-follow-up-builder', childCreatedAt: 1787472200000, mode: 'continuable', label: 'Continue preview verification' }, - ].map((data, index) => ({ type: 'subagent/catalog', seq: historical.events.length + index, - time: historical.events.at(-1)!.time, data })) : [] - expect(current).toEqual({ ...historical, events: [...historical.events, ...appended] }) + if (original.files[path] !== undefined) { + expect(projected.files[path]).toEqual(original.files[path]) + } else { + const sourcePath = path.replace(/\/session\.v\d+\.jsonl$/u, '/session.v3.jsonl') + expect(current).toEqual(restore(original.files[sourcePath])) + } expect(JSON.parse(text(projected.files[path]).split('\n')[0]!)).toMatchObject({ version: currentVersion }) } expect(packPreviewFixture(fixture.trees).image).toEqual(projected.image) diff --git a/packages/experimental/webworker-runtime/README.i18n.yaml b/packages/experimental/webworker-runtime/README.i18n.yaml index d70dd93cb7..3ac3336a7a 100644 --- a/packages/experimental/webworker-runtime/README.i18n.yaml +++ b/packages/experimental/webworker-runtime/README.i18n.yaml @@ -15,8 +15,8 @@ en: 4e53164159b5ce41 zh: 89582dc0294d0776 /deepseek-ai-dsh-experimental-webworker-runtime/use-this-package: - en: 6dd3d8495bc6ee61 - zh: 71f7da310233a37b + en: aed3c07b75b29e34 + zh: b609ae0f5796aa34 /deepseek-ai-dsh-experimental-webworker-runtime/model-experience: en: 61fce9b4c7dc96e6 zh: dc2d931063a38327 diff --git a/packages/experimental/webworker-runtime/README.md b/packages/experimental/webworker-runtime/README.md index 8394296bf2..2f5619640f 100644 --- a/packages/experimental/webworker-runtime/README.md +++ b/packages/experimental/webworker-runtime/README.md @@ -32,7 +32,7 @@ Three build artifacts and one source-owned process layer: - **`src/shell/` (the worker's own process layer)** — a browser worker cannot fork, so `node:child_process` is not a stub but an implementation: `spawn` starts the command in its own Web Worker — this same bundle, told by its first frame to be a shell process — and reports it through the `ChildProcess` surface the subprocess service consumes. The command runs off the host's thread, `SIGKILL` terminates it whatever it is doing, and it reaches the VFS only by message (the host serves those frames). Worker platform executables preserve native-package protocols such as Landlock without replacing their JavaScript packages or coupling their implementations to `node:child_process`; `xdg-open` sends one VFS text file to the page's read-only viewer, so desktop-opener actions such as **Open configuration file** show the file in the page; ordinary commands use the package's evaluator and coreutils command table. The grammar is `@yarnpkg/parsers`' `parseShell`, while `execSync`/`fork` still refuse because they need a real process. - **`lib/client.js` (page half)** — startup has two independent stages. `chooseWorkerHostSource({ image?, fixtureManifest? })` optionally owns the boot barrier and fixture manifest: without `preview-fixture` it waits at the source chooser, while a valid query selects directly; either path returns ordered overlays. `connectWorkerHost(worker, { image?, overlays? })` remains the public base-runtime connector; callers that skip the chooser get an empty overlay list. `apps/web` invokes both and supplies its statically bundled Worker. The opening `init` frame carries the base and ordered overlay URLs, the boot payload delivers the structured index-injection table, and `applyIndexInjections` executes it before the shell entry runs. Script preload rows are advisory and skipped because `/plugins` resources resolve only through the tunnel; `loadBundle` fetches each combo on first demand, embeds its tunnel-only source map as a Base64 data URL, and executes the script as a Blob. The worker's unsolicited `view-text` frame opens the page's modal text viewer. The tunnel also exposes fetch-shaped transport, the independent file-upload carrier, and the API client. Request frames preserve Blob bodies through structured clone and transfer `ReadableStream` ownership. The Host Worker streams both forms into the route, so neither browser thread creates a complete byte array for a generic-file upload. A Remote stream's uplink crosses as `stream-uplink-item` / `stream-uplink-end` frames into an unbounded `TunnelUplink` that drops items arriving after `end`: the page and its worker are one trusted same-origin boundary, so the Host inbox cap does not apply. -Acceptance lives in `apps/web/tests/preview-boot.e2e.ts`, which serves the real built pages and drives the pre-boot chooser plus Worker activation in headless Chromium. The empty selection exercises first-run startup. The `vfs-example` overlay supplies ordinary workspace files and plaintext persistence artifacts for cold Workspace/Session discovery, tool presentation, subagent navigation, and history paging without a model request. The [packer](../webworker-packer/README.md) prepares current-generation successors from committed historical logs in Node; those source logs remain byte-identical in the overlay. The fixture generator owns the acceptance test's current projection cache. The chooser reserves WebFS as a separate user-authorized source; that provider does not read the built-in fixture. +Acceptance lives in `apps/web/tests/preview-boot.e2e.ts`, which serves the real built pages and drives the pre-boot chooser plus Worker activation in headless Chromium. The empty selection exercises first-run startup. The `vfs-example` overlay supplies ordinary workspace files and plaintext persistence artifacts for cold Workspace/Session discovery, tool presentation, subagent navigation, and history paging without a model request. The showcase mixes empty, whitespace-only, and non-empty reasoning with a long multiline command and a parent-path file link; these are authored fixtures, not live model output. The [packer](../webworker-packer/README.md) prepares current-generation successors from committed historical logs in Node; those source logs remain byte-identical in the overlay. The fixture generator owns the acceptance test's current projection cache. The chooser reserves WebFS as a separate user-authorized source; that provider does not read the built-in fixture. The [built-bundle import sweep](tests/compile/transform-corpus-check.ts) checks bare Node imports after the library build. Its Dockkit exception accepts Node’s unknown-`.css`-extension refusal for any stylesheet rather than one pinned path; another extension, error code, or message, and an unexpectedly successful exempt import, remain errors. diff --git a/packages/experimental/webworker-runtime/README.zh.md b/packages/experimental/webworker-runtime/README.zh.md index b63f81247b..dffbb30718 100644 --- a/packages/experimental/webworker-runtime/README.zh.md +++ b/packages/experimental/webworker-runtime/README.zh.md @@ -32,7 +32,7 @@ kind: "package-library" - **`src/shell/`(worker 自己的进程层)**——浏览器 worker 无法 fork,所以 `node:child_process` 不是 stub 而是实现:`spawn` 把命令放进它自己的 Web Worker——就是这同一个束,由首帧告诉它「你是 shell 进程」——并以 subprocess 服务消费的 `ChildProcess` 面报告结果。命令不占宿主线程,`SIGKILL` 不管它在干什么都能终止它,而它只能靠消息触达 VFS(由宿主应答这些帧)。Worker 平台 executable 在不替换 JavaScript 包、也不把具体实现耦合进 `node:child_process` 的情况下保持 Landlock 等 native 包协议;`xdg-open` 把一个 VFS 文本文件交给页面的只读查看器,因此 **打开配置文件** 等桌面打开操作会在页面内显示该文件;普通命令使用本包的求值器与 coreutils 命令表。语法来自 `@yarnpkg/parsers` 的 `parseShell`,而 `execSync`/`fork` 依然拒绝,因为它们需要真进程。 - **`lib/client.js`(页面半)**——启动分为相互独立的两段。`chooseWorkerHostSource({ image?, fixtureManifest? })` 可选地拥有 boot barrier 与 fixture manifest:没有 `preview-fixture` 时停在来源选择面板,合法 query 则直接选择;两条路径都返回按序排列的 overlays。`connectWorkerHost(worker, { image?, overlays? })` 仍是公开的基础运行态连接器;调用方跳过选择器时 overlay 列表为空。`apps/web` 调用这两段并提供静态打包的 Worker。开局 `init` 帧携带基础镜像与按序排列的 overlay URL,boot 载荷送达结构化 index 注入表,`applyIndexInjections` 在壳入口运行前逐行执行。脚本 preload 行只是提示,因此会被跳过:`/plugins` 资源只能经 tunnel 解析,`loadBundle` 会在首次需要时获取 combo、把仅 tunnel 可达的 sourcemap 内嵌为 Base64 data URL,再以 Blob 执行脚本。worker 主动发出的 `view-text` 帧会打开页面的模态文本查看器。Tunnel 还暴露 fetch 形式的传输、独立文件上传载体和 API 客户端。请求帧通过结构化克隆保留 Blob 请求体,并转移 `ReadableStream` 的所有权。Host Worker 将两种请求体都逐块送入路由,因此通用文件上传不会在任何浏览器线程创建完整字节数组。Remote 流的上行以 `stream-uplink-item` / `stream-uplink-end` 帧进入没有上限的 `TunnelUplink`,`end` 之后到达的项被丢弃:页面与其 worker 是同一个可信的同源边界,Host 的 inbox 上限在此不适用。 -验收在 `apps/web/tests/preview-boot.e2e.ts`:静态服务真实构建页面,在 headless Chromium 里驱动 pre-boot 选择面板与 Worker 激活。空白选择验证首次启动;`vfs-example` overlay 提供普通 workspace 文件与明文 persistence 产物,无需模型请求即可验证 Workspace/Session 冷发现、工具呈现、subagent 导航和历史分页。[打包器](../webworker-packer/README.zh.md)在 Node 中根据已提交的历史日志准备当前代后继文件;这些源日志在 overlay 中逐字节保持不变。fixture 生成器负责验收测试的当前投影缓存。选择面板为 WebFS 保留独立的用户授权来源;该 provider 不读取内置 fixture。 +验收在 `apps/web/tests/preview-boot.e2e.ts`:静态服务真实构建页面,在 headless Chromium 里驱动 pre-boot 选择面板与 Worker 激活。空白选择验证首次启动;`vfs-example` overlay 提供普通 workspace 文件与明文 persistence 产物,无需模型请求即可验证 Workspace/Session 冷发现、工具呈现、subagent 导航和历史分页。showcase 混排空字符串、纯空白与非空推理块,并包含多行长命令和父路径文件链接;这些是人工构造的 fixture,不是真实模型输出。[打包器](../webworker-packer/README.zh.md)在 Node 中根据已提交的历史日志准备当前代后继文件;这些源日志在 overlay 中逐字节保持不变。fixture 生成器负责验收测试的当前投影缓存。选择面板为 WebFS 保留独立的用户授权来源;该 provider 不读取内置 fixture。 [已构建 bundle 导入检查](tests/compile/transform-corpus-check.ts)在库构建后检查裸 Node 导入。Dockkit 例外接受 Node 针对任意样式表报告的未知 `.css` 扩展名错误,而不限定某一固定路径;其他扩展名、错误码或消息,以及意外成功的豁免导入,仍然报错。 diff --git a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-showcase/session.v4.jsonl b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-showcase/session.v4.jsonl new file mode 100644 index 0000000000..abed3fcfd9 --- /dev/null +++ b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/sessions/--dsh-workspace--/preview-showcase/session.v4.jsonl @@ -0,0 +1,204 @@ +{"type":"session","version":4,"id":"preview-showcase","createdAt":1787472000000,"cwd":"/dsh/workspace","isSeeded":false,"delegationDepth":0,"agentPreset":"standard"} +{"type":"turn/start","data":{"turn":1},"seq":0,"time":1787472000000} +{"type":"user/message","data":{"id":"preview-user-01","role":"user","content":[{"type":"text","text":"History checkpoint 01: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":1,"time":1787472000001} +{"type":"session/title","data":{"title":"WebWorker Preview Showcase","messageSeqs":[],"source":{"kind":"user"}},"seq":2,"time":1787472000002} +{"type":"step/start","data":{"turn":1,"step":1},"seq":3,"time":1787472000003} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"id":"preview-assistant-01","role":"assistant","content":[{"type":"text","text":"Checkpoint 01 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 01 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 01 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":4,"time":1787472000004} +{"type":"step/end","data":{"turn":1,"step":1},"seq":5,"time":1787472000005} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}},"seq":6,"time":1787472000006} +{"type":"turn/start","data":{"turn":2},"seq":7,"time":1787472000007} +{"type":"user/message","data":{"id":"preview-user-02","role":"user","content":[{"type":"text","text":"History checkpoint 02: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":8,"time":1787472000008} +{"type":"step/start","data":{"turn":2,"step":1},"seq":9,"time":1787472000009} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"id":"preview-assistant-02","role":"assistant","content":[{"type":"text","text":"Checkpoint 02 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 02 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 02 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":10,"time":1787472000010} +{"type":"step/end","data":{"turn":2,"step":1},"seq":11,"time":1787472000011} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}},"seq":12,"time":1787472000012} +{"type":"turn/start","data":{"turn":3},"seq":13,"time":1787472000013} +{"type":"user/message","data":{"id":"preview-user-03","role":"user","content":[{"type":"text","text":"History checkpoint 03: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":14,"time":1787472000014} +{"type":"step/start","data":{"turn":3,"step":1},"seq":15,"time":1787472000015} +{"type":"assistant/message","data":{"turn":3,"step":1,"message":{"id":"preview-assistant-03","role":"assistant","content":[{"type":"text","text":"Checkpoint 03 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 03 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 03 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":16,"time":1787472000016} +{"type":"step/end","data":{"turn":3,"step":1},"seq":17,"time":1787472000017} +{"type":"turn/end","data":{"turn":3,"reason":{"kind":"completed"}},"seq":18,"time":1787472000018} +{"type":"turn/start","data":{"turn":4},"seq":19,"time":1787472000019} +{"type":"user/message","data":{"id":"preview-user-04","role":"user","content":[{"type":"text","text":"History checkpoint 04: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":20,"time":1787472000020} +{"type":"step/start","data":{"turn":4,"step":1},"seq":21,"time":1787472000021} +{"type":"assistant/message","data":{"turn":4,"step":1,"message":{"id":"preview-assistant-04","role":"assistant","content":[{"type":"text","text":"Checkpoint 04 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 04 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 04 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":22,"time":1787472000022} +{"type":"step/end","data":{"turn":4,"step":1},"seq":23,"time":1787472000023} +{"type":"turn/end","data":{"turn":4,"reason":{"kind":"completed"}},"seq":24,"time":1787472000024} +{"type":"turn/start","data":{"turn":5},"seq":25,"time":1787472000025} +{"type":"user/message","data":{"id":"preview-user-05","role":"user","content":[{"type":"text","text":"History checkpoint 05: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":26,"time":1787472000026} +{"type":"step/start","data":{"turn":5,"step":1},"seq":27,"time":1787472000027} +{"type":"assistant/message","data":{"turn":5,"step":1,"message":{"id":"preview-assistant-05","role":"assistant","content":[{"type":"text","text":"Checkpoint 05 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 05 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 05 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":28,"time":1787472000028} +{"type":"step/end","data":{"turn":5,"step":1},"seq":29,"time":1787472000029} +{"type":"turn/end","data":{"turn":5,"reason":{"kind":"completed"}},"seq":30,"time":1787472000030} +{"type":"turn/start","data":{"turn":6},"seq":31,"time":1787472000031} +{"type":"user/message","data":{"id":"preview-user-06","role":"user","content":[{"type":"text","text":"History checkpoint 06: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":32,"time":1787472000032} +{"type":"step/start","data":{"turn":6,"step":1},"seq":33,"time":1787472000033} +{"type":"assistant/message","data":{"turn":6,"step":1,"message":{"id":"preview-assistant-06","role":"assistant","content":[{"type":"text","text":"Checkpoint 06 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 06 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 06 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":34,"time":1787472000034} +{"type":"step/end","data":{"turn":6,"step":1},"seq":35,"time":1787472000035} +{"type":"turn/end","data":{"turn":6,"reason":{"kind":"completed"}},"seq":36,"time":1787472000036} +{"type":"turn/start","data":{"turn":7},"seq":37,"time":1787472000037} +{"type":"user/message","data":{"id":"preview-user-07","role":"user","content":[{"type":"text","text":"History checkpoint 07: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":38,"time":1787472000038} +{"type":"step/start","data":{"turn":7,"step":1},"seq":39,"time":1787472000039} +{"type":"assistant/message","data":{"turn":7,"step":1,"message":{"id":"preview-assistant-07","role":"assistant","content":[{"type":"text","text":"Checkpoint 07 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 07 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 07 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":40,"time":1787472000040} +{"type":"step/end","data":{"turn":7,"step":1},"seq":41,"time":1787472000041} +{"type":"turn/end","data":{"turn":7,"reason":{"kind":"completed"}},"seq":42,"time":1787472000042} +{"type":"turn/start","data":{"turn":8},"seq":43,"time":1787472000043} +{"type":"user/message","data":{"id":"preview-user-08","role":"user","content":[{"type":"text","text":"History checkpoint 08: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":44,"time":1787472000044} +{"type":"step/start","data":{"turn":8,"step":1},"seq":45,"time":1787472000045} +{"type":"assistant/message","data":{"turn":8,"step":1,"message":{"id":"preview-assistant-08","role":"assistant","content":[{"type":"text","text":"Checkpoint 08 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 08 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 08 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":46,"time":1787472000046} +{"type":"step/end","data":{"turn":8,"step":1},"seq":47,"time":1787472000047} +{"type":"turn/end","data":{"turn":8,"reason":{"kind":"completed"}},"seq":48,"time":1787472000048} +{"type":"turn/start","data":{"turn":9},"seq":49,"time":1787472000049} +{"type":"user/message","data":{"id":"preview-user-09","role":"user","content":[{"type":"text","text":"History checkpoint 09: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":50,"time":1787472000050} +{"type":"step/start","data":{"turn":9,"step":1},"seq":51,"time":1787472000051} +{"type":"assistant/message","data":{"turn":9,"step":1,"message":{"id":"preview-assistant-09","role":"assistant","content":[{"type":"text","text":"Checkpoint 09 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 09 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 09 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":52,"time":1787472000052} +{"type":"step/end","data":{"turn":9,"step":1},"seq":53,"time":1787472000053} +{"type":"turn/end","data":{"turn":9,"reason":{"kind":"completed"}},"seq":54,"time":1787472000054} +{"type":"turn/start","data":{"turn":10},"seq":55,"time":1787472000055} +{"type":"user/message","data":{"id":"preview-user-10","role":"user","content":[{"type":"text","text":"History checkpoint 10: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":56,"time":1787472000056} +{"type":"step/start","data":{"turn":10,"step":1},"seq":57,"time":1787472000057} +{"type":"assistant/message","data":{"turn":10,"step":1,"message":{"id":"preview-assistant-10","role":"assistant","content":[{"type":"text","text":"Checkpoint 10 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 10 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 10 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":58,"time":1787472000058} +{"type":"step/end","data":{"turn":10,"step":1},"seq":59,"time":1787472000059} +{"type":"turn/end","data":{"turn":10,"reason":{"kind":"completed"}},"seq":60,"time":1787472000060} +{"type":"turn/start","data":{"turn":11},"seq":61,"time":1787472000061} +{"type":"user/message","data":{"id":"preview-user-11","role":"user","content":[{"type":"text","text":"History checkpoint 11: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":62,"time":1787472000062} +{"type":"step/start","data":{"turn":11,"step":1},"seq":63,"time":1787472000063} +{"type":"assistant/message","data":{"turn":11,"step":1,"message":{"id":"preview-assistant-11","role":"assistant","content":[{"type":"text","text":"Checkpoint 11 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 11 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 11 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":64,"time":1787472000064} +{"type":"step/end","data":{"turn":11,"step":1},"seq":65,"time":1787472000065} +{"type":"turn/end","data":{"turn":11,"reason":{"kind":"completed"}},"seq":66,"time":1787472000066} +{"type":"turn/start","data":{"turn":12},"seq":67,"time":1787472000067} +{"type":"user/message","data":{"id":"preview-user-12","role":"user","content":[{"type":"text","text":"History checkpoint 12: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":68,"time":1787472000068} +{"type":"step/start","data":{"turn":12,"step":1},"seq":69,"time":1787472000069} +{"type":"assistant/message","data":{"turn":12,"step":1,"message":{"id":"preview-assistant-12","role":"assistant","content":[{"type":"text","text":"Checkpoint 12 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 12 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 12 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":70,"time":1787472000070} +{"type":"step/end","data":{"turn":12,"step":1},"seq":71,"time":1787472000071} +{"type":"turn/end","data":{"turn":12,"reason":{"kind":"completed"}},"seq":72,"time":1787472000072} +{"type":"turn/start","data":{"turn":13},"seq":73,"time":1787472000073} +{"type":"user/message","data":{"id":"preview-user-13","role":"user","content":[{"type":"text","text":"History checkpoint 13: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":74,"time":1787472000074} +{"type":"step/start","data":{"turn":13,"step":1},"seq":75,"time":1787472000075} +{"type":"assistant/message","data":{"turn":13,"step":1,"message":{"id":"preview-assistant-13","role":"assistant","content":[{"type":"text","text":"Checkpoint 13 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 13 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 13 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":76,"time":1787472000076} +{"type":"step/end","data":{"turn":13,"step":1},"seq":77,"time":1787472000077} +{"type":"turn/end","data":{"turn":13,"reason":{"kind":"completed"}},"seq":78,"time":1787472000078} +{"type":"turn/start","data":{"turn":14},"seq":79,"time":1787472000079} +{"type":"user/message","data":{"id":"preview-user-14","role":"user","content":[{"type":"text","text":"History checkpoint 14: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":80,"time":1787472000080} +{"type":"step/start","data":{"turn":14,"step":1},"seq":81,"time":1787472000081} +{"type":"assistant/message","data":{"turn":14,"step":1,"message":{"id":"preview-assistant-14","role":"assistant","content":[{"type":"text","text":"Checkpoint 14 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 14 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 14 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":82,"time":1787472000082} +{"type":"step/end","data":{"turn":14,"step":1},"seq":83,"time":1787472000083} +{"type":"turn/end","data":{"turn":14,"reason":{"kind":"completed"}},"seq":84,"time":1787472000084} +{"type":"turn/start","data":{"turn":15},"seq":85,"time":1787472000085} +{"type":"user/message","data":{"id":"preview-user-15","role":"user","content":[{"type":"text","text":"History checkpoint 15: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":86,"time":1787472000086} +{"type":"step/start","data":{"turn":15,"step":1},"seq":87,"time":1787472000087} +{"type":"assistant/message","data":{"turn":15,"step":1,"message":{"id":"preview-assistant-15","role":"assistant","content":[{"type":"text","text":"Checkpoint 15 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 15 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 15 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":88,"time":1787472000088} +{"type":"step/end","data":{"turn":15,"step":1},"seq":89,"time":1787472000089} +{"type":"turn/end","data":{"turn":15,"reason":{"kind":"completed"}},"seq":90,"time":1787472000090} +{"type":"turn/start","data":{"turn":16},"seq":91,"time":1787472000091} +{"type":"user/message","data":{"id":"preview-user-16","role":"user","content":[{"type":"text","text":"History checkpoint 16: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":92,"time":1787472000092} +{"type":"step/start","data":{"turn":16,"step":1},"seq":93,"time":1787472000093} +{"type":"assistant/message","data":{"turn":16,"step":1,"message":{"id":"preview-assistant-16","role":"assistant","content":[{"type":"text","text":"Checkpoint 16 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 16 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 16 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":94,"time":1787472000094} +{"type":"step/end","data":{"turn":16,"step":1},"seq":95,"time":1787472000095} +{"type":"turn/end","data":{"turn":16,"reason":{"kind":"completed"}},"seq":96,"time":1787472000096} +{"type":"turn/start","data":{"turn":17},"seq":97,"time":1787472000097} +{"type":"user/message","data":{"id":"preview-user-17","role":"user","content":[{"type":"text","text":"History checkpoint 17: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":98,"time":1787472000098} +{"type":"step/start","data":{"turn":17,"step":1},"seq":99,"time":1787472000099} +{"type":"assistant/message","data":{"turn":17,"step":1,"message":{"id":"preview-assistant-17","role":"assistant","content":[{"type":"text","text":"Checkpoint 17 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 17 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 17 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":100,"time":1787472000100} +{"type":"step/end","data":{"turn":17,"step":1},"seq":101,"time":1787472000101} +{"type":"turn/end","data":{"turn":17,"reason":{"kind":"completed"}},"seq":102,"time":1787472000102} +{"type":"turn/start","data":{"turn":18},"seq":103,"time":1787472000103} +{"type":"user/message","data":{"id":"preview-user-18","role":"user","content":[{"type":"text","text":"History checkpoint 18: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":104,"time":1787472000104} +{"type":"step/start","data":{"turn":18,"step":1},"seq":105,"time":1787472000105} +{"type":"assistant/message","data":{"turn":18,"step":1,"message":{"id":"preview-assistant-18","role":"assistant","content":[{"type":"text","text":"Checkpoint 18 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 18 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 18 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":106,"time":1787472000106} +{"type":"step/end","data":{"turn":18,"step":1},"seq":107,"time":1787472000107} +{"type":"turn/end","data":{"turn":18,"reason":{"kind":"completed"}},"seq":108,"time":1787472000108} +{"type":"turn/start","data":{"turn":19},"seq":109,"time":1787472000109} +{"type":"user/message","data":{"id":"preview-user-19","role":"user","content":[{"type":"text","text":"History checkpoint 19: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":110,"time":1787472000110} +{"type":"step/start","data":{"turn":19,"step":1},"seq":111,"time":1787472000111} +{"type":"assistant/message","data":{"turn":19,"step":1,"message":{"id":"preview-assistant-19","role":"assistant","content":[{"type":"text","text":"Checkpoint 19 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 19 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 19 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":112,"time":1787472000112} +{"type":"step/end","data":{"turn":19,"step":1},"seq":113,"time":1787472000113} +{"type":"turn/end","data":{"turn":19,"reason":{"kind":"completed"}},"seq":114,"time":1787472000114} +{"type":"turn/start","data":{"turn":20},"seq":115,"time":1787472000115} +{"type":"user/message","data":{"id":"preview-user-20","role":"user","content":[{"type":"text","text":"History checkpoint 20: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":116,"time":1787472000116} +{"type":"step/start","data":{"turn":20,"step":1},"seq":117,"time":1787472000117} +{"type":"assistant/message","data":{"turn":20,"step":1,"message":{"id":"preview-assistant-20","role":"assistant","content":[{"type":"text","text":"Checkpoint 20 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 20 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 20 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":118,"time":1787472000118} +{"type":"step/end","data":{"turn":20,"step":1},"seq":119,"time":1787472000119} +{"type":"turn/end","data":{"turn":20,"reason":{"kind":"completed"}},"seq":120,"time":1787472000120} +{"type":"turn/start","data":{"turn":21},"seq":121,"time":1787472000121} +{"type":"user/message","data":{"id":"preview-user-21","role":"user","content":[{"type":"text","text":"History checkpoint 21: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":122,"time":1787472000122} +{"type":"step/start","data":{"turn":21,"step":1},"seq":123,"time":1787472000123} +{"type":"assistant/message","data":{"turn":21,"step":1,"message":{"id":"preview-assistant-21","role":"assistant","content":[{"type":"text","text":"Checkpoint 21 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 21 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 21 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":124,"time":1787472000124} +{"type":"step/end","data":{"turn":21,"step":1},"seq":125,"time":1787472000125} +{"type":"turn/end","data":{"turn":21,"reason":{"kind":"completed"}},"seq":126,"time":1787472000126} +{"type":"turn/start","data":{"turn":22},"seq":127,"time":1787472000127} +{"type":"user/message","data":{"id":"preview-user-22","role":"user","content":[{"type":"text","text":"History checkpoint 22: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":128,"time":1787472000128} +{"type":"step/start","data":{"turn":22,"step":1},"seq":129,"time":1787472000129} +{"type":"assistant/message","data":{"turn":22,"step":1,"message":{"id":"preview-assistant-22","role":"assistant","content":[{"type":"text","text":"Checkpoint 22 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 22 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 22 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":130,"time":1787472000130} +{"type":"step/end","data":{"turn":22,"step":1},"seq":131,"time":1787472000131} +{"type":"turn/end","data":{"turn":22,"reason":{"kind":"completed"}},"seq":132,"time":1787472000132} +{"type":"turn/start","data":{"turn":23},"seq":133,"time":1787472000133} +{"type":"user/message","data":{"id":"preview-user-23","role":"user","content":[{"type":"text","text":"History checkpoint 23: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":134,"time":1787472000134} +{"type":"step/start","data":{"turn":23,"step":1},"seq":135,"time":1787472000135} +{"type":"assistant/message","data":{"turn":23,"step":1,"message":{"id":"preview-assistant-23","role":"assistant","content":[{"type":"text","text":"Checkpoint 23 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 23 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 23 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":136,"time":1787472000136} +{"type":"step/end","data":{"turn":23,"step":1},"seq":137,"time":1787472000137} +{"type":"turn/end","data":{"turn":23,"reason":{"kind":"completed"}},"seq":138,"time":1787472000138} +{"type":"turn/start","data":{"turn":24},"seq":139,"time":1787472000139} +{"type":"user/message","data":{"id":"preview-user-24","role":"user","content":[{"type":"text","text":"History checkpoint 24: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":140,"time":1787472000140} +{"type":"step/start","data":{"turn":24,"step":1},"seq":141,"time":1787472000141} +{"type":"assistant/message","data":{"turn":24,"step":1,"message":{"id":"preview-assistant-24","role":"assistant","content":[{"type":"text","text":"Checkpoint 24 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 24 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 24 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":142,"time":1787472000142} +{"type":"step/end","data":{"turn":24,"step":1},"seq":143,"time":1787472000143} +{"type":"turn/end","data":{"turn":24,"reason":{"kind":"completed"}},"seq":144,"time":1787472000144} +{"type":"turn/start","data":{"turn":25},"seq":145,"time":1787472000145} +{"type":"user/message","data":{"id":"preview-user-25","role":"user","content":[{"type":"text","text":"History checkpoint 25: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":146,"time":1787472000146} +{"type":"step/start","data":{"turn":25,"step":1},"seq":147,"time":1787472000147} +{"type":"assistant/message","data":{"turn":25,"step":1,"message":{"id":"preview-assistant-25","role":"assistant","content":[{"type":"text","text":"Checkpoint 25 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 25 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 25 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":148,"time":1787472000148} +{"type":"step/end","data":{"turn":25,"step":1},"seq":149,"time":1787472000149} +{"type":"turn/end","data":{"turn":25,"reason":{"kind":"completed"}},"seq":150,"time":1787472000150} +{"type":"turn/start","data":{"turn":26},"seq":151,"time":1787472000151} +{"type":"user/message","data":{"id":"preview-user-26","role":"user","content":[{"type":"text","text":"History checkpoint 26: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":152,"time":1787472000152} +{"type":"step/start","data":{"turn":26,"step":1},"seq":153,"time":1787472000153} +{"type":"assistant/message","data":{"turn":26,"step":1,"message":{"id":"preview-assistant-26","role":"assistant","content":[{"type":"text","text":"Checkpoint 26 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 26 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 26 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":154,"time":1787472000154} +{"type":"step/end","data":{"turn":26,"step":1},"seq":155,"time":1787472000155} +{"type":"turn/end","data":{"turn":26,"reason":{"kind":"completed"}},"seq":156,"time":1787472000156} +{"type":"turn/start","data":{"turn":27},"seq":157,"time":1787472000157} +{"type":"user/message","data":{"id":"preview-user-27","role":"user","content":[{"type":"text","text":"History checkpoint 27: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":158,"time":1787472000158} +{"type":"step/start","data":{"turn":27,"step":1},"seq":159,"time":1787472000159} +{"type":"assistant/message","data":{"turn":27,"step":1,"message":{"id":"preview-assistant-27","role":"assistant","content":[{"type":"text","text":"Checkpoint 27 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 27 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 27 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":160,"time":1787472000160} +{"type":"step/end","data":{"turn":27,"step":1},"seq":161,"time":1787472000161} +{"type":"turn/end","data":{"turn":27,"reason":{"kind":"completed"}},"seq":162,"time":1787472000162} +{"type":"turn/start","data":{"turn":28},"seq":163,"time":1787472000163} +{"type":"user/message","data":{"id":"preview-user-28","role":"user","content":[{"type":"text","text":"History checkpoint 28: verify deterministic preview state."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":164,"time":1787472000164} +{"type":"step/start","data":{"turn":28,"step":1},"seq":165,"time":1787472000165} +{"type":"assistant/message","data":{"turn":28,"step":1,"message":{"id":"preview-assistant-28","role":"assistant","content":[{"type":"text","text":"Checkpoint 28 is recorded."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["Checkpoint 28 is recorded."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Checkpoint 28 is recorded."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":166,"time":1787472000166} +{"type":"step/end","data":{"turn":28,"step":1},"seq":167,"time":1787472000167} +{"type":"turn/end","data":{"turn":28,"reason":{"kind":"completed"}},"seq":168,"time":1787472000168} +{"type":"turn/start","data":{"turn":29},"seq":169,"time":1787472000169} +{"type":"user/message","data":{"id":"preview-gallery-user","role":"user","content":[{"type":"text","text":"Show the seeded workspace, tool cards, subagents, and pagination in one tour."}],"source":{"kind":"user"}},"surfaceOp":"append","seq":170,"time":1787472000170} +{"type":"step/start","data":{"turn":29,"step":1},"seq":171,"time":1787472000171} +{"type":"assistant/message","data":{"turn":29,"step":1,"message":{"id":"preview-gallery-tools","role":"assistant","content":[{"type":"reasoning","text":""},{"type":"reasoning","text":" \t\n"},{"type":"reasoning","text":"I will inspect the deterministic workspace and collect each preview surface."},{"type":"reasoning","text":""},{"type":"reasoning","text":"Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link."},{"type":"reasoning","text":"\n "},{"type":"tool-call","id":"preview-read","name":"read","arguments":"{\"file_path\":\"PREVIEW.md\"}"},{"type":"tool-call","id":"preview-write","name":"write","arguments":"{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"},{"type":"tool-call","id":"preview-bash","name":"bash","arguments":"{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"},{"type":"tool-call","id":"preview-wrapped-bash","name":"bash","arguments":"{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"},{"type":"tool-call","id":"preview-glob","name":"glob","arguments":"{\"pattern\":\"**/*\",\"path\":\".\"}"},{"type":"tool-call","id":"preview-grep","name":"grep","arguments":"{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"},{"type":"tool-call","id":"preview-web-search","name":"web_search","arguments":"{\"queries\":[\"Web Worker filesystem compatibility\"]}"},{"type":"tool-call","id":"preview-todo","name":"todo_write","arguments":"{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"},{"type":"tool-call","id":"preview-subagent","name":"subagent","arguments":"{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"},{"type":"tool-call","id":"preview-subagent-fork","name":"subagent_fork","arguments":"{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"},{"type":"tool-call","id":"preview-failure","name":"read","arguments":"{\"file_path\":\"missing.txt\"}"}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":0,"dt":[],"texts":[""]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":""}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":1,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":1,"dt":[],"texts":[" \t\n"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":1,"block":{"type":"reasoning","text":" \t\n"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":2,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":2,"dt":[],"texts":["I will inspect the deterministic workspace and collect each preview surface."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":2,"block":{"type":"reasoning","text":"I will inspect the deterministic workspace and collect each preview surface."}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":3,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":3,"dt":[],"texts":[""]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":3,"block":{"type":"reasoning","text":""}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":4,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":4,"dt":[],"texts":["Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":4,"block":{"type":"reasoning","text":"Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link."}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":5,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":0,"index":5,"dt":[],"texts":["\n "]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":5,"block":{"type":"reasoning","text":"\n "}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":6,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":6,"dt":[],"id":"preview-read","name":"read","args":["{\"file_path\":\"PREVIEW.md\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":6,"block":{"type":"tool-call","id":"preview-read","name":"read","arguments":"{\"file_path\":\"PREVIEW.md\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":7,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":7,"dt":[],"id":"preview-write","name":"write","args":["{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":7,"block":{"type":"tool-call","id":"preview-write","name":"write","arguments":"{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":8,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":8,"dt":[],"id":"preview-bash","name":"bash","args":["{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":8,"block":{"type":"tool-call","id":"preview-bash","name":"bash","arguments":"{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":9,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":9,"dt":[],"id":"preview-wrapped-bash","name":"bash","args":["{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":9,"block":{"type":"tool-call","id":"preview-wrapped-bash","name":"bash","arguments":"{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":10,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":10,"dt":[],"id":"preview-glob","name":"glob","args":["{\"pattern\":\"**/*\",\"path\":\".\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":10,"block":{"type":"tool-call","id":"preview-glob","name":"glob","arguments":"{\"pattern\":\"**/*\",\"path\":\".\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":11,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":11,"dt":[],"id":"preview-grep","name":"grep","args":["{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":11,"block":{"type":"tool-call","id":"preview-grep","name":"grep","arguments":"{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":12,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":12,"dt":[],"id":"preview-web-search","name":"web_search","args":["{\"queries\":[\"Web Worker filesystem compatibility\"]}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":12,"block":{"type":"tool-call","id":"preview-web-search","name":"web_search","arguments":"{\"queries\":[\"Web Worker filesystem compatibility\"]}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":13,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":13,"dt":[],"id":"preview-todo","name":"todo_write","args":["{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":13,"block":{"type":"tool-call","id":"preview-todo","name":"todo_write","arguments":"{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":14,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":14,"dt":[],"id":"preview-subagent","name":"subagent","args":["{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":14,"block":{"type":"tool-call","id":"preview-subagent","name":"subagent","arguments":"{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":15,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":15,"dt":[],"id":"preview-subagent-fork","name":"subagent_fork","args":["{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":15,"block":{"type":"tool-call","id":"preview-subagent-fork","name":"subagent_fork","arguments":"{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"}}},{"type":"chunk","time":0,"chunk":{"type":"block-start","index":16,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":16,"dt":[],"id":"preview-failure","name":"read","args":["{\"file_path\":\"missing.txt\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":16,"block":{"type":"tool-call","id":"preview-failure","name":"read","arguments":"{\"file_path\":\"missing.txt\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append","seq":172,"time":1787472000172} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-read","name":"read","arguments":"{\"file_path\":\"PREVIEW.md\"}"},"seq":173,"time":1787472000173} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-read-result","role":"tool","toolCallId":"preview-read","source":{"kind":"tool","callId":"preview-read"},"content":[{"type":"text","text":"PREVIEW.md\nfile\n\n1: # Preview Workspace\n2: \n3: This deterministic workspace is bundled with the browser-only preview.\n4: \n5: - `src/preview.ts` is the file changed by the example write result.\n6: - `data/tasks.json` mirrors the completed preview checklist.\n7: - `.agents/skills/preview-tour/SKILL.md` proves dot directories survive image packing.\n8: \n9: Refresh the preview to restore these image bytes.\n\n(End of file - total 9 lines)\n"}],"isError":false},"meta":{"path":"PREVIEW.md","offset":1,"lines":[{"number":1,"text":"# Preview Workspace"},{"number":2,"text":""},{"number":3,"text":"This deterministic workspace is bundled with the browser-only preview."},{"number":4,"text":""},{"number":5,"text":"- `src/preview.ts` is the file changed by the example write result."},{"number":6,"text":"- `data/tasks.json` mirrors the completed preview checklist."},{"number":7,"text":"- `.agents/skills/preview-tour/SKILL.md` proves dot directories survive image packing."},{"number":8,"text":""},{"number":9,"text":"Refresh the preview to restore these image bytes."}],"totalLines":9,"lang":"md"}},"surfaceOp":"append","seq":174,"time":1787472000174} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-write","name":"write","arguments":"{\"file_path\":\"src/preview.ts\",\"content\":\"export const previewStatus = 'ready'\\n\\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\\n\"}"},"seq":175,"time":1787472000175} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-write-result","role":"tool","toolCallId":"preview-write","source":{"kind":"tool","callId":"preview-write"},"content":[{"type":"text","text":"src/preview.ts\nfile\n\nUpdated file\n"}],"isError":false},"meta":{"diffs":[{"path":"src/preview.ts","oldText":"export const previewStatus = 'draft'\n","newText":"export const previewStatus = 'ready'\n\nexport const previewFeatures = ['tools', 'subagents', 'pagination'] as const\n"}]}},"surfaceOp":"append","seq":176,"time":1787472000176} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-bash","name":"bash","arguments":"{\"command\":\"printf 'preview ready\\\\n'\",\"description\":\"Print the preview readiness marker\"}"},"seq":177,"time":1787472000177} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-bash-result","role":"tool","toolCallId":"preview-bash","source":{"kind":"tool","callId":"preview-bash"},"content":[{"type":"text","text":"preview ready\n"}],"isError":false}},"surfaceOp":"append","seq":178,"time":1787472000178} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-wrapped-bash","name":"bash","arguments":"{\"command\":\"printf 'preview command fixture\\\\n' # wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-wrapped-argument-\\nprintf 'wrap complete\\\\n'\\n\",\"description\":\"Show wrapped command and first-line status\"}"},"seq":179,"time":1787472000179} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-wrapped-bash-result","role":"tool","toolCallId":"preview-wrapped-bash","source":{"kind":"tool","callId":"preview-wrapped-bash"},"content":[{"type":"text","text":"preview command fixture\nwrap complete\n[exit code: 0]"}],"isError":false}},"surfaceOp":"append","seq":180,"time":1787472000180} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-glob","name":"glob","arguments":"{\"pattern\":\"**/*\",\"path\":\".\"}"},"seq":181,"time":1787472000181} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-glob-result","role":"tool","toolCallId":"preview-glob","source":{"kind":"tool","callId":"preview-glob"},"content":[{"type":"text","text":"PREVIEW.md\ndata/tasks.json\nsrc/preview.ts"}],"isError":false},"meta":{"shape":"paths","paths":["PREVIEW.md","data/tasks.json","src/preview.ts"],"truncated":false,"total":3}},"surfaceOp":"append","seq":182,"time":1787472000182} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-grep","name":"grep","arguments":"{\"pattern\":\"preview\",\"path\":\".\",\"include\":\"*.{md,ts,json}\"}"},"seq":183,"time":1787472000183} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-grep-result","role":"tool","toolCallId":"preview-grep","source":{"kind":"tool","callId":"preview-grep"},"content":[{"type":"text","text":"PREVIEW.md:3:This deterministic workspace is bundled with the browser-only preview.\nsrc/preview.ts:1:export const previewStatus = 'ready'"}],"isError":false},"meta":{"shape":"matches","files":[{"path":"PREVIEW.md","matches":[{"lineNumber":3,"line":"This deterministic workspace is bundled with the browser-only preview."}]},{"path":"src/preview.ts","matches":[{"lineNumber":1,"line":"export const previewStatus = 'ready'"}]}],"truncated":false,"total":2}},"surfaceOp":"append","seq":184,"time":1787472000184} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-web-search","name":"web_search","arguments":"{\"queries\":[\"Web Worker filesystem compatibility\"]}"},"seq":185,"time":1787472000185} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-web-search-result","role":"tool","toolCallId":"preview-web-search","source":{"kind":"tool","callId":"preview-web-search"},"content":[{"type":"text","text":"Browser workers can host deterministic in-memory filesystems.\n\nSources:\n1. MDN Web Workers API — https://developer.mozilla.org/docs/Web/API/Web_Workers_API"}],"isError":false},"meta":{"sources":[{"url":"https://developer.mozilla.org/docs/Web/API/Web_Workers_API","title":"Web Workers API","snippet":"Web Workers run scripts in background threads."}],"truncated":false,"answer":"Browser workers can host deterministic in-memory filesystems."}},"surfaceOp":"append","seq":186,"time":1787472000186} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-todo","name":"todo_write","arguments":"{\"todos\":[{\"content\":\"Inspect tool cards\",\"status\":\"completed\"},{\"content\":\"Open both subagents\",\"status\":\"completed\"},{\"content\":\"Load earlier history\",\"status\":\"in_progress\"}]}"},"seq":187,"time":1787472000187} +{"type":"todo/write","data":{"todos":[{"content":"Inspect tool cards","status":"completed"},{"content":"Open both subagents","status":"completed"},{"content":"Load earlier history","status":"in_progress"}]},"seq":188,"time":1787472000188} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-todo-result","role":"tool","toolCallId":"preview-todo","source":{"kind":"tool","callId":"preview-todo"},"content":[{"type":"text","text":"Updated todo list: 0 pending, 1 in progress, 2 completed."}],"isError":false}},"surfaceOp":"append","seq":189,"time":1787472000189} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-subagent","name":"subagent","arguments":"{\"description\":\"Continue preview verification\",\"prompt\":\"Check the remaining preview cases.\",\"run_in_background\":true}"},"seq":190,"time":1787472000190} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-subagent-result","role":"tool","toolCallId":"preview-subagent","source":{"kind":"tool","callId":"preview-subagent"},"content":[{"type":"text","text":"started subagent preview-follow-up-builder"}],"isError":false}},"surfaceOp":"append","seq":191,"time":1787472000191} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-subagent-fork","name":"subagent_fork","arguments":"{\"description\":\"Review preview architecture\",\"prompt\":\"Review the fixture architecture.\",\"run_in_background\":false}"},"seq":192,"time":1787472000192} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-subagent-fork-result","role":"tool","toolCallId":"preview-subagent-fork","source":{"kind":"tool","callId":"preview-subagent-fork"},"content":[{"type":"text","text":"The preview fixture remains separate from user-owned WebFS data."}],"isError":false}},"surfaceOp":"append","seq":193,"time":1787472000193} +{"type":"tool/call","data":{"turn":29,"step":1,"callId":"preview-failure","name":"read","arguments":"{\"file_path\":\"missing.txt\"}"},"seq":194,"time":1787472000194} +{"type":"tool/result","data":{"turn":29,"step":1,"message":{"id":"preview-failure-result","role":"tool","toolCallId":"preview-failure","source":{"kind":"tool","callId":"preview-failure"},"content":[{"type":"text","text":"Error: ENOENT: no such file, open missing.txt"}],"isError":true},"error":{"name":"FsError","code":"ENOENT"}},"surfaceOp":"append","seq":195,"time":1787472000195} +{"type":"subagent/catalog","data":{"version":0,"childId":"preview-architecture-review","childCreatedAt":1787472100000,"mode":"one-shot","label":"Review preview architecture"},"seq":196,"time":1787472000196} +{"type":"subagent/catalog","data":{"version":0,"childId":"preview-follow-up-builder","childCreatedAt":1787472200000,"mode":"continuable","label":"Continue preview verification"},"seq":197,"time":1787472000197} +{"type":"step/end","data":{"turn":29,"step":1},"seq":198,"time":1787472000198} +{"type":"step/start","data":{"turn":29,"step":2},"seq":199,"time":1787472000199} +{"type":"assistant/message","data":{"turn":29,"step":2,"message":{"id":"preview-gallery-final","role":"assistant","content":[{"type":"text","text":"## Preview tour complete\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path."}],"source":{"kind":"model","provider":"preview-fixture","model":"deterministic"}},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["## Preview tour complete\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path."]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"## Preview tour complete\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path."}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append","seq":200,"time":1787472000200} +{"type":"step/end","data":{"turn":29,"step":2},"seq":201,"time":1787472000201} +{"type":"turn/end","data":{"turn":29,"reason":{"kind":"completed"}},"seq":202,"time":1787472000202} diff --git a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json index 3ecdae0660..d26f67472b 100644 --- a/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json +++ b/packages/experimental/webworker-runtime/tests/fixtures/vfs-example/home/storages/session_projcache.json @@ -8,7 +8,7 @@ "sessions": { "preview-showcase": { "identity": { - "formatVersion": 3, + "formatVersion": 4, "createdAt": 1787472000000, "cwd": "/dsh/workspace", "isSeeded": false, @@ -17,7 +17,7 @@ "rows": { "title": { "ver": 1, - "seq": 198, + "seq": 202, "val": "WebWorker Preview Showcase" } } diff --git a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts index 8ae9dcf6fa..5e588839a4 100644 --- a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts +++ b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.spec.ts @@ -14,6 +14,8 @@ import { buildVfsExampleFiles, VFS_EXAMPLE_OLDEST_MESSAGE, VFS_EXAMPLE_ROOT, + VFS_EXAMPLE_REASONING, + VFS_EXAMPLE_WRAPPED_COMMAND, VFS_EXAMPLE_SCHEDULE_IDS, VFS_EXAMPLE_SESSION_IDS, VFS_EXAMPLE_TAIL_MESSAGE, @@ -59,27 +61,29 @@ function textOf(event: SessionEvent): string { } describe('WebWorker preview VFS example', () => { - it('retains V3 inputs that strictly restore to the deterministic current output', () => { + it('keeps the current showcase and strictly restorable historical child inputs beside their predecessors', () => { const expected = buildVfsExampleFiles() const currentName = generationLogFilename(SESSION_FORMAT_VERSION, 'none') - const committedPath = (path: string): string => path.endsWith(`/${currentName}`) + const main = `home/sessions/--dsh-workspace--/${VFS_EXAMPLE_SESSION_IDS.main}/` + const committedPath = (path: string): string => path.endsWith(`/${currentName}`) && !path.startsWith(main) ? `${path.slice(0, -currentName.length)}session.v3.jsonl` : path const predecessors = Object.values(VFS_EXAMPLE_SESSION_IDS) .map(id => `home/sessions/--dsh-workspace--/${id}/session.v2.jsonl`) + predecessors.push(`${main}session.v3.jsonl`) expect(filesUnder(VFS_EXAMPLE_ROOT)).toEqual([...expected.keys()].map(committedPath).concat(predecessors).sort()) for (const [path, content] of expected) { - if (path === 'home/storages/session_projcache.json') continue const committed = readFileSync(join(VFS_EXAMPLE_ROOT, committedPath(path)), 'utf8') - if (path.endsWith(`/${currentName}`)) { + if (path.endsWith(`/${currentName}`) && !path.startsWith(main)) { expect(restoreSession(committed, 3), path).toEqual(restoreSession(content, SESSION_FORMAT_VERSION)) } else { expect(committed, path).toBe(content) + if (path.startsWith(main)) restoreSession(committed, SESSION_FORMAT_VERSION) } } }) - it('retains V3 cache identity while the generated cache uses the current writer', () => { + it('keeps the projection cache aligned with the current showcase writer and tail', () => { const committed = JSON.parse(readFileSync( join(VFS_EXAMPLE_ROOT, 'home/storages/session_projcache.json'), 'utf8', @@ -101,12 +105,10 @@ describe('WebWorker preview VFS example', () => { const generatedText = buildVfsExampleFiles().get('home/storages/session_projcache.json') if (generatedText === undefined) throw new Error('missing generated VFS example projection cache') const generated = JSON.parse(generatedText) as typeof committed - const expectedCurrent = structuredClone(committed) - for (const session of Object.values(expectedCurrent.tables.sessions)) { - expect(session.identity.formatVersion).toBe(3) - session.identity.formatVersion = SESSION_FORMAT_VERSION - } - expect(generated).toEqual(expectedCurrent) + expect(generated).toEqual(committed) + expect(generated.tables.sessions[VFS_EXAMPLE_SESSION_IDS.main]?.rows.title).toMatchObject({ + seq: readSession(VFS_EXAMPLE_SESSION_IDS.main).events.at(-1)?.seq, + }) expect(generated.unit).toEqual({ name: projectionCacheDomainSpec.name, version: projectionCacheDomainSpec.version, @@ -180,6 +182,46 @@ describe('WebWorker preview VFS example', () => { expect(events.some(event => event.type === 'tool/result' && event.data.message.isError === true)).toBe(true) }) + it('preserves the 28-turn history prefix and both child catalog identities', () => { + const main = readSession(VFS_EXAMPLE_SESSION_IDS.main) + const child = readSession(VFS_EXAMPLE_SESSION_IDS.oneShot) + const historical = restoreSession(readFileSync(join(VFS_EXAMPLE_ROOT, + `home/sessions/--dsh-workspace--/${VFS_EXAMPLE_SESSION_IDS.main}/session.v3.jsonl`), 'utf8'), 3) + const prefix = main.events.slice(0, child.inheritedEventCount) + expect(prefix.filter(event => event.type === 'turn/start')).toHaveLength(28) + expect(prefix).toEqual(historical.events.slice(0, child.inheritedEventCount)) + expect(child.events.slice(0, child.inheritedEventCount)).toEqual(prefix) + expect(main.events.filter(event => event.type === 'subagent/catalog').map(event => event.data)).toEqual([ + { version: 0, childId: VFS_EXAMPLE_SESSION_IDS.oneShot, childCreatedAt: 1_787_472_100_000, + mode: 'one-shot', label: 'Review preview architecture' }, + { version: 0, childId: VFS_EXAMPLE_SESSION_IDS.continuable, childCreatedAt: 1_787_472_200_000, + mode: 'continuable', label: 'Continue preview verification' }, + ]) + }) + + it('carries mixed reasoning, a wrapped command, and an authored parent-path link in the existing tour', () => { + const { events } = readSession(VFS_EXAMPLE_SESSION_IDS.main) + const gallery = events.find(event => event.type === 'assistant/message' && event.data.message.id === 'preview-gallery-tools') + if (gallery?.type !== 'assistant/message') throw new Error('missing preview gallery message') + const reasoning = gallery.data.message.content.flatMap(block => block.type === 'reasoning' ? [block.text] : []) + expect(reasoning).toEqual(['', ' \t\n', VFS_EXAMPLE_REASONING[0], '', VFS_EXAMPLE_REASONING[1], '\n ']) + expect(reasoning.filter(text => text.trim() !== '')).toEqual(VFS_EXAMPLE_REASONING) + const call = events.find(event => event.type === 'tool/call' && event.data.callId === 'preview-wrapped-bash') + if (call?.type !== 'tool/call') throw new Error('missing wrapped command call') + expect(JSON.parse(call.data.arguments)).toEqual({ + command: VFS_EXAMPLE_WRAPPED_COMMAND, description: 'Show wrapped command and first-line status', + }) + expect(VFS_EXAMPLE_WRAPPED_COMMAND.split('\n')[0]?.length).toBeGreaterThan(400) + expect(VFS_EXAMPLE_WRAPPED_COMMAND.endsWith('\n')).toBe(true) + expect(events.find(event => event.type === 'tool/result' && event.data.message.source.callId === 'preview-wrapped-bash')) + .toMatchObject({ data: { message: { isError: false, content: [{ type: 'text', text: 'preview command fixture\nwrap complete\n[exit code: 0]' }] } } }) + const tail = events.findLast(event => event.type === 'assistant/message') + if (tail === undefined) throw new Error('missing preview tour tail') + expect(textOf(tail)).toContain(`## ${VFS_EXAMPLE_TAIL_MESSAGE}`) + expect(textOf(tail)).toContain('[Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>)') + expect(textOf(tail)).toContain('fixture-authored demonstration data, not a live model run') + }) + it('restores one-shot and continuable child Sessions with durable descriptors', () => { const expected = [ [VFS_EXAMPLE_SESSION_IDS.oneShot, 'one-shot'], diff --git a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts index fd00a86139..2f015bf246 100644 --- a/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts +++ b/packages/experimental/webworker-runtime/tests/vfs-example-fixture.ts @@ -17,6 +17,7 @@ import { import { projectionCacheDomainSpec } from '@deepseek-ai/dsh-session-projection-cache' import { scheduleDomain } from '@deepseek-ai/dsh-schedule' import { snapshotSubagentDescriptor, SUBAGENT_DESCRIPTOR_VERSION } from '@deepseek-ai/dsh-subagent' +import { SUBAGENT_CATALOG_VERSION } from '@deepseek-ai/dsh-subagent/src/catalog.ts' /** Root copied by the preview image's repository adapter. */ export const VFS_EXAMPLE_ROOT = fileURLToPath(new URL('./fixtures/vfs-example', import.meta.url)) @@ -37,6 +38,15 @@ export const VFS_EXAMPLE_OLDEST_MESSAGE = 'History checkpoint 01: verify determi /** Settled tail marker used by browser acceptance and the demonstration GIF. */ export const VFS_EXAMPLE_TAIL_MESSAGE = 'Preview tour complete' +/** Non-empty reasoning bodies surrounded by empty and whitespace-only fixture blocks. */ +export const VFS_EXAMPLE_REASONING = [ + 'I will inspect the deterministic workspace and collect each preview surface.', + 'Check the Chat presentation\n\nI will inspect the wrapped command, its first-line status, and the parent-path file link.', +] as const + +/** Authored long command and a second line for wrapping and status-dot acceptance. */ +export const VFS_EXAMPLE_WRAPPED_COMMAND = `printf 'preview command fixture\\n' # ${'wrapped-argument-'.repeat(28)}\nprintf 'wrap complete\\n'\n` + /** Durable task ids for the Host Schedule rows seeded into the preview's `DSH_HOME`. */ export const VFS_EXAMPLE_SCHEDULE_IDS = { daily: 'preview-daily-digest', @@ -211,6 +221,12 @@ function galleryCalls(): GalleryCall[] { args: { command: "printf 'preview ready\\n'", description: 'Print the preview readiness marker' }, result: 'preview ready\n', }, + { + id: 'preview-wrapped-bash', + name: 'bash', + args: { command: VFS_EXAMPLE_WRAPPED_COMMAND, description: 'Show wrapped command and first-line status' }, + result: 'preview command fixture\nwrap complete\n[exit code: 0]', + }, { id: 'preview-glob', name: 'glob', @@ -327,7 +343,8 @@ function mainLog(): { log.add(userMessage('preview-gallery-user', 'Show the seeded workspace, tool cards, subagents, and pagination in one tour.')) log.add({ type: 'step/start', data: { turn, step: 1 } }) log.add(assistantMessage('preview-gallery-tools', turn, 1, [ - { type: 'reasoning', text: 'I will inspect the deterministic workspace and collect each preview surface.' }, + ...['', ' \t\n', VFS_EXAMPLE_REASONING[0], '', VFS_EXAMPLE_REASONING[1], '\n '] + .map(text => ({ type: 'reasoning', text })), ...calls.map(call => ({ type: 'tool-call', id: call.id, name: call.name, arguments: JSON.stringify(call.args) })), ])) for (const call of calls) { @@ -355,11 +372,17 @@ function mainLog(): { surfaceOp: 'append', }) } + for (const child of [ + { childId: VFS_EXAMPLE_SESSION_IDS.oneShot, childCreatedAt: CREATED_AT + 100_000, mode: 'one-shot', label: 'Review preview architecture' }, + { childId: VFS_EXAMPLE_SESSION_IDS.continuable, childCreatedAt: CREATED_AT + 200_000, mode: 'continuable', label: 'Continue preview verification' }, + ] as const) { + log.add({ type: 'subagent/catalog', data: { version: SUBAGENT_CATALOG_VERSION, ...child } }) + } log.add({ type: 'step/end', data: { turn, step: 1 } }) log.add({ type: 'step/start', data: { turn, step: 2 } }) log.add(assistantMessage('preview-gallery-final', turn, 2, [{ type: 'text', - text: `## ${VFS_EXAMPLE_TAIL_MESSAGE}\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.`, + text: `## ${VFS_EXAMPLE_TAIL_MESSAGE}\n\nThe workspace, specialized tool cards, two subagent histories, and an earlier history page are ready to inspect.\n\nThis is fixture-authored demonstration data, not a live model run. Open [Parent workspace guide:1–8](<../workspace/PREVIEW.md#L1-L8>) to inspect the same workspace file through a parent path.`, }])) log.add({ type: 'step/end', data: { turn, step: 2 } }) log.add({ type: 'turn/end', data: { turn, reason: { kind: 'completed' } } }) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index daddade30d..1d89944016 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -30,8 +30,8 @@ en: 6826dfaadb24f3da zh: 2e2ee715247fc015 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work: - en: a30c8288cb571461 - zh: e94cf8507f4b8b54 + en: 0adcf97622e86f3b + zh: 8bcdc336011cd7e1 /deepseek-ai-dsh-experimental-worktree/known-limitations-and-deferred-work/dev-note: en: ad12746a6cc96d8a zh: 66275f30a35c88e4 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index 54e0a25b86..117bd50dae 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -83,9 +83,9 @@ This package contributes no prompt text. Its consumers own the appended tool res - **Retained artifacts** — leaving a worktree keeps its branch and files. Setup failures can also retain partial artifacts; removal, pruning, and branch deletion belong to the user or another consumer. -- **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. Missing local objects cause creation to fail. +- **Local revisions only** — creation does not fetch commits or missing partial-clone objects, initialize submodules, install dependencies, or copy uncommitted files. On Git that meets the execution requirements, missing local objects cause creation to fail. - **Filtered representations** — checkout skips configured filters to avoid executing repository-configured programs or triggering implicit downloads. Git LFS pointers and encrypted blobs stay in their stored representation; hydration or decryption is a separate user-controlled operation. -- **Execution requirements** — the subprocess provider must offer Git 2.45 or newer and Node in the same execution world as the filesystem provider. Git must support `--no-lazy-fetch`; unsupported executables fail before directory allocation. The existing sandbox must permit all checkout and shared Git metadata writes. +- **Execution requirements** — the subprocess provider must offer Git and Node in the same execution world as the filesystem provider. Git must honor `GIT_NO_LAZY_FETCH`, which Git 2.45 and the 2.39.4, 2.40.2, 2.41.1, 2.42.2, 2.43.4, and 2.44.1 maintenance releases do; older releases ignore it and proceed instead of failing, so creation can fetch missing partial-clone objects from a promisor remote. The `git --no-lazy-fetch` option would reject these releases, but it exists only in Git 2.45 and later and also rejects the patched maintenance releases. The existing sandbox must permit all checkout and shared Git metadata writes. ### Dev Note diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index 5f12a876f5..3f952697dd 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -83,9 +83,9 @@ Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调 - **保留产物**——离开工作树会保留其分支和文件。初始化失败也可能留下部分产物;移除、清理注册信息与删除分支由用户或其他消费方负责。 -- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。本地对象缺失时,创建失败。 +- **仅限本地提交**——创建操作不会获取远端提交或部分克隆中缺失的对象、初始化子模块、安装依赖或复制未提交文件。Git 满足执行要求时,本地对象缺失会导致创建失败。 - **过滤器处理前的内容**——检出时跳过已配置的过滤器,以避免执行仓库配置的程序或隐式下载。Git LFS 指针与加密 blob 保持存储时的形式;拉取实体内容或解密由用户另行执行。 -- **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 2.45 或更新版本以及 Node。Git 必须支持 `--no-lazy-fetch`;不支持的可执行程序会在分配目录前报错。现有沙箱必须允许写入检出目录与共享 Git 元数据。 +- **执行要求**——子进程提供方必须在与文件系统提供方相同的执行环境中提供 Git 与 Node。Git 必须识别 `GIT_NO_LAZY_FETCH`:Git 2.45 及 2.39.4、2.40.2、2.41.1、2.42.2、2.43.4、2.44.1 维护版本均支持;更早的版本会忽略该变量并继续执行而不报错,因此创建操作可能从 promisor 远程获取缺失的部分克隆对象。`git --no-lazy-fetch` 选项会拒绝这些版本,但它仅在 Git 2.45 及以后存在,也会拒绝上述已修补的维护版本。现有沙箱必须允许写入检出目录与共享 Git 元数据。 ### 开发备注 diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index 508b347ef0..71095313a0 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -21,7 +21,7 @@ export interface Config { directory?: string /** Prefix for automatically generated branch and checkout names. */ namePrefix?: string - /** Git 2.45 or newer executable name or absolute execution-world path. */ + /** Executable name or absolute execution-world path of a Git release that honors `GIT_NO_LAZY_FETCH`. */ gitCommand?: string /** Node executable used for sandboxed directory allocation. */ nodeCommand?: string @@ -129,7 +129,7 @@ export class WorktreeService extends Service { const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = (directory: string, args: string[], allowedExitCodes?: number[], env?: NodeJS.ProcessEnv) => runCommand( this.ctx, this.config, policy, directory, - [this.config.gitCommand, '--no-lazy-fetch', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], + [this.config.gitCommand, '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false', ...args], signal, allowedExitCodes, env, ) await run(cwd, ['check-ref-format', `refs/heads/${branch}`]) diff --git a/packages/experimental/worktree/src/process.ts b/packages/experimental/worktree/src/process.ts index ee90b13805..74c8fa1c1b 100644 --- a/packages/experimental/worktree/src/process.ts +++ b/packages/experimental/worktree/src/process.ts @@ -56,7 +56,7 @@ export async function runCommand( const child = ctx.subprocess.spawn({ argv: wrapped, cwd, - env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', ...env }, + env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_LFS_SKIP_SMUDGE: '1', GIT_NO_LAZY_FETCH: '1', ...env }, signal: timeout.signal, graceMs: config.graceMs, stdio: { diff --git a/packages/extensions/cordis-client-runner/locale/en.json b/packages/extensions/cordis-client-runner/locale/en.json new file mode 100644 index 0000000000..2722f3c653 --- /dev/null +++ b/packages/extensions/cordis-client-runner/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "cordis-client-runner" + } +} diff --git a/packages/extensions/cordis-client-runner/locale/zh.json b/packages/extensions/cordis-client-runner/locale/zh.json new file mode 100644 index 0000000000..96dd065277 --- /dev/null +++ b/packages/extensions/cordis-client-runner/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "动态插件浏览器运行器", + "description": "加载并运行临时动态插件的浏览器部分。" + } +} diff --git a/packages/extensions/cordis-client-runner/package.json b/packages/extensions/cordis-client-runner/package.json index 44b4f09d32..fdfc292ef3 100644 --- a/packages/extensions/cordis-client-runner/package.json +++ b/packages/extensions/cordis-client-runner/package.json @@ -23,7 +23,8 @@ "default": "./lib/client.js" }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { @@ -50,12 +51,12 @@ "@deepseek-ai/dsh-client-modules": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-theme": "workspace:*", - "@types/react": "~18.3.1", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "@deepseek-ai/dsh-util-values": "workspace:*" }, "files": [ + "locale/*.json", "lib/index.js", "lib/client.js", "lib/types/**/*.d.ts" diff --git a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts index 4ff7bd728d..469db60766 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -341,9 +341,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'target', description: 'known Session identity or durable direct-parent subagent address to display.' }], }, { - signature: 'openWorkspace(workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void): Promise', + signature: 'openWorkspace( workspaceId: WorkspaceId, beforeOpen?: (sessionId: SessionId) => void, options?: Pick, ): Promise', description: 'Connect a Workspace and open its Session unless a later navigation supersedes it.', - parameters: [{ name: 'workspaceId', description: 'target Workspace.' }, { name: 'beforeOpen', description: 'optional synchronous preparation for the selected Session, skipped after supersession; a throw aborts the open and releases the retained reference.' }], + parameters: [{ name: 'workspaceId', description: 'target Workspace.' }, { name: 'beforeOpen', description: 'optional synchronous preparation for the selected Session, skipped after supersession; a throw aborts the open and releases the retained reference.' }, { name: 'options', description: 'choices for the Session the connection creates or reuses.' }], returns: 'completion; a superseded request may create a Session but does not open it.', throws: ['on failure; a refused creation is also shown through the Workspace notice unless a later navigation or disposal superseded the request.'], }, @@ -354,15 +354,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ returns: 'the child SessionId after creation and inherited-title increment.', }, { - signature: 'connectWorkspace(workspaceId: WorkspaceId): Promise', - description: 'Resolve the reusable or newly created blank Session for a Workspace.', - parameters: [{ name: 'workspaceId', description: 'target Workspace.' }], + signature: 'connectWorkspace(workspaceId: WorkspaceId, options?: Pick): Promise', + description: 'Resolve the Session for a new conversation in a Workspace: the Host reuses the first listed blank member while it is reusable and otherwise creates one, under the requested preset or the Host default.', + parameters: [{ name: 'workspaceId', description: 'target Workspace.' }, { name: 'options', description: 'choices for the created or reused Session.' }], returns: 'a Session already addressable through the Session Controller.', }, { signature: 'startSession(workspaceId?: WorkspaceId, options?: StartSessionOptions): void', description: 'Create a fresh Session, or reuse a blank when preparing an explicit draft. A creation the Host refuses is shown through the Workspace notice and leaves the selection as it was.', - parameters: [{ name: 'workspaceId', description: 'explicit target; absent inherits the current or most recent Workspace.' }, { name: 'options', description: 'initial content; existing text or attachments are preserved unless clearPreviousDraft is true.' }], + parameters: [{ name: 'workspaceId', description: 'explicit target; absent inherits the current or most recent Workspace.' }, { name: 'options', description: 'initial content and the reused blank\'s preset; existing text or attachments are preserved unless clearPreviousDraft is true.' }], }, { signature: 'archiveSession(sessionId: SessionId, options?: { readonly stopActivity?: boolean }): Promise', @@ -649,7 +649,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ISessions', - declaration: 'export interface ISessions {\n readonly list: ObservableSnapshot;\n retain(target: SessionTarget, options: SessionRetainOptions): SessionReference;\n using(target: SessionTarget, options: SessionRetainOptions, operation: (reference: SessionReference) => T | Promise): Promise;\n retainInfo(id: SessionId): ObservableSnapshot;\n readonly searchResultLimit: number;\n create(opts?: {\n workspaceId?: WorkspaceId;\n cwd?: string;\n sessionId?: SessionId;\n }): Promise;\n subagentAddress(id: SessionId): SubagentAddress | undefined;\n refreshProjections(sessionId: SessionId): Promise;\n refresh(): Promise;\n search(query: string, signal: AbortSignal): Promise>;\n fork(opts: {\n sessionId: SessionId;\n atSeq?: number;\n increaseTitle?: boolean;\n onCreated?: (childId: SessionId) => void;\n allowMigration?: boolean;\n }): Promise;\n scope(id: SessionId): AgentContext | undefined;\n scopeOf(ctx: Context): SessionId | undefined;\n sessionOf(ctx: Context): SessionFace | undefined;\n binding(id: SessionId): SessionBinding | undefined;\n}', + declaration: 'export interface ISessions {\n readonly list: ObservableSnapshot;\n retain(target: SessionTarget, options: SessionRetainOptions): SessionReference;\n using(target: SessionTarget, options: SessionRetainOptions, operation: (reference: SessionReference) => T | Promise): Promise;\n retainInfo(id: SessionId): ObservableSnapshot;\n readonly searchResultLimit: number;\n create(opts?: {\n workspaceId?: WorkspaceId;\n cwd?: string;\n sessionId?: SessionId;\n agentPreset?: string;\n }): Promise;\n subagentAddress(id: SessionId): SubagentAddress | undefined;\n refreshProjections(sessionId: SessionId): Promise;\n refresh(): Promise;\n search(query: string, signal: AbortSignal): Promise>;\n fork(opts: {\n sessionId: SessionId;\n atSeq?: number;\n increaseTitle?: boolean;\n onCreated?: (childId: SessionId) => void;\n allowMigration?: boolean;\n }): Promise;\n scope(id: SessionId): AgentContext | undefined;\n scopeOf(ctx: Context): SessionId | undefined;\n sessionOf(ctx: Context): SessionFace | undefined;\n binding(id: SessionId): SessionBinding | undefined;\n}', }, { name: 'KeyedHooksSources', @@ -957,7 +957,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SlotEntryDef', - declaration: 'export interface SlotEntryDef {\n kind: SlotKind;\n scope: SlotScope;\n owner?: object;\n keyProps?: Record;\n hookContext?: unknown;\n inject?: object;\n}', + declaration: 'export interface SlotEntryDef {\n kind: SlotKind;\n scope: SlotScope;\n inline?: true;\n owner?: object;\n keyProps?: Record;\n hookContext?: unknown;\n inject?: object;\n}', }, { name: 'SlotFactoryMap', @@ -993,7 +993,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SlotSpec', - declaration: 'export type SlotSpec = {\n kind: E[\'kind\'];\n scope: E[\'scope\'];\n} & (\'inject\' extends keyof E ? E extends {\n inject: infer Injected extends object;\n} ? {\n inject: Injected;\n} : {\n inject?: object;\n} : {\n inject?: never;\n});', + declaration: 'export type SlotSpec = {\n kind: E[\'kind\'];\n scope: E[\'scope\'];\n inline?: true;\n} & (\'inject\' extends keyof E ? E extends {\n inject: infer Injected extends object;\n} ? {\n inject: Injected;\n} : {\n inject?: object;\n} : {\n inject?: never;\n});', }, { name: 'SnapshotSelectorHook', @@ -1001,7 +1001,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'StartSessionOptions', - declaration: 'export type StartSessionOptions = DraftInitializationOptions;', + declaration: 'export interface StartSessionOptions extends DraftInitializationOptions {\n readonly agentPreset?: string;\n}', }, { name: 'StoreDecl', diff --git a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts index e134f1d984..7ec9c04ce8 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -176,7 +176,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.assistant-actions\', () => ctx.slots.register(\n { name: \'conversation.chat.assistant-actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:414', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:439', }, { key: 'conversation.chat.commandview', @@ -224,7 +224,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.commandview\', () => ctx.slots.register(\n { name: \'conversation.chat.commandview\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:396', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:421', }, { key: 'conversation.chat.flow', @@ -234,7 +234,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ doc: 'Ordered Chat rows and local echoes with viewport-bound visibility hooks.', registerOptions: [], ownerProps: [ - '/** Ordered rows and reconciled local echoes rendered inside one Chat viewport. */\nexport interface ChatFlowOwnerProps extends Pick {\n readonly entries: readonly RenderEntry[]\n readonly pendingInputs: readonly (PendingSubmission | InboxState[\'next-step\'][number])[]\n readonly lastInputTurn: number | undefined\n readonly deferCollapse: boolean\n}', + '/** Ordered rows and reconciled local echoes rendered inside one Chat viewport. */\nexport interface ChatFlowOwnerProps extends Pick {\n readonly entries: readonly RenderEntry[]\n readonly pendingInputs: readonly (PendingSubmission | InboxState[\'next-step\'][number])[]\n readonly lastInputTurn: number | undefined\n readonly deferCollapse: boolean\n}', ], ownerPropsReferences: [ 'ChatNodeOwnerProps', @@ -267,7 +267,50 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.flow\', () => ctx.slots.register(\n { name: \'conversation.chat.flow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:365', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:388', + }, + { + key: 'conversation.chat.message.images', + kind: 'single', + scope: 'session', + summary: 'Renderer for one consecutive group of durable message images.', + doc: 'Renderer for one consecutive group of durable message images. The owner\nsupplies image references, an authorized loader, and alignment. A\nregistration replaces the shipped gallery; without one, images are omitted.', + registerOptions: [], + ownerProps: [ + '/** Message image group handed to the optional attachment presentation plugin. */\nexport interface MessageImagesOwnerProps {\n /** Durable references or submission-echo previews in source order. */\n images: readonly MessageImageSource[]\n /** Session-authorized image URL loader for the durable arm. */\n loadImage: MessageImageLoader\n /** Horizontal placement inside the owning record. */\n align: \'start\' | \'end\'\n /** Force every image into the compact message-attachment tile size. */\n compact?: boolean\n /** Fixed, uncropped thumbnail for an attachment list row. */\n thumbnail?: boolean\n}', + ], + ownerPropsReferences: [ + 'Message', + 'MessageImageLoader', + 'MessageImageSource', + ], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'conversation.chat.node\' (client-ui-chat), so it exists while that entry is mounted', + occupants: [ + 'client-ui-attachment MessageImages', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.message.images\', () => ctx.slots.register(\n { name: \'conversation.chat.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:413', }, { key: 'conversation.chat.node', @@ -284,13 +327,12 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ }, ], ownerProps: [ - '/** Stable owner currency delivered to a keyed Chat renderer. */\nexport interface ChatNodeOwnerProps {\n /** Renderer-owned Node portion selected by the grouping Definition. */\n groupPart?: string\n cwd?: string | undefined\n /** Open the current source file of a skill referenced by a sent message. */\n openSkill: (name: string) => void\n openFile: (path: string, options?: OpenFileOptions) => void\n inspectCall: ((callId: ToolCallId) => void) | undefined\n forkAt: (seq: number) => void\n /**\n * Session-authorized image loader, down-threaded from the Chat view so a\n * chat-node renderer can render the attachment presentation slot directly\n * with only the durable references plus this loader, instead of receiving a\n * rendering closure.\n */\n loadImage: MessageImageLoader\n renderMessageImages: RenderMessageImages\n fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined\n /** Turn-process state when this Node belongs to a projected Turn. */\n turnProcess?: TurnProcessOwnerProps | undefined\n}', + '/** Stable owner currency delivered to a keyed Chat renderer. */\nexport interface ChatNodeOwnerProps {\n /** Renderer-owned Node portion selected by the grouping Definition. */\n groupPart?: string\n cwd?: string | undefined\n openFile: (path: string, options?: OpenFileOptions) => void\n inspectCall: ((callId: ToolCallId) => void) | undefined\n forkAt: (seq: number) => void\n /** Session-authorized image loader supplied by the Chat view. */\n loadImage: MessageImageLoader\n fileMentions: (owner: TurnTailOwnerProps) => MarkdownFileMentions | undefined\n /** Turn-process state when this Node belongs to a projected Turn. */\n turnProcess?: TurnProcessOwnerProps | undefined\n}', ], ownerPropsReferences: [ 'MarkdownFileMentions', 'MessageImageLoader', 'OpenFileOptions', - 'RenderMessageImages', 'TurnProcessOwnerProps', 'TurnTailOwnerProps', ], @@ -338,7 +380,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.node\', () => ctx.slots.register(\n { name: \'conversation.chat.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:377', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:400', }, { key: 'conversation.chat.reasoning.body', @@ -378,7 +420,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.reasoning.body\', () => ctx.slots.register(\n { name: \'conversation.chat.reasoning.body\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:402', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:427', }, { key: 'conversation.chat.turnTail', @@ -440,7 +482,50 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.turnTail\', () => ctx.slots.register(\n { name: \'conversation.chat.turnTail\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:408', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', + }, + { + key: 'conversation.chat.user.images', + kind: 'single', + scope: 'session', + summary: 'User-message images, including pending and local-echo previews, independently replaceable from output images.', + doc: 'User-message images, including pending and local-echo previews, independently replaceable from output images.', + registerOptions: [], + ownerProps: [ + '/** Message image group handed to the optional attachment presentation plugin. */\nexport interface MessageImagesOwnerProps {\n /** Durable references or submission-echo previews in source order. */\n images: readonly MessageImageSource[]\n /** Session-authorized image URL loader for the durable arm. */\n loadImage: MessageImageLoader\n /** Horizontal placement inside the owning record. */\n align: \'start\' | \'end\'\n /** Force every image into the compact message-attachment tile size. */\n compact?: boolean\n /** Fixed, uncropped thumbnail for an attachment list row. */\n thumbnail?: boolean\n}', + ], + ownerPropsReferences: [ + 'Message', + 'MessageImageLoader', + 'MessageImageSource', + ], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'factory \'conversation.chat.user.content\' (client-ui-chat), so it exists while that definition is registered', + occupants: [ + 'client-ui-attachment MessageImages', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.images\', () => ctx.slots.register(\n { name: \'conversation.chat.user.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:415', }, { key: 'conversation.composer', @@ -492,7 +577,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer\', () => ctx.slots.register(\n { name: \'conversation.composer\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:187', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:260', }, { key: 'conversation.composer.bar', @@ -531,7 +616,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.bar\', () => ctx.slots.register(\n { name: \'conversation.composer.bar\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:207', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:280', }, { key: 'conversation.composer.dock', @@ -588,7 +673,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.composer.dock\', () => ctx.slots.register(\n { name: \'conversation.composer.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:199', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:272', }, { key: 'conversation.header', @@ -623,7 +708,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.header\', () => ctx.slots.register(\n { name: \'conversation.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:139', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:212', }, { key: 'conversation.header.leading', @@ -652,7 +737,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.header.leading\', () => ctx.slots.register(\n { name: \'conversation.header.leading\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:168', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:241', }, { key: 'conversation.hero.agentPreset', @@ -689,7 +774,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.agentPreset\', () => ctx.slots.register(\n { name: \'conversation.hero.agentPreset\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:193', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:266', }, { key: 'conversation.hero.brand.mark', @@ -718,7 +803,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.brand.mark\', () => ctx.slots.register(\n { name: \'conversation.hero.brand.mark\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:191', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:264', }, { key: 'conversation.hero.workspace', @@ -751,7 +836,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:189', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:262', }, { key: 'conversation.hero.workspace.directoryFlow', @@ -783,7 +868,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.hero.workspace.directoryFlow\', () => ctx.slots.register(\n { name: \'conversation.hero.workspace.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:118', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:119', }, { key: 'conversation.input.activity', @@ -824,7 +909,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.activity\', () => ctx.slots.register(\n { name: \'conversation.input.activity\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:205', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:278', }, { key: 'conversation.input.attachments', @@ -865,7 +950,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.attachments\', () => ctx.slots.register(\n { name: \'conversation.input.attachments\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:209', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:282', }, { key: 'conversation.input.dock', @@ -929,7 +1014,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.dock\', () => ctx.slots.register(\n { name: \'conversation.input.dock\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:195', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:268', }, { key: 'conversation.input.left', @@ -983,7 +1068,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.left\', () => ctx.slots.register(\n { name: \'conversation.input.left\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:201', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:274', }, { key: 'conversation.input.model', @@ -1022,7 +1107,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.model\', () => ctx.slots.register(\n { name: \'conversation.input.model\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:223', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:296', }, { key: 'conversation.input.overlay', @@ -1080,7 +1165,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.overlay\', () => ctx.slots.register(\n { name: \'conversation.input.overlay\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:197', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:270', }, { key: 'conversation.input.permission', @@ -1119,7 +1204,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.permission\', () => ctx.slots.register(\n { name: \'conversation.input.permission\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:217', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:290', }, { key: 'conversation.input.plan', @@ -1158,7 +1243,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.plan\', () => ctx.slots.register(\n { name: \'conversation.input.plan\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:215', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:288', }, { key: 'conversation.input.right', @@ -1212,50 +1297,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ occupants: [], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.input.right\', () => ctx.slots.register(\n { name: \'conversation.input.right\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:203', - }, - { - key: 'conversation.message.images', - kind: 'single', - scope: 'session', - summary: 'Renderer for one consecutive group of durable message images.', - doc: 'Renderer for one consecutive group of durable message images. The owner\nsupplies image references, an authorized loader, and alignment. A\nregistration replaces the shipped gallery; without one, images are omitted.', - registerOptions: [], - ownerProps: [ - '/** Message image group handed to the optional attachment presentation plugin. */\nexport interface MessageImagesOwnerProps {\n /** Durable references or submission-echo previews in source order. */\n images: readonly MessageImageSource[]\n /** Session-authorized image URL loader for the durable arm. */\n loadImage: MessageImageLoader\n /** Horizontal placement inside the owning record. */\n align: \'start\' | \'end\'\n /** Force every image into the compact message-attachment tile size. */\n compact?: boolean\n /** Fixed, uncropped thumbnail for an attachment list row. */\n thumbnail?: boolean\n}', - ], - ownerPropsReferences: [ - 'Message', - 'MessageImageLoader', - 'MessageImageSource', - ], - standardProps: [ - 'useResource: UseResource', - 'useWorkspaces: SnapshotSelectorHook', - 'usePanelInfo: UsePanelInfo', - 'useSessions: UseSessions', - 'useSessionStatus: UseSessionStatus', - 'useSessionRetainInfo: UseSessionRetainInfo', - 'useWorkspaces: SnapshotSelectorHook', - 'useChat: UseChat', - 'useConversation: UseConversation', - 'useInput: SnapshotSelectorHook', - 'inputActions: InputActions', - 'useSession: SessionSnapshotSelector', - 'sessionId: SessionId', - 'useProjection: UseProjection', - 'useTrajectory: UseTrajectory', - ], - keyDomain: '', - hookContext: '', - slotInject: '', - declaredBy: 'an entry in \'conversation.chat.flow\' (client-ui-chat), so it exists while that entry is mounted', - occupants: [ - 'client-ui-attachment MessageImages', - ], - replaceRisk: 'shadows-shipped-ui', - example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.message.images\', () => ctx.slots.register(\n { name: \'conversation.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:390', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:276', }, { key: 'conversation.plan-review.actions', @@ -1350,7 +1392,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session\', () => ctx.slots.register(\n { name: \'conversation.session\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:133', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:206', }, { key: 'conversation.session.header', @@ -1387,7 +1429,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header\', () => ctx.slots.register(\n { name: \'conversation.session.header\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:141', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:214', }, { key: 'conversation.session.header.actions', @@ -1448,7 +1490,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.actions\', () => ctx.slots.register(\n { name: \'conversation.session.header.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:156', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:229', }, { key: 'conversation.session.header.corner', @@ -1487,7 +1529,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.corner\', () => ctx.slots.register(\n { name: \'conversation.session.header.corner\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:179', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:252', }, { key: 'conversation.session.header.lineage', @@ -1528,7 +1570,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.lineage\', () => ctx.slots.register(\n { name: \'conversation.session.header.lineage\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:150', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:223', }, { key: 'conversation.session.header.utilities', @@ -1588,7 +1630,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.session.header.utilities\', () => ctx.slots.register(\n { name: \'conversation.session.header.utilities\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:162', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:235', }, { key: 'conversation.trajectory.images', @@ -1633,6 +1675,58 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.trajectory.images\', () => ctx.slots.register(\n { name: \'conversation.trajectory.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-trajectory/src/client/trajectory-contract.ts:103', }, + { + key: 'conversation.user.text.node', + kind: 'keyed', + scope: 'session', + summary: 'One business-owned inline renderer for a pure JSON text node.', + doc: 'One business-owned inline renderer for a pure JSON text node.', + registerOptions: [ + { + name: 'key', + requirement: 'required', + type: 'string', + doc: 'Your cell key: the entry renders where the owner dispatches this exact key. Registering an already-occupied key replaces that occupant.', + }, + ], + ownerProps: [ + '/** JSON-only owner data common to every business text node. */\nexport interface UserTextNodeOwnerProps {\n readonly raw: string\n readonly interactive: boolean\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useResource: UseResource', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useWorkspaces: SnapshotSelectorHook', + 'useChat: UseChat', + 'useConversation: UseConversation', + 'useInput: SnapshotSelectorHook', + 'inputActions: InputActions', + 'useSession: SessionSnapshotSelector', + 'sessionId: SessionId', + 'useProjection: UseProjection', + 'useTrajectory: UseTrajectory', + ], + keyDomain: 'fixed by the owner\'s key table { [Id in UserTextId]: { node: UserTextNode } }, already taken: command, file, folder, secret, session, skill, text', + hookContext: '', + slotInject: '', + declaredBy: 'factory \'conversation.user.text\' (client-ui-conversation), so it exists while that definition is registered', + occupants: [ + 'client-ui-conversation PlainUserText key \'text\'', + 'client-ui-conversation SessionReference key \'session\'', + 'client-ui-goal GoalCommandReference key \'command\'', + 'client-ui-reference FileReference key \'file\'', + 'client-ui-reference FolderReference key \'folder\'', + 'client-ui-secret-mask SecretText key \'secret\'', + 'client-ui-skill SkillReference key \'skill\'', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.user.text.node\', () => ctx.slots.register(\n { name: \'conversation.user.text.node\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:196', + }, { key: 'conversation.view', kind: 'list', @@ -1692,7 +1786,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.view\', () => ctx.slots.register(\n { name: \'conversation.view\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:185', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:258', }, { key: 'deliverables.file.actions', @@ -1884,7 +1978,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'main.conversation\', () => ctx.slots.register(\n { name: \'main.conversation\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-conversation/src/client/contract/slots.ts:131', + source: 'packages/client/ui-conversation/src/client/contract/slots.ts:204', }, { key: 'plugins.add.actions', @@ -3020,7 +3114,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'shell.quota-notice\', () => ctx.slots.register(\n { name: \'shell.quota-notice\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:422', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:447', }, { key: 'sidebar', @@ -3871,7 +3965,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.session.row.hover\', () => ctx.slots.register(\n { name: \'sidebar.session.row.hover\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:135', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:136', }, { key: 'sidebar.session.row.leading', @@ -3923,7 +4017,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.session.row.leading\', () => ctx.slots.register(\n { name: \'sidebar.session.row.leading\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:130', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:131', }, { key: 'sidebar.settings', @@ -4046,14 +4140,14 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'shadows-shipped-ui', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.workspaces.directoryFlow\', () => ctx.slots.register(\n { name: \'sidebar.workspaces.directoryFlow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-workspace/src/client/contract/slots.ts:120', + source: 'packages/client/ui-workspace/src/client/contract/slots.ts:121', }, { key: 'sidebar.workspaces.session.menu.item', kind: 'list', scope: 'root', summary: 'The rows of one Session\'s "..." menu, in ascending `order`.', - doc: 'The rows of one Session\'s "..." menu, in ascending `order`. ui-workspace\nregisters the shipped rows here — `pin` (100), `rename` (200), `fork`\n(300), `archive` (400) — so a plugin row is placed by its own `order`\namong them. Use a package-namespaced `id`; reusing a shipped id at\nanother `priority` shadows that row. Each entry renders one\n`role="menuitem"` `